Is there a way to set the text color of an ad-hoc selection in vimscript?

Something like:

" change the text color of the first three rows to red
:1,3 call changeTextColor('red')
  • 2
    Possibly useful: lardcave.net/text/…
    – muru
    Commented Jul 16, 2015 at 3:07
  • What about matchaddpos()? That allows you to highlight arbitrary areas of text. Commented Jul 16, 2015 at 13:16
  • @EvergreenTree matchaddpos() has the same limitation as match, it was broken until recently, it has a horrendous syntax, and it can handle at most 8 lines. To highlight lines 3-5 you need to do it like this: call matchaddpos('FleetingFlashyFiretrucks', [[3], [4], [5]]). Really, it isn't one of Vim's best features.
    – lcd047
    Commented Jul 16, 2015 at 18:04

1 Answer 1


As the link posted by @muru points out, it can be done, the following will highlight lines 3-5:

highlight FleetingFlashyFiretrucks ctermfg=red
match FleetingFlashyFiretrucks /\%>2l\%<6l/

However, the highlighting defined this way is tied to the line numbers, not to the contents of the file. If you delete or insert lines before the highlighted region the highlight will stay at lines 3-5, while the contents will move up or down. For this reason it's almost always better to find a pattern in the text to highlight, rather than a line range.

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.