Question

From time to time I would like to apply some custom extra syntax highlighting on the current buffer.

How can this be done using the build in vim syntax/highlight system (I do not want to use the Highlight plugin)

As example, I would like to highlight all assert statements in current buffer.

Was it helpful?

Solution

If the highlighting is for certain filetypes (e.g. Java) only, and you want it all the time, I'd extend the original syntax with :syn match ... definitions placed in ~/.vim/after/syntax/java.vim.

For spontaneous highlighting, use :match (or :2match), as dwalter has shown.

If you're gonna write a more elaborate mapping, maybe with toggling on/off logic, use matchadd() / matchdelete().

Finally, if you need highlighting for arbitrary words / strings, like marking up a document with a text marker, I'd suggest the comfort of a plugin like Mark (which I have taken over maintaining).

OTHER TIPS

You can use match and highlight if you want.

example:

    :hi MyAsserts term=bold ctermbg=Cyan
    :match MyAsserts /assert(.*)/

to highlight your assert() statements with Cyan background. :match without any arguments will reset it.

for more information on either highlight or match look at the documentation via :help hi or :help match

To reuse your highlighting you can save those commands in a file and use :source file.vim to load it anytime you want. Another way would be to define a command inside your .vimrc.

     hi MyAsserts ctermbg=Cyan
     command -bar -nargs=0 HiAsserts match MyAsserts /assert(.*)/
     "highlight any given regex
     command -bar -nargs=1 HiIt match MyAsserts /<args>/

and call it with :HiAsserts to highlight your assert() statements or :HiIt foo to highlight every foo in your buffer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top