Whenever I am browsing folded code in vim and press the l
key I want it to open that fold recursively. For that I did the following: nmap l lzO
. Which worked ok, apart from the fact of getting a E490: No fold found
whenever I would press l
not in a fold. I used that an excuse to learn about Vimscript and write a function for that and avoid the error.
Now, I am missing the part of how can I call a vim command like l
or lzO
from inside a function?
function! OpenFoldOrNot()
if foldclosed(line(".")) == -1
echo "just l"
l # TODO
else
echo "open fold"
lzO # TODO
endif
endfunction
nmap l :call OpenFoldOrNot()<CR>
Learn Vim Navigation with hjkl Keys and Vim Numbers. Home row - Keep your hands on the home row to translate code from your brain to a text file faster. Vim hjkl keys - Switch from mouse and arrow key navigation to the hjkl keys.
One important thing to note when using Vim, is that the function of a key depends on the “mode” the editor is in. For example, pressing the alphabet “j” will move the cursor down one line in the “command mode”. You’ll have to switch to the “insert mode” to make the keys input the character they represent.
Learn Vim Navigation with hjkl Keys and Vim Numbers. Home row - Keep your hands on the home row to translate code from your brain to a text file faster. Vim hjkl keys - Switch from mouse and arrow key navigation to the hjkl keys. Vim numbers - Learn how to zoom straight to a line in a Vim file and navigate faster with numbers.
Since vim is derived from vi, it uses the same hjkl keys. And while we're at it, notice where the ESC key is positioned. ESC is where TAB is on modern keyboards.
Try the normal
command. For this case you will need normal!
to avoid recursive execution of your function.
You could try the following, using the normal command (my vimscript is very rusty):
function! OpenFoldOrNot()
if foldclosed(line(".")) == -1
normal! l
else
normal! lzO
endif
endfunction
nmap l :call OpenFoldOrNot()<CR>
Alternatively you can use a map-expression to make this kind of job easier.
nnoremap <expr> l foldclosed(line(".")) == -1 ? 'l' : 'lzO'
In a map expression the right hand side, {rhs}
, of the mapping is a VimScript expression. This is evaluated to obtain what to execute. In your case it is used to determine if the mapping calls l
or lz0
.
For more help see:
:h :map-expression
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