Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limiting a match in vim to certain filetypes?

I have the following in my .vimrc to highlight lines longer than 80 chars:

highlight OverLength ctermbg=red ctermfg=white guibg=#592929
match OverLength /\%81v.*/

This works quite well. However, the problem is that I would prefer it if it only worked on certain file types. Basically, any programming language should be highlighted and things like html, xml, and txt files should not be. I'm pretty sure I could do this easily with an autocmd, but I'm not sure if that is the best way to accomplish that goal. Anybody have any opinions?

like image 479
Paul Wicks Avatar asked Nov 09 '09 17:11

Paul Wicks


2 Answers

Sounds like you might want something like:

autocmd FileType html,xml highlight OverLength ctermbg=red ctermfg=white guibg=#592929
autocmd FileType html,xml match OverLength /\%81v.*/

Seems to work for me anyway :-)

like image 168
Benj Avatar answered Sep 23 '22 08:09

Benj


The issue with using match for a task like this is that it is local to the active window, not to the buffer being edited. I'd try something along the following lines:

highlight OverLength ctermbg=red ctermfg=white guibg=#592929
fun! UpdateMatch()
    if &ft !~ '^\%(html\|xml\)$'
        match OverLength /\%81v.*/
    else
        match NONE
    endif
endfun
autocmd BufEnter,BufWinEnter * call UpdateMatch()

Basically, you want to trigger whenever the buffer in the current window changes. At that point, you evaluate what filetype the buffer has and adjust whether the match should be active or not.

If you also want to support editing an unnamed buffer and then setting its filetype (either via saving or manually setting &ft), the FileType even should be added to the list.

like image 36
jamessan Avatar answered Sep 21 '22 08:09

jamessan