Quantcast
Viewing all articles
Browse latest Browse all 16

Different background color in Vim past 80 columns

Or any number of columns, but 80 seems to be the standard for code.

Preface

I’ve tried different ways of highlighting lines past 80 columns but was never satisfied with the results. Since Vim 7.3 there’s a nice colorcolumn option, but it just didn’t look any good:

Image may be NSFW.
Clik here to view.

Vim with :set colorcolumn=80

It’s not just the red color, which can be easily changed, but the whole “highlight a single seemingly random column” didn’t appeal to me. After searching for inspiration on Google, I found this StackOverflow question with the following screenshot of TextMate:

Image may be NSFW.
Clik here to view.

TextMate with “Highlight right margin” option

Well, well, that looks much prettier. Is it possible to get something similar in Vim?

Highlight range of columns

The answer, as usual in Vim, is “of course!”. From a comment on StackOverflow I learned that you can let colorcolumn highlight several columns:

colorcolumn=81,82,83,84,85

So if we want to highlight the background past 80 columns we would just have to set colorcolumn to all integers from 81 to (81+256-1), since it can highlight a maximum of 256 columns (according to my tests it’s actually 255). Not that hard to do, but there should be a more elegant way to define the range. A Google search proved that my intuition was right; you can add the following in your .vimrc instead:

execute "set colorcolumn=" . join(range(81,335), ',')

If you want to change the colors you can adjust the ColorColumn highlight in your .vimrc or colortheme. Here’s my final result:

Image may be NSFW.
Clik here to view.
Vim with a different background past column 80

A smarter way?

A comment on StackOverflow pointed out that you could highlight the first 80 columns instead and change the background of Normal. I tried to do that, but it clashed with some other highlights, for example my DiffAdd, DiffChange, DiffDelete, and DiffText ctermbg seemed to be overridden. Another limitation I see with this method is that you can’t set a special textcolor for text past 80 columns, if that’s what you fancy. But that’s only as far as I know, and I admit that I know very little when it comes to the inner workings of Vim.


Image may be NSFW.
Clik here to view.
Image may be NSFW.
Clik here to view.

Viewing all articles
Browse latest Browse all 16

Trending Articles