Vim weekly tips is a series of small articles that I intend to write every week to share tips about my favorite editor : Vim
I want to start this collection by showing you one feature that a lot of people don't know about.
In Vim, you can use the large panel of external commands available in the *nix ecosystem inside your terminal. By example, say you want to list the files in your current directory, you can type :
:!ls Press ENTER or type command to continue [No write since last change] archetypes config.toml content public resources static themes
You could use some *nix natural way to suspend a program by pressing Ctr+Z that will freeze your vim session and puts it in the background. You can then check your files in your terminal and to bring it to the foreground again by typing :
Ctr^Z  + 23189 suspended % ls archetypes config.toml content public resources static themes % fg
And you're back in your session. 😉
Vim provides also a shortcut quite interesting to use external command : !G
It opens a prompt with the range :.,$! already filled.
How that is interesting you may ask! Try to imagine you're working on a file and you want to sort alphabetically three lines just above your cursor :
balloon bout but
You hit !G and you can give the range for this 3 lines. If they are on between the lines 12 and 15, you can hit !G and then change it from :
:.,$! to :12,15!sort
And you will have your lines sorted alphabetically.
An other example of how to use an external command to count the numbers of words in your file :
:! wc %
This tells Vim to run the file (%) through the wc utility and report the results to the screen. Note that you should save the file before doing this command because it doesn't count the current buffer but read what's in the file.
If you just want to rerun the last external command, you can use
For those unfamiliar with Vim, you can use this command to read or to insert a file in your current buffer :
You can combine this with the ! command to read the output of some shell commands this way by example :
:r ! ls -l ~/.ssh/
That will include the output of that folder in your buffer :
-rw-r--r-- 1 hyde hyde 1205 May 14 2019 authorized_keys -rw-r--r-- 1 hyde hyde 2200 May 14 2019 config -rw------- 1 hyde hyde 1675 May 14 2019 id_rsa -rw-r--r-- 1 hyde hyde 392 May 14 2019 id_rsa.pub -rw-r--r-- 1 hyde hyde 2944 Feb 5 08:28 known_hosts
You could use the same command to print the resuls of the counting words in the example above directly in your buffer.
You can of course use a pipe and other *nix tools to manipulate a command and get the output in your current file.
That could be really handy if you have to write a report about an app based on your server logs :
:r ! grep ERROR /var/log/your_app/error.log
That will grep errors from your logs and print them in your file.
That's all for this week.
vim editor tips