Managing split and multiple files with Vim - vim

I'm brand new in the Vim game, and I'm looking for the best tips and shorcuts to manage multiple files projects.
I saw people on the internet having a window with all the directory they have in there projects, and I'm really interested to find how they do that.
So feel free to put all your tips here.
Thanks

One tip I can give you on making changes in a bunch of files is (based on vimcasts):
Let' say you have many markdown files and want to substitute the word ISSUE for SOLVED...
vim *.md
At this point you have all markdown files as arguments...
:args
So you have the argdo command, but in order to use it you have to set the hidden option (it allows you to go to the next file without saving the current one)
:set hidden
Now
:argdo %s/ISSUE/SOLVED/ge
The g flag makes the substitution in all occurrences at each line
the e flag makes vim ignore files where the pattern does not appear
Another good thing is avoiding messeges during substitution of each file, we can add silent at the beggining
:silent argdo %s/ISSUE/SOLVED/ge
If you realize you made a mistake
:silent argdo edit!
Because the command edit! with exclamation makes the file get back to its original state
If you are sure you made it all correct
:argdo update
There are tons of good tips about dealing with many files on vim, you can visit the vimcasts original tip here.
More about the arglist here.
Another great tool to combine with vim is FZF, you can see a good video about it here.
When you have a couple of files opened you can also use the buffer list easily with this mapping (on your ~/.vimrc or ~/.cofig/nvim/init.vim)
" list buffers and jump to a chosen one
nnoremap <Leader>b :buffers<CR>:b<Space>
A shortcut you can use to get back to the last edited file is Ctrl-6.
In order to open you vim on the last edited file add this alias to your ~/.bashrc or ~/.zshrc
alias lvim='vim -c "normal '\''0"'
Open a new terminal and run
lvim

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.

How to autocomplete file paths in Vim, just like in zsh?

In Zsh, I can use filename completion with slashes to target a file deep in my source tree. For instance if I type:
vim s/w/t/u/f >TAB<
zsh replaces the pattern with:
vim src/wp-contents/themes/us/functions.php
What I'd like is to be able to target files the same way at the Vim command line, so that typing
:vi s/w/t/u/f >TAB<
will autocomplete to:
:vi src/wp-contents/themes/us/functions.php
I'm trying to parse the Vim docs for wildmode, but I don't see what settings would give me this. It's doing autocompletion for individual filenames, but not file paths. Does Vim support this natively? Or how can I customize the autocomplete algorithm for files?
Thanks for any advice!
-mykle-
I couldn't find a plugin to do this, so I wrote one. It's called vim-zsh-path-completion. It does what you're looking for, although via <C-s> rather than <Tab>. You can use it with <Tab> for even more control over what matches, though.
It's got bugs, but for basic paths without spaces/special characters, it should work. I think it's useful enough in its current state to be helpful. I hope to iron out the bugs and clean up the code, but I figured I'd start soliciting feedback now.
Thanks for the idea!
Original (wrong) answer, but with some useful information about Vim's wildmode.
Put the following in your .vimrc:
set wildmenu
set wildmode=list:longest
That will complete to the longest unique match on <Tab>, including appending a / and descending into directories where appropriate. If there are multiple matches, it will show a list of matches for what you've entered so far. Then you can type more characters and <Tab> again to complete.
I prefer the following setting, which completes to the first unique match on <Tab>, and then pops up a menu if you hit <Tab> again, which you can navigate with the arrow keys and hit enter to select from:
set wildmode=list:longest,list:full
Check out :help wildmenu and :help wildmode. You might also want to set wildignore to a list of patterns to ignore when completing. I have mine as:
set wildignore=.git,*.swp,*/tmp/*
Vim doesn't have such a feature by default. The closest buil-in feature is the wildmenu/wildmode combo but it's still very different.
A quick look at the script section of vim.org didn't return anything but I didn't look too far: you should dig further. Maybe it's there, somewhere.
Did you try Command-T, LustyExplorer, FuzzyFinder, CtrlP or one of the many similar plugins?
I use CtrlP and fuzzy matching can be done on filepath or filename. When done on filepath, I can use the keysequence below to open src/wp-contents/themes/us/functions.php (assuming functions.php is the only file under us that starts with a f):
,f " my custom mapping for the :CtrlP command
swtuf<CR>
edit
In thinking about a possible solution I'm afraid I was a little myopic. I was focused on your exact requirements but Vim has cool tricks when it comes to opening files!
The :e[dit] command accepts two types of wildcards: * is like the * you would use in your shell and ** means "any subdirectory".
So it's entirely possible to do:
:e s*/w*/t*/u*/f*<Tab>
or something like:
:e **/us/f<Tab>
or even:
:e **/fun<Tab>
Combined with the wildmode settings in Jim's answer, I think you have got a pretty powerful file navigation tool, here.

closing pending vim windows to open

