O'Reilly logo

Learning the vi and Vim Editors, 7th Edition by Linda Lamb, Elbert Hannah, Arnold Robbins

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Some Additional Thoughts About Vim Scripting

We’ve covered only a small corner of the entire Vim scripting universe, but we hope you get the sense of Vim’s power. Virtually everything you can do interactively using Vim can be coded in a script.

In this section we look at a nice example included in the built-in Vim documentation, discuss in more detail concepts we touched on earlier, and look at a few new features.

A Useful Vim Script Example

Vim’s built-in documentation includes a handy script we think you’ll want to use. It specifically addresses keeping a current timestamp in the meta line of an HTML file, but it could easily be used for many other types of files where it is useful to have the most recent modification time of the file within the text of that file.

Here is the example essentially intact (we have modified it slightly):

autocmd BufWritePre,FileWritePre *.html   mark s|call LastMod()|'s
fun LastMod()
  " if there are more than 20 lines, set our max to 20, otherwise, scan
  " entire file.
  if line("$") > 20
    let lastModifiedline = 20
  else
    let lastModifiedline = line("$")
  endif
  exe "1," . lastModifiedline . "g/Last modified: /s/Last modified: 
      .*/Last modified: " .
  \ strftime("%Y %b %d")
endfun

Here’s a brief breakdown of the autocmd command:

BufWritePre, FileWritePre

These are the events for which the command is triggered. In this case, Vim executes the autocommand before the file or buffer gets written to the storage device.

*.html

Execute this autocommand for any file whose name ends ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required