I noticed that the TODO
part of #TODO
is highlighted in yellow when editing Python files using Vim. How can I add custom highlighting? For example, I want the BUG
part of #BUG
to be highlighted in red.
I searched for some answers, but they are too complicated and did not achieve the desired matching effect.
Does anyone have a better method?
House Peace is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
You can do this by introducing a new group into Vim’s Python syntax definition.
The original definition can be found in $VIMRUNTIME/syntax/python.vim
and can serve as a reference.
Tweaks for built-in files are supposed to go into the after files of your user’s Vim directory, e.g. ~/.vim/after/syntax/python.vim
or $HOME/vimfiles/after/syntax/python.vim
on Windows.
You may create the directories and the file if they don’t already exist.
This file will be :source
d after the global config.
Refer to the documentation in :help runtimepath
and :help after-directory
.
The following lines need to go into ~/.vim/after/syntax/python.vim
:
syntax match pythonComment "#.*$" contains=pythonBug,pythonTodo,@Spell
syntax keyword pythonBug BUG contained
highlight link pythonBug Error
The first line is copied from the global syntax file and we just add our new syntax group pythonBug
.
Now comments can also contain pythonBug
just as they can contain pythonTodo
(the group responsible for highlighting “TODO” etc.).
The second line defines that pythonBug
should match the keyword “BUG” but only if it’s contained within another group (that’s pythonComment
).
The third line links the appearance of pythonBug
to Error
which will – depending on your colorscheme – probably be something reddish. You can also browse all known highlight groups with :highlight
and pick one you like better.
While it’s possible to explicitly give “BUG” a red background, it’s better to let the colorscheme take care of the actual colors.
Notable sections of the documentation are :help :syn-keyword
and :help :highlight
.