Skip to content

Instantly share code, notes, and snippets.

@sjmulder
Created October 26, 2012 18:53
Show Gist options
  • Save sjmulder/3960693 to your computer and use it in GitHub Desktop.
Save sjmulder/3960693 to your computer and use it in GitHub Desktop.
Super basic Sublime Text 2 CSS formatter
from sublime import Region
from sublime_plugin import TextCommand
class LineIndenter:
def __init__(self, view, lines):
first = view.substr(lines[0])
self.lines = lines
self.base_indent = first[:len(first) - len(first.lstrip())]
self.depth = 0
def reindent_line(self, line):
print("reindenting '%s'" % line)
self.depth -= line.count("}")
indent = self.base_indent + ("\t" * self.depth)
self.depth += line.count("{")
return indent + line.lstrip()
def format_colon(line):
parts = line.split(":", 2)
if len(parts) < 2:
return line
else:
return parts[0].rstrip() + ": " + parts[1].lstrip()
class FormatCssCommand(TextCommand):
def run(self, edit):
regions = self.view.sel()
if len(regions) == 1 and regions[0].empty():
regions = [Region(0, self.view.size())]
for region in regions:
lines = self.view.lines(region)
if len(lines) == 0:
continue
indenter = LineIndenter(self.view, lines)
new_text = ""
for line_region in lines:
line = self.view.substr(line_region)
line = indenter.reindent_line(line)
line = format_colon(line)
new_text += line + "\n"
self.view.replace(edit, region, new_text)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment