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?
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:
let in order to assign variables (cf. set for options).true and false; use 1 and 0 instead.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.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With