Technology, Social Media, Travel
RSS icon Email icon Home icon
  • Tidy Up Your XML in Vim

    Posted on June 13th, 2009 John Berns 3 comments

    You have some nice, compact XML, the kind without whitespace or newlines, like this:

    01-raw-xml-in-vim-no-whitespace

    Not easy to read. OK for computers to crunch–but if you want to get an idea of the document’s structure at a glance or do some editing–well, you might want it formatted a little nicer.

    So let’s use Tidy to clean it up–all from the comfort of your Vim session…

    (You could also use xmllint–your choice–depends on what you have installed and what you prefer.)

    You can execute a shell command from Vim by typing:

    :!

    Then to tidy up your XML run tidy with the following options:

    tidy -mi -xml -utf8

    “-im” means indent and modify the original file; “-xml” means, you are dealing with XML and “-utf8″ is optional, it means “use UTF-8 for both input and output” so you’ll get readable characters instead of encodings if you have umlats or grave symbols.

    You can see all of tidy’s formatting, encoding and other options by typing

    tidy -h

    So the whole command we type into Vim is:

    :! tidy -mi -xml -utf8

    02-raw-xml-tidy-command

    You will drop to shell while the command executes:

    03-raw-xml-tidy-complete

    Hit “return” when you are done and then Vim will ask if you want to reload the file:

    04-raw-xml-reload

    And there you go, beautifully formatted HTML to read!

    05-formatted-xml

    Enjoy ;-) !

     

    3 responses to “Tidy Up Your XML in Vim” RSS icon

    • Wow, what a return from your 8 month blogging hiatus. Welcome back Mr Berns!

      I had no idea you were such a vim power user, I am truly impressed my good man. I will experiment with your ! tidy command next time I’m working with XML in vim. :-)

    • you don’t have to type in the name of the file, let Vim type/replace it for you:

      :! tidy -mi -xml -utf8 %

      expands to

      :! tidy -mi -xml -utf8

      cheers!

    • and you can do this:
      :%!tidy -xml -i -q -w 0

      this will _pipe_ the current buffer to tidy’s STDIN and reading tidy’s STDOUT, effectively replacing the current buffer in vim with the filter’s output.

      nuff said.


    Leave a reply