Prettying XML in Komodo

Wednesday 2 December 2009

I use ActiveState Komodo as my editor these days, and have for a while. It’s got just the right feature set for me, including scriptability in Python.

I haven’t dug into the scripting much, but one constant need finally drove me to learn more about it. At work, we often deal with chunks of data sent from servers in either XML or JSON formats, and that data is rarely indented for readability. So I often need to pretty up a file so that I can see what’s going on.

Here’s a Komodo Python script to prettify XML, either the current selection, or the entire document:

import xml.dom.minidom as md

def pretty_xml(x):
    """Make xml string `x` nicely formatted."""
    # Hat tip to http://code.activestate.com/recipes/576750/
    new_xml = md.parseString(x.strip()).toprettyxml(indent=' '*2)
    return '\n'.join([line for line in new_xml.split('\n') if line.strip()])

def filter_selection_or_document(fn):
    """Filter the current selection, or if none, the entire document.
    
    `fn` is a function taking text and returning text.
    
    """
    the_sel = komodo.editor.selText
    if not the_sel:
        komodo.editor.selectAll()
        the_sel = komodo.editor.selText
    
    komodo.editor.replaceSel(fn(the_sel))

filter_selection_or_document(pretty_xml)

Unfortunately, the Komodo scripting docs are not great: they are fairly terse, with not much introductory material to help you find your way around. And the Python bindings are step-children: you have to read about JavaScript, then translate to Python in your head.

But you can call into the extensive Python standard library to get done what you need done, so the power is there. I also made a JSON prettifier by using this filter function in the above code:

def pretty_json(j):
    """Make JSON prettier."""
    return json.dumps(json.loads(j), indent=2)

Comments

[gravatar]
Dave 9:49 AM on 14 Feb 2012

Thanks for this, worked nicely. One thing you didn't mention is how to add it, for the benefit of anyone else who was unsure like I was: Toolbox > Add > New Macro... Then choose python as the type and paste the code in. Save and you can now access it via the Toolbox menu.

[gravatar]
Javier Mata 4:54 AM on 21 Nov 2012

Thanks for this. It's brilliant! Just a note about the json script for the benefit of others:

To make the script for json:

- replace the function pretty_xml in the first script above with pretty_json (i.e. the 2nd script above)
- add import json at the top of your script
- change the variable name - either 'x' to 'j' or 'j' to 'x'

[gravatar]
peter2108 10:09 AM on 24 Apr 2013

Many thanks

Add a comment:

Ignore this:
Leave this empty:
Name is required. Either email or web are required. Email won't be displayed and I won't spam you. Your web site won't be indexed by search engines.
Don't put anything here:
Leave this empty:
URLs auto-link and some tags are allowed: <a><b><i><p><br><pre>.