Quickly search for a specific window in vim based on filename - vim

Many times I end up opening a large number of files in vim using split and vsplit. In such a situation, is there some way by which I can search (by filename) for the window that has a specific file open?
I am looking for functionality similar to tmux find window where we can activate a window by searching for text in that window's scroll buffer. However, in case of of vim, I want to be able to set focus on a window by searching for the filename.

first of all, opening multiple files in split makes file editing easier. However if you open "a large number of files" in split..... I don't know what reason makes you do it. If you want to batch process files, you can considering sed/awk/...
Anyway, you can execute this cmd line in your vim, you give the filename, and this cmd will bring you to the window containing the buf.
:call win_gotoid(bufwinid('YourFileName'))

You can use the buffer command and append the start of your file name - you'll then be able to tab complete the full name. To make tab completion a little more useful (IMO), you can add these settings to your vimrc file:
" first tab completed to the longest common match, or full match,
" second tab completed to show list of all matches,
" third tab starts to cycle through matches
set wildmode=longest,list,full
If you have 3 buffers open - install.sh, readme.md, app.js -
:b in<TAB> will complete the command to :b install.sh - pressing enter will open the buffer containing the install.sh file. If your search term has multiple matches, keep hitting TAB to cycle through all the results.
For more info, checkout :help buffer

Related

Gvim: Move tab to new window

The opposite question seems to be asked a lot: how to move a window into a new tab in an existing window. What I'm hoping is that a tab that I have open in gvim can be moved out into its own window or into another existing window.
Is this possible?
Thanks!
Same Vim instance
If that tab shows just a single window, you just have to note its buffer number (e.g. via :ls or :echo bufnr(''), or by including it in the statusline), and then close the tab via :close (:set hidden helps with modified buffers), then going to the target tab / window, and re-opening the buffer there via :buf N or :sbuf N.
If you need to support multiple windows in a tab page, you'd have to write a custom command / mapping that first remembers the buffers, and then applies the above steps for all of them.
Different Vim instances
Edit: The above is for movement within a single Vim instance. If you want to move a buffer to another GVIM instance, you first have to :bdelete it in the current Vim, to avoid swap file messages. Launching in new instances is easy:
:execute 'bdelete | !start gvim' shellescape(expand('%:p'), 1)
This passes the (full absolute) path of the current file to a fresh GVIM.
To move a file to an existing GVIM (you need to know its v:servername), you need to use the remote client-server communication (:help remote.txt), e.g. by sending a similar :drop command via remote_send(), like this:
:execute 'bdelete | call remote_send("GVIM1", ":drop " . ' . string(fnameescape(expand('%:p'))) . '. "\<CR>")'
Here is how you can "move" the current buffer to a second GVim instance:
:!gvim --remote %
:bw
Note that Vim must be built with the +clientserver option.
No, it is not possible.
You cannot move a vim tab into a window, no matter new or existing. Because a vim tab page is a collection of windows. You cannot move a collection of windows into one single window.

How to edit the same file in multiple tabs in vim?

