public
Created

  • Download Gist
html_export.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
#!/usr/bin/env python
#coding: utf8
#################################### IMPORTS ###################################
 
# Std Libs
import cgi
import os
import pprint
import string
import time
import webbrowser
 
from os.path import split, join, normpath, splitext
 
# Sublime Modules
import sublime
import sublime_plugin
 
# APP Libs
from plist import parse_plist
 
################################# SETTINGS #####################################
 
settings = sublime.load_settings('html-export.sublime-settings')
 
defaults = {
"open_html_in_editor" : False,
"open_html_in_browser" : True,
"copy_css_to_clipboard" : True,
"copy_html_to_clipboard" : True,
"encode_as" : "utf-8",
"add_line_numbers" : True
}
 
class Settings(object):
def __init__(self, kw):
self.kw = kw
 
def __getattr__(self, attr):
if attr in getattr(self, 'kw'): return self.kw.get(attr)
if settings.has(attr): return settings.get(attr)
else: return defaults.get(attr)
 
################################### TODO #######################################
 
"""
clean up 4 000,000 line function
 
multiple selections, for posting snippets with foo() ... bar() = DONE =
 
contract selections so there are no empty lines 4 mult-sel
 
pre tag + css to clipboard = almost DONE =
 
compress clipboard css = DONE =
 
embedded style="bla" attributes, no messing around with style
sheets for quick posts
 
in <head> css styles
 
line numbers in float:left pre tag so can easily copy paste
 
"""
 
################################# TEMPLATES ####################################
 
HTML_TEMPLATE = """<html>
<head>
<title> %s </title>
<link rel="stylesheet" href="%s.css" type="text/css" charset="utf-8" />
<style type='text/css'>
body {margin:0; padding:0;}
pre {padding: 1em; font: 12px "DejaVu Sans Mono", monospace;}
</style>
</head>
<body>
%s
</body>
</html>
"""
 
LINE_NUMBER = '<span class="lineNumber">%s</span>'
 
################################### BUILD CSS ##################################
 
CSSMAP = {
 
'background': 'background-color',
'caret': None,
'fontStyle': None,
'foreground': 'color',
'invisibles': None,
'lineHighlight': None,
'selection': None,
}
 
################################################################################
 
def camelize_string(to_camel):
to_camel = [(l if l in string.ascii_letters else ' ') for l in to_camel]
to_camel = [w.capitalize() for w in "".join(to_camel).split(' ')]
to_camel = "".join(to_camel)
 
return to_camel[:1].lower() + to_camel[1:] #sometimes to_camel will be ''
 
def create_title(input_dict):
name, author = input_dict['name'], input_dict['author']
return "Theme: %s\nAuthor: %s" % (name, author)
 
def get_css_from_tm_settings(settings):
css = {}
for rule in settings:
if rule in CSSMAP and CSSMAP[rule]:
css[CSSMAP[rule]] = settings[rule]
 
return sorted(css.items())
 
def create_rule(rule_starter, listing):
rule = rule_starter
css = get_css_from_tm_settings(listing['settings'])
for property_, value in css:
if property_ in ("background-color", 'color'):
value = value[:7]
 
rule.append(" %s: %s;" % (property_, value))
rule.append("}")
return "\n".join(rule)
 
def create_main_rule(listing, theme_name):
return create_rule(["pre.%s {" % camelize_string(theme_name)], listing)
 
def create_scope_rule(listing, theme_name):
name = camelize_string(listing['name'])
return create_rule(["pre.%s .%s {" % (camelize_string(theme_name), name)],
listing)
 
def get_css_from_theme_dict(theme):
name = theme['name']
settings = theme['settings']
main_settings = settings[0]
 
css = [create_main_rule(main_settings, name)]
 
for scope_rule in settings[1:]:
css.append(create_scope_rule(scope_rule, name))
 
css+=["pre.%s .lineNumber {\n color: #7f909f;\n}" % camelize_string(name)]
 
return "\n\n".join(css)
 
def get_scopes(theme):
scopes = {}
 
for scope in theme["settings"][1:]:
if 'scope' in scope:
scopes[scope['scope']] = camelize_string(scope['name'])
return tuple(scopes.items())
 
#################################### HELPERS ###################################
 
def memoize(func):
"Implementation taken from python test suite"
saved = {}
def call(*args):
try:
return saved[args]
except KeyError:
res = func(*args)
saved[args] = res
return res
except TypeError:
# Unhashable argument
return func(*args)
call.func_name = func.func_name
return call
 
def write_html(html, fn, theme):
with open('%s.html' % fn, 'w') as fh:
html = HTML_TEMPLATE % (fn, camelize_string(theme), html)
fh.write(html.encode(settings.get('encode_as')))
 
return '%s.html' % fn #TODO: refactor
 
def get_theme_name(color_scheme):
return splitext(split(color_scheme)[1])[0]
 
