Search code examples
vimvim-syntax-highlighting

auto highlight dictionary words when opening text file in vim


How would I make vim highlight all the words that are in my dictionary when opening a text file (at startup)?

My preferred way would be to add some 2 or 3 lines settings/fun/autocmd to my vimrc, but if it is not possible, what would be the plugin offering exactly this dictionary word highlight function? Thanks in advance.


Solution

  • I tried various approaches such as creating custom dictionaries and then redefining the highlighting for Normal and SpellBad words. I also tried marking the desired words as being “rare” (since Vim uses different highlighting for rare words) but those ideas didn’t work out. Here's the best I could come up with:

    Define highlighting

    First, define how you want the words to be highlighted. In this example, I want all the numbers from one to ten to be highlighted so I call my group, “Numbers” and tell Vim that I want these words to appear in red with either the terminal or the GUI version.

    highlight Numbers ctermfg=red guifg=red
    

    Option 1: Syntax

    If there are a lot of words, use the syntax command to define the keywords to be highlighted:

    syntax on
    syntax keyword Numbers one two three four five six seven eight nine ten One Two Three Four Five Six Seven Eight Nine Ten 
    

    Option 2: Match

    Note that using syntax option, you need to include different permutations of upper and lower case. If you don’t want to do that, you could instead use the match keyword which operates on regular expression patterns rather than a list of words. Use the \c option to ignore case.

    match Numbers /\c\<one\>\|\<two\>\|\<three\>\|\<four\>\|\<five\>\|\<six\>\|\<seven\>\|\<eight\>\|\<nine\>\|\<ten\>/
    

    The drawback to using match is that Vim has to keep evaluating the match pattern for changes in the text. This becomes computationally expensive if the regular expression pattern is too long (lots of words). This would cause Vim to become too slow.