/home/posts/vim-thesaurus

Using a Thesaurus File in Vim

Published on

As you use vim more and more, you will uncover new tips and tricks. One such trick is how to use vim’s builtin thesaurus functionality to replace words you may find yourself using too much.

#The Thesaurus File

Each line in the file should contain words with similar meaning, separated by non-keyword characters (white space is preferred).

:h thesaurus

Unfortunately, this is about as much guidance as vim will give us on this one. Essentially, vim wants things in the form of word {synonym 1} {synonym 2} {synonym 3}..., like so:

angry upset mad pissed
happy glad uplifting
throw chuck push
Notice there are no multiple-word synonyms like "happy full of joy".

However, I was unable to find any thesaurus files online to fit this pattern. What I was able to find was several files in the following format:

angry,acid,acrimonious,aggravated,algetic,anarchic,angered,annoyed
happy,a propos,accepting,accidental,ad rem,adapted,addled,advantageous
throw,abandon,addle,agitate,amaze,apply,assume,baffle,bake

This vim thesaurus plugin has plenty of links to thesaurus files like this.

#The Whitespace Lie

Remember what :h thesaurus said about thesaurus files?

white space is preferred

Well, this isn’t entirely true. After looking at some GitHub issues, it seems that whitespace is the only delimiter that vim allows for thesaurus files.

At this point, we have two options: try and twist our mthesaur.txt into something vim can read, or write our own thesaurus functionality. Luckily for us, someone has already written a function that allows us to use this format:

vim

function! s:thesaurus()
    let s:saved_ut = &ut
    if &ut > 200 | let &ut = 200 | endif
    augroup ThesaurusAuGroup
        autocmd CursorHold,CursorHoldI <buffer>
                    \ let &ut = s:saved_ut |
                    \ set iskeyword-=32 |
                    \ autocmd! ThesaurusAuGroup
    augroup END
    return ":set iskeyword+=32\<cr>vaWovea\<c-x>\<c-t>"
endfunction

nnoremap <expr> <leader>t <SID>thesaurus()

Throw this snippet into your ~/.vimrc (or init.vim, whatever suits your fancy) and we’ve got ourselves a handy-dandy thesaurus! Let’s break down that last line:

Now that we’ve gathered a thesaurus file and added the new function, all that’s left is to press \t in normal mode over the word you’d like to replace.

Meet the Author

John Allbritten

Nashville, TN

I love learning new technologies, and I have a passion for open source. As I learn things, my notes turn into articles to share.

Related Posts