简体   繁体   中英

Custom syntax highlighting in Vim

how to highlight strings that begin with sql_ and are inside quotes?

My Logfile:

MGPostgreSQLConnection.OpenQuery; "sql_p_factory_history"-ExecTime: 47ms
2010-11-12T17:28:18+01:00;custom; MGPostgreSQLConnection.OpenQuery; "sql_p_factory_history"-ExecTime+FetchTime: 47ms
2010-11-12T17:28:18+01:00;custom; MGPostgreSQLConnection.OpenQuery; "sql_factory"-ExecTime: 47ms
2010-11-12T17:28:18+01:00;custom; MGPostgreSQLConnection.OpenQuery; "sql_factory_contactperson"-ExecTime+FetchTime: 62ms

My vimrc (This doesn't work, of course):

au BufRead,BufNewFile *.log syn match "sql_*"
au BufRead,BufNewFile *.log hi sql guifg=white guibg=red

You were nearly there! This version (works and) doesn't highlight the quotation marks.

au BufRead,BufNewFile *.log hi sql guifg=white guibg=red ctermfg=white ctermbg=red
au BufRead,BufNewFile *.log syn match sql /"\zssql_\w*\ze"/

屏幕截图

See the following for more information:

  • :help :syn-match " for syntax matching, erm, syntax
  • :help /\\zs " sets the start of the match there
  • :help /\\ze " sets the end of the match there
  • :help /\\w " word character

Debugging:

The command :verbose :syn should give you something like this:

--- Syntax items ---
[...]
sql            xxx match /"\zssql_\w*\ze"/

And :verbose :hi :

        Last set from ~/.vimrc
[...]
sql            xxx cterm=bold ctermfg=7 ctermbg=1 guifg=white guibg=red

The xxx should be in the same colours as you have specified (and look like the highlighting in my screen-shot). If you don't see those, check that your .vimrc (or _vimrc on Windows) is sourced:

:scriptnames
1: /home/javh/.vimrc
[...]

Of course this only works when:

:echo has('syntax')

...returns 1 (or :version includes +syntax ).

The syntax for syn match is syn match highlight_group reg_exp .

So, try :

au BufRead,BufNewFile *.log syn match Todo /"sql_\w\+"/

Why don't you read the help for :syn ? Vim help is so good that you find all answers fast :)

:help :syntax

Another way to do it, without syntax match , is to use the :match command or the matchadd() command directly.

In brief:

" to enable
:match Todo /"\@<=sql_\w\+"\@=/
" reference:
" \@<= is such a beautiful duck, :help /\@<= for more help
" :help /\@= for the \@= part, also.
"
" to cancel
:match none
" :help :match / :help :2match / :help :3match

or

" to enable
:call matchadd('Todo', '"\zssql_\w\+\ze"')
" or
:let foobarbaz = matchadd('Todo', '"\zssql_\w\+\ze"')
"
" to disable
:call matchdelete(foobarbaz)
" or
:call clearmatches()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM