Skip to content

Instantly share code, notes, and snippets.

@GRArmstrong
Created August 21, 2013 11:06
Show Gist options
  • Save GRArmstrong/6293129 to your computer and use it in GitHub Desktop.
Save GRArmstrong/6293129 to your computer and use it in GitHub Desktop.
I came across this really useful snippet of code from http://www.bergspot.com/blog/2012/05/formatting-xml-in-sublime-text-2-xmllint/ to format XML data using the xmllint command. I've modified it to iron out bugs I had using it with Sublime Text 3 (Build 3047). To add it to Sublime, place this tidy_xml_lint.py file in your Sublime install's Pack…
[
{
"caption": "Selection",
"children": [
{
"caption": "Format",
"children": [
{
"caption": "Tidy with XML Lint",
"command": "tidy_xml_lint"
}
],
"id": "format"
}
],
"id": "selection"
}
]
import sublime
import sublime_plugin
import subprocess
class TidyXmlLintCommand(sublime_plugin.TextCommand):
def run(self, edit):
command = "XMLLINT_INDENT='\t' xmllint --format --encode utf-8 -"
# help from http://www.sublimetext.com/forum/viewtopic.php?f=2&p=12451
xmlRegion = sublime.Region(0, self.view.size())
p = subprocess.Popen(command, bufsize=-1, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, shell=True)
result, err = p.communicate(self.view.substr(self.view.sel()[0]).encode('utf-8'))
err = err.decode('utf-8')
if err != "":
print("tidy_xml_lint: Error:" + err)
self.view.set_status('xmllint', "xmllint: " + err)
sublime.set_timeout(self.clear,10000)
else:
self.view.replace(edit, self.view.sel()[0], result.decode('utf-8'))
sublime.set_timeout(self.clear,0)
def clear(self):
self.view.erase_status('xmllint')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment