Command T to open file in previously opened buffer - vim

I'm using Janus MacVim by Carlhuda, and I wonder if there's a way to tweak Command-T to open a file (buffer) only once, instead of into multiple splits of the same buffer.
Eg: Assumming your directory/project has two files: A.txt and B.txt.
1) Cmd T, then select A.txt.
2) Work on A.txt, then Cmd T, split B.txt with Ctrl V.
3) Work on B.txt, then need to switch back to A: Cmd T, A.txt. Currently Command T would either open A buffer to current split, or create a new split of A. What I want is that the previously opened A buffer would be active again (the cursor would jump back to A) instead of a new split A got created.
So essentially if a buffer has already been opened, resume to that split buffer. Is there a tweak or shortcuts for this?

You probably want :drop or :tab drop instead of the default :tabe for opening files in the Command-T search buffer. This is configurable in your .gvimrc file:
function! CommandTAcceptSelectionTab()
ruby $command_t.accept_selection :command => 'tab drop'
endfunction
This one bothered the heck out of me, too!

There is a 'switchbuf' option but that works only for :sbuffer and few more commands but not for :split, :new and others.
As far as I know it needs some vimscript woodoo, which I used some time ago but do not use anymore and just use :sb with completion.

Related

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.

vi, vim buffers overrun

I'm losing all previous buffers when by mistake I'm trying to switch behind the last buffer [n:].
If for example I open couple of files in editor
:ls
1 # "/etc/moduli" line 1
2 %a "/etc/motd" line 1
:n
E163: There is only one file to edit
:p
E163: There is only one file to edit
now i can navigate between tabs just using :b [number]
Please advice how to fix this behavior. How can I prevent buffers from closing in this case?
I think you're confusing something there. A buffer is something like an open file. When you switch to the next file in the argument list using :n you close the current buffer and open the next one, so the changes must either be saved or discarded at this point.
Additionally the default behaviour of vim is to display an error message if you try to go beyond the last file in your argument list, so losing anything is not very easy in vim.
Maybe describing your actions (pressed keys) could help here, if this does not answer your question.
[edit]
Ok, now I know what the problem is: There is a difference between a buffer and the list of files to edit that you supply when starting vim. If you start vim with
vim a.txt b.txt
there are 2 files to edit. This does not mean, there are multiple buffers. You can navigate using :n and :p (meaning n(ext) file and p(revious) file). If you have the global flag :hidden set, this means that every buffer you close will become a hidden buffer. The file is still being edited, but it is not shown in any window. This value is possibly set upon startup of vim in your system. Try adding :se nohidden to your .vimrc and try the following:
:help buffer-hidden
[/edit]
:bn
will display the next file in your buffer (in your case "/etc/moduli")
:bp
will display the previous file in your buffer (also "/etc/moduli" because it does a permutation)
One thing that you'll notice is that the file you're editing is marked with
%a
whereas
#
means it's the last file you displayed.
Hope it helps you.
:n and :p doesn't switch between buffers :)
try :bufnext and :bufprev
maybe you'll like:
nmap <LEADER>k :bnext<CR>:redraw<CR>
nmap <LEADER>j :bprevious<CR>:redraw<CR>
nmap <LEADER>d :bd<CR>
nnoremap <LEADER>b :buffers<CR>:buffer<space>
Press ,j for the previous buffer, ,k for the next buffer, ,d to close the current buffer and ,b to list your buffers and select one with number keys.

How to effectively work with multiple files in Vim

