如何在 VI 编辑器中标记/突出显示重复行? [英] How can I mark/highlight duplicate lines in VI editor?

查看:12
本文介绍了如何在 VI 编辑器中标记/突出显示重复行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您将如何标记缓冲区中与其他行完全相同的所有行?通过标记它们,我的意思是突出它们或添加字符或其他东西.我想保留缓冲区中行的顺序.

How would you go about marking all of the lines in a buffer that are exact duplicates of other lines? By marking them, I mean highlighting them or adding a character or something. I want to retain the order of the lines in the buffer.

之前:

foo
bar
foo
baz

之后:

foo*
bar
foo*
baz

推荐答案

作为前单行:

:syn clear Repeat | g/^(.*)
ze\%(.*
)*1$/exe 'syn match Repeat "^' . escape(getline('.'), '".^$*[]') . '$"' | nohlsearch

这使用 Repeat 组来突出显示重复的行.

This uses the Repeat group to highlight the repeated lines.

分解:

  • syn clear Repeat :: 删除任何以前找到的重复项
  • g/^(.*) ze\%(.* )*1$/ :: 用于文件后面重复的任何行
    • 正则表达式
      • ^(.*) :: 整行
      • ze :: end of match - 验证模式的其余部分,但不使用匹配的文本(正向前瞻)
      • \%(.* )* :: 任意数量的完整行
      • 1$ ::匹配的整行的整行重复
      • syn clear Repeat :: remove any previously found repeats
      • g/^(.*) ze\%(.* )*1$/ :: for any line that is repeated later in the file
        • the regex
          • ^(.*) :: a full line
          • ze :: end of match - verify the rest of the pattern, but don't consume the matched text (positive lookahead)
          • \%(.* )* :: any number of full lines
          • 1$ :: a full line repeat of the matched full line
          • exe :: 将给定的字符串作为 ex 命令执行
          • getline('.') :: g//
          • 匹配的当前行内容
          • escape(..., '".^$*[]') :: 用反斜杠转义给定的字符以生成合法的正则表达式
          • syn match Repeat "^...$" :: 将给定字符串添加到 Repeat 语法组
          • exe :: execute the given string as an ex command
          • getline('.') :: the contents of the current line matched by g//
          • escape(..., '".^$*[]') :: escape the given characters with backslashes to make a legit regex
          • syn match Repeat "^...$" :: add the given string to the Repeat syntax group

          Justin 的非正则表达式方法可能更快:

          Justin's non-regex method is probably faster:

          function! HighlightRepeats() range
            let lineCounts = {}
            let lineNum = a:firstline
            while lineNum <= a:lastline
              let lineText = getline(lineNum)
              if lineText != ""
                let lineCounts[lineText] = (has_key(lineCounts, lineText) ? lineCounts[lineText] : 0) + 1
              endif
              let lineNum = lineNum + 1
            endwhile
            exe 'syn clear Repeat'
            for lineText in keys(lineCounts)
              if lineCounts[lineText] >= 2
                exe 'syn match Repeat "^' . escape(lineText, '".^$*[]') . '$"'
              endif
            endfor
          endfunction
          
          command! -range=% HighlightRepeats <line1>,<line2>call HighlightRepeats()
          

          这篇关于如何在 VI 编辑器中标记/突出显示重复行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