2

:command Linecomment :normal ^i/*<ESC>$a*/<ESC>
The above command is one that I came up with in order to comment out an entire line in C, normally for debugging purposes and whatnot.

I was wondering what sort of modifications would be needed to turn this into a function, and what similar function would comment from the cursor position to the end of the line?

1 Answers1

4

To factor out a function (which is useful when the mapping commands become longer), the only thing you need to consider is that the special keys like <Esc> that work in the right-hand side of the mapping don't work inside the function; you need to use :execute with double-quotes, and escape them:

function Linecomment()
    execute "normal ^i/*\<ESC>$a*/\<ESC>"
endfunction
command Linecomment call Linecomment()

To comment from the cursor position, you just need to drop the ^ motion at the start.

However, for a truly powerful and robust commenting solution, I would recommend to use one of the popular plugins:

Ingo Karkat
  • 23,523