Skip to content

Instantly share code, notes, and snippets.

@coldnebo
Created August 10, 2011 23:20
Show Gist options
  • Save coldnebo/1138554 to your computer and use it in GitHub Desktop.
Save coldnebo/1138554 to your computer and use it in GitHub Desktop.
simple scripts to prettify your xml and json in sublime text 2
[
{ "keys": ["ctrl+shift+x"], "command": "tidy_xml" },
{ "keys": ["ctrl+shift+j"], "command": "prettify_json" }
]
import sublime, sublime_plugin, subprocess
class PrettifyJsonCommand(sublime_plugin.TextCommand):
def run(self, edit):
command = 'python -mjson.tool'
# help from http://www.sublimetext.com/forum/viewtopic.php?f=2&p=12451
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'))
# gave up trying this approach: result always has '\n' strings in it that refuse to render
#result = json.dumps( self.view.substr(self.view.sel()[0]), indent=2)
# http://code.activestate.com/recipes/65211/ seems to say that Python "ruins" non-raw strings by
# actually placing '\','n' in the friggin string unless it's marked 'raw'? Is that true? Shouldn't a string be a string
# and the raw/not raw output be a function of the runtime? Why does "print" have some magic to reescape these strings and
# yet there are no other buffer objects that seem to do it (aka StringIO or BytesIO).
if result != "":
self.view.replace(edit, self.view.sel()[0], result.decode('utf-8'))
sublime.set_timeout(self.clear,0)
else:
self.view.set_status('tidyjson', "tidyjson: "+err)
sublime.set_timeout(self.clear,10000)
def clear(self):
self.view.erase_status('tidyjson')
import sublime, sublime_plugin, subprocess
class TidyXmlCommand(sublime_plugin.TextCommand):
def run(self, edit):
command = 'tidy -xml -i -utf8 -w -q'
# help from http://www.sublimetext.com/forum/viewtopic.php?f=2&p=12451
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'))
if err != "":
self.view.set_status('tidyxml', "tidyxml: "+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('tidyxml')
@dserodio
Copy link

dserodio commented May 2, 2012

Forgive the newbie question, but how can I run this from the Command Palette instead of from a key binding?

@coldnebo
Copy link
Author

coldnebo commented May 2, 2012

@dserodio, you know, that's a really great question and I don't know the answer either. There's got to be a way to add this to the list of commands... I'll take a look when I get some time.

@dserodio
Copy link

dserodio commented May 2, 2012

@coldnebo I asked on the Sublime forums and got a very nice reply. Basically:

To add a command to the Command Palette you need define it in a .sublime-commands file.

The linked forum post contains links to the documentation and a one-liner to add this command to the Command Pallete.

@coldnebo
Copy link
Author

coldnebo commented May 3, 2012

ah, figured it was something simple. I love Sublime. Thanks for posting this!

@LIFO-nodelay
Copy link

thank you!

@jtmille3
Copy link

I've got the same CR CR LF problem. I haven't been able to figure it out. A shame.

@jtmille3
Copy link

I ended up replacing all \r\n with \n. I'm not sure if this is a windows only fix. I'll have to test on my macbook later tonight.

self.view.replace(edit, self.view.sel()[0], result.decode('utf-8').replace('\r\n', '\n'))

@jtmille3
Copy link

I also made one more tweak by replacing self.view.sel()[0] with sublime.Region(0, self.view.size()). So now I don't have to select anything and it will format my whole document. I could make this smarter so it only formats text selections when the region is not empty, but 99.9% of the time I just want to format the whole document anyways.

Thanks for the snippets mate.

@jtmille3
Copy link

See my updated gist. https://gist.github.com/3390999

@rootsical
Copy link

jtmille3's update gist sorted out carriage return problems for me on windows.. but thanks for all of this.. also i got confused and added HTMLTidy through Sublime Text 2 package control - no no no.. yes the windows binary were the right thing to download from http://tidy.sourceforge.net/#binaries and then where i put the exe file i added that location to the environment PATH variable by right clicking computer -> properties -> advanced system settings -> environment variables -> system variables -> PATH -> edit -> and adding the path to my exe in there.. on windows 7 x64.. thanks again for this it's great to have nice xml

@rootsical
Copy link

jtmille3's update gist sorted out carriage return problems for me on windows.. but thanks for all of this.. also i got confused and added HTMLTidy through Sublime Text 2 package control - no no no.. yes the windows binary were the right thing to download from http://tidy.sourceforge.net/#binaries and then where i put the exe file i added that location to the environment PATH variable by right clicking computer -> properties -> advanced system settings -> environment variables -> system variables -> PATH -> edit -> and adding the path to my exe in there.. on windows 7 x64.. thanks again for this it's great to have nice xml

@rootsical
Copy link

jtmille3's update gist sorted out carriage return problems for me on windows.. but thanks for all of this.. also i got confused and added HTMLTidy through Sublime Text 2 package control - no no no.. yes the windows binary were the right thing to download and then where i put the exe file i added that location to the environment PATH variable by right clicking computer -> properties -> advanced system settings -> environment variables -> system variables -> PATH -> edit -> and adding the path to my exe in there.. on windows 7 x64.. thanks again for this it's great to have nice xml

@rootsical
Copy link

thanks for this.. jtmille3's version sorted the carriage return problems for on windows 7 x64.. nice to have pretty xml again.. thanks!

@ShawnCarnell
Copy link

Really appreciate the time you put into this, man. Thanks.

@eulerfx
Copy link

eulerfx commented Dec 24, 2012

Thank You! Works great on Windows with http://tidy.sourceforge.net/#binaries as specified.

@dyodji
Copy link

dyodji commented Jan 25, 2013

Woot! Works great so far...thanks!

@Timetear
Copy link

Timetear commented Feb 3, 2013

Tidy actually edits CDATA value and then wrongly handles what is after it.
e.g., The following "one-lined" XML. 'y = 3;' has got 2 tabulations before and one LF after. 'x * y = ?' has got 2 tabulations.

<?xml version="1.0" encoding="utf-8"?>
<report><bob>aze<![CDATA[ x = 2;
        y = 3;
        x * y = ?]]><alice>qsd</alice></bob></report>

After running tidy_xml.py, the output is the following

<?xml version="1.0" encoding="utf-8"?>
<report>
  <bob>aze
<![CDATA[ x = 2;
                y = 3;
                x * y = ?]]>
<alice>qsd</alice></bob>
</report>

The CDATA value is not considered as a whole. The tabulations before 'y = 3;' and 'x * y = ?' are replaced with spaces from indentation.

xmllint handles that a little better, the CDATA value remains untouched, but still fail after that.

<?xml version="1.0" encoding="utf-8"?>
<report>
    <bob>aze<![CDATA[ x = 2;
        y = 3;
        x * y = ?]]><alice>qsd</alice></bob>
</report>

@rmrfboy
Copy link

rmrfboy commented Feb 19, 2013

thanks! help me a lot.

@markkhosla
Copy link

This is brilliant - thanks!

@boris-chervenkov
Copy link

🍺

@pankajwellogic
Copy link

Thanks a lot... working perfectly fine.

@thatKaran
Copy link

I'm getting 'broken pipe' error. Any ideas?

Traceback (most recent call last):
  File ".\sublime_plugin.py", line 362, in run_
  File ".\tidy_xml.py", line 10, in run
  File ".\subprocess.py", line 701, in communicate
  File ".\subprocess.py", line 911, in _communicate
IOError: [Errno 32] Broken pipe

@newthinker
Copy link

pretty_json is working, but tiny_xml isn't and there is no response when i use the key "ctrl+shift+x". i don't know why.

@newthinker
Copy link

i know, there isn't libtidy. The tool is very good and thank you very much!

@iamsilvio
Copy link

Changed Tidy xml to work with Sublime Text 3 Beta 3047
Added some error output to the console

https://gist.github.com/skat-delayed/5923717

@gree2
Copy link

gree2 commented Dec 3, 2013

nice work
thx

@rodolf0s
Copy link

nice, work perfect to me.

Thx!

@VannaDii
Copy link

Pretty JSON works great for me and installs direct and clean through Package Control.

https://sublime.wbond.net/packages/Pretty%20JSON

@ravijoshi2
Copy link

Very impressive. Thank you!

@wangyijiangshui
Copy link

It is very good , Thank you !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment