-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathnumenvs.py
executable file
·112 lines (80 loc) · 2.79 KB
/
numenvs.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#!/usr/bin/env python3
"""
Simple pandoc filter to create flexible environments in markdown. Style of
environments controlled via latex environment definitions or css for html.
Numbered theorem environment example:
begin-Theorem
$2+2=4$
end-Theorem
Unnumered environment:
begin+Example
This.
end+Example
The `begin` and `end` statements must be at the beginning of new paragraph.
"""
from pandocfilters import toJSONFilter, RawBlock
env_counts = {}
def html(string):
"""Return html block from string."""
return RawBlock('html', string)
def latex(string):
"""Return latex block from string."""
return RawBlock('latex', string)
def parse_env_latex(key, value):
"""Parse paragraph opening to extract environment name."""
if key == 'Para':
if len(value) >= 1:
content = value[0]['c']
if content[:6] == 'begin+' or content[:6] == 'begin-':
return 'begin', content[6:]
if content[:4] == 'end-' or content[:4] == 'end+':
return 'end', content[4:]
return '', ''
def parse_env_html(key, value):
"""Parse paragraph opening to extract environment name."""
if key == 'Para':
if len(value) >= 1:
content = value[0]['c']
if content[:6] == 'begin-':
global env_counts
name = content[6:]
if name in env_counts:
env_counts[name] += 1
else:
env_counts[name] = 1
return 'begin', name, env_counts[name]
if content[:6] == 'begin+':
name = content[6:]
return 'begin', name, None
if content[:4] == 'end-' or content[:4] == 'end+':
return 'end', content[4:], None
return '', '', None
def num_envs_latex(key, value):
"""Create numbered divs environments."""
instr, label = parse_env_latex(key, value)
if instr == 'begin':
return latex('\\begin{%s}\n' % label)
if instr == 'end':
return latex('\\end{%s}\n' % label)
def num_envs_html(key, value):
"""Create numbered divs environments."""
instr, label, num = parse_env_html(key, value)
if instr == 'begin':
if num:
title = label + ' ' + str(num)
else:
title = label
return [html('<div class="numenv %s">' % label),
html('<span class="numenv %s title">%s.</span>' % (label, title))]
if instr == 'end':
return html('</div>')
#pylint: disable=unused-argument
def num_envs(key, value, fmt, meta):
"""Select action based on format."""
if fmt == 'html5':
return num_envs_html(key, value)
if fmt == 'latex':
return num_envs_latex(key, value)
return None
if __name__ == "__main__":
toJSONFilter(num_envs)