Skip to content

Commit

Permalink
Support ANSI colors code blocks
Browse files Browse the repository at this point in the history
Fixes pyvec#61
  • Loading branch information
hroncok committed Mar 16, 2017
1 parent 18e8782 commit 34ae998
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 1 deletion.
11 changes: 10 additions & 1 deletion naucse/markdown_util.py
@@ -1,12 +1,16 @@
from textwrap import dedent
import re

from ansi2html import Ansi2HTMLConverter
import mistune
from jinja2 import Markup
import pygments
import pygments.lexers
import pygments.formatters.html


ansi_convertor = Ansi2HTMLConverter(inline=True)

pygments_formatter = pygments.formatters.html.HtmlFormatter(
cssclass='codehilite'
)
Expand Down Expand Up @@ -54,6 +58,8 @@ def parse_deflist(self, m):


class Renderer(mistune.Renderer):
code_tmpl = '<div class="codehilite"><pre><code>{}</code></pre></div>'

def admonition(self, name, content):
return '<div class="admonition {}">{}</div>'.format(name, content)

Expand All @@ -62,7 +68,10 @@ def block_code(self, code, lang):
lang = lang.strip()
if not lang or lang == 'plain':
escaped = mistune.escape(code)
return '<div class="codehilite"><pre><code>{}</code></pre></div>'.format(escaped)
return self.code_tmpl.format(escaped)
if lang == 'ansi':
converted = ansi_convertor.convert(code, full=False)
return self.code_tmpl.format(converted)
lexer = pygments.lexers.get_lexer_by_name(lang)
return pygments.highlight(code, lexer, pygments_formatter).strip()

Expand Down
1 change: 1 addition & 0 deletions requirements.txt
@@ -1,4 +1,5 @@
PyYAML
ansi2html
flask
elsa>=0.1.2
frozen-flask
Expand Down
32 changes: 32 additions & 0 deletions test_naucse/test_markdown.py
Expand Up @@ -91,6 +91,38 @@ def test_markdown_definition_list_advanced():
assert convert_markdown(src).strip() == expected


def test_markdown_ansi_colors():
src = dedent("""
```ansi
On branch ansicolors
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
modified: naucse/markdown_util.py
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: test_naucse/test_markdown.py
```
""")
expected = dedent("""
<div class="codehilite"><pre><code>On branch ansicolors
Changes to be committed:
(use "git reset HEAD &lt;file&gt;..." to unstage)
<span style="color: #00aa00">modified: naucse/markdown_util.py</span>
Changes not staged for commit:
(use "git add &lt;file&gt;..." to update what will be committed)
(use "git checkout -- &lt;file&gt;..." to discard changes in working directory)
<span style="color: #aa0000">modified: test_naucse/test_markdown.py</span></code></pre></div>
""").strip()
assert convert_markdown(src) == expected


def test_markdown_keeps_nbsp():
text = 'Some text\N{NO-BREAK SPACE}more text'
assert convert_markdown(text).strip() == '<p>{}</p>'.format(text)

0 comments on commit 34ae998

Please sign in to comment.