2

How can I check if the cursor is inside a comment section like this in C:

/*
 * Comment section
 */

Or in python:

"""
Doc string
"""
# Comment line

My idea for C is, that I just look, what the first characters are but I have no clue how to check, if the cursor is inside a doc string. Do you have any ideas?

1

Sure. Use the generic “get syntax” trick (provided by many plugins, including one of mine, and easy to write yourself):

echo synID(line('.'), col('.'), 0)->synIDattr('name') =~# 'Comment' ? 'In comment' : 'Not in comment'
4
  • I'm getting this error message: E15: Invalid expression: >synIDattr('name') =~# 'Comment' ? 'In comment' : 'Not in comment' Do you know how I can fix this?
    – TornaxO7
    Jan 23 at 13:46
  • Ok, I took a look into the help page and changed your command into that: echo synIDattr(synID(line('.'), col('.'), 0), 'name') but this gives me nothing, if I'm inside of a doc string in python. If I'm in a commentary string than it returns pythonComment which is fine.
    – TornaxO7
    Jan 23 at 13:49
  • Oh, the problem was, that the doc-string was empty. Sorry, my fault! Thank you for your help :)
    – TornaxO7
    Jan 23 at 13:52
  • @TornaxO7 I used a more recent method-style syntax; in most cases you can take what’s right of the arrow and make it a function argument (usually the first)
    – D. Ben Knoble
    Jan 23 at 14:04

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.