Permalink
Browse files

Added a JSON prettifier command (ctrl+shift+f)

git-svn-id: http://svn.textmate.org/trunk/Bundles/JSON.tmbundle@8505 dfb7d73b-c2ec-0310-8fea-fb051d288c6d
  • Loading branch information...
1 parent 9be0a51 commit ae1f0558f01bd3b81a18d52ede07b78a77a9df6b @canadaduane canadaduane committed Nov 23, 2007
Showing with 76 additions and 0 deletions.
  1. +71 −0 Commands/Format Nicely.tmCommand
  2. +5 −0 info.plist
View
71 Commands/Format Nicely.tmCommand
@@ -0,0 +1,71 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>beforeRunningCommand</key>
+ <string>nop</string>
+ <key>command</key>
+ <string>#!/usr/bin/env ruby
+require 'strscan'
+
+def indent
+ " " * $indent * 4
+end
+
+s = StringScanner.new(STDIN.read)
+brace_stack = []
+comma_needed = false
+first_line = true
+$indent = 0
+until s.eos?
+ if s.scan(/\{/m)
+ if comma_needed then puts "," else puts end
+ comma_needed = false
+ print indent + "{"
+ first_line = false
+ $indent += 1
+ brace_stack.push "{"
+ elsif s.scan(/\}/m)
+ $indent -= 1
+ print "\n" + indent + "}"
+ if (b = brace_stack.pop) != "{"
+ puts "Expected '}' (#{brace_stack.inspect} / #{b})"
+ exit -1
+ end
+ elsif s.scan(/\[/m)
+ if comma_needed then puts "," else puts end
+ comma_needed = false
+ print indent + "["
+ $indent += 1
+ brace_stack.push "["
+ elsif s.scan(/\]/m)
+ $indent -= 1
+ print "\n" + indent + "]"
+ if (b = brace_stack.pop) != "["
+ puts "Expected ']' (#{brace_stack.inspect} / #{b})"
+ exit -2
+ end
+ elsif s.scan(/,/m)
+ comma_needed = true
+ #print "==#{brace_stack.inspect}=="
+ #puts (brace_stack.last == "{" ? "" : indent) + ","
+ else
+ if comma_needed then puts "," else puts end
+ comma_needed = false
+ print indent + s.scan(/[^{}\[\],]+/m)
+ end
+end</string>
+ <key>input</key>
+ <string>selection</string>
+ <key>keyEquivalent</key>
+ <string>^F</string>
+ <key>name</key>
+ <string>Format Nicely</string>
+ <key>output</key>
+ <string>replaceSelectedText</string>
+ <key>scope</key>
+ <string>source.json</string>
+ <key>uuid</key>
+ <string>4B74F2DE-E051-4E8D-9124-EBD90A2CDD2B</string>
+</dict>
+</plist>
View
5 info.plist
@@ -10,6 +10,11 @@
<string>Syntax highlight for &lt;a href="http://json.org/"&gt;JavaScript Object Notation&lt;/a&gt; files, often used as a lightweight serialization format.</string>
<key>name</key>
<string>JSON</string>
+ <key>ordering</key>
+ <array>
+ <string>0C3868E4-F96B-4E55-B204-1DCB5A20748B</string>
+ <string>4B74F2DE-E051-4E8D-9124-EBD90A2CDD2B</string>
+ </array>
<key>uuid</key>
<string>8BB0DBAF-E65C-4E14-A6A7-467D4AA535E0</string>
</dict>

0 comments on commit ae1f055

Please sign in to comment.