I'd like to create a keymapping with a conditional statement, so that it behaves differently when a given line is blank.

This thread gave me the following snippet, which is great – except that it doesn't match lines that are blank-except-for-a-comment-marker. I'd like to capture those lines, too.

inoremap <expr> [KEY SEQUENCE] getline(line(".")+1) =~ "^$" ? "[COMMAND]" : "[COMMAND]"

So I set out to build a regular expression. '\v^(#|"|*)?$' is what I came up with. I tested it in vim's command line, and it looks like it should work:

:echo getline(line(".")) =~ '\v^(#|"|*)?$'

returns 1 on the target lines, and returns 0 on all others.

But then the same expression used in the following mapping throws an error:

nnoremap <expr> <Leader>o (getline(line(".")) =~ '\v^(#|"|*)?$') ? (":echo '1'") : (":echo '0'")


E115: Missing quote: '\v^(#
E15: Invalid expression: (getline(line(".")) =~ '\v^(#`

Then I tried rewriting the regular expression without the \v flag: '^\(\#\|\"\|\*\)\?$'. It still works in command-line testing, and eliminates the error, but still doesn't match as expected. (It matches blank lines, but not those beginning with a comment marker.)

What am I missing? (Additionally, does Vimscript have a way to specify "current-filetype's-comment-marker", so I don't have to lump all three of these together as one?)

1 Answer 1

  1. The parentheses are unnecessary.
  2. The error is caused by the unescaped pipes in your pattern. Escape them to fix that error:

    nnoremap <expr> <key> getline(line(".")) =~ '\v^(#\|"\|*)?$' ? ":echo 1\<CR>" : ":echo 0\<CR>"

Additionally, does Vimscript have a way to specify "current-filetype's-comment-marker", so I don't have to lump all three of these together as one?

Yes, you can use &commentstring but it may or may not be correctly set for every filetype.

  • you can define &commentstring in a ftplugin for the filetypes missing!
    – Wolfie
    Oct 7, 2016 at 10:35
  • THANK YOU, I'd been futzing around all day with that nonsense. Now a follow-up question: When I replace (#\|"\|*) with (&commentstring), I get a could not pop the stack! error. Do you know the appropriate syntax offhand? (or... can vim regular expressions interpolate variables at all?)
    – Ryan Lue
    Oct 7, 2016 at 10:53
  • 1
    '(' . &commentstring . ')'
    – romainl
    Oct 7, 2016 at 11:21

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.