Skip to content

Instantly share code, notes, and snippets.

@jtmille3
Created August 19, 2012 02:08
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jtmille3/3390999 to your computer and use it in GitHub Desktop.
Save jtmille3/3390999 to your computer and use it in GitHub Desktop.
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
Copy link
Author

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
Copy link

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