Vim's Feature of the Day #2: Context-Aware Completion for XML

(in 5 minutes!!!)

You're editing yet another Debian sub-policy. Of course the policy is written in Docbook XML and (should I even need to mention it?) of course you're using Vim. The Docbook v4.4 specification is huuuuge and you happen to know just a tiny teeny part of it. Hence you're dreaming of XML Spy or Emacs context-aware completion. Shame on you misbeliever!, Vim can do the same!!

Here is how to set-up in 9 easy steps context aware completion for Docbook v4.4 with Vim7 in Debian/unstable:

# aptitude install docbook vim-scripts perlsgml

$ mkdir -p ~/.vim/autoload/xml/ ~/.vim/after/ftplugin/xml/

$ cp -r /usr/share/sgml/docbook/dtd/xml/4.4/ /tmp/docbook-dtd/
$ cd /tmp/docbook-dtd/
$ SGML_CATALOG_FILES=/etc/sgml/catalog dtd2vim docbookx.dtd docbk44
$ mv docbookx.vim ~/.vim/autoload/xml/docbk44.vim
$ rm -rf /tmp/docbook-dtd/

$ echo "runtime ftplugin/xml.vim" >> ~/.vim/after/ftplugin/docbk.vim
$ echo "XMLns docbk44" >> ~/.vim/after/ftplugin/docbk.vim

Now just start Vim on an .xml file containing some Docbook markup and let the fun begin:

  • in insert mode place the cursor just after a '<' character and type CTRL-x CTRL-o: Vim will present you a choice of opening tags which can be placed there respecting the content model

  • in insert mode place the cursor before the '>' character of an opening tag and type CTRL-x CTRL-o: Vim will present you a choice of attributed which can belong to the current opening tag

Warnings: dtd2vim is a recent addition to vim-scripts, you will need >= 7.05. If you start editing a file which Vim is not yet able to recognized as a Docbook file (e.g. an empty file) don't panic, setf docbk is your friend.

Enjoy!

PS an even higher fun level while editing XML with Vim can be obtained using the "xml" ftplugin shipped by vim-scripts ...