Skip to content

Commit

Permalink
Merge pull request #28 from hartwork/issue_25
Browse files Browse the repository at this point in the history
Fix issue 25
  • Loading branch information
ralphbean committed Sep 23, 2013
2 parents 74d237c + f277f8f commit 8c77f6d
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 7 deletions.
43 changes: 36 additions & 7 deletions ansi2html/converter.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# This file is part of ansi2html
# Convert ANSI (terminal) colours and attributes to HTML
# Copyright (C) 2012 Ralph Bean <rbean@redhat.com>
# Copyright (C) 2013 Sebastian Pipping <sebastian@pipping.org>
#
# Inspired by and developed off of the work by pixelbeat and blackjack.
#
Expand Down Expand Up @@ -142,20 +143,48 @@ def _apply_regex(self, ansi):
except ValueError:
params = [0]

# Special control codes. Mutate into an explicit-color css class.
if params[0] in [38, 48]:
params = ["%i-%i" % (params[0], params[2])] + params[3:]

if 0 in params:
# Find latest reset marker
last_null_index = None
skip_after_index = -1
for i, v in enumerate(params):
if i <= skip_after_index:
continue

if v == 0:
last_null_index = i
elif v in [38, 48]:
skip_after_index = i + 2

# Process reset marker, drop everything before
if last_null_index is not None:
params = params[last_null_index + 1:]
# If the control code 0 is present, close all tags we've
# opened so far. i.e. reset all attributes
yield '</span>' * n_open
n_open = 0
continue

if not params:
continue

# Turn codes into CSS classes
css_classes = []
skip_after_index = -1
for i, v in enumerate(params):
if i <= skip_after_index:
continue

if v in [38, 48]: # 256 color mode switches
try:
css_class = 'ansi%i-%i' % (params[i], params[i + 2])
except IndexError:
continue
skip_after_index = i + 2
else:
css_class = 'ansi%d' % v
css_classes.append(css_class)

# Count how many tags we're opening
n_open += 1
css_classes = ["ansi%s" % str(p) for p in params]

if self.inline:
style = [self.styles[klass].kw for klass in css_classes if
Expand Down
8 changes: 8 additions & 0 deletions tests/test_ansi2html.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,5 +183,13 @@ def test_no_markup_lines(self):
html = Ansi2HTMLConverter().convert(test, full=False)
self.assertEqual(expected, html)

def test_issue_25(self):
sample = '\x1b[0;38;5;238;48;5;231mTEXT\x1b[0m'

html = Ansi2HTMLConverter(inline=False).convert(sample, full=False)
expected = six.u('<span class="ansi38-238 ansi48-231">TEXT</span>')

self.assertEqual(expected, html)

if __name__ == '__main__':
unittest.main()

0 comments on commit 8c77f6d

Please sign in to comment.