Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle function in vim

Tags:

function

vim

Basically what I want to do is

map ,e :call ToggleEssayMode()<CR>
function! ToggleEssayMode()
if toggle==true
  :map j gj
  :map k gk
  toggle=false
else
  :umap j
  :umap k
  toggle=true
enndfunction

I've looked around for a while, but all i could find people using were the reserved vim variables. Can I make my own variable? Is there a more correct way of doing this?

like image 988
Ponyisasquare Avatar asked Dec 14 '13 02:12

Ponyisasquare


2 Answers

Unless you use separate functions for enabling and disabling, you will need a flag variable, and in order to isolate this from the rest of your configuration, I would recommend writing a small plugin. For example, create a file essay.vim (the actual name is irrelevant, as long as it ends in .vim) in ~/.vim/plugin/ with the following content:

let s:enabled = 0

function! ToggleEssayMode()
    if s:enabled
        unmap j
        unmap k
        let s:enabled = 0
    else
        nnoremap j gj
        nnoremap k gk
        let s:enabled = 1
    endif
endfunction

The mapping to call ToggleEssayMode() can then be in the same file or in your .vimrc.

Some remarks about your code:

  • Use let in order to assign variables (cf. set for options).
  • Vim does not support true and false; use 1 and 0 instead.
  • Every if needs a closing endif.
  • umap should be unmap; the former does not exist.
  • nnoremap should be used in order to avoid recursive mappings.
  • : is unnecessary before commands in scripts.
like image 87
Nikita Kouevda Avatar answered Sep 17 '22 23:09

Nikita Kouevda


Nikita Kouevda's answer helped me piece it together, but I still needed to look a few things up. For posterity, this is the script again:

let s:enabled = 0

function! ToggleEssayMode()
    if s:enabled
        unmap j
        unmap k
        let s:enabled = 0
    else
        nnoremap j gj
        nnoremap k gk
        let s:enabled = 1
    endif
endfunction

The s: part of s:enabled indicates it's a variable. If you just do let enabled = 0 and later if enabled, it will error on the if.

The function needs to start with a capital letter, for some reason vim enforces that. When I was customizing the function, I ran into that requirement.

To later call your function, you need to use :call. For example, :call ToggleEssayMode().

I just placed this in my .vimrc, not a plugin folder.

Finally, a protip: use :so % to reload your .vimrc without restarting vim. It might give a bunch of errors from things that are already defined, but it seems to work anyway.

like image 26
Luc Avatar answered Sep 21 '22 23:09

Luc