I've started using Vim to develop Perl scripts and am starting to find it very powerful.
One thing I like is to be able to open multiple files at once with:
vi main.pl maintenance.pl
and then hop between them with:
:n
:prev
and see which file are open with:
:args
And to add a file, I can say:
:n test.pl
which I expect would then be added to my list of files, but instead it wipes out my current file list and when I type :args I only have test.pl open.
So how can I add and remove files in my args list?
Why not use tabs (introduced in Vim 7)?
You can switch between tabs with :tabn and :tabp,
With :tabe <filepath> you can add a new tab; and with a regular :q or :wq you close a tab.
If you map :tabn and :tabp to your F7/F8 keys you can easily switch between files.
If there are not that many files or you don't have Vim 7 you can also split your screen in multiple files: :sp <filepath>. Then you can switch between splitscreens with Ctrl+W and then an arrow key in the direction you want to move (or instead of arrow keys, w for next and W for previous splitscreen)
Listing
To see a list of current buffers, I use:
:ls
Opening
To open a new file, I use
:e ../myFile.pl
with enhanced tab completion (put set wildmenu in your .vimrc).
Note: you can also use :find which will search a set of paths for you, but you need to customize those paths first.
Switching
To switch between all open files, I use
:b myfile
with enhanced tab completion (still set wildmenu).
Note: :b# chooses the last visited file, so you can use it to switch quickly between two files.
Using windows
Ctrl-W s and Ctrl-W v to split the current window horizontally and vertically. You can also use :split and :vertical split (:sp and :vs)
Ctrl-W w to switch between open windows, and Ctrl-W h (or j or k or l) to navigate through open windows.
Ctrl-W c to close the current window, and Ctrl-W o to close all windows except the current one.
Starting vim with a -o or -O flag opens each file in its own split.
With all these I don't need tabs in Vim, and my fingers find my buffers, not my eyes.
Note: if you want all files to go to the same instance of Vim, start Vim with the --remote-silent option.
:ls
for list of open buffers
:bp previous buffer
:bn next buffer
:bn (n a number) move to n'th buffer
:b <filename-part> with tab-key providing auto-completion (awesome !!)
In some versions of vim, bn and bp are actually bnext and bprevious respectively. Tab auto-complete is helpful in this case.
Or when you are in normal mode, use ^ to switch to the last file you were working on.
Plus, you can save sessions of vim
:mksession! ~/today.ses
The above command saves the current open file buffers and settings to ~/today.ses. You can load that session by using
vim -S ~/today.ses
No hassle remembering where you left off yesterday. ;)
To add to the args list:
:argadd
To delete from the args list:
:argdelete
In your example, you could use :argedit test.pl to add test.pl to the args list and edit the file in one step.
:help args gives much more detail and advanced usage
I use buffer commands - :bn (next buffer), :bp (previous buffer) :buffers (list open buffers) :b<n> (open buffer n) :bd (delete buffer). :e <filename> will just open into a new buffer.
I think you may be using the wrong command for looking at the list of files that you have open.
Try doing an :ls to see the list of files that you have open and you'll see:
1 %a "./checkin.pl" line 1
2 # "./grabakamailogs.pl" line 1
3 "./grabwmlogs.pl" line 0
etc.
You can then bounce through the files by referring to them by the numbers listed, e.g.
:3b
or you can split your screen by entering the number but using sb instead of just b.
As an aside % refers to the file currently visible and # refers to the alternate file.
You can easily toggle between these two files by pressing Ctrl Shift 6
Edit: like :ls you can use :reg to see the current contents of your registers including the 0-9 registers that contain what you've deleted. This is especially useful if you want to reuse some text that you've previously deleted.
Vim (but not the original Vi!) has tabs which I find (in many contexts) superior to buffers. You can say :tabe [filename] to open a file in a new tab. Cycling between tabs is done by clicking on the tab or by the key combinations [n]gt and gT. Graphical Vim even has graphical tabs.
Things like :e and :badd will only accept ONE argument, therefore the following will fail
:e foo.txt bar.txt
:e /foo/bar/*.txt
:badd /foo/bar/*
If you want to add multiple files from within vim, use arga[dd]
:arga foo.txt bar.txt
:arga /foo/bar/*.txt
:argadd /foo/bar/*
Many answers here! What I use without reinventing the wheel - the most famous plugins (that are not going to die any time soon and are used by many people) to be ultra fast and geeky.
ctrlpvim/ctrlp.vim - to find file by name fuzzy search by its location or just its name
jlanzarotta/bufexplorer - to browse opened buffers (when you do not remember how many files you opened and modified recently and you do not remember where they are, probably because you searched for them with Ag)
rking/ag.vim to search the files with respect to gitignore
scrooloose/nerdtree to see the directory structure, lookaround, add/delete/modify files
EDIT: Recently I have been using dyng/ctrlsf.vim to search with contextual view (like Sublime search) and I switched the engine from ag to ripgrep. The performance is outstanding.
EDIT2: Along with CtrlSF you can use mg979/vim-visual-multi, make changes to multiple files at once and then at the end save them in one go.
Some answers in this thread suggest using tabs and others suggest using buffer to accomplish the same thing. Tabs and Buffers are different. I strongly suggest you read this article "Vim Tab madness - Buffers vs Tabs".
Here's a nice summary I pulled from the article:
Summary:
A buffer is the in-memory text of a file.
A window is a viewport on a buffer.
A tab page is a collection of windows.
To change all buffers to tab view.
:tab sball
will open all the buffers to tab view. Then we can use any tab related commands
gt or :tabn " go to next tab
gT or :tabp or :tabN " go to previous tab
details at :help tab-page-commands.
We can instruct vim to open ,as tab view, multiple files by vim -p file1 file2.
alias vim='vim -p' will be useful.
The same thing can also be achieved by having following autocommand in ~/.vimrc
au VimEnter * if !&diff | tab all | tabfirst | endif
Anyway to answer the question:
To add to arg list: arga file,
To delete from arg list: argd pattern
More at :help arglist
When using multiple files in vim, I use these commands mostly (with ~350 files open):
:b <partial filename><tab> (jump to a buffer)
:bw (buffer wipe, remove a buffer)
:e <file path> (edit, open a new buffer>
pltags - enable jumping to subroutine/method definitions
You may want to use Vim global marks.
This way you can quickly bounce between files, and even to the marked location in the file. Also, the key commands are short:
'C takes me to the code I'm working with,
'T takes me to the unit test I'm working with.
When you change places, resetting the marks is quick too:
mC marks the new code spot,
mT marks the new test spot.
If using only vim built-in commands, the best one that I ever saw to switch among multiple buffers is this:
nnoremap <Leader>f :set nomore<Bar>:ls<Bar>:set more<CR>:b<Space>
It perfectly combines both :ls and :b commands -- listing all opened buffers and waiting for you to input the command to switch buffer.
Given above mapping in vimrc, once you type <Leader>f,
All opened buffers are displayed
You can:
Type 23 to go to buffer 23,
Type # to go to the alternative/MRU buffer,
Type partial name of file, then type <Tab>, or <C-i> to autocomplete,
Or just <CR> or <Esc> to stay on current buffer
A snapshot of output for the above key mapping is:
:set nomore|:ls|:set more
1 h "script.py" line 1
2 #h + "file1.txt" line 6 -- '#' for alternative buffer
3 %a "README.md" line 17 -- '%' for current buffer
4 "file3.txt" line 0 -- line 0 for hasn't switched to
5 + "/etc/passwd" line 42 -- '+' for modified
:b '<Cursor> here'
In the above snapshot:
Second column: %a for current, h for hidden, # for previous, empty for hasn't been switched to.
Third column: + for modified.
Also, I strongly suggest set hidden. See :help 'hidden'.
I use the same .vimrc file for gVim and the command line Vim. I tend to use tabs in gVim and buffers in the command line Vim, so I have my .vimrc set up to make working with both of them easier:
" Movement between tabs OR buffers
nnoremap L :call MyNext()<CR>
nnoremap H :call MyPrev()<CR>
" MyNext() and MyPrev(): Movement between tabs OR buffers
function! MyNext()
if exists( '*tabpagenr' ) && tabpagenr('$') != 1
" Tab support && tabs open
normal gt
else
" No tab support, or no tabs open
execute ":bnext"
endif
endfunction
function! MyPrev()
if exists( '*tabpagenr' ) && tabpagenr('$') != '1'
" Tab support && tabs open
normal gT
else
" No tab support, or no tabs open
execute ":bprev"
endif
endfunction
This clobbers the existing mappings for H and L, but it makes switching between files extremely fast and easy. Just hit H for next and L for previous; whether you're using tabs or buffers, you'll get the intended results.
If you are going to use multiple buffers, I think the most important thing is to
set hidden
so that it will let you switch buffers even if you have unsaved changes in the one you are leaving.
I use the following, this gives you lots of features that you'd expect to have in other editors such as Sublime Text / Textmate
Use buffers not 'tab pages'. Buffers are the same concept as tabs in almost all other editors.
If you want the same look of having tabs you can use the vim-airline plugin with the following setting in your .vimrc: let g:airline#extensions#tabline#enabled = 1. This automatically displays all the buffers as tab headers when you have no tab pages opened
Use Tim Pope's vim-unimpaired which gives [b and ]b for moving to previous/next buffers respectively (plus a whole host of other goodies)
Have set wildmenu in your .vimrc then when you type :b <file part> + Tab for a buffer you will get a list of possible buffers that you can use left/right arrows to scroll through
Use Tim Pope's vim-obsession plugin to store sessions that play nicely with airline (I had lots of pain with sessions and plugins)
Use Tim Pope's vim-vinegar plugin. This works with the native :Explore but makes it much easier to work with. You just type - to open the explorer, which is the same key as to go up a directory in the explorer. Makes navigating faster (however with fzf I rarely use this)
fzf (which can be installed as a vim plugin) is also a really powerful fuzzy finder that you can use for searching for files (and buffers too). fzf also plays very nicely with fd (a faster version of find)
Use Ripgrep with vim-ripgrep to search through your code base and then you can use :cdo on the results to do search and replace
My way to effectively work with multiple files is to use tmux.
It allows you to split windows vertically and horizontally, as in:
I have it working this way on both my mac and linux machines and I find it better than the native window pane switching mechanism that's provided (on Macs). I find the switching easier and only with tmux have I been able to get the 'new page at the same current directory' working on my mac (despite the fact that there seems to be options to open new panes in the same directory) which is a surprisingly critical piece. An instant new pane at the current location is amazingly useful. A method that does new panes with the same key combos for both OS's is critical for me and a bonus for all for future personal compatibility.
Aside from multiple tmux panes, I've also tried using multiple tabs, e.g. and multiple new windows, e.g. and ultimately I've found that multiple tmux panes to be the most useful for me. I am very 'visual' and like to keep my various contexts right in front of me, connected together as panes.
tmux also support horizontal and vertical panes which the older screen didn't (though mac's iterm2 seems to support it, but again, the current directory setting didn't work for me). tmux 1.8
In my and other many vim users, the best option is to,
Open the file using,
:e file_name.extension
And then just Ctrl + 6 to change to the last buffer. Or, you can always press
:ls to list the buffer and then change the buffer using b followed by the buffer number.
We make a vertical or horizontal split using
:vsp for vertical split
:sp for horizantal split
And then <C-W><C-H/K/L/j> to change the working split.
You can ofcourse edit any file in any number of splits.
I use the command line and git a lot, so I have this alias in my bashrc:
alias gvim="gvim --servername \$(git rev-parse --show-toplevel || echo 'default') --remote-tab"
This will open each new file in a new tab on an existing window and will create one window for each git repository.
So if you open two files from repo A, and 3 files from repo B, you will end up with two windows, one for repo A with two tabs and one for repo B with three tabs.
If the file you are opening is not contained in a git repo it will go to a default window.
To jump between tabs I use these mappings:
nmap <C-p> :tabprevious<CR>
nmap <C-n> :tabnext<CR>
To open multiple files at once you should combine this with one of the other solutions.
I use multiple buffers that are set hidden in my ~/.vimrc file.
The mini-buffer explorer script is nice too to get a nice compact listing of your buffers. Then :b1 or :b2... to go to the appropriate buffer or use the mini-buffer explorer and tab through the buffers.
have a try following maps for convenience editing multiple files
" split windows
nmap <leader>sh :leftabove vnew<CR>
nmap <leader>sl :rightbelow vnew<CR>
nmap <leader>sk :leftabove new<CR>
nmap <leader>sj :rightbelow new<CR>
" moving around
nmap <C-j> <C-w>j
nmap <C-k> <C-w>k
nmap <C-l> <C-w>l
nmap <C-h> <C-w>h
I made a very simple video showing the workflow that I use. Basically I use the Ctrl-P Vim plugin, and I mapped the buffer navigation to the Enter key.
In this way I can press Enter in normal mode, look at the list of open files (that shows up in a small new window at the bottom of the screen), select the file I want to edit and press Enter again. To quickly search through multiple open files, just type part of the file name, select the file and press Enter.
I don't have many files open in the video, but it becomes incredibly helpful when you start having a lot of them.
Since the plugin sorts the buffers using a MRU ordering, you can just press Enter twice and jump to the most recent file you were editing.
After the plugin is installed, the only configuration you need is:
nmap <CR> :CtrlPBuffer<CR>
Of course you can map it to a different key, but I find the mapping to enter to be very handy.
I would suggest using the plugin
NERDtree
Here is the github link with instructions.
Nerdtree
I use vim-plug as a plugin manager, but you can use Vundle as well.
vim-plug
Vundle
When I started using VIM I didn't realize that tabs were supposed to be used as different window layouts, and buffer serves the role for multiple file editing / switching between each other. Actually in the beginning tabs are not even there before v7.0 and I just opened one VIM inside a terminal tab (I was using gnome-terminal at the moment), and switch between tabs using alt+numbers, since I thought using commands like :buffers, :bn and :bp were too much for me. When VIM 7.0 was released I find it's easier to manager a lot of files and switched to it, but recently I just realized that buffers should always be the way to go, unless one thing: you need to configure it to make it works right.
So I tried vim-airline and enabled the visual on-top tab-like buffer bar, but graphic was having problem with my iTerm2, so I tried a couple of others and it seems that MBE works the best for me. I also set shift+h/l as shortcuts, since the original ones (moving to the head/tail of the current page) is not very useful to me.
map <S-h> :bprev<Return>
map <S-l> :bnext<Return>
It seems to be even easier than gt and gT, and :e is easier than :tabnew too. I find :bd is not as convenient as :q though (MBE is having some problem with it) but I can live with all files in buffer I think.
Most of the answers in this thread are using plain vim commands which is of course fine but I thought I would provide an extensive answer using a combination of plugins and functions that I find particularly useful (at least some of these tips came from Gary Bernhardt's file navigation tips):
To toggle between the last two file just press <leader> twice. I recommend assigning <leader> to the spacebar:
nnoremap <leader><leader> <c-^>
For quickly moving around a project the answer is a fuzzy matching solution such as CtrlP. I bind it to <leader>a for quick access.
In the case I want to see a visual representation of the currently open buffers I use the BufExplorer plugin. Simple but effective.
If I want to browse around the file system I would use the command line or an external utility (Quicklsilver, Afred etc.) but to look at the current project structure NERD Tree is a classic. Do not use this though in the place of 2 as your main file finding method. It will really slow you down. I use the binding <leader>ff.
These should be enough for finding and opening files. From there of course use horizontal and vertical splits. Concerning splits I find these functions particularly useful:
Open new splits in smaller areas when there is not enough room and expand them on navigation. Refer here for comments on what these do exactly:
set winwidth=84
set winheight=5
set winminheight=5
set winheight=999
nnoremap <C-w>v :111vs<CR>
nnoremap <C-w>s :rightbelow split<CR>
set splitright
Move from split to split easily:
nnoremap <C-J> <C-W><C-J>
nnoremap <C-K> <C-W><C-K>
nnoremap <C-L> <C-W><C-L>
nnoremap <C-H> <C-W><C-H>
if you're on osx and want to be able to click on your tabs, use MouseTerm and SIMBL (taken from here). Also, check out this related discussion.
You can be an absolute madman and alias vim to vim -p by adding in your .bashrc:
alias vim="vim -p"
This will result in opening multiple files from the shell in tabs, without having to invoke :tab ball from within vim afterwards.
To open 2 or more files with vim type: vim -p file1 file2
After that command to go threw that files you can use CTRL+Shift+↑ or ↓ , it will change your files in vim.
If u want to add one more file vim and work on it use: :tabnew file3
Also u can use which will not create a new tab and will open file on screen slicing your screen: :new file3
If u want to use a plugin that will help u work with directories
and files i suggest u NERDTree.
To download it u need to have vim-plug so to download other plugins also NERDTree to type this commands in your ~/.vimrc.
let data_dir = has('nvim') ? stdpath('data') . '/site' : '~/.vim'
if empty(glob(data_dir . '/autoload/plug.vim'))
silent execute '!curl -fLo '.data_dir.'/autoload/plug.vim --create-dirs
https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim'
autocmd VimEnter * PlugInstall --sync | source $MYVIMRC
endif
call plug#begin('~/.vim/plugged')
Plug 'scrooloose/nerdtree'
call plug#end()
Then save .vimrc via command :wq , get back to it and type: :PlugInstall
After that the plugins will be installed and u could use your NERDTree with other plugins.

Close file without quitting VIM application?

I use the :e and :w commands to edit and to write a file. I am not sure if there is "close" command to close the current file without leaving Vim?
I know that the :q command can be used to close a file, but if it is the last file, Vim is closed as well; Actually on Mac OS MacVim does quit. Only the Vim window is closed and I could use Control-N to open a blank Vim window again. I would like Vim to remain open with a blank screen.
This deletes the buffer (which translates to close the file)
:bd
As already mentioned, you're looking for :bd, however this doesn't completely remove the buffer, it's still accessible:
:e foo
:e bar
:buffers
1 #h "foo" line 1
2 %a "bar" line 1
Press ENTER or type command to continue
:bd 2
:buffers
1 %a "foo" line 1
Press ENTER or type command to continue
:b 2
2 bar
You may instead want :bw which completely removes it.
:bw 2
:b 2
E86: Buffer 2 does not exist
Not knowing about :bw bugged me for quite a while.
If you have multiple split windows in your Vim window then :bd closes the split window of the current file, so I like to use something a little more advanced:
map fc <Esc>:call CleanClose(1)
map fq <Esc>:call CleanClose(0)
function! CleanClose(tosave)
if (a:tosave == 1)
w!
endif
let todelbufNr = bufnr("%")
let newbufNr = bufnr("#")
if ((newbufNr != -1) && (newbufNr != todelbufNr) && buflisted(newbufNr))
exe "b".newbufNr
else
bnext
endif
if (bufnr("%") == todelbufNr)
new
endif
exe "bd".todelbufNr
endfunction
:[N]bd[elete][!] *:bd* *:bdel* *:bdelete* *E516*
:bd[elete][!] [N]
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. Any windows for this buffer are
closed. If buffer [N] is the current buffer, another buffer
will be displayed instead. This is the most recent entry in
the jump list that points into a loaded buffer.
Actually, the buffer isn't completely deleted, it is removed
from the buffer list |unlisted-buffer| and option values,
variables and mappings/abbreviations for the buffer are
cleared.
If you've saved the last file already, then :enew is your friend (:enew! if you don't want to save the last file). Note that the original file will still be in your buffer list (the one accessible via :ls).
If you modify a file and want to close it without quitting Vim and without saving, you should type :bd!.
:bd can be mapped. I map it to F4, Shift-F4 if I need to force-close because of some change I no longer want.
The bufkill.vim plugin adds BD etc., to delete the buffer without closing any splits (as bd) would alone.
Insert the following in your .vimrc file and, with pressing F4, it will close the current file.
:map <F4> :bd<CR>
Look at the Butane plugin to keep the window layout when closing a buffer.
For me close-buffers is pretty useful plugin:
:Bdelete this to close that you can remap.
I have the same issue so I made the plugin.
This plugin replace :q and other commands and then prevent the window closed.
if you still have issue, please try to use following plugin.
https://github.com/taka-vagyok/prevent-win-closed.vim

Resources