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:
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>
I've rewritten the answer of Jonathan Hartley for the older Vim versions like 7.2 as there is no colorcolumn in older Vims.
highlight OverLength ctermbg=red ctermfg=white guibg=#592929
let s:OverLengthToggleVariable=0
function! ToggleOverLength()
if s:OverLengthToggleVariable == 0
match OverLength /\%81v.\+/
let s:OverLengthToggleVariable=1
else
match OverLength //
let s:OverLengthToggleVariable=0
endif
endfunction
" I like <leader>h since highlight starts with h.
nnoremap <leader>h :call ToggleOverLength()<cr>