Vim Tips Wiki

Check for comments independent of filetype

1,613pages on
this wiki
Revision as of 05:19, July 13, 2012 by JohnBot (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Tip 218 Printable Monobook Previous Next

created 2002 · complexity advanced · author Mark A. Hillebrand · version 6.0

For some scripts it might be useful to detect, whether a specific position in a buffer is inside of a comment or not. Syntax highlighting can save us the work for parsing the comments ourselves. The command

:echo synIDattr(synIDtrans(synID(line("."), col("."), 0)), "name")

echoes the group used for highlighting the character at the current cursor position, see :help synIDtrans(). It will usually be Comment if the cursor is inside of a comment, so

synIDattr(synIDtrans(synID(line("."), col("."), 0)), "name") == "Comment"

detects, independent of the filetype (which have their own group names for comments), if the cursor is inside a comment or not.

The expression

synIDattr(synIDtrans(synID(line("."), col("."), 0)), "name") =~ 'Comment\|Constant\|PreProc'

will detect additionally, if the cursor is inside of a string or some preprocessor statement.


Around Wikia's network

Random Wiki