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 ...

Get Learning the vi and Vim Editors, 7th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.