Вопрос

if is a ".log" file, want to make every line containing keyword "dog" in the file to be in red, and make every line containing keyword "cat" in the file to be in yellow. This should be done automatically when I open a ".log" file in vim. Is there any way to do this?

Это было полезно?

Решение

First, define the colors as highlight groups:

:hi Dogs ctermbg=red guibg=red
:hi Cats ctermbg=yellow guibg=yellow

You can add (window-local) highlighting via the :match commands or the matchadd() function. By matching the entire line containing the keyword, you'll get all highlighted. The :autocmd installs that for your log files (though I would prefer to use Vim's filetype detection instead of hard-coding the file pattern).

:autocmd BufWinEnter *.log call matchadd('Dogs', '^.*dog.*$') | call matchadd('Cats', '^.*cat.*$')

The benefit of :match is that is doesn't interfere with syntax highlighting (which would be an alternative). The downside is that the highlighting will persist when you view a non-log buffer in the same window. (You can fix this by adding more autocmds, but it's not trivial.)

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top