识别相同的代码块

时间:2009-08-31 11:44:59

标签: vim full-text-search text-editor vi

假设我在文件中有以下代码的多个块(空格是无关紧要的):

sdgfsdg dfg
dfgdfgf ddfg
dfgdfgdfg  dfgfdg

如何查找/突出显示所有事件?

我最理想的做法是直观地选择代码块,然后按搜索查找所有匹配项。

4 个答案:

答案 0 :(得分:2)

也许你应该看看: Search for visually selected text

我是从here

取的

答案 1 :(得分:2)

试试这个。在运行时路径中的某处包含此脚本(请参阅:help runtimepath)。一个简单的选择是将它放在你的vimrc中。以视觉方式选择要搜索的内容,然后按,/(逗号键,然后按正斜杠键)。

" Search for other instances of the current visual range

" This works by:
" <ESC>                Cancel the visual range (it's location is remembered)
" /                    Start the search
" <C-R>=               Insert the result of an expression on
"                      the search line (see :help c_CTRL-R_= )
" GetVisualRange()<CR> Call the function created below
" <CR>                 Run the search
vmap ,/ <ESC>/<C-R>=GetVisualRange()<CR><CR>

" Create the function that extracts the contents of the visual range
function! GetVisualRange()
    " Get the start and end positions of the current range
    let StartPosition = getpos("'<")
    let EndPosition = getpos("'>")

    " Prefix the range with \V to disable "magic"
    " See :help \V
    let VisualRange = '\V'

    " If the start and end of the range are on the same line
    if StartPosition[1] == EndPosition[1]
        " Just extract the relevant part of the line
        let VisualRange .= getline(StartPosition[1])[StartPosition[2]-1:EndPosition[2]-1]
    else
        " Otherwise, get the end of the first line
        let VisualRange .= getline(StartPosition[1])[StartPosition[2]-1:]
        " Then the all of the intermediate lines
        for LineNum in range(StartPosition[1]+1, EndPosition[1]-1)
            let VisualRange .= '\n' . getline(LineNum)
        endfor
        " Then the start of the last line
        let VisualRange .= '\n' . getline(EndPosition[1])[:EndPosition[2]-1]
    endif
    " Replace legitimate backslashes with double backslashes to prevent
    " a literal \t being interpreted as a tab
    let VisualRange = substitute(VisualRange, '\\[nV]\@!', '\\\\', "g")

    " Return the result
    return VisualRange

endfunction

答案 2 :(得分:1)

正在搜索的文本存储在/寄存器中。你不能直接拉入或删除这个寄存器,但你可以使用`let'分配给它。

试试这个:

  • 使用可视模式突出显示要搜索的代码
  • 键入"ay,将突出显示的选项拉入注册a
  • 输入:let @/ = @a将注册a复制到搜索注册/

此时,所有与您的选择匹配的代码都会突出显示,您可以使用n / N浏览事件,就像常规搜索一样。

当然,您可以使用任何临时寄存器而不是a。并且为了方便起见,将这个命令序列映射起来应该不会太困难。

答案 3 :(得分:1)

快速而肮脏的部分解决方案:

:set hlsearch
*

hlsearch选项(默认情况下在某些vim配置中打开,但我总是将其关闭)使vim突出显示当前搜索的所有已找到实例。在正常模式下按*搜索光标下的单词。因此,这将突出显示光标下单词的所有实例。

相关问题