This thread is for posting Vim tips. A great way to improve Vim skills is to learn a few new tricks at a time and slowly incorporate them into your workflow.
I’ll start with a few tips, and we can keep adding more in the comments as we learn them.
Here are a few related tips about %
and !
in Vim:
How to run Vim without sudo
I suspect that it’s better not to run Vim with sudo
. Plugins and some other things might be able to execute code as root if Vim is run as root. I open Vim without sudo
and then save protected files like this:
:w !sudo tee %
Find out more about the tee
command by typing man tee
in a bash (or similar) terminal.
Running shell commands on your file
An exclamation point (!
) will run shell commands (like in the :w !sudo tee %
example above).
Say you have an unsorted list with duplicates in your editor like this:
elephant
bear
cat
alligator
alligator
bear
dog
You could sort it and remove duplicates by visually selecting all (ggVG
– go to top, visually select line, go to bottom) and then running this command:
:!sort|uniq
That takes the selected text and runs (!
) it through the shell’s sort
command and then pipes it into the uniq
command. The final result should be:
alligator
bear
cat
dog
elephant
You can use a variety of shell commands there.
Another quick example: read the output of a command into your current buffer:
:r !ls -alh
(It should work in Emacs’ Evil Mode too.)
Reloading the .vimrc
file while editing it
%
refers to the current file in Vim. (See the sudo
example above for one example.)
If you’re editing your .vimrc
file and want to reload it without restarting vim, you can source
the file (execute the commands in it) with:
:source %
or shorthand:
:so %
%
and find/replace
The %
in a Vim search and replace also refers to the current file:
:%s/foo/bar/gc
It means: within the file (%
) substitute foo
with bar
globally, and confirm each change.
If you visually select some text (for example, with shift-v
), you can enter command mode with the :
and then perform a substitution. The percent sign (meaning the current file) won’t be there this time, but it will look more like this:
:'<,'>s/foo/bar/gc
You can also limit substitutions by line numbers. So the following command would perform a search and replace to just lines 20-25:
:20,25s/foo/bar/gc
It can be fun to play around with ex
too. (Command mode in Vim uses ex
.) I think that seeing the older way of doing things with ex
makes Vim’s way of doing things seem less strange. To print the file you can type %p
and the same substitution commands (:3,4/s/t/TTTTT/g
) work:
To open a file in ex
do something like:
$ ex my-file.txt
To switch from ex
to Vim, type :visual
.