0

I want to make a Python ftplugin (but other filetypes will also have this option) where, if the previous line has a comment that starts with #, the next line can be commented via <Shift><CR>, an insert-mode mapping (inoremap). How can I code Vimscript so that it checks whether the current line is commented, and subsequently allows the inoremap to make a new line commented?

And please don't recommend a third-party plugin like NERD Commenter (which, btw, I respect very much), I want something as close to vanilla-Vim as possible for this.

  • I don't get the goal of this mapping. If you want to be able to use <CR> to add a line with no comment and <Shift-CR> to add a comment, why do you need it to be conditional on whether the current line has a comment? If you don't want a comment added when you're not currently on a commented line, why would you pressing <Shift-CR> in that case? Am I misunderstanding the behaviour of the mapping you want to create? – Rich Feb 22 at 16:11
  • Oh...shoot you're right. I didn't think of that before lol – K. Paul Feb 23 at 2:41
3

To check if the current line is commented, you can use

:echo synIDattr(synIDtrans(synID(line("."), col("$")-1, 1)), "name")

This checks, if the current line ends with a comment syntax item.

You can then do something like this:

inoremap <expr><silent> <f6> synIDattr(synID(line('.')-1, strlen(getline(line('.')-1)), 1),'name')=~?'comment'?'#':' '

this maps the F6 key to check if the syntax group from the end of the previous line matches comment and if so returns the comment character #, else it will simply return a Space.

  • Checking the syntax instead of the content is super clever! – Rich Feb 22 at 16:12
  • One could probably even lean on 'commentstring' (which i think tpope’s commentary does). – D. Ben Knoble Feb 22 at 20:35
  • Checking the syntax was much more helpful than other things I've tried! Thanks for the help. – K. Paul Feb 23 at 2:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.