I often edit long files in vim that have blocks of code in multiple disparate places in the file that I need to be constantly going back and forth between. Obviously, one way of solving this is to split the window with :split and edit each portion in a different split window, and a :w in either window will save the whole file. This is well and good if you have a large enough screen but sometimes I have to use vim on a low-resolution laptop and I don't want to reduce my screen space further by splitting the window.
In this case, what I'd really like to do is edit the file in multiple tabs, and treat each separate tab exactly like a separate view split. I can sort of mimic this by using :tabopen <the same filename> once I have one copy of the file open, but this is sort of hacky — it doesn't work if I've already made changes to the file because vim thinks I'm just opening the file a second time.
Is there a good way to get the behavior I want with tabs in vim?
The :tab command takes a command as argument.
So you can do this:
:tab split
This will work even if the buffer is modified, and a save in either tab saves the file, updating the saved state in both.
You can use the :tab command:
:[count]tab {cmd}`
Execute {cmd} and when it opens a new window open a new tab page instead. [...] When [count] is omitted the tab page appears after the current one. When [count] is specified the new tab page comes after tab page [count]. Use :0tab cmd to get the new tab page as the first one.
Examples:
:tab split " opens the current buffer in new tab page
:tab help gt " opens tab page with help for "gt"

Can you use vi with multiple file names specified on command line?

Is it possible to specify multiple file names on the command line when starting vi?
Yep just use :n to go to the next file in the list, and :N to go to the previous.
You can open multiple files by using globbing E.g., vi *.html will open all the HTML files in your current directory. And, as Alex says in his answer, you can navigate back and forth through the files with :n and :N.
If you want to open multiple files at the same time, you can also use the split command.
Open the first file as usual, then, then use the command :split yourfile.ext
You should now see both files at the same time in a split-screen view. You can do this with more than 2 files (but I'm not sure what the limit is).
Now, you can navigate between the windows with ctrl-w and the arrow keys. So, if you're in the bottom pane, and you want your cursor in the upper pane, you'd first press ctrl-w, then press the up-arrow key.
Also, you can resize one of the panes by adding or subtracting rows/lines in that view. So if you're in the upper pane and you want it to be 5 lines larger, you'd press 5, then ctrl-w, then +. Same for reducing with the - key.
I'm sure that there are many other commands you can use, but these are the ones I use.
Good luck!
Also convenient:
vim -p file1 file2 file3
That will open up vim with tabs containing each file specified. You can jump between files with
gt
and
gT
If you do
:set mouse=a
you can also click on the tabs to open or drag them (although hardcore vim users would frown on this :) )

Vim searching through all existing buffers

When dealing with a single file, I'm used to:
/blah
do some work
n
do some work
n
do some work
Suppose now I want to search for some pattern over all buffers loaded in Vim, do some work on them, and move on. What commands do I use for this work flow?
Use the bufdo command.
:bufdo command
:bufdo command is roughly equivalent to iterating over each buffer and executing command. For example, let's say you want to do a find and replace throughout all buffers:
:bufdo! %s/FIND/REPLACE/g
Or let's say we want to delete all lines of text that match the regex "SQL" from all buffers:
:bufdo! g/SQL/del
Or maybe we want to set the file encoding to UTF-8 on all the buffers:
:bufdo! set fenc=utf-8
The above can be extrapolated for Windows (:windo), Tabs (:tabdo), and arguments (:argdo). See help on :bufdo for more information.
We can do this using vimgrep and searching across the argslist. But first let's populate our argslist with all our buffers:
:bufdo :args ## %
Now we can search in our argslist
:vimgrep /blah/ ##
Where % == the current filepath and ## == the arglist.
I recommend watching these vimcasts if you want to learn more: Populate the arglist, Search multiple files with vimgrep
I have the following mappings (inspired by Vimperator) that make switching previous/next buffer easier.
nmap <C-P> :bp<CR>
nmap <C-N> :bn<CR>
This works really well with 'n'. When you're done working with your file, just hit CTRL-n before hitting n again and you're searching in the next buffer. Redo until you're through all buffers.
Another way of working with many files is the argument list.
It contains any files passed as parameters when you started vim (e.g: vim someFile.txt someOtherFile.py). The file within [brackets] is the current file.
:args
[someFile.txt] someOtherFile.py
:n will bring you to the next file in the list and :N will bring you back. You can also add to the argslist with :argadd, or create a new args list with
:n some.py files.py you.py want.py to.py work.py with.py
or to open all *.py files recursively from some project.
:n ~/MyProjects/TimeMachine/**/*.py
The args list work well with macros too (see :help q), if you have similar changes to your files. Just record your macro on the first file, finish with :n to move to the next file, and stop recording.
qq/searchForSomethingAndDoStuffOrWhatever:nq
Then run your macro through all files (6#q), have a look to make sure everything went well, and finish with a :wall.
It kinda depends on what you want to do. If you just have one change that is exactly the same across many files (and those are the only ones you have loaded), I also like the :ba (:tabdo sp) command. It's very quick and you can see what's happening.
And if you have a bunch of buffers open, you can load up the files you want to work within, each in a window, and do a regexp on all of them.
CTRL-w v :b someFile
:sp anotherFile
...
:windo :%s/foo/bar/g
I really recommend FuzzyFinder, it makes your life a lot easier when opening files.
http://www.vim.org/scripts/script.php?script_id=1984
MMmMmmmm VIM IS NICE! SO SEXY! : )
Anytime you want to switch to another buffer try this.
:b + <any part of file in buffer> + tab
For an example. I have this in my buffer
77 "/var/www/html/TopMenuAlertAlert.vue" line 65
78 "/var/www/html/MainSidebar.vue" line 29
79 "/var/www/html/FullScreenSearch.vue" line 26
80 "/var/www/html/Menu.vue" line 93
81 "/var/www/html/layouts/RightSidebar.vue" line 195
As I want to change to another buffer, I probably remember some detail about the file like 'Alert'
So I just go
:b Alert + tab
if the file given is not the one I want, I just keep on pressing tab.
Vim will keep on giving the next file close to it.
Once you got it. Press Enter.
Here is your gospel:
https://github.com/jeetsukumaran/vim-buffersaurus
This lovely plugin shows you all the files that match your query in a separate window, from which you can choose. It support regex.
I don't believe it's possible to extend the 'n' functionanly across files or buffers. You could use
:grep blah *
And then do
:cn
To move to the next line with blah on it. That will switch between files but it's not quite as neat. It's more cumbersome to type the colon all the time, and it will only take you to the line, not the word.
What I usually do is either to open the files I want to searched in tabs and then use 'n' and 'gt' to jump to next tab when I reach the end of the file, or list the files on the command line to I can skip to the next file with ':wn' when I'm done editing it.
Hope it helps!
Another approach:
:call setqflist([]) " clear quickfix list
:silent bufdo grepadd! foo % " edit foo in command-line history window
:cw " view search results
Or mapped:
cmap bbb call setqflist([]) \| silent bufdo grepadd! %<C-F>$hha
I would open all the buffers in a new tab using the following two commands:
:tab sp
:bufdo sp
Then search through each file one by one and close its window when you are done (use :q or :close). Use CTRL+W_ to maximize each window as you are working in it. When you're finished and you close the last window, the tab page will close and you'll be dropped back wherever you were before you decided to do the search.

How do I close a single buffer (out of many) in Vim?

I open several files in Vim by, for example, running
vim a/*.php
which opens 23 files.
I then make my edit and run the following twice
:q
which closes all my buffers.
How can you close only one buffer in Vim?
A word of caution: “the w in bw does not stand for write but for wipeout!”
More from manuals:
:bd
Unload buffer [N] (default: current
buffer) and delete it from
the buffer list. If the buffer was changed, this fails,
unless when [!] is specified, in which case changes are
lost.
The file remains unaffected.
If you know what you’re doing, you can also use :bw
:bw
Like |:bdelete|, but really delete the
buffer.
If this isn't made obvious by the the previous answers:
:bd will close the current buffer. If you don't want to grab the buffer list.
Check your buffer id using
:buffers
you will see list of buffers there like
1 a.php
2 b.php
3 c.php
if you want to remove b.php from buffer
:2bw
if you want to remove/close all from buffers
:1,3bw
Rather than browse the ouput of the :ls command and delete (unload, wipe..) a buffer by specifying its number, I find that using file names is often more effective.
For instance, after I opened a couple of .txt file to refresh my memories of some fine point.. copy and paste a few lines of text to use as a template of sorts.. etc. I would type the following:
:bd txt <Tab>
Note that the matching string does not have to be at the start of the file name.
The above displays the list of file names that match 'txt' at the bottom of the screen and keeps the :bd command I initially typed untouched, ready to be completed.
Here's an example:
doc1.txt doc2.txt
:bd txt
I could backspace over the 'txt' bit and type in the file name I wish to delete, but where this becomes really convenient is that I don't have to: if I hit the Tab key a second time, Vim automatically completes my command with the first match:
:bd doc1.txt
If I want to get rid of this particular buffer I just need to hit Enter.
And if the buffer I want to delete happens to be the second (third.. etc.) match, I only need to keep hitting the Tab key to make my :bd command cycle through the list of matches.
Naturally, this method can also be used to switch to a given buffer via such commands as :b.. :sb.. etc.
This approach is particularly useful when the 'hidden' Vim option is set, because the buffer list can quickly become quite large, covering several screens, and making it difficult to spot the particular buffer I am looking for.
To make the most of this feature, it's probably best to read the following Vim help file and tweak the behavior of Tab command-line completion accordingly so that it best suits your workflow:
:help wildmode
The behavior I described above results from the following setting, which I chose for consistency's sake in order to emulate bash completion:
:set wildmode=list:longest,full
As opposed to using buffer numbers, the merit of this approach is that I usually remember at least part of a given file name letting me target the buffer directly rather than having to first look up its number via the :ls command.
Use:
:ls - to list buffers
:bd#n - to close buffer where #n is the buffer number (use ls to get it)
Examples:
to delete buffer 2:
:bd2
You can map next and previous to function keys too, making cycling through buffers a breeze
map <F2> :bprevious<CR>
map <F3> :bnext<CR>
from my vimrc
Close buffer without closing the window
If you want to close a buffer without destroying your window layout (current layout based on splits), you can use a Plugin like bbye. Based on this, you can just use
:Bdelete (instead of :bdelete)
:Bwipeout (instead of :bwipeout)
Or just create a mapping in your .vimrc for easier access like
:nnoremap <Leader>q :Bdelete<CR>
Advantage over vim's :bdelete and :bwipeout
From the plugin's documentation:
Close and remove the buffer.
Show another file in that window.
Show an empty file if you've got no other files open.
Do not leave useless [no file] buffers if you decide to edit another file in that window.
Work even if a file's open in multiple windows.
Work a-okay with various buffer explorers and tabbars.
:bdelete vs :bwipeout
From the plugin's documentation:
Vim has two commands for closing a buffer: :bdelete and :bwipeout. The former removes the file from the buffer list, clears its options, variables and mappings. However, it remains in the jumplist, so Ctrl-o takes you back and reopens the file. If that's not what you want, use :bwipeout or Bbye's equivalent :Bwipeout where you would've used :bdelete.
How about
vim -O a a
That way you can edit a single file on your left and navigate the whole dir on your right...
Just a thought, not the solution...
[EDIT: this was a stupid suggestion from a time I did not know Vim well enough. Please don't use tabs instead of buffers; tabs are Vim's "window layouts"]
Maybe switch to using tabs?
vim -p a/*.php opens the same files in tabs
gt and gT switch tabs back and forth
:q closes only the current tab
:qa closes everything and exits
:tabo closes everything but the current tab
Those using a buffer or tree navigation plugin, like Buffergator or NERDTree, will need to toggle these splits before destroying the current buffer - else you'll send your splits into wonkyville
I use:
"" Buffer Navigation
" Toggle left sidebar: NERDTree and BufferGator
fu! UiToggle()
let b = bufnr("%")
execute "NERDTreeToggle | BuffergatorToggle"
execute ( bufwinnr(b) . "wincmd w" )
execute ":set number!"
endf
map <silent> <Leader>w <esc>:call UiToggle()<cr>
Where "NERDTreeToggle" in that list is the same as typing :NERDTreeToggle. You can modify this function to integrate with your own configuration.

Resources