I want to test, if the cursor is currently in a comment line. For example in C it looks like this:

// This is a comment line

now it's also possible that it's a big comment section:

 * Big comment section

Now I'd like to read the current line and look what the first character is. Is there a function where I can compare a regex-pattern with the current line? Like this:

if match(getline(line(".")), "^[/\*]")
    (do something)

but match seems to have another functionality according to the :h match help page. Do you have an idea how I can achieve a "regex-pattern-comparison"?

  • I thought we just did this vi.stackexchange.com/q/28856/10604
    – D. Ben Knoble
    Jan 26, 2021 at 13:19
  • cf :help =~# though
    – D. Ben Knoble
    Jan 26, 2021 at 13:19
  • @D.BenKnoble yes, but I was also wondering if there's another possibility which works, while the user is typing, so the cursor needn't to be in the comment line. So I created this new question. I hope that it's fine for you, this question isn't supposed to repeat my previous post. It just didn't work while the was typing (or at least at the end of the comment) so I created this new question.
    – TornaxO7
    Jan 26, 2021 at 21:22

2 Answers 2


:h :match is about command, while :h match() is about a function. Make sure you've read and understood :h help-context, :h help-summary and How do I navigate to topics in Vim's documentation? before you move on.

But it's a wrong idea to do your job twice. Whenever is the :syntax on Vim already does its best at source code parsing. This is how to make use of it:

function! IsCursorOn(item) abort
    if !exists('b:current_syntax')
        " really don't know

    " get syntax ID under cursor
    let l:id = synID(line('.'), col('.'), 1)

    " test if name matches
    return synIDattr(l:id, 'name') =~? a:item

:echo IsCursorOn("Comment")
  • The problem is, that it can only validate the syntax if the cursor is inside the comment, but I'd like to control it, I'm writing a comment.
    – TornaxO7
    Jan 26, 2021 at 12:32
  • @TornaxO7 This is just an example. You can check any position in the buffer.
    – Matt
    Jan 26, 2021 at 13:06

As Matt has said, the correct approach is to test the current syntax type.

In C and C++ case, I test comments with the pattern '\c\vcomment|doxygen'

" autoload/lh/syntax.vim

function! lh#syntax#match_at(syn_pattern, l, c) abort
    let stack = synstack(a:l, a:c)
    let names = map(stack, 'synIDattr(v:val, "name")')
    let idx = match(names, a:syn_pattern)
    return idx >= 0
  catch /.*/
    throw "Cannot fetch synstack at line:".a:l.", col:".a:c
  return 0

function! lh#syntax#is_a_comment_at(l,c) abort
  return lh#syntax#match_at('\c\vcomment|doxygen', a:l, a:c)

Your Answer

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

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