Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling hjkl keys from vim's command line

Tags:

vim

fold

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>
like image 904
nunos Avatar asked May 22 '15 16:05

nunos


People also ask

How to navigate Vim with HJKL keys?

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.

How do I use the keys in Vim?

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.

How to navigate in Vim with numbers?

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.

Where is the Esc key on a Vim keyboard?

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.


3 Answers

Try the normal command. For this case you will need normal! to avoid recursive execution of your function.

like image 197
mMontu Avatar answered Oct 23 '22 22:10

mMontu


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>
like image 21
Jason Down Avatar answered Oct 23 '22 22:10

Jason Down


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
like image 42
Peter Rincker Avatar answered Oct 23 '22 23:10

Peter Rincker