Pedro Cattori
Pedro Cattori

Reputation: 2805

How to highlight past dynamically-specified column in vim?

I want to make a function im my .vimrc to highlight all columns past #, where # is specified in an autocmd for each file type.

For instance, if I wanted Python files to highlight past column 80, but Java files past column 100 I would like to be able to do so as:

autocmd FileType python :call HighlightPastCol(80)
autocmd FileType java :call HighlightPastCol(100)

I am trying to write the HighlightPastCol(col) function as follows:

function HighlightPastCol(col)
    let pastColRegex = '\v\%>' . a:col . 'v.\+'
    match ErrorMsg pastColRegex
endfunction

Where pastColRegex is of the form '\%>#v.+' and # is the column passed in to the function. I got this regex from a related stackoverflow question, but with a static column number instead of the dynamic column specification I want. That regex has been working for me, but I don't want to keep hand-crafting regexes like that for every file type that I want to have this behavior but with a different column count.

The issue I'm running into is that vimscript throws an error on:

match ErrorMsg pastColRegex

stating 'Invalid argument: pastColRegex'.

If there's a better way to go about doing this or a plugin with this functionality, that would be appreciated, though I would still like to know why this approach is failing.

Upvotes: 1

Views: 85

Answers (1)

Ry-
Ry-

Reputation: 224904

You’ll need to add delimiters and execute match dynamically. I think this is about right:

function HighlightPastCol(col)
    let pastColRegex = '/\v\%>' . a:col . 'v.\+/'
    exec 'match ErrorMsg ' . pastColRegex
endfunction

There’s also the colorcolumn option, which doesn’t behave in exactly the same way, but is quite convenient.

Upvotes: 1

Related Questions