| 1 |
|
| 2 |
|
| 3 |
import re |
| 4 |
|
| 5 |
from docutils import nodes |
| 6 |
from pygments.filter import simplefilter |
| 7 |
from pygments.token import Comment, Token |
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
Annotation = Comment.Annotation |
| 12 |
|
| 13 |
|
| 14 |
annotation_pat = re.compile('(\\(\\w+\\))') |
| 15 |
|
| 16 |
|
| 17 |
@simplefilter |
| 18 |
def annotation_filter(self, lexer, stream, options): |
| 19 |
"""Pygments filter for annotations in comments.""" |
| 20 |
for ttype, value in stream: |
| 21 |
if ttype is Comment: |
| 22 |
tokens = annotation_pat.split(value) |
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
if len(tokens) == 3: |
| 29 |
|
| 30 |
if not tokens[0][1:].strip() and not tokens[-1].strip(): |
| 31 |
yield Annotation, tokens[1][1:-1] |
| 32 |
continue |
| 33 |
|
| 34 |
for idx, token in enumerate(tokens): |
| 35 |
yield ((ttype, token) if idx % 2 == 0 else |
| 36 |
(Annotation, token[1:-1])) |
| 37 |
continue |
| 38 |
yield ttype, value |
| 39 |
|
| 40 |
|
| 41 |
class annotation(nodes.reference): |
| 42 |
pass |
| 43 |
|
| 44 |
|
| 45 |
def annotation_role(name, rawtext, text, lineno, inliner, options={}, |
| 46 |
content=[]): |
| 47 |
return [annotation(rawtext, text)], [] |
| 48 |
|
| 49 |
|
| 50 |
def visit_annotation_html(self, node): |
| 51 |
|
| 52 |
|
| 53 |
self.body.append('<span class="highlight"><span class="c-Annotation">') |
| 54 |
|
| 55 |
|
| 56 |
def depart_annotation_html(self, node): |
| 57 |
self.body.append('</span></span>') |
| 58 |
|
| 59 |
|
| 60 |
def visit_annotation_latex(self, node): |
| 61 |
|
| 62 |
|
| 63 |
|
| 64 |
|
| 65 |
self.body.append( |
| 66 |
'\\raisebox{0.2ex}[0pt][0pt]{\\tt\\tiny\\PYG{c+cAnnotation}{') |
| 67 |
|
| 68 |
|
| 69 |
def depart_annotation_latex(self, node): |
| 70 |
self.body.append('}}') |
| 71 |
|
| 72 |
|
| 73 |
def setup(app): |
| 74 |
|
| 75 |
from sphinx.highlighting import PygmentsBridge, lexers |
| 76 |
lexers['python'].add_filter(annotation_filter()) |
| 77 |
|
| 78 |
|
| 79 |
app.add_node(annotation, |
| 80 |
html=(visit_annotation_html, depart_annotation_html), |
| 81 |
latex=(visit_annotation_latex, depart_annotation_latex), |
| 82 |
) |
| 83 |
app.add_role('an', annotation_role) |