Find/Grep in all VI buffers - search

With many buffers open, I need a simple way to search all buffers for a regex and navigate the search result (quick list?)
I know I can :bufdo command, and it is easy to search and replace with %s, but I can't find a way to do just a simple search and then navigate the results.
I found plugins for that (e.g., buffergrep), but I'll be surprised if this simple task is not natively supported with a vim trick.. is it?

:grep & co. will populate the QuickFix buffer, which allows for fast navigation among results.

from :help grepadd
:grepa[dd][!] [arguments]
Just like ":grep", but instead of making a new list of
errors the matches are appended to the current list.
Example:
:call setqflist([])
:bufdo grepadd! something %
The first command makes a new error list which is
empty. The second command executes "grepadd" for each
listed buffer. Note the use of ! to avoid that
":grepadd" jumps to the first error, which is not
allowed with |:bufdo|.
An example that uses the argument list and avoids
errors for files without matches:
:silent argdo try
\ | grepadd! something %
\ | catch /E480:/
\ | endtry"

"I found plugins for that (e.g., buffergrep), but I'll be surprised if this simple task is not natively supported with a vim trick.. is it?"
Not that I know of. And existence of multiple plugins trying to offer this functionality tends to confirm that. . .
What plugins have you tried and what have they been lacking?
http://www.vim.org/scripts/script.php?script_id=2545
http://www.vim.org/scripts/script.php?script_id=2255
Also, just to make sure, you are aware of vimgrep, right? Vimgrep is an internal command that loads files into buffers and does greps on the buffers, with results in quickfix window. I haven't confirmed, but I assume if a searched file is already open in a buffer that Vimgrep doesn't reload it, at least not if it has 'nomodified' flag set. If so, one way to use Vimgrep for quick-and-easy buffer grepping would be to just create a file list for Vimgrep using the output from the :buffers command.

Related

How do I search for and then jump to a word in another file in vim

