Question

I would like something similar too this in my .vimrc.

let dir=“/home/user/Downloads/”
set path=$dir
nnoremap gr :grep '\b<cword>\b' $dir/*<CR>

The code above is wrong of course, but maybe you can understand what I am trying to do. I would like to set path to the value of dir to /home/user/Downloads/, and replace the word dir in the third line with the value of dir. I tried and failed, can anyone tell help me out, any help appreciated!

Était-ce utile?

La solution

First of all, there are fancy quotes; you need to use plain (") ones. Other than that, the :let is okay.

let dir = "/home/user/Downloads/"

You could use :execute to evaluate the defined variable with :set, but it's easier to use :let, because it can change Vim options, too, with the special notation &{optionname}:

let &path = dir

For the mapping, if dir doesn't change during runtime, it's easiest to use :execute. Note how the quoted backslashes must be escaped (i.e. doubled):

execute "nnoremap gr :grep '\\b<cword>\\b' " . dir . "/*<CR>"

All that information is part of :help eval. Learn how the excellent and comprehensive help is structured; all the information is in there (you just need to know how to find it)!

Autres conseils

You must use this notation:

let variable_name = "value"

and use straight quotes.

To set path:

set path=/home/user/Downloads/

or to append a directory to path.

set path+=/home/user/Downloads/

Path is an Vim variable which does not seem very appropriate to use if you are going to only use it for this one remapping. It would be better to declare you own variable, as path can also have many directories within it which will not work with grep.

let g:search_path="/path/to/your/dir"

nnoremap gr :grep '\<<cword>\>' <C-R>=eval("g:search_path")<CR>

Ctrl+R lets us insert a register here, when then use that to call the expression register, which we use to evaluate g:search_path.

Check out :help expr-register for more on that!

This will evaluate your g:search_path variable on every execution of the mapping, allowing you to change the path and not have to remap gr each time.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top