Skip to content

Commit

Permalink
Format all file if there are no selection regions
Browse files Browse the repository at this point in the history
  • Loading branch information
Your Name committed Nov 20, 2011
1 parent ecc0ab5 commit 075520b
Showing 1 changed file with 27 additions and 18 deletions.
45 changes: 27 additions & 18 deletions indentxml.py
Expand Up @@ -14,9 +14,6 @@ def is_enabled(self):
view = self.view
if view == None:
return False
regionset = view.sel()
if len(regionset) == 0 or len(regionset[0]) == 0:
return False
syntax = view.settings().get('syntax')
language = basename(syntax).replace('.tmLanguage', '').lower() if syntax != None else "plain text"
return ((language == "xml") or (language == "plain text"))
Expand All @@ -26,18 +23,30 @@ def run(self, edit):
Main plugin logic for the 'indentxml' command.
"""
view = self.view
for region in view.sel():
if not region.empty():
s = view.substr(region)
# convert to plain string without indents and spaces
s = re.compile('>\s+([^\s])', re.DOTALL).sub('>\g<1>', s)
# replace tags to convince minidom process cdata as text
s = s.replace('<![CDATA[', '%CDATAESTART%').replace(']]>', '%CDATAEEND%')
s = parseString(s).toprettyxml()
# remove line breaks
s = re.compile('>\n\s+([^<>\s].*?)\n\s+</', re.DOTALL).sub('>\g<1></', s)
# restore cdata
s = s.replace('%CDATAESTART%', '<![CDATA[').replace('%CDATAEEND%', ']]>')
# remove xml header
s = s.replace("<?xml version=\"1.0\" ?>", "").strip()
view.replace(edit, region, s)
regions = view.sel()
# if there are more than 1 region or region one and it's not empty
if len(regions) > 1 or not regions[0].empty():
for region in view.sel():
if not region.empty():
s = view.substr(region)
s = self.indentxml(s)
view.replace(edit, region, s)
else: #format all text
alltextreg = sublime.Region(0, view.size())
s = view.substr(alltextreg)
s = self.indentxml(s)
view.replace(edit, alltextreg, s)

def indentxml(self, s):
# convert to plain string without indents and spaces
s = re.compile('>\s+([^\s])', re.DOTALL).sub('>\g<1>', s)
# replace tags to convince minidom process cdata as text
s = s.replace('<![CDATA[', '%CDATAESTART%').replace(']]>', '%CDATAEEND%')
s = parseString(s).toprettyxml()
# remove line breaks
s = re.compile('>\n\s+([^<>\s].*?)\n\s+</', re.DOTALL).sub('>\g<1></', s)
# restore cdata
s = s.replace('%CDATAESTART%', '<![CDATA[').replace('%CDATAEEND%', ']]>')
# remove xml header
s = s.replace("<?xml version=\"1.0\" ?>", "").strip()
return s

0 comments on commit 075520b

Please sign in to comment.