In particular, I'm editing files in Verilog and would like to see other instances of a word under the cursor in other files. Ideally, it'd bring up a list like the auto-complete list. I can then select the line entry and vim would open the file (either in the same window or a new tab).
I've seen this feature in Emacs. I have to think it exists in Vim somewhere.
This would be really fun to write in vimscript, but I don't exactly have time at the moment. Hopefully this will get you going in the right direction:
There is a vim plugin called Fugitive
It allows you to do things like git grep, or git blame right from you vim console. https://github.com/tpope/vim-fugitive
Their git grep command, Ggrep, should get you a list of local files with whatever word you want to grep for. Possibly check out this Q/A for getting it to work nicely: Getting 'git grep' to work effectively in vim
Last thing I would do is write a little vimscript function and a keystroke alias that would call Ggrep with the word under the cursor.
(hopefully I'll have time to write a better answer later)
If you have a tags file available, you might be able to use :tselect identifier for that purpose.
Vimgrep is your friend.
:vimgrep /pattern/ <path>/**
This will add lines to the quickfix window. Each line is the text from the line in a file that matches the pattern. The ** is shorthand for recurse into subdirectories.

Vim: See all instances on page and choose one

I seem to recall a vim plugin that will allow you to, essentially, execute ":g/pattern/p" and then prompt you to select one. Does anyone know of this plugin? Or is it a built-in function?
Basically, I want to perform a search, see all instances on the current page (or even in open buffers), and then be able to select which one to go to.
Thanks!
EDIT:
I want it to actually take me to the line number when I make my selection, and I want it to be a fairly simple solution. I'm pretty sure I've seen a plugin for this, but I can't remember what it was. Any thoughts?
PS. Thank you to all who are answering. They're great answers.
You can use :vim[grep] or :gr[ep].
:vim foo % | cw
See :help quickfix.
If you want a plugin, you'll have to search vim.org.
This might get you close. Its not an interactive menu but it does tell you the line number for the match
:g/<regex>/#
The # tell global to print the line numbers. Take a look at :h :number (# is a synonym for :number)
You could populate the result into the quickfix window via the :vimgrep command
:vimgrep/regex/ %
% represents the current buffer's filename. Note: buffer must be a file and not a scratch buffer.
Then use quickfix commands like :cnext and :cprev to move through the list. Or open the list via :copen and press <cr> to jump to the match.
You can :vimgrep any number of files:
All *.c files e.g. :vimgrep/regex/ *.c.
Use ** to search down into deep directories e.g. :vimgrep/regex/ **/*.c.
You can also use vimgrep with the args list via :vimgrep/regex/ ##.
For more help see:
:h :vimgrep
:h quickfix
:h c_%
:h arglist
:g/regex/p
:g executes :p by default, so it can be omitted; the trailing slash can also be dropped:
:g/regex
Note that :g jumps to the last occurrence in the file, so you can then execute N/ (in normal mode) to jump to the Nth occurrence. Or, if there are many matches and you don't care to count which one you want, you can at least jump to its line, L, with LG or Lgg or :L.
If you don't use :set number but want line numbers in the output of :p, append nu[mber] or # as #FDinoff suggests:
:g/regex/nu
:g/regex/#
You can confirm one change after another in all open buffers with:
:bufdo %s;<pattern>;<replace>;c | update
The :bufdo goes through all buffers. The c is the flag to confirm all changes. The update writes the current buffer which allows going to the next.

VIM search multiple closed files

One thing that I like to do from time to time is do a quick search on the directory I am working on and find all the references to a specific string, specially when debugging code from some one else. Is it still not possible for VIM to do such search? Is there an alternative to do it directly with plain terminal?
ATM (since I'm still learning VIM) I do the search in TextMate and find the string that way.
You can use the vim command :vimgrep. This will search for a pattern in the specified files and puts the results in the quickfix window which you can then use to jump to a specific match. So for example to search for foo recursively in every .php file in your current directory you would do
:vimgrep "foo" **/*.php
Another option is the command :grep which actually calls the grep program (or whatever grepprg is set to). It also puts the results in the quickfix window for easy navigation. However this requires that you have grep on your system.
vim's an editor, not really a file searcher. It's trivially simple to call out to a shell and run 'grep', however. Assuming you're on a Unix-ish environment (TextMate - MacOs?) While in command mode, hit ctrl-z and you'll be at the shell prompt, then do
grep somestring *.c
and you'll get all matches for 'somestring' in any C source files.
Once done grepping, just do a fg (foreground) command and boom - back to VIM.
vimgrep will work, but if the source happens to be in Git then you can use tpope's excellent https://github.com/tpope/vim-fugitive plugin, which exposes :Ggrep which hangs off git grep for more flexibility.
If it's specific entities you're looking for (functions, variables, etc) the integration with ctags is probably of interest to you as well.
Sounds like you might like to have a look at vim tag search functionality combined with ctags. ctags is an utility that can be used to generate an index (a tags file) of various language objects for source code (full project tree, not just a directory). In vim a tag is sort of identifier that can be jumped to or searched for.
See vim documentation:
:help tagsrch
Or:
http://vimdoc.sourceforge.net/htmldoc/tagsrch.html#ctags

Recent file history in Vim?

I would like to access recent files that I had opened and then closed in GVim. I open and close GVim frequently. I would like to access recent files from previous sessions as well.
Does GVim store recent files somewhere as Word and many other desktop apps store? How to access them?
At least terminal vim stores the previous ten files into ~/.viminfo in the filemarks section. You can use '0, '1, '2, ... '9 to jump among them.
(Probably only useful for '0 to get back to the last file you were editing, unless your memory is stronger than mine.)
You can also use the :browse oldfiles command to get a menu with numbers.
The best way that I use is
:browse oldfiles
Easiest way on vim.
There is mru.vim, which adds the :MRU command.
Very late answer here ... expounding on #sarnolds answer - You can view the file history with the oldfiles command #see :h oldfiles or :h viminfo
:oldfiles
Furthermore, you can have fine-grained file management with views and sessions ... #see :h mkview and :h mksession for specifics ...
Use :bro ol then press the number that corresponds to the file you want to open.
There is an Swiss knife of file switching CtrlP plugin, which is also part of janus distributive. It has :CtrlPMRU command with smart lookup among recently used files.
Note:
CtrlP maintains its own list of most recent used files in g:ctrlp_cache_dir."mru/cache.txt". It is not reusing viminfo (set viminfo?) which contains a list of file marks. This is useful if you want to clear this list.
Adding my 2 cents here because fzf was was not mentioned in earlier answers, which is such a wonderful tool:
fzf.vim has a :History command that lets you search the most recent used files in a fuzzy and search while you type manner.
I customize the (default) behavior of this command by not letting fzf reorder the search results list to the best match: I want the order of all matching filenames to keep being the order in which these files were last used.
To accomplish this customization, I added the following in my .vimrc to override the default History command defined by the fzf.vim plugin:
command! -bang -nargs=* History
\ call fzf#vim#history({'options': '--no-sort'})
EDIT:
Currently I'm using a neovim only plugin telescope.nvim which is very similar to fzf.vim, it has the command :Telescope old_files. And it can use the fzf algorithm as a sorting algorithm in the backend (which is currently recommended over the default sorter).
It looks a bit nicer, but can be a bit slower depending on the context. It is not as mature as fzf, but to me easier to customize, it is all lua script.
If you are a neovim only user, definitely worth checking out imho.
MRU has lot of features as explained here: http://www.thegeekstuff.com/2009/08/vim-editor-how-to-setup-most-recently-used-documents-features-using-mru-plugin/
The CtrlP plugin lets you search through your recently used files as well as files in the current directory with this command:
nnoremap <c-p> :CtrlPMixed<cr>
This saves you the hassle of having to deal with built in Vim commands and the MRU plugin, neither of which let you do fuzzy file searching, which is critical when working on larger projects.
You might be able to access the list from the command line with:
grep '^>' ~/.viminfo|cut -c3-|sed 's,~,'"$HOME"','
Explanation:
grep '^>' ~/.viminfo #find the list of recent files
cut -c3- #remove the first 2 characters
sed 's,~,'"$HOME"',' #replace ~ with absolute path
You could have a bash alias if you use this regularly
alias vim_mru="grep '^>' ~/.viminfo|cut -c3-|sed 's,~,'\"$HOME\"','"
As seen in the comments here (http://stackoverflow.com/questions/571955/undo-close-tab-in-vim), your file is probably still open in a buffer:
:ls " get the buffer number
:tabnew +Nbuf " where N is the buffer number
For example you can reopen the third buffer in a new tab (use :e instead if you don't use tabs):
:tabnew +3buf
:ls to list recent files with buffer number on left-hand column.
Then do :b{buffer-number} to jump there.
Example:
:ls shows list of files. I want to jump to third-last file I visited.
:b3 will take me there.
For faster searching, map :ls to something, e.g. <Leader>. in your .vimrc file.
One more plugin that let's you choose file from the list of last modified ones is staritfy. It replaces your start screen with a list of most recently modified files. You can always open this page later using :Startify command.
Also you can go back with ctrl+O.

Hide all (not)matching lines in Vim

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. How do I make it show only lines containing ERROR and how to show only lines without ERROR?
Is there a solution without deleting all matching lines and then just undoing it?
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
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.
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
The best way to do this is->
:vimgrep /something/g % | copen
This will open the list of matches for your keyword and also will show only the matched lines in quickfix window.
Replace % with path to file if not considering the current file.
:vimgrep /something/g % | copen works awesome. Also :g/<pattern>/d can be used to delete lines with the pattern
in case you happen to use fzf you could use:
:Lines in all open files
:BLines only in open buffer
:Rg [pattern] using ripgrep
You probably mean command in less vi vim
& /pattern/
which shows lines containing /pattern/ (like grep).
Some hackish dirty way to do this:
:w (save)
ggdG (deletes everything)
:.!grep something % (replace current line with grep output)

Resources