Skip to content

Commit

Permalink
Prune CSS classes from output that are not used
Browse files Browse the repository at this point in the history
  • Loading branch information
cfstras committed Mar 29, 2018
1 parent fcaf9a7 commit 61f4b53
Showing 1 changed file with 11 additions and 5 deletions.
16 changes: 11 additions & 5 deletions ansi2html/converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,8 @@ def __init__(self,
self.ansi_codes_prog = re.compile('\033\\[' '([\\d;]*)' '([a-zA-z])')

def apply_regex(self, ansi):
parts = self._apply_regex(ansi)
styles_used = set()
parts = self._apply_regex(ansi, styles_used)
parts = self._collapse_cursor(parts)
parts = list(parts)

Expand All @@ -250,9 +251,9 @@ def apply_regex(self, ansi):
for i, line in enumerate(combined.split('\n'))
])

return combined
return combined, styles_used

def _apply_regex(self, ansi):
def _apply_regex(self, ansi, styles_used):
if self.escaped:
if self.latex: # Known Perl function which does this: https://tex.stackexchange.com/questions/34580/escape-character-in-latex/119383#119383
specials = OrderedDict([
Expand Down Expand Up @@ -340,6 +341,7 @@ def _apply_regex(self, ansi):
css_classes = state.to_css_classes()
if not css_classes:
continue
styles_used.update(css_classes)

if self.inline:
if self.latex:
Expand Down Expand Up @@ -393,7 +395,7 @@ def _collapse_cursor(self, parts):
def prepare(self, ansi='', ensure_trailing_newline=False):
""" Load the contents of 'ansi' into this object """

body = self.apply_regex(ansi)
body, styles = self.apply_regex(ansi)

if ensure_trailing_newline and _needs_extra_newline(body):
body += '\n'
Expand All @@ -402,6 +404,7 @@ def prepare(self, ansi='', ensure_trailing_newline=False):
'dark_bg': self.dark_bg,
'font_size': self.font_size,
'body': body,
'styles': styles,
}

return self._attrs
Expand All @@ -421,8 +424,11 @@ def convert(self, ansi, full=True, ensure_trailing_newline=False):
_template = _latex_template
else:
_template = _html_template
all_styles = get_styles(self.dark_bg, self.scheme)
used_styles = filter(lambda e: e.klass.lstrip(".") in attrs["styles"], all_styles)

return _template % {
'style' : "\n".join(map(str, get_styles(self.dark_bg, self.scheme))),
'style' : "\n".join(map(str, used_styles)),
'title' : self.title,
'font_size' : self.font_size,
'content' : attrs["body"],
Expand Down

0 comments on commit 61f4b53

Please sign in to comment.