Skip to Content
Learning the vi and Vim Editors, 7th Edition
book

Learning the vi and Vim Editors, 7th Edition

by Arnold Robbins, Elbert Hannah, Linda Lamb
July 2008
Beginner
492 pages
16h
English
O'Reilly Media, Inc.
Content preview from Learning the vi and Vim Editors, 7th Edition

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

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning the vi and Vim Editors, 8th Edition

Learning the vi and Vim Editors, 8th Edition

Arnold Robbins, Elbert Hannah
Vim Masterclass

Vim Masterclass

Jason Cannon
Mastering Vim

Mastering Vim

Ruslan Osipov

Publisher Resources

ISBN: 9780596529833Errata Page