Jens
Jens

Reputation: 72717

vim: How to cycle through a list of options using the same key?

I want to cycle through a list of languages for spellchecking, e.g.

:setlocal spell spelllang=en_EN
:setlocal spell spelllang=en_US
:setlocal spell spelllang=de
:setlocal spell spelllang=fr
:setlocal nospell

with a single keypress.
One obvious way is to put each of these on a separate key, like F1 to F5. But this is hard on the precious few function keys I have. So I tried putting them on just one function key, which would remap itself to cycle through the list. But it turns out that the length of the mapping would increase with O(N^2). I believe there is a more elegant way of achieving this with vim functions, which I'm sure can keep state somewhere in a variable. Sadly, my vim programming fu is not developed enough to tackle this. (No, I don't want to use a menu in gvim).

Upvotes: 4

Views: 432

Answers (1)

kev
kev

Reputation: 161884

Try this:

nnoremap <F2> :call CycleLang()<CR>

fun! CycleLang()
    let langs = ['', 'en_gb', 'en_us', 'de', 'fr']

    let i = index(langs, &spl)
    let j = (i+1)%len(langs)
    let &spl = langs[j]

    if empty(&spl)
        set nospell
    else
        set spell
    endif
endfun

Upvotes: 6

Related Questions