Smart (`infercase`) Dictionary Completions in Vim While Preserving Your Preferred `ignorecase` Settings

Dictionary completions in Vim can use a ‘infer case’ mode, where, e.g., “Probab” will correctly autocomplete to, e.g., “Probability”, even though the entry in the dictionary might be in a different case. The problem is that this mode only works if ignorecase is on. And sometimes, we want one (infercase) but not the other (ignorecase).

The following function, if added to your “\~/.vimrc”, sets it up so that ignorecase is forced on when dictionary completions are invoked via the `` keys, and then restored to its original state when exiting.

function! s:_setup_cidictcompletion()
    let g:_old_ignorecase_state=&ignorecase
    inoremap <C-X><C-K> <ESC>:let g:_old_ignorecase_state=&ignorecase<CR>:set ignorecase<CR>:set infercase<CR>a<C-X><C-K>
    " inoremap <expr> <CR> pumvisible() ? "\<C-y><ESC>:set noignorecase<CR>a" : "\<C-g>u\<CR>"
    " inoremap <expr> <C-J> pumvisible() ? "\<C-y><ESC>:set noignorecase<CR>a" : "\<C-g>u\<C-J>"
    let restore=' pumvisible() ? "\<C-y><ESC>:let &ignorecase=g:_old_ignorecase_state<CR>'
    for key in ["<CR>", "<C-J>", "<C-Y>"]
        execute "inoremap <expr> " . key . restore . 'a" : "\<C-g>u\<CR>"'
    for key in ["<ESC>", "<C-C>"]
        execute "inoremap <expr> " . key . restore . '" : "\' . key . '"'
call <SID>_setup_cidictcompletion()