Skip to content

Instantly share code, notes, and snippets.

@jtmille3 jtmille3/tidy_xml.py
Created Aug 19, 2012

Embed
What would you like to do?
Enhanced XML Formatting for Sublime Text 2
import sublime, sublime_plugin, subprocess
class TidyXmlCommand(sublime_plugin.TextCommand):
def run(self, edit):
if self.view.sel()[0].size() > 0:
self.cursor = None
for region in self.view.sel():
self.format(edit, region)
else:
self.cursor = self.view.sel()[0]
region = sublime.Region(0, self.view.size())
self.format(edit, region)
def clear(self):
self.view.erase_status('tidyxml')
def format(self, edit, region):
command = 'tidy -xml -i -utf8 -w -q'
p = subprocess.Popen(command, bufsize=-1, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, shell=True)
result, err = p.communicate(self.view.substr(region).encode('utf-8'))
if err != "":
self.view.set_status('tidyxml', "tidyxml: "+err)
sublime.set_timeout(self.clear,10000)
else:
self.view.replace(edit, self.view.line(region), result.decode('utf-8').replace('\r\n', '\n'))
sublime.set_timeout(self.clear,0)
sublime.set_timeout(self.move_cursor,1) # minor delay necessary, not sure why
def move_cursor(self):
if self.cursor != None:
self.view.sel().clear()
self.view.sel().add(self.cursor)
self.view.show(self.cursor)
@jtmille3

This comment has been minimized.

Copy link
Owner Author

commented Aug 19, 2012

Updated XML formatting plugin from https://gist.github.com/1138554.

If no selection is made it will select all and format the entire file. If formatted in this way, the cursor will be returned to it's last location after the formatting. I couldn't figure out how to make that smoother or more seamless. Still it beats scrolling through large XML's all the time.

Updated the script to handle formatting multiple selections as well.

Thank you to the original author to get me to this point.

@rootsical

This comment has been minimized.

Copy link

commented Oct 14, 2012

just wanted to say a big thank you for this.. it works a treat for me on windows.. thank you very much

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.