Color textwidth column (e.g. column 80) for long lines, per file type

3 Points

Ory Band Ory Band

9 years ago

Python convention is to write max 79 characters per line. However, this is not the case with Go lang for example.

This snippet colors your textwidth character when you write past it, per file type.

For example a long Python line will have its 80th column colored. A long Go lang line won't.

" Color 'textwidth' character on lines longer than 'textwidth'.
" Ignores a buffer if it's filetype is 'go'.
" This can of course be edited to suit your needs and various file types.
function! ColorColumnPerFileType()
    call clearmatches()
    " This will actually color the column when your reach a character before, thus warning you that you've reached your maximum chars per line. This can be edited to suit your needs.
    if &ft != 'go' | call matchadd('ColorColumn', printf('\%%%dv', &textwidth+1), -1) | endif

" Using an augroup is recommended to avoid recursive decleration every time you `:source $MYVIMRC`
augroup Buf-Win-Enter
    " Set color column on every buffer change.
    autocmd BufWinEnter * call ColorColumnPerFileType()
augroup END