Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

vim

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).

like image 554
Jens Avatar asked Nov 06 '25 01:11

Jens


1 Answers

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
like image 68
kev Avatar answered Nov 09 '25 08:11

kev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!