A bit about the stuff I've done

Friday 13 January 2012

Editing xml in vim

Yes, I use vim!

And large html, xml and xsl documents can be frustrating so here are a few things I sussed out today to make it easier:

  1. None of the commandline tools I could find were capable of cleanly formatting an xml document and putting comments in the correct alignment. All of them put the comments with no indentation.
    Some of you may prefer this but it stosp the following tips from working correctly in vim
    So I wrote a quick 5 min tool to do this, and here it is.
    Extract that archive somewhere into your path and then simply cat unformatted.xml | xmltidy > formatted.xml
    easy :)
    N.B. You'll need to have mono installed.
  2. Next I've assigned this new tool to an easy key in vim
    In your .vimrc file enter the following:
    :map <F2> :1,$!xmltidy<Enter>
    You can use any key you like of course
  3. Next I enabled code-folding
    Now there are plenty of posts out on the web about getting code folding with xml to work however I had issues with all of them.
    What I found to work was to enable folding by indentation (hence why comments have to be in the correct alignment).
    These 2 lines of vimrc sorted that out for me:
    au FileType htm,html,xml.xsl,xslt exe ":set foldmethod=indent"
    au BufNewFile,BufRead *.htm,*.html,*.xml,*.xsl,*.xslt exe ":set shiftwidth=2"

    N.B. I have my tabstop set to 2 so that pressing the tabkey indents the line by 2 columns instead of the usual 
  4.  Finally; if, like me, you don't like that ugly banner on the code folding lines then you'll want to change the colours with this line:
    :highlight Folded ctermbg=black
Having enabled the code folding you can use zo and zc to open and close a fold respectively.
N.B. when folding it folds everything at that level, not everything that is a child.
In other words if you had this document:
<xml>   <node1>     <node1a/>     <node1b/>   </node1>   <node2>     <node2a/>     <node2b/>   </node2> </xml>
and you press zc when the cursor is on the line with node1 then rather than hiding node1a and node1b like you might expect - it hides node1 and node2 (as well as their children)

No comments:

Post a Comment