Make Vim display a line at the edge of the set textwidth

Most of the text editors and IDEs that I use these days have a feature where they can display a line at a certain character length in the text buffer. It's useful when you want to keep lines in a file under a certain length.

Is there any way to get Vim to do this, preferably using the already defined textwidth value? Lines will automatically wrap at that point, but I'd really like to be able to see where it is as well.

In case it matters, I'm mainly using gVim on Windows, but I'd love it if the solution works across Vim versions.


Solution 1:

for (g)vim, use the following:

set colorcolumn=80

or whatever width you wish. Works in both vim & gvim. I have mine within an IF so it's conditional based on which type of files I edit.

You may also use a +x/-x to base position of the column +/- from &textwidth.

set textwidth=80
set colorcolumn=-2

would effective draw the colored bar at char position 78. Of course, you may or may not set textwidth yourself, so it might be 0 (default). I use the absolute position form.

You may also change the color used if you wish:

highlight ColorColumn ctermbg=green guibg=orange

(I don't recommend THOSE colors though)

This option was added in (g)vim 7.3.

Solution 2:

There's a snippet at Google Code you can try:

augroup vimrc_autocmds
au!
    autocmd BufRead * highlight OverLength ctermbg=red ctermfg=white guibg=#592929 
    autocmd BufRead * match OverLength /\%81v.*/
augroup END