Hide all (not)matching lines in Vim

后端 未结 8 647
盖世英雄少女心
盖世英雄少女心 2021-01-30 01:35

Is it possible to show/hide all matching lines in vi or Vim? Not highlight but just show only those lines.

For example I have a text with word the word ERROR

相关标签:
8条回答
  • 2021-01-30 01:48

    You probably mean command in less vi vim & /pattern/ which shows lines containing /pattern/ (like grep).

    0 讨论(0)
  • 2021-01-30 01:51

    You can use

    :g/ERROR/
    

    to print all the lines with ERROR

    Also there is a Vim plugin which I saw many times but didn't use: foldsearch : fold away lines that don't match a given pattern

    0 讨论(0)
  • 2021-01-30 01:55

    Another approach depending on your use case would be using vimgrep and its results in quickfix. You can do the following:

    :vimgrep pattern % will search the current file and take you to the first search result. More importantly it also puts the results in the "quickfix list".

    :copen will then open the quickfix list in a separate quickfix-window. So you will have a separate window with all lines from your last vimgrep. Inside the quickfix-window you can then hit Enter or double-click on a line to jump to the corresponding line in your original file.

    :colder will let you go back to older quickfix lists (older vimgrep results). And :cnewer goes forward to newer search results.

    Note that the quickfix list is also updated when running :make (which is why its called quickfix for fixing errors). Because of this there also is an alterative to the quickfix list called the "location list". To use it instead you use :lvimgrep, then use l-prefixed commands rather than c-prefixed commands - :lopen, :lolder, :lnewer.

    There is, of course, a lot more you can do. See :help quickfix for more info.

    PS, You said you didn't want an approach that deletes lines and then undoing them. But since you marked g/ERRORas the answer I thought I would point out a quick and dirty way is to do g!/ERROR/d. You can then easily undo it using u. Also FYI, you can do :set hlsearch to highlight patterns matched with :g commands.

    0 讨论(0)
  • 2021-01-30 01:55

    :vimgrep /something/g % | copen works awesome. Also :g/<pattern>/d can be used to delete lines with the pattern

    0 讨论(0)
  • 2021-01-30 02:00

    Do you know about the :global command? Does this do what you want?

    :g/ERROR
    

    and for the opposite:

    :g!/Error
    

    or equivalently:

    :v/Error
    
    0 讨论(0)
  • 2021-01-30 02:04

    in case you happen to use fzf you could use:

    • :Lines in all open files
    • :BLines only in open buffer
    • :Rg [pattern] using ripgrep
    0 讨论(0)
提交回复
热议问题