0

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

Jean-Francois
  • 1,332
  • 3
  • 17
  • 24

3 Answers3

3

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.

Ingo Karkat
  • 167,457
  • 16
  • 250
  • 324
2

try:

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

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

Kent
  • 189,393
  • 32
  • 233
  • 301
  • Hi, command does not work. I keep getting 'E78: Unknown mark'. For your comment about the directory, the documentations says "{directory} (which defaults to the current directory)". Since I change often of cwd using NERDTree, I would like to see the directory I am currently in to minimize the human errors facto while I work. :) Thank you for your help. – Jean-Francois Dec 04 '14 at 15:29
  • Are you sure you added expr in your mapping? – Kent Dec 04 '14 at 16:06
  • I gave it another try ot morning and it worked! I must havedone a mistake before. Thanks. – Jean-Francois Dec 05 '14 at 13:18
0

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>
Peter Rincker
  • 43,539
  • 9
  • 74
  • 101
  • Thank you for your answer. You are using an interesting approach with the expression register. I did not know about that. Thanks for sharing. Also, I reassure you, my mappings looks like that: nnoremap f ':Ag --ignore node_modules --ignore assets -S "" "' . getcwd() . '"' and nnoremap fw ':Ag --ignore node_modules --ignore assets -S "" "' . getcwd() . '"' I did not display the full mapping in the original post for simplicity. I am basically doing the same thing as you. :) – Jean-Francois Dec 09 '14 at 13:58