Custom syntax highlighting in Vim
Recently I have been doing quite a lot of documentation covering an existing technology solution (a mobile app) and I have been using the usual suspects of Vim
, Vimwiki
and Markdown
which will then go into Confluence
with some Gliffy
diagrams I expect.
Which is all well and good but when you are using Markdown
both as the documentation and essentially as project management / checklist management as to what information is missing, one can find that Markdown
can be a little sparse and oh please can’t you give me a couple more highlighting options?
So, hey, we are Vim mastahs so let’s add in a custom bit of syntax highlighting for @todo
, @random_person
and I would also like to make the marks in checkboxes pop.
To do this, we put the following in ~/.config/nvim/after/syntax/vimwiki.vim
(you can override the syntax for any filetype in similar files e.g. after/syntax/php.vim
):
" Match strings like @michael
syntax match atWord '@\w\+'
highlight link atWord Special
" Match @todo, will override previous match
syntax match myTodo '@\ctodo'
highlight link myTodo Todo
" Modify checkboxes and marks to stand out more
syntax region myCheckMark matchgroup=myCheckBox start='[-*]\s\[' end='\][^(]' skip='[ \.oOX]{1}' oneline
highlight link myCheckBox Delimiter
highlight link myCheckMark Special
Some of this is self explanatory. syntax match
will link a highlight group (a word that is then linked to a colour) such as atWord
to a regex pattern. highlight link
will match our custom highlight group to an existing highlight group e.g. the Special
group which on my current colour scheme is orange.
syntax region
is a more complicated chestnut and in the example I am using it to separately set highlight groups for the square brackets and what is inside the brackets in something such as:
- [X] Item 1
- [ ] Item 2
Which is what I use for a list of items that can be checked off. start
is used to signify the start of the match, end
what signifies the end of the match and skip
is the meat, if you will, of the match. matchgroup
let’s you specify the outside highlight group separately to the inside which is myCheckBox
and myCheckMark
respectively in the example.
Update: the checkbox addition broke on links such as - [link](link)
until I put in oneline
which makes sure the match must be completed on the one line.
If you are interested in going further regarding custom syntax highlighting I found the Vimwikia page one of the best to get going and of course steve losh’s pages are always good.