I know that I can close all opened buffers in vim by :qall.
I want to close event to pending opening buffers.
I have problem while reviewing my changes in P4 sandbox. When I have changes in multiple files and I try to review my code with "P4 diff" and set my P4DIFF to vimdiff.
It opens one by one vimdiff of all changed files. Now if I have 10 opened files and after reviewing 2 files I want to close diff for remaining 8 files. How can I do that?
Thanks,
This sounds like a job for hastily learnt Vimscript!
Particularly, the :bufdo, if, and match statements!
Try out the following:
:bufdo if match(expand("%"), ".vim") >= 0 | bw | endif
bw is for buffer wipe in Ex-mode (the : operator)
expand("%") returns the name of the current buffer
match(string, pattern) finds the index of a pattern in string
|'s separate lines if you're in Ex-mode
This matches buffers that contain .vim in their filenames and closes those buffers.
I'm guessing if these are temp buffers that are fed into vimdiff, they wouldn't have file names to begin with. Maybe you can use bufnr(".") to output the number of the current buffer. Then you can close all buffers past or before a certain number.
You can probably do even more buffer manipulation with certain plugins. I've been considering adopting one of the following three plugins that help manage plugins:
LustyExplorer
FuzzyFinder
minibufexpl
I can't speak for any merits, but I've heard them mentioned several times over the internet and on IRC.
I'm assuming you open vim with a number of arguments (known as... the argument list).
You should probably reset it:
:args %
You can also selectively manage the list (:argdelete). More information: :he arglist
DISCLAIMER: I've not used perforce, so I've had to make an assumption: that when multiple files have uncommitted changes, it will behave like a lot of VCS's and run the configured diff command (in this case, vimdiff) on each changed file in turn (I'm thinking this is what you meant by "opens one by one vimdiff of all changed files").
If this is the case, then vim won't have any references to any of the remaining files when viewing the changes for any particular file, so no amount of trickery within a single vim session is going to help you.
If you are willing to change your workflow at all, you may be able to do something with this vim script I found: http://www.vim.org/scripts/script.php?script_id=240
It claims to be modelled after the P4 GUI, so hopefully could fit neatly into your usage. From the overview of the script, it sounds like it should be able to show you a summary of which files have changed and allow you to view the changes.
If none of this is suitable for you, you could always try the old favourite Ctrl-C immediately after closing a vimdiff session for a file.
This is a bad hack but putting it here as no other answers worked for me.
Add "qall" without qoutes on top of your .vimrc .
:e ~/.vimrc
:source ~/.vimrc
:q
All files will close automatically after opening.
Then open vimrc in emacs or sed and remove qall.

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.

Opening files in Vim using Fuzzy Search

I'm looking for a way to make Vim have the ability to open a file by fuzzy-searching its name.
Basically, I want to be able to define a project once, and then have a shortcut which will give me a place to type a file name, and will match if any letters match up.
This kind of functionality exists in most editors I've seen, but for the life of me I can't understand how to get Vim to do this.
Note that I'm looking for something that won't require me to have any idea where in my directory tree a file is. I just want to be able to open it by the filename, regardless of what directory it's in.
Thanks
There are two great vim plugins for this.
ctrlp:
Written in pure VimL
Works pretty much everywhere
Supports custom finders for improved performance
Most popular fuzzy search plugin for Vim
Command-T:
Written in C, VimL and Ruby
Fast out of the box
Requires +ruby support in Vim
Recommends Vim version >= 7.3
EDIT:
I use CtrlP with ag as my custom finder and it's incredibly quick (even on massive projects) and very portable.
An example of using ag with CtrlP:
if executable('ag')
" Use Ag over Grep
set grepprg=ag\ --nogroup\ --nocolor
" Use ag in CtrlP for listing files. Lightning fast and respects .gitignore
let g:ctrlp_user_command = 'ag %s -l --nocolor -g ""'
endif
CommandT for Vim is very much the comparable feature as in TextMate. My work flow is now
1) open up MacVim
2) :cd ~/my_project
3) (I have this mapped as described in the installation help)
4) C-v the file to open the file in a vertical split, or CR to open a new horizontal split.
5) to close the split, use :bd (buffer delete)
6) to switch to another buffer, I have BufferExplorer installed, so just \be and select
This workflow is comparable to TextMate, it takes a while to get used to, and I'm still learning.
Basic solution
Simply add this to your .vimrc
nnoremap <C-p> :find ./**/*
Pressing Ctrl+p will now allow you to fuzzyfind files in your current working directory and sub-directories thereof. Use the tab key to cycle through options.
Related solution
For those who want to keep it basic i.e. no plugins, this entertaining video shows another way to achieve fuzzy file find in vim.
They actually use
set path+=**
set wildmenu
in their .vimrc to find files in current sub-directories.
For example, with :find *Murph followd by tab, I would find the files KilianMurphy2012Why.R and KilianMurphy2014ROLE.R in subdir code which I can cycle through with the tab key. The first solution above has the advantage that the relative path is also shown.
Note that your current working directory will matter and that other files on your path (:set path?) will also be found with the this type of solution. The wildmenu option adds visual information and is not essential.
For a keyboard shortcut, add
nnoremap <C-p> :find *
to your .vimrc. Now you will be able to quickly search for files inside your project/current dir with Ctrl+p in normal mode.
What about http://www.vim.org/scripts/script.php?script_id=1984 Then there is http://github.com/jamis/fuzzy_file_finder .
Also see these blog posts: http://weblog.jamisbuck.org/2008/10/10/coming-home-to-vim and http://weblog.jamisbuck.org/2009/1/28/the-future-of-fuzzyfinder-textmate
HTH

Resources