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.

2
  • 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, 2019 at 16:11
  • Oh...shoot you're right. I didn't think of that before lol
    – Paul Kim
    Feb 23, 2019 at 2:41

1 Answer 1

4

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.

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

Your Answer

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

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