Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Sublime 3 xml_pp (xmltwig) based xml auto formatter.
"""
Sublime 3 xml_pp (xmltwig) based xml auto formatter.
Setup in Sublime:
- sudo apt-get install xml-twig-tools
- in Sublime go to menu: Tools -> New Plugin...
- paste this file into the editor.
- save: use the preset location (~/.config/sublime-text-3/Packages/User)
and name it exactly "xmlppformat.py".
- in Sublime go to menu: Preferences -> Key Bindings - User
- add an keybinding i.e.:
[{ "keys": ["ctrl+shift+x"], "command": "xmlppformat" }]
- go to some xml file and have fun.
"""
import sublime
import sublime_plugin
import subprocess
class XmlppformatCommand(sublime_plugin.TextCommand):
def run(self, edit):
command = "xml_pp -s indented_a"
# help from http://www.sublimetext.com/forum/viewtopic.php?f=2&p=12451
if self.view.sel()[0].empty():
xml_region = sublime.Region(0, self.view.size())
else:
xml_region = self.view.sel()[0]
proc = subprocess.Popen(
command,
bufsize=-1,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE,
shell=True
)
result, err = proc.communicate(
self.view.substr(
xml_region
).encode('utf-8')
)
if err != b"":
msg = 'ERROR in xml_pp: ' + err.decode("utf-8").strip()
msg = msg.replace('\n', ' : ')
msg = msg.replace('\r', '')
sublime.status_message(msg)
return
self.view.replace(
edit,
xml_region,
result.decode('utf-8').replace("\r", "")
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment