How to open a file in a list of files in Vim? - vim

I have a longish list of files opened in vim that looks like this:
/dir1/file1
/dir2/file2
/dir2/file3
.....
How can I open all of them one by one the easiest way possible in the same session of vim either with split or edit?

I'd say with -p for tabs
vim -p `cat yourlistoffiles`

You can use quickfix mode, as following
:set errorformat=%f
:cf myfilelist
at this point you can use the normal quickfix shortcuts to go through your files, :cn for the next file, :cp for the previous one and :cr to go to the first again.
EDIT:
oh, if you want to read the list from the current buffer, use :cb instead of :cf in in the instructions above

You can do the following
cat file | xargs vim
Where "file" contains your list of files, this will open the files in the same vim session. As usual when opening multiple buffers, you can navigate forward with :bn and backward :bp.

I'm going to assume you have the file list open inside Vim, and want to simulate the "gf" command across the whole list...
Edit your .vimrc to include this function:
function Openall()
edit <cfile>
bfirst
endfunction
You can then highlight the entire file (or the set of paths you want to open) using visual mode (1G, Shift-V, G) and typing ":call Openall()". Afterwards the command row will show this:
:'<,'>call Openall()
This will run the new Openall() function across all highlighted lines.
Press Enter and all the files will be opened in background buffers. You can then access them using the usual buffer commands. :ls will display them as a list.

I suppose you want to select and list in vim. all the files of a certain extension. From your home directory or a particular source.
find . -name "*.sh" | vim -
Then within vim, you could search and view this potentially huge list.
(Another topic)
You found your file, now you want to open it in a split?
CTRL-W F *CTRL-W_F*
Split current window in two. Edit file name under cursor and
jump to the line number following the file name. See |gF| for
details on how the line number is obtained.
{not available when the |+file_in_path| feature was disabled
at compile time}
CTRL-W gf *CTRL-W_gf*
Open a new tab page and edit the file name under the cursor.
Like "tab split" and "gf", but the new tab page isn't created
if the file does not exist.
{not available when the |+file_in_path| feature was disabled
at compile time}

For my use case, where you already have a buffer open with the list of files in it, I have found the best way to do this. You can type this in vim cmd mode:
:% normal gf<C-v><C-o>
(where <C-v> is you literally typing Ctrl and v, same for <C-o>)
and it becomes:
:% normal gf^O
How this works:
% runs the command for every line in the file
normal runs everything after it in normal mode
gf opens the file under the cursor in a new buffer
<C-v> lets you enter a control-code (<C-o> in this case)
<C-o> goes back to the last location, which will always be this buffer with the list of files
Potential usage:
# open buffer with list of files from grep
$ grep -rl "new User()" mycode/ libraries/ | vim -
# then runs this in vim:
:% normal gf^O
Bonus: Make a keyboard shortcut
Add the following to your ~/.vimrc :
" Open all files in current buffer (e.g. after piping to `vim -`)
nnoremap <leader>oa :% normal gf^O<cr>
This maps \oa to run the command (since <leader> is \ for me).
An alternate method using a macro:
qogf<C-o>j
which runs gf (go file) then uses <C-o> to get back to the initial unnamed buffer, then just goes down one line with j, ready to be repeated.
Then see how many lines in the buffer (12) and run the macro like this:
12#o

I often need to open a changing list of files that had been modified in my SVN checkout.
This one liner works to open all modified files in vim tabs.
svn st | grep ^M | awk "{print($2)}" | xargs vim -p

Try this with bash:
$ vim -S <(sed "s/^/badd /" <your file name>)
But I don't know why the first line of the file is ignored... :-O
This script works as expected:
rm -f myfile
for i in `seq 10000`
do
touch $i
echo $i >> myfile
done
vi -c "badd `head -1 myfile`" -S <(sed "s/^/badd /" myfile)
http://vimdoc.sourceforge.net/htmldoc/starting.html#-S
http://vimdoc.sourceforge.net/htmldoc/windows.html#:bad

Maybe this could help:
http://vimdoc.sourceforge.net/htmldoc/windows.html

It's as simple as typing
vim /dir1/file1 /dir2/file1 /dir2/file2 ...
Once you're in vim, you can switch betwen then with ":n" to go to the next file, ":prev" to go to the previous file.

My searchInRuntime plugin has a :Sp and a :Vsp commands that'll do the trick when called banged. However, the files have to exist.

Related

Opening file present in another folder which has same relative path as current opened file in vim using vertical diffsplit?

Say I have following 2 similar files in 2 different workspace on same linux machine.
/user1/ws1/ip/src/ip_main.c
/user1/ws2/ip/src/ip_main.c
Now I did,
cd user1/ws1/
vim ip/src/ip_main.c
then I press ESC then executed
:cd ../ws2
which shows my pwd as "user1/ws2"
Now I want to open ip/src/ip_main.c in pwd i.e "user1/ws2"
using ESC
:vertical diffsplit "some logic to get to ws2/ip/src/ip_main.c"
note after :cd ../ws2
:pwd command show "user1/ws2" but :echo $PWD command still show "user1/ws1"
How can i do it,Can anyone help ?
Diffing both files is easily done via shell globbing, e.g. in Bash:
$ vimdiff -O /user1/ws{1,2}/ip/src/ip_main.c
Withing Vim, you have to use relative paths (i.e. prepend ../.., then go down into the other hierarchy). <C-R>% on the command-line (cp. :help c_CTRL-R) inserts the current path; this may avoid retyping much of the similar path, especially when used with the command-line window (:help c_CTRL-F).
With my EditSimilar plugin, you can use this:
:DiffSplitSubstitute 1=2

Open more than 10 files matching a pattern with vim's CLI

Is there way (from the CLI) to increase the number of files that can be opened using vim's -p option?
E.g.
$ vim -p lib/**/*.rb # opens 10 files in tabs
Is there a way to alter the above command such that it will open all (or more than 10) files?
Alternatively, is there a better way to open the collection of files (in tabs) from the command line?
You can change this by setting the tabpagemax option in your .vimrc:
set tabpagemax=15
While you can increase the tabpagemax by
$ echo "set tabpagemax=30" >> ~/.vimrc
The better solution would be to use the same command without -p, opening all matching files in buffers:
$ vim lib/**/*.rb # opens all matching files in buffers
One can then navigate between files in vim's buffer using :bnext and :bprevious.

Vim: Wiping Out Buffers Editing Nonexistent Files

Often when I'm editing in Vim, I end up restoring a Vim session that refers to a some files in a directory that was moved. The problem occurs after I use :n to open all of the files located in the new directory. Now, when I use :b <buffer-name> to switch to the buffer editing a particular file located in the new directory, there is an ambiguity: two buffers are opened on files with the same name, and one of these files does not exist. So I'm forced to use :ls, manually search for the indices of buffers that are editing nonexistent files, and call :bw on each one of them. Is there some simple command that will automatically wipe out the buffers editing nonexistent files for me?
Also, after manually wiping out the offending buffers, there are abrupt breaks in the indices between consecutive buffers, which makes switching between buffers using :<n>b more difficult. Is there a command that will re-index the buffers for me so that the set of indices is some contiguous range?
Thanks for your help!
Try the following command:
function s:WipeBuffersWithoutFiles()
let bufs=filter(range(1, bufnr('$')), 'bufexists(v:val) && '.
\'empty(getbufvar(v:val, "&buftype")) && '.
\'!filereadable(bufname(v:val))')
if !empty(bufs)
execute 'bwipeout' join(bufs)
endif
endfunction
command BWnex call s:WipeBuffersWithoutFiles()
Usage:
:BWnex<CR>
Note some tricks:
filter(range(1, bufnr('$')), 'bufexists(v:val)') will present you a list of all buffers (buffer numbers) that vim currently has.
empty(getbufvar(v:val, '&buftype')) checks whether buffer actually should have a file. There are some plugins opening buffers that are never supposed to be represented in filesystem: for example, buffer with a list of currently opened buffers emitted by plugins such as minibufexplorer. These buffers always have &buftype set to something like nofile, normal buffers have empty buftype.
Aren't buffers supposed to be unique?
After this sequence of commands:
:e .bashrc
:e .profile
:e .bashrc
:e .profile
:e .bashrc
:e .profile
:e .bashrc
:e .profile
:e .bashrc
I still have only two buffers available as shown by :buffers or :ls: .bashrc and .profile. Even if I use multiple windows and tabs.
Are you confusing "buffers" with "windows"?
Both of my suggestions are workarounds, but I thought worth mentioning. One way is to :ls then grab with the mouse, paste into a scratch buffer and then launch from command line.
When my buffers get cluttered, I usually close the window. Then I have a command from my shell that launches all checked out files from my source control -- which 90% of the time are the files I am interested in.
I'm usually on cygwin bash. And run
gvim `p4list` `svnopened`
The functions p4list and svnopened are below:
function p4list() {
export tempscript=`mktemp`
echo "#!bash" > $tempscript
p4 opened $# | sed -e 's/#.*//g' | sed -e 's/$/ \\/g' | sed -e '1~300s/^/\
\
p4 where /' >> $tempscript
chmod +x $tempscript
$tempscript | sed -e 's/.* //g' | sed -e 's/
//g' | sed -e 's/\///g'
rm $tempscript
}
function svnopened() {
svn st $# | grep "^\M" | sed -e 's/^.\{8\}//'
}

Indenting in VIM with all the files in Folder

I have a folder containing hundreds of TTL (TeraTermLanguage) files.
Now I wanted indent all these files.
I have created teraterm.vim for indentation and I open a file using VIM and do "gg=G" and whole file gets indented properly.
But is there any way, where I can indent all the files in folder.
I wanted to do with help of Shell. But in VIM I couldnt pass file indent command as the argument to VIM.
Please suggest which is the best way I can do indentation to all the files in VIM.
Much simpler than scripting vim from the bash command line is to use vimscript from inside of vim (or perhaps a much simpler one-liner for scripting vim from the command line). I personally prefer using the arg list for all multi-file manipulation. For example:
:args ~/src/myproject/**/*.ttl | argdo execute "normal gg=G" | update
args sets the arglist, using wildcards (** will match the current directory as well as subdirectories)
| lets us run multiple commands on one line
argdo runs the following commands on each arg (it will swallow up the second |)
execute prevents normal from swallowing up the next pipe.
normal runs the following normal mode commands (what you were working with in the first place)
update is like :w, but only saves when the buffer is modified.
This :args ... | argdo ... | update pattern is very useful for any sort of project wide file manipulation (e.g. search and replace via %s/foo/bar/ge or setting uniform fileformat or fileencoding).
(other people prefer a similar pattern using the buffer list and :bufdo, but with the arg list I don't need to worry about closing current buffers or opening up new vim session.)
Open up a terminal. Type:
$ vim -w indentme.scr foo.c
Then, type this exactly (in command mode):
gg=G:wq
This will close vim, saving the process of indenting all lines in the file to a Vim script called indentme.scr.
Note: indentme.scr will contain a record of all key commands typed, so when you are done indenting the file, don't spend a lot of time using the arrow keys to look around the file, because this will lead to a much larger script and will severely slow down batch operations.
Now, in order to indent all the lines in a file, just type the following command:
$ vim -s indentme.scr unindented-file.c
Vim will flash open-shut (if you're on a fast computer and not editing a huge file), indenting all lines, then saving the file in-place.
Unfortunately, this will only work on one file at a time, but you can scale the functionality easily using sh's for loop:
for filename in *.ttl ; do
vim -s indentme.scr "$filename"
done
Note: This will save-over any file. Unless set bk is in your ~/.vimrc, don't expect a backup to be saved.
I went off of amphetamachine's solution. However, I needed to recursively search through multiple directories. Here's the solution that I used:
$ find . -type f -name '*.ttl' -exec vim -s indentme.scr "{}" \;
Taking reference from the above answers I would like to make this complete.
I will start from the scratch so that a beginner can understand.
Step-1
Install astyle (tool used for formatting ) by using the following command
Open up a terminal. Type:
sudo apt-get install astyle
Step-2 Make sure you have vim installed on your system.Run the below commands from the directory in which your code files are.The below command will create a script that we intend to run recursively so as to beautify each and every file in our directory.(as mentioned in the above answer)
vim -w indentme.scr foo.c
Step-3 Then, type this exactly (in command mode) and press enter
:%!astyle
Step-4Then type this exactly (in command mode) and press enter
:wq
Step-5 Last run this recursively by the following command:
find . -type f -name '*.cpp' -exec vim -s indentme.scr "{}" \;
All your cpp files will be formatted properly.

How to search across a directory of files in vim?

A common programming task for me in vim is:
:s/some pattern/
do some work
n # finds the next entry
do some work
n # finds the next entry
...
Now, s/.... only searches in the current file.
Is there a way I can do this, but search across a directory of files? Say do "s/..../" over all files in subdirectoires of pwd that ends in .hpp of .cpp ?
Thanks!
You can simply use the :grep command: or for a more complete integration of search tools, use the grep.vim extension.
Simply type :help grep to get a nice documentation of what is available out of the box in Vim.
Using :grep foo *.?pp should do what you want.
This will open the QuickFix list, just like the one you get using :make, enabling to jump to the found occurrences.
There is a fantastic plugin named ctrlsf.vim ,which makes you search in vim efficiently.
Here is a snapshot of it.Quite cool ,isn't it?
For instance , If you want search word like "hello" in current dir , after installation , all you need to do is Simply type:
:CtrlSF "hello"
then you'll get what you expect.
Have fun!
:help windo
:help bufdo
man find
man xargs
find ./start/point -iname "*.cpp" -print0 | xargs -0 vim
:bufdo s/baar/foo/gc
:wall
:qall
gc "global confirm", wall (write all), qall (quite all). To see file list :ls top jump to next file :wn (write next) or :bn (buffer next). By the way, xargs manage large chunks of file in memory to deliver to vim withou erros.

Resources