def get_theme_abs_path(color_scheme):
appdata_path = split(sublime.packages_path())[0]
return normpath(join(appdata_path, color_scheme))
 
@memoize
def get_css_rules(color_scheme):
rules = get_scopes(parse_plist(get_theme_abs_path(color_scheme)))
sublime.set_clipboard(pprint.pformat(rules))
return rules
 
def get_view_css(view):
color_scheme = view.settings().get('color_scheme')
# theme = get_theme_name(color_scheme)
return get_css_rules(color_scheme)
 
def write_css(color_scheme, wd=None):
theme = camelize_string(get_theme_name(color_scheme))
theme_p_list = get_theme_abs_path(color_scheme)
css = get_css_from_theme_dict(parse_plist(theme_p_list))
 
with open(os.path.join(wd, "%s.css" % theme), 'w') as fh:
fh.write(css.encode(settings.get('encode_as')))
 
return css #TODO fix this
 
def selections_or_full_buffer_if_empty(view):
if view.has_non_empty_selection_region():
return [view.line(s) for s in view.sel()]
else:
return [sublime.Region(0, view.size())]
 
################################# COMMANDS #####################################
 
def scope_events(view, rng=None):
rng = rng or xrange(0, view.size())
opened = []
 
for pt in rng:
scope = view.scope_name(pt).rstrip()
ch = view.substr(pt)
 
for i, (os, ss) in enumerate(map(None, opened, scope.split())):
if not ss or os != ss:
for ev in opened[i:]:
yield (pt, 'close', os)
 
del opened[i:]
 
if ss and (not os or os != ss):
opened.append(ss)
yield (pt, 'open', ' '.join(opened))
 
yield (pt, 'char', ch)
 
# close up shop
for p in opened:
yield (pt, 'close', None)
 
def sort_by_selector ( scope,
to_sort,
selector_index=0,
keep_non_matches=True ):
candidates =[]
 
for i, item in enumerate(to_sort):
selector = item[selector_index]
specificity = sublime.score_selector(scope, selector )
 
if specificity or keep_non_matches:
candidates.append((specificity, i ))
 
return [to_sort[i[1]] for i in sorted( candidates,
key=lambda c: c[0], reverse=True)]
 
@memoize
def css_class_for_scope(scope, color_scheme):
css_rules = get_css_rules(color_scheme)
candidates = sort_by_selector( scope, css_rules, keep_non_matches=False)
 
if candidates:
return candidates[0][1]
 
class HtmlExportCommand(sublime_plugin.TextCommand):
def run(self, edit, **kw):
view = self.view
t = time.time()
s = Settings(kw)
 
# Perf boost?
add_line_numbers = s.add_line_numbers
copy_css_to_clipboard = s.copy_css_to_clipboard
copy_html_to_clipboard = s.copy_html_to_clipboard
open_html_in_browser = s.open_html_in_browser
open_html_in_editor = s.open_html_in_editor
 
color_scheme = view.settings().get('color_scheme')
theme = get_theme_name(color_scheme)
 
html = ["<pre class='%s'>" % camelize_string(theme)]
selections = selections_or_full_buffer_if_empty(view)
ln_cols = len(`view.rowcol(selections[-1].end()-1)[0]`)
 
for i, sel in enumerate(selections):
if i > 0: html += [LINE_NUMBER % ("\n\n%s\n\n" % (ln_cols * '.'))]
 
if add_line_numbers:
current_line_number = view.rowcol(sel.begin())[0] + 1
line_numbers_template = LINE_NUMBER % ("%"+ `ln_cols` + "d ")
 
html += [line_numbers_template % current_line_number]
 
for pt, event, value in scope_events(view, xrange(sel.begin(), sel.end())):
if event == 'open':
kls = css_class_for_scope(value, color_scheme)
html.append("<span class='%s'>" % kls)
 
elif event == 'close':
html.append("</span>")
 
else: # event == 'char'
html.append(cgi.escape(value))
 
if add_line_numbers and value == '\n':
current_line_number += 1
html += [line_numbers_template % current_line_number]
 
html = "".join(html + ["</pre>"])
 
sublime.status_message (
"HTML and CSS conversion complete: %s " % (time.time() -t) )
 
write_out_html = open_html_in_editor or open_html_in_browser
 
if write_out_html:
html_file = write_html(html, view.file_name(), theme) # HACK TODO
 
css_string = write_css(color_scheme, wd=os.path.dirname(
str(view.file_name())))
 
if open_html_in_browser: webbrowser.open(html_file)
if open_html_in_editor: view.window().open_file(html_file)
 
clipboard = ''
if copy_css_to_clipboard:
# compress the css
css = ' '.join([l.strip('\n') for l in css_string.split('\n')])
clipboard += ' '.join([w.strip(' ') for w in css.split(' ')]) + '\n'
 
if copy_html_to_clipboard: clipboard += html
if clipboard:
sublime.set_clipboard(clipboard)
 
################################################################################

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.