1

I am trying to make text bold if it appears after a series of # hashes. This is the line in my .vimrc:

au BufRead,BufNewFile *.txt hi header cterm=cyan ctermbg=red

and my attempted regular expressions:

au BufRead,BufNewFile *.txt syn match header /\n#+\zs.*\ze/
au BufRead,BufNewFile *.txt syn match header /^#+\zs.*\ze/ "Why doesn't ^ work?

This sort of works, but it also matches the #s and some incorrect text. It's also very slow and takes about ~10 seconds to match on my macbook:

au BufRead,BufNewFile *.txt syn match header /\zs\n#*\w*\ze/

I'm not sure what I'm doing wrong -- these work on online regex testers.

On this tester, the regex ^#*(.*) works perfectly, where I'm matching with the first capture group. How do I translate this for vim?

Cheers.

2

The multiplier for 1 or more matches is \+; you forgot the backslash (or the \v "very magic" modifier). Using \ze at the end is superfluous. ^ matches at every beginning of line \n only starting on the second line. Please be aware that Vim uses a special regular expression dialect, so what various web sites tell you may need adaptation. The :help pattern pages are the best and authoritative reference.

syn match header /^#\+\zs.*/

Also, your syntax addition may be obscured by existing syntax rules. You can try appending containedin=ALL, but that's not a general solution. You may need to analyze the existing syntax and craft a special solution for each syntax. As an alternative, you may use the :match command. This works on top (and independent) of syntax highlighting. The downside is that this is window-local, so you need :autocmd magic if you want to apply this only to certain buffers, or also to window splits.

match header /^#\+\zs.*/

style critique

With your au BufRead,BufNewFile *.txt syn match, your intermingling several aspects: filetype detection (the mapping of *.txt to an (here: implicit) filetype), filetype customization, syntax highlighting). It would be cleaner (and more extensible) to separate the things:

  1. Define a text filetype: au BufRead,BufNewFile *.txt setf text. This detection may already exist in your Vim version.
  2. Define syntax highlighting (or extension) in ~/.vim/syntax/text.vim (or ~/.vim/after/syntax/text.vim to extend an existing syntax).
  • That works great -- thanks for your help! Especially the style critique -- it can be difficult to find the proper conventions. – haz Nov 6 '17 at 9:52

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.