1

I want to add comments dependant on the column i'm writing for example if i'm adding a comment over a code which is indented 4 spaces the comment should look like

/* Comment -------------*/

as many dashes as needed to fill up the line till column 100. It should recognize where the position is and how long the comment is.

I can't figure it out with vimscript myself.

1 Answer 1

4

You can solve this with an expression mapping; see :help :map-expr:

:inoreabbrev <expr> comsep '/* Comment ' . repeat('-', 17 - indent('.')) . '*/'

This determines the width by subtracting the current indent (via indent()) from a constant. You could use &textwidth here, too.

Whenever you type comsep, it'll be expanded. Alternatively, you could also use an :inoremap <expr> <C-g> ... instead.

To insert the comment text, you could either use input(), or first just insert dashes and re-position the cursor by appending a number of "\<Left> keycodes.

If you use a snippet plugin like snipMate or Ultisnips, those may have functionality to dynamically modify the snippet, but the built-in methods should suffice.

Sign up to request clarification or add additional context in comments.

7 Comments

ill have a try. in the documentation of snipmate i didn't find something similar to my problem (like repeating n times)
Original snipMate cannot do this dynamically as you type the comment (Ultisnips might). You can use Vimscript expressions in backticks, but these are only evaluated once when expanding the snippet.
the command you posted actually doesnt work. it puts just the code into the line after hitting enter.
You need the <expr>; it'll expand after space or enter.
yes i meant i actually type "comsep" press enter and then it inserts this: '/* Comment ' . repeat('-', 17 - indent('.')) . '*/'
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.