Elroyjetson

Working with External Commands in VIM

Posted on: by

Introduction

Some of the power you get from Vim, besides the incredible text processing ability, is that you have access to run command line programs from within the application. If you are running on a Unix based system, that means you have the power of Unix at your disposal as well as the most powerful text editor.

If you develop in PHP, it would be nice to run php lint without having to open another terminal or exiting Vim. If you don’t have permission to write to a file, it would be nice to fix that so you can save all the changes you have made. These are just a few of the common uses, but the sky is the limit.

Vim has this all built right in and it is simple to use.

Take Note

Here is a list of the commands we will use and what they do before I show examples:

  • :! This tells Vim to execute the command that follows in a shell
  • % Not really a command but it references the current file
  • %:p The current file and it’s full path
  • :r Read contents into the current buffer
  • :shell Drop to a command prompt, exit to return to vim

Examples

Get the word count of the current file

:! wc -w %

Get a directory listing and read it into the current buffer

:r ! ls -l

Run PHP lint on the current file

:! php -l %

Conclusion

This provide you with tremendous power all without ever leaving the confines of Vim. Obviously commands can be strung together in any way you can imagine them.

Updated: