Reputation: 1587
I want to be able to search files that only reside in the directory of the file that I opened inside vim.
The documentary of Ack says:
:Ack[!] [options] {pattern n} [{directory}] *:Ack*
Search recursively in {directory} (which defaults to the current
directory) for the {pattern}. Behaves just like the |:grep| command, but
will open the |Quickfix| window for you. If [!] is not given the first
occurrence is jumped to.
On VimFandom I found that I could get the current directory of the file with
echo expand('%:p:h')
but how could I get this to evaluate in the Ack command?
I'd need something like this:
:Ack searchpattern expand('%:p:h')
Upvotes: 0
Views: 2098
Reputation: 386
If directory has no further children (otherwise is recursive search):
nnoremap <leader>f <Esc>:cd %:p:h<CR><Esc>:Ag<CR>
Where,
:cd %:p:h
changes directory to the location of current file:Ag<CR>
directly goes to the interactive search window if you have fzf-vimBy "interactive search" I mean customizing your search pattern dynamically (try wildcard, test if adding more keywords, ...)
On the other hand, if you don't need the interactive search, you are sure what you look for, then:
nnoremap <leader>f <Esc>:cd %:p:h<CR><Esc>:Ag<Space>
Upvotes: 1
Reputation: 4673
I have a little mapping for cases like this: %%
inserts the directory of the current file.
cnoremap <expr> %% filename#command_dir('%%')
And the function definition:
function filename#command_dir(keymap) abort
if getcmdtype() isnot# ':'
return a:keymap
endif
let l:dir = expand('%:h')
return empty(l:dir) ? '.' : (dir.'/')
endfunction
Upvotes: 0
Reputation: 94483
Use :exe[cute]
:
:exe 'Ack searchpattern ' . expand('%:p:h')
.
(dot) means string concatenation.
Upvotes: 0
Reputation: 45117
The expression register, "=
, will let you evaluate an expression and put/paste the output. Using <c-r>
on the command-line will insert content from a register.
:Ack pat <c-r>=expand('%:p:h')<cr>
For more help see:
:h "=
:h i_CTRL-R
:grep
instead of :Ack
You can set 'grepprg'
to use the silver searcher or other grep-like tool, e.g. ripgrep.
set grepprg=ag\ --vimgrep\ $*
set grepformat=%f:%l:%c:%m
:grep
understands %
and :h
as parameters. This means you can do:
:grep pat %:h
For more help see:
:h 'grepprg'
:h :grep
Upvotes: 2