Enabling Dictionary Completion Everywhere

How to make <C-X><C-K> work with 'dictionary' and 'spell' unset

Vim’s insert mode completion has a very nice feature where you can start typing a natural language word and then press Ctrl-XCtrl-K to complete it.

By default, it pulls the words used for the completions from the file specified with your 'dictionary' option, but this requires you to have such a file, which is not always1 the case for the computers I do my Vimmin’ on.

But there is a backup! If 'dictionary' is empty, and you have spell checking switched on, then Vim will use the active word list(s) from its spell checking feature for completion.

But sometimes I have 'spell' switched off!

So I added this little snippet to my vimrc so I can ABC (Always Be Completing):

inoremap <expr> <C-X><C-K> !empty(&dictionary) <bar><bar> &spell ? '<C-X><C-K>' : '<C-O>:call <SID>dictionary_complete_nospell()<CR><C-X><C-K>'

function! s:dictionary_complete_nospell() abort
  set spell
  augroup dictionary_complete_nospell
    autocmd!
    autocmd CompleteDone <buffer> ++once set nospell
  augroup END
endfunction

This replaces the default Ctrl-XCtrl-K with a mapping. When either 'dictionary' or 'spell' is set, the mapping just calls the built-in command, but if neither of them are, it first switches on 'spell' temporarily, setting up an autocommand to switch it off again when the completion is accepted or aborted.2

See :help :map-expression and :help ternary for more details on how the mapping works.