Is it possible to visualize the right margin in Vim?

There is no simple way to visualize a vertical edge for the textwidth-margin in Vim 7.2 or earlier; starting with version 7.3, there is dedicated colorcolumn option. However, one can highlight all characters beyond the 80-column limit using the :match command:

:match ErrorMsg /\%>80v.\+/

All we need to make it a general solution, is to build the match pattern on the fly to substitute the correct value of the textwidth option:

:autocmd BufWinEnter * call matchadd('ErrorMsg', '\%>'.&l:textwidth.'v.\+', -1)

I've written a vimscript function in my .vimrc to toggle colorcolumn when I press ,8 (comma followed by 8, where comma is the defined leader for user-defined commands, and eight is my mnemonic key for 'show a margin at the 80th column):

" toggle colored right border after 80 chars
set colorcolumn=81
let s:color_column_old = 0

function! s:ToggleColorColumn()
    if s:color_column_old == 0
        let s:color_column_old = &colorcolumn
        windo let &colorcolumn = 0
    else
        windo let &colorcolumn=s:color_column_old
        let s:color_column_old = 0
    endif
endfunction

nnoremap <Leader>8 :call <SID>ToggleColorColumn()<cr>

Vim 7.3 introduced colorcolumn.

:set colorcolumn=80

It may be easier for you to remember the short form.

:set cc=80

Tags:

Vim