简体   繁体   English

Vim Ack、Ag:在您正在编辑的文件目录中搜索

[英]Vim Ack, Ag: Search in directory of file that you are editing in

I want to be able to search files that only reside in the directory of the file that I opened inside vim.我希望能够搜索仅驻留在我在 vim 中打开的文件目录中的文件。

The documentary of Ack says: Ack的纪录片说:

: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?VimFandom 上,我发现可以使用echo expand('%:p:h')获取文件的当前目录,但是如何在 Ack 命令中对其进行评估?

I'd need something like this:我需要这样的东西:

:Ack searchpattern expand('%:p:h')

The expression register, "= , will let you evaluate an expression and put/paste the output. Using <cr> on the command-line will insert content from a register.表达式寄存器"=将让您评估表达式并放置/粘贴输出。在命令行上使用<cr>将插入寄存器中的内容。

:Ack pat <c-r>=expand('%:p:h')<cr>

For more help see:如需更多帮助,请参阅:

:h "=
:h i_CTRL-R

Using :grep instead of :Ack使用:grep而不是:Ack

You can set 'grepprg' to use the silver searcher or other grep-like tool, eg ripgrep.您可以设置'grepprg'以使用 Silver 搜索器或其他类似 grep 的工具,例如 ripgrep。

set grepprg=ag\ --vimgrep\ $*
set grepformat=%f:%l:%c:%m

:grep understands % and :h as parameters. :grep %:h理解为参数。 This means you can do:这意味着您可以:

:grep pat %:h

For more help see:如需更多帮助,请参阅:

:h 'grepprg'
:h :grep

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 :cd %:p:h改变目录到当前文件所在的位置
  • :Ag<CR> directly goes to the interactive search window if you have fzf-vim如果你有fzf-vim, :Ag<CR>直接进入交互式搜索窗口

By "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>

Use :exe[cute] :使用:exe[cute] :

:exe 'Ack searchpattern ' . expand('%:p:h')

. (dot) means string concatenation. (dot) 表示字符串连接。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM