0

I have a tab-delimited text file with fairly long lines. To improve readability, I would like to color text in each column individually. Is this possible in Vim?

For example, the first column text would be green, the second magenta and the third one in yellow.

It would be nice if a shortcut could be set so that I can quickly activate this mode when needed.

1 Answer 1

2

I assume by "column" you mean in a tab-delimited sense. You can get this effect with the following code. Turn on and off with :DoColorColumns/:NoColorColumns. You can easily make a mapping if desired. All this is doing is using matchadd( with a regular expression that skips the appropriate number of text+tab blocks.

function! ColorColumns(state)
  let l:colors = ['green', 'magenta', 'yellow',
        \ 'red', 'blue', 'darkyellow', 'cyan', 'white']

  if exists('s:column_matchids')
    call map(filter(s:column_matchids, 'v:val > -1'),
          \'matchdelete(v:val)')
  endif
  let s:column_matchids = repeat([-1], len(l:colors))

  if !a:state | return | endif

  for l:i in range(len(l:colors))
    exe 'hi Column'.l:i 'guifg='.l:colors[l:i] 'ctermbg='.l:colors[l:i]
    let s:column_matchids[l:i] = matchadd('Column'.l:i,
          \ '^'.repeat('.\{-}\t',l:i).'\zs.\{-}\ze$')
  endfor
endfunction

command! DoColorColumns call ColorColumns(1)
command! NoColorColumns call ColorColumns(0)

See also the plugin https://github.com/chrisbra/csv.vim, which works for tab-delimited files as well as comma-separated ones.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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