Vim, custom tab and vertical split organization on open - vim

Say the files in my working directory are src/example.c src/second.c src/third.c include/example.h include/second.h include/third.h.
I want to open vim in a way that automatically opens three tabs (example, second and third), where each tab contains a vertical split screen between a .c and corresponding .h file. Like the following commands would.
:tabnew include/example.h | vs src/example.c
:tabnew include/second.h | vs src/second.c
:tabnew include/third.h | vs src/third.c
Is there a way I can make a special script that will do this when I open vim?
It is safe to assume files will have the same name.
Ideally, this would happen from a shell script rather than modifying my .vimrc, if that is possible.

well if you want to do that, you clearly need a way to execute vim commands from your shell. Lets see if the vim application supplies that, by using the help command which we should ask first for every shell command:
?> vim --help | grep cmd
--cmd <cmd> Execute <cmd> before any config
+<cmd>, -c <cmd> Execute <cmd> after config and first file
So all that is needed is to chain these commands:
vim -c 'tabnew include/example.h' -c 'vs src/example.c' -c 'tabnew include/second.h' -c 'vs src/second.c' -c 'tabnew include/third.h' -c 'vs src/third.c'
as #Enlico pointed out in the comment, you should use edit or e instead of tabnew in the first command, else you will get 4 tabs. But I used your commands so you can see how easily you would have been able to solve this by reading the --help output.

Related

How to redirect vim's output to terminal?

I'm currently writing a small bash script to create a pre-filled file at a specific location. To do so, my bash script call vim and execute a vim script.
In this vim script, I want to ask to the user if the location where the created file is going to be saved is the correct one. The user then enter yes or no.
To do so, I'm using this set of command:
call inputsave()
let name = input('Is it the correct location ? y/n')
call inputrestore()
this input function works fine when I'm in gvim or vim. But from a script, nothing is displayed is the terminal where I launched my bash script.
Is there a way to redirect outputs to my terminal ?
I found :redir > {file} but this is obviously redirecting all vim outputs to a file which not interactive.
I also managed to echo something int the terminal by using this:
let tmp = "!echo what I want to display"
execute tmp
unlet tmp
but again this is only to display something. I won't be able to enter an input
my bash script:
#!/bin/bash
touch tmp.txt #file used to pass argument to vim
echo "$1" >> tmp.txt #append argument to the end of the txt file
vim -e tmp.txt <create_new_file.vim #launch vim and execute the scrip inside create_new_file.vim
rm tmp.txt
echo "new file created"
the create_new_file.vim basically just call my function CreateFile(_name) located in my .vimrc. This is this function who call inputsave(), input() and inputrestore().
You're feeding commands directly into Vim via standard input; this way, Vim has no way to interact with you (the user), and this use of Vim is atypical and therefore discouraged.
Alternatives
Unless you really need special Vim capabilities, you're probably better off using non-interactive tools like sed, awk, or Perl / Python / Ruby / your favorite scripting language here.
That said, you can use Vim non-interactively:
Full Automation
For more advanced processing involving multiple windows, and real automation of Vim (where you might interact with the user or leave Vim running to let the user take over), use:
vim -N -u NONE -n -c "set nomore" -S "create_new_file.vim" tmp.txt
This should allow you to interact with Vim while following a script of commands.
Here's a summary of the used (or useful) arguments:
-N -u NONE Do not load vimrc and plugins, alternatively:
--noplugin Do not load plugins.
-n No swapfile.
-i NONE Ignore the |viminfo| file (to avoid disturbing the
user's settings).
-es Ex mode + silent batch mode -s-ex
Attention: Must be given in that order!
-S ... Source script.
-c 'set nomore' Suppress the more-prompt when the screen is filled
with messages or output to avoid blocking.

Running arbitrary vim commands from bash command line to script vim

I want to script vim to edit files from the command line. For example I want to do something along the lines of:
vim -<SOME_OPTION> 'Iworld<Esc>bIhello <Esc>:wq helloworld.txt<CR>'
or:
echo 'Iworld<Esc>bIhello <Esc>:wq helloworld.txt<CR>' | vim
and have it save the file helloworld.txt with a body of hello world
Is this possible? I've tried a few different approaches but none seem to do it. I realize I can do things like vim +PluginInstall to run Ex commands from the command line, but I'd love to be able to string together arbitrary motions
This can be achieved with the + flag and the :normal command:
$ vim +"norm Iworld" +"norm Ihello " +"wq helloworld.txt"
I think what you are looking for is vim's -w/W and -s {scriptin} option. Well in your case you should make a scriptfile, and with -s file to let vim execute all your "key presses"
I think vimgolf has used these options too.

vim: deleting non-matching lines in command line

I'm using vim to parse a file in the command line (I'm running gentoo linux):
One of the commands is not working as [I think] it should:
vim -c "v/pattern/d | wq" file
For some reason, this is not deleting the lines without the specified pattern when adding | wq. If I open the file with vim and run the same command, it works. If I run it in the command line without | wq it works.
Why is this not working?
The reason is that Vim sees this as :v/pattern/(d | wq), see :help :bar for an explanation. To avoid this, either wrap the :v in :execute:
vim -c "exe 'v/pattern/d' | wq" file
or, simpler, submit this as two separate commands:
vim -c "v/pattern/d" -c "wq" file
PS: Of course, #Bogdan has a point; you don't need Vim for that simple a task.
I suggest you use sed for that:
sed -i '/pattern/d' ./file

Execute an external command on startup

I use vim regularily for all my needs. On very rare occasions I need to open binary files via a hex editor look, and for that I start vim on the file and then run it through xxd via the command: %!xxd
My question is, how can I have my command line open a file directly in this manner, if the option exists? something like typing: gvimbin <file> and then it opens in the right manner.
Edit: to be clear, I am looking for a complete solution that allows running vim exec commands on startup.
You can execute commands after Vim startup by passing them via -c:
$ gvim -c '%!xxd' file.bin
This can even be simplified so that when Vim is started in binary mode (-b argument), it'll automatically convert the file. Put the following into your ~/.vimrc:
if &binary
%!xxd
endif
and start with:
$ gvim -b file.bin
Also have a look at the hexman.vim - Simpler Hex viewing and editing plugin; it makes it easier to deal with hexdumps.
Like Felix say:
xxd <file> | vim -
You can put this into script for example vimxxd:
#!/bin/sh
xxd $1 | vim -
and use like: vimxxd file.txt

Search and replace in Vim across all the project files

I'm looking for the best way to do search-and-replace (with confirmation) across all project files in Vim. By "project files" I mean files in the current directory, some of which do not have to be open.
One way to do this could be to simply open all of the files in the current directory:
:args ./**
and then do the search and replace on all open files:
:argdo %s/Search/Replace/gce
However, when I do this, Vim's memory usage jumps from a couple dozen of MB to over 2 GB, which doesn't work for me.
I also have the EasyGrep plugin installed, but it almost never works—either it doesn't find all the occurrences, or it just hangs until I press CtrlC. So far my preferred way to accomplish this task it to ack-grep for the search term, using it's quickfix window open any file that contains the term and was not opened before, and finally :bufdo %s/Search/Replace/gce.
I'm looking either for a good, working plugin that can be used for this, or alternatively a command/sequence of commands that would be easier than the one I'm using now.
The other big option here is simply not to use vim:
sed -i 's/pattern/replacement/' <files>
or if you have some way of generating a list of files, perhaps something like this:
find . -name *.cpp | xargs sed -i 's/pattern/replacement/'
grep -rl 'pattern1' | xargs sed -i 's/pattern2/replacement/'
and so on!
EDIT: Use cfdo command instead of cdo to significantly reduce the amount of commands that will be run to accomplish this (because cdo runs commands on each element while cfdo runs commands on each file)
Thanks to the recently added cdo command, you can now do this in two simple commands using whatever grep tool you have installed. No extra plugins required!:
1. :grep <search term>
2. :cdo %s/<search term>/<replace term>/gc
3. (If you want to save the changes in all files) :cdo update
(cdo executes the given command to each term in the quickfix list, which your grep command populates.)
(Remove the c at the end of the 2nd command if you want to replace each search term without confirming each time)
I've decided to use ack and Perl to solve this problem in order to take advantage of the more powerful full Perl regular expressions rather than the GNU subset.
ack -l 'pattern' | xargs perl -pi -E 's/pattern/replacement/g'
Explanation
ack
ack is an awesome command line tool that is a mix of grep, find, and full Perl regular expressions (not just the GNU subset). Its written in pure Perl, its fast, it has syntax highlighting, works on Windows and its friendlier to programmers than the traditional command line tools. Install it on Ubuntu with sudo apt-get install ack-grep.
xargs
Xargs is an old unix command line tool. It reads items from standard input and executes the command specified followed by the items read for standard input. So basically the list of files generated by ack are being appended to the end of the perl -pi -E 's/pattern/replacemnt/g' command.
perl -pi
Perl is a programming language. The -p option causes Perl to create a loop around your program which iterates over filename arguments. The -i option causes Perl to edit the file in place. You can modify this to create backups. The -E option causes Perl to execute the one line of code specified as the program. In our case the program is just a Perl regex substitution. For more information on Perl command line options perldoc perlrun. For more information on Perl see http://www.perl.org/.
Greplace works well for me.
There's also a pathogen ready version on github.
maybe do this:
:noautocmd vim /Search/ **/*
:set hidden
:cfirst
qa
:%s//Replace/gce
:cnf
q
1000#a
:wa
Explanation:
:noautocmd vim /Search/ **/* ⇒ lookup (vim is an abbreviation for vimgrep) pattern in all files in all subdirectories of the cwd without triggering autocmds (:noautocmd), for speed's sake.
:set hidden ⇒ allow having modified buffers not displayed in a window (could be in your vimrc)
:cfirst ⇒ jump to first search result
qa ⇒ start recording a macro into register a
:%s//Replace/gce ⇒ replace all occurrences of the last search pattern (still /Search/ at that time) with Replace:
several times on a same line (g flag)
with user confirmation (c flag)
without error if no pattern found (e flag)
:cnf ⇒ jump to next file in the list created by the vim command
q ⇒ stop recording macro
1000#a ⇒ play macro stored in register a 1000 times
:wa ⇒ save all modified buffers
* EDIT * Vim 8 way:
Starting with Vim 8 there is a better way to do it, as :cfdo iterates on all files in the quickfix list:
:noautocmd vim /Search/ **/*
:set hidden
:cfdo %s//Replace/gce
:wa
Populate :args from a shell command
It's possible (on some operating systems1)) to supply the files for :args via a shell command.
For example, if you have ack2 installed,
:args `ack -l pattern`
will ask ack to return a list of files containing 'pattern' and put these on the argument list.
Or with plain ol' grep i guess it'd be:
:args `grep -lr pattern .`
You can then just use :argdo as described by the OP:
:argdo %s/pattern/replacement/gce
Populate :args from the quickfix list
Also check out nelstrom's answer to a related question describing a simple user defined command that populates the arglist from the current quickfix list. This works great with many commands and plugins whose output ends up in the quickfix list (:vimgrep, :Ack3, :Ggrep4).
The sequence to perform a project wide search could then be done with:
:vimgrep /pattern/ **/*
:Qargs
:argdo %s/findme/replacement/gc
where :Qargs is the call to the user defined command that populates the arglist from the quickfix list.
You'll also find links in the ensuing discussion to simple plugins that get this workflow down to 2 or 3 commands.
Links
:h {arglist} - vimdoc.sourceforge.net/htmldoc/editing.html#{arglist}
ack - betterthangrep.com/
ack.vim - github.com/mileszs/ack.vim
fugitive - github.com/tpope/vim-fugitive
One more option in 2016, far.vim plugin:
1. :grep <search term> (or whatever you use to populate the quickfix window)
2. :cfdo %s/<search term>/<replace term>/g | update
Step 1 populates the quickfix list with items you want. In this case, it's propagated with search terms you want to change via grep.
cfdo runs the command following on each file in the quickfix list. Type :help cfdo for details.
s/<search term>/<replace term>/g replaces each term. /g means replace every occurrence in the file.
| update saves the file after every replace.
I pieced this together based upon this answer and its comments, but felt it deserved its own answer since it's all in one place.
If you don't mind of introducing external dependency, I have brewed a plugin ctrlsf.vim (depends on ack or ag) to do the job.
It can format and display search result from ack/ag, and synchronize your changes in result buffer to actual files on disk.
Maybe following demo explains more
Make sure you’re using Neovim (or Vim 7.4.8+, but really just use Neovim)
Install FZF for the command line and as a vim plugin
Install Ag, so that it’s available automatically to FZF in vim
If using iTerm2 on OSX, set the alt/option key to Esc+
Usage
Search the text you want to change in the current directory and it’s children with
:Ag text
Keep typing to fuzzy filter items
Select items with alt-a
Deselect items with alt-d
Enter will populate the quickfix list
:cfdo %s/text/newText/g | :w
Now you have chabges made inside Vim NeoVim
source
You can do it with shell and vim's ex-mode. This has the added benefit of not needing to memorize other search-and-replace escape sequences.
Any command that can list files will work (rg -l, grep -rl, fd...). For example in bash:
for f in $(rg -l Search); do
vim -Nes "$f" <<EOF
%s/Search/Replace/g
wq
EOF
done
You can use any command, those prefixed with : in command mode, the same way you would inside vim, just drop the : at the start
I think that is because you have a huge amount of files been captured in memory. For my case, I do this by group files in different types, for example:
:args **/*.md
argdo <command>
:args **/*.haml
argdo <command>
Basically, I wanted the replace in a single command and more importantly within vim itself
Based on the answer by #Jefromi i've created a keyboard shortcut, which I had set in my .vimrc file like this
nmap <leader>r :!grep -r -l * \| xargs sed -i -e 's///g'
now from the vim, on a stroke of leader+r I get the command loaded in vim, which i edit like below,
:!grep -r -l <find> <file pattern> | xargs sed -i -e 's/<find>/<replace>/g'
Hence, I do the replace with a single command and more importantly within vim itself

Resources