如何在Vim中限制搜索范围,只针对当前光标所在的函数/类/代码块,而不必查找行号?如果能够在可视化选择中搜索也可以,因为有方法可以选择当前代码块。
(类似于这个问题,但更加通用)
我将直接复制并粘贴来自Vim Tips Wiki的“在可视选择中使用/和?”(搜索)的全部内容。
在可视模式下,/和?会像其他光标移动命令一样更新可视选择(也就是说,在可视模式下搜索会扩展选择范围)。
为了在可视选择中实际搜索,您需要使用
\%V
原子或使用由可视选择定义的标记与\%>'<
和\%<'>
原子。最好在输入搜索之前通过Esc离开可视选择。您可能想考虑映射以自动退出可视选择并输入适当的原子。例如::vnoremap <M-/> <Esc>/\%V
使用此映射,您可以按下Alt-/来自动填写一个“范围”,就像使用Ex命令
:
一样。要使用这个功能,请移动到所关注的第一行,并按下V开始逐行选择。向下移动(按j选择一行或}选择一段落等)。当你选择好要搜索的区域后,按下Alt-/。可视选择将被删除,并开始搜索命令。您会看到:/\%V
输入您要查找的内容,然后按下Enter。例如,您可以输入“绿色”并查看:
当你按下 Enter 键时,每个“green”的出现都会被突出显示,但仅限于之前选定的区域。/\%Vgreen
这里有两个进一步的示例,它们不使用可视化选择。第一个命令仅在第10到20行中进行搜索。第二个命令仅在标记a和b之间进行搜索。/\%>9l\%<21lgreen /\%>'a\%<'bgreen
简而言之:
" tldr;
v i { <ESC> /\%Vsearch-term
" Search for search-term within the current code block (defined by curly braces {}).
" Begin in normal mode, then enter the following:
" enter visual mode
v
" look for stuff in-between the current...
i
" curly braces enclosure
{
" (now the enclosure should be highlighted)
" exit visual mode
<ESC>
" search the last visual mode selection for search-term
/\%Vsearch-term
" note: to search within other enclosures, you can substitute curly braces for:
" - parenthesis,
" - square brackets,
" - or other enclosure pair characters