Skip to content

Instantly share code, notes, and snippets.

@knatsakis
Last active September 29, 2019 19:59
Show Gist options
  • Save knatsakis/ccf03e3df450fefac2ddcaec02ac6071 to your computer and use it in GitHub Desktop.
Save knatsakis/ccf03e3df450fefac2ddcaec02ac6071 to your computer and use it in GitHub Desktop.
vimscript: Highlight trailing whitespace and overlength lines
highlight Trailing ctermbg = DarkRed " Used when no colorscheme is set
highlight Overlength ctermfg = Yellow " Used when no colorscheme is set
augroup colorScheme " Used when switching colorschemes
autocmd! " Added so that ~/.vimrc can be re-sourced multiple times
autocmd ColorScheme * highlight Trailing ctermbg = DarkRed
autocmd ColorScheme * highlight Overlength ctermfg = Yellow
augroup END
let g:highlightsExcludeFileTypes = [] " File types where no highlighting should occur (e.g.: ['deb'])
function! s:Highlights()
let l:buftype = getbufvar(str2nr(expand('<abuf>')), '&buftype') " Buffer type of the buffer that triggered the autocommand
let l:filetype = getbufvar(str2nr(expand('<abuf>')), '&filetype') " File type of the buffer that triggered the autocommand
if l:buftype != '' || index(g:highlightsExcludeFileTypes, l:filetype) >= 0 " Buffer type is non-empty (empty means normal buffer) or file type is in exclude list
if exists('w:Trailing')
call matchdelete(w:Trailing)
unlet w:Trailing
endif
if exists('w:Overlength')
call matchdelete(w:Overlength)
unlet w:Overlength
endif
else " Current buffer type is empty (normal buffer) and file type is not in exclude list
if !exists('w:Trailing')
let w:Trailing = matchadd('Trailing', '\s\+$', -1)
endif
if !exists('w:Overlength')
let w:Overlength = matchadd('Overlength', '\%>80v.*', -2)
endif
endif
endfunction
augroup highlights
autocmd! " Added so that ~/.vimrc can be re-sourced multiple times
autocmd FileType,VimEnter,WinEnter * call s:Highlights() " Adjust highlights when starting vim, entering window or changing filetype
augroup END
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment