1

The colorcolumn works well when there are no wrapped lines. set colorcolumn=80:

Vim colorcolumn

However, when there are long lines that are wrapped, the colorcolumn breaks into multiple pieces:

Vim colorcolumn on wrapped lines

Is there a way to make it such that the colorcolumn will always be a single unbroken line?

1

The colorcolumn setting accepts multiple values, for example set colorcolumn=30,60 will highlight column 30 and 60.

You can use this to display a single unbroken line for wrapped lines; for example for a 130-column line on a 40 column display you would use set colorcolumn=30,70,110 to highlight the first three columns.

You can set this automatically with a little command:

command! -nargs=1 WrappedCC let &colorcolumn = join(map(range(10), {i -> &columns * i + <args>}), ',')

This uses &columns to get the screen width, and adds the first ten colour columns at the correct place.


You can also hook in to OptionSet autocommand to automatically do this whenever colorcolumn is set, so you don't need a new command:

augroup wrappedcc
    autocmd!
    autocmd OptionSet colorcolumn
        \  if &cc != '' && &cc !~ ','
        \|   let &colorcolumn = join(map(range(10), {i -> &columns * i + &cc}), ',')
        \| endif
augroup end

Then you can just use set cc=80 instead of WrappedCC 80. You can still use set cc= to clear the highlight, or set cc=80,120 to only set those two columns.


You will need to re-apply this if you resize your Vim window, which you can do automatically with the VimResized autocmd; since the OptionSet autocmd isn't triggered inside autocommands we need to re-implement the logic for it; combining it with the above we get:

augroup wrappedcc
    autocmd!
    autocmd OptionSet colorcolumn
        \  if &cc != '' && &cc !~ ','
        \|   let &colorcolumn = join(map(range(10), {i -> &columns * i + &cc}), ',')
        \| endif

    autocmd VimResized *
        \  if len(matchlist(&cc, ',')) >= 4
        \|   let &colorcolumn = join(map(range(10), {i -> &columns * i + str2nr(&cc)}), ',')
        \| endif
augroup end

This assumes that anything with more than four columns is a "wrapped column".

If you use the :WrappedCC command then you can call that inside the VimResized autocommand.


Aside: if you have a fairly new Vim version (8.1.1996, from Sep 2019) then you can use methods to make it a bit more readable:

let &colorcolumn = range(10)->map({i -> &columns * i + str2nr(&cc)})->join(',')

But many distros still ship with older Vim versions.

1
  • 1
    Note: just noticed this will break set cc=+1 to set the colour column relative to the text width. I'll leave this answer as-is for now; I'll fix it later. Jan 30 at 7:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.