Is it possible to visualize the right margin in Vim?

Vim

Vim Problem Overview


Is there any way to make Vim (or gVim, or both) highlight the right margin of the current buffer?

I have just begun to work with Vim for a while, and find it annoying not to have the right margin visible (say, at column 80).

Vim Solutions


Solution 1 - Vim

Vim 7.3 introduced colorcolumn.

:set colorcolumn=80

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

:set cc=80

Solution 2 - 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)

Solution 3 - Vim

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>

Solution 4 - Vim

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>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHa-Duong NguyenView Question on Stackoverflow
Solution 1 - VimwilhelmtellView Answer on Stackoverflow
Solution 2 - Vimib.View Answer on Stackoverflow
Solution 3 - VimJonathan HartleyView Answer on Stackoverflow
Solution 4 - VimMateusz PiotrowskiView Answer on Stackoverflow