Peter Stuifzand

External programs in Vim

When you’re typing some text in Vim, you will sometimes need a piece of text that is easy to generate on the command line or with a simple perl script. Maybe you want to insert the current date, a simple calendar or a list of day names.

Don’t you worry there’s a simple vim command that will help you with this. Here are some examples. From simple to complex.

Insert the current date

Type:

date

on a line by itself. Then move the cursor to that line and type !!sh<cr>. This will filter date through the shell (which is equivalent to :r!date. The current date will be replaced into the buffer. If the output isn’t correct or different from what you expected, then you can always use u to undo the change.

Insert a simple calendar

Type:

cal

And type the same command as before !!sh<cr>. The nice thing about using the !! command this way, is that you can create a command line in Vim.

SQL queries collecting output

Sometimes it’s easier to use the command line when conversing with you’re MySQL database instead of using phpmyadmin. This will happen when you need to create queries based on output of other queries. An example:

SELECT `id`
FROM `entry`
WHERE `post_date`
    BETWEEN '2006-10-25' AND '2005-11-05'

This query of a fictitious database will get the id’s of the entries in a datarange. This query can be piped into mysql by using the following command:

mysql -u dbuser -pdbpass databasename

As always prefix the command with !!mysql .... This will send the query to the database. The output of the query will be replaced into the current buffer one id on each line.

After this you can use the output together with vim to creates new queries. Assume we got the following output:

10
11
12
13

These are the id’s we got. We can translate the id into new queries by using some Vim commands.

UPDATE `entry` SET `visible` = 1 WHERE `id` = 10
UPDATE `entry` SET `visible` = 1 WHERE `id` = 11
UPDATE `entry` SET `visible` = 1 WHERE `id` = 12
UPDATE `entry` SET `visible` = 1 WHERE `id` = 13

Now selected these queries by using V visual line mode. When you press ! now, vim will ask for a program to start, just like in the other examples. When you use mysql, vim will send each query to the database.

A script

To print all the letters of the alphabet you can use the keyboard and type all the letters one after another. If you are a bit more lazy and want to learn some nice vim command and perl code, you can use the next command.

print 'a' .. 'z';

This is a line of perl code that will print all the letters of the alphabet when executed. This line of code can be executed by typing !!perl<cr> on the line of code. The code will expand into abcdefghijklmnopqrstuvwxyz.

© 2023 Peter Stuifzand