Toggle function in vim

Viewed 3422

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?

3 Answers

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.

I just provided a shorter one:

let s:_toggle=0
function! s:toggleFunc() abort
    let s:_toggle = s:_toggle? 0: 1
    return s:_toggle
endfunction

Screenshot (Clickable):

Related