How to append the output of a function in a normal mapping command

303 views Asked by At

I have this mapping in vim

map f :Ag --ignore node_modules

I would like to append the result of the 'getcwd()' at the end of the command.

Something like (not working, but gives the idea):

map f :Ag --ignore node_modules :call getcwd()

So the command in vim would look like

:Ag --ignore node_modules ~/project

More context

I am using The silver search through vim using ag.vim. I want to have a normal mode mapping that specify the current working directory in the ag command.

https://github.com/ggreer/the_silver_searcher

https://github.com/rking/ag.vim

Thank you. JF

3

There are 3 answers

3
Kent On BEST ANSWER

try:

nnoremap <expr> f ':Ag blahblah '. getcwd()

if you don't provide the directory, ag will take current directory, the same as getcwd() right?

0
Ingo Karkat On

Vim's evaluation rules are different than most programming languages. You need to use :execute in order to evaluate a variable; otherwise, it's taken literally; i.e. Vim uses the variable name itself as the argument.

nnoremap f :execute 'Ag blahblah ' . getcwd()<CR>

This is an alternative to @Kent's use of <expr>.

PS: You should use :noremap; it makes the mapping immune to remapping and recursion.

1
Peter Rincker On

Yet another way is to use the expression register via <c-r>= to execute the expression, getcwd()

nnoremap <leader>f :Ag blahblah <c-r>=getcwd()<cr><c-b><s-right><s-right>><space>''<left>

I added the parts after the <cr> to insert single quotes after blahblah and put the cursor in between them.

Note: Don't overshadow the f command. It is very handy. See :h f. Look into use leader. See :h mapleader

For more help see:

:h c_ctrl-r
:h "=
:h c_ctrl-b
:h c_<s-right>