Debian Codegraph @

docs/ext/annotate.py

raw symbols SCIP
1 # coding=utf-8
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 # Create the annotation token.
11 Annotation = Comment.Annotation
12
13 # Regular expression pattern for annotations.
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 # Normal comments are even and labels are odd. Labels include
24 # parenthesis at start/end and are stripped by slicing with [1:-1].
25
26 # Special case for a single label in the comment: Drop the leading
27 # hash (#).
28 if len(tokens) == 3:
29 # Strip '#' from the first token.
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 # Use pygments generated css classes to highlight annotations in HTML
52 # ouput.
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 # Use pygments generated LaTeX commands to highlight annotations.
62
63 # Use a raisebox to lift annotation box a little bit, so that it appears
64 # vertically centered in line.
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 # FIXME Hack: Add our own custom filter for highlighting annotations.
75 from sphinx.highlighting import PygmentsBridge, lexers
76 lexers['python'].add_filter(annotation_filter())
77
78 # Add node and role for annotations.
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)