-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshort-title-for-toc.py
60 lines (44 loc) · 1.42 KB
/
short-title-for-toc.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
#!/usr/bin/env python3
"""
Usage:
Copy this code to short-title-for-toc.py
pip3 install pandocfilters
pandoc --filter ./short-title-for-toc.py
"""
from pandocfilters import toJSONFilter, RawBlock, get_value, stringify
LEVEL2TAG = {
-1: 'part',
0: 'chapter',
1: 'section',
2: 'subsection',
3: 'subsubsection',
}
def f(key, value, format, meta):
if not (format == 'latex' and key == 'Header'):
return
# get data
level, (_, classes, keyvals), _ = value # level, (ident, classes, keyvals), internal_pandoc
short, _ = get_value(keyvals, 'short')
link, _ = get_value(keyvals, 'link')
if level not in LEVEL2TAG:
raise Exception('short-title-for-toc.py: level %d not handled' % level)
tag = LEVEL2TAG[level]
# check if we should override pandoc default behavior
if not short and not link:
return
if classes:
raise Exception(
'short-title-for-toc.py: If class "short" is used, I cant handle another one (Header="%s")'
% (stringify(value))
)
# build overriden code
if short:
latextitle = '\\%s[%s]{%s}' % (tag, short, stringify(value))
else:
latextitle = '\\%s{%s}' % (tag, stringify(value))
if link:
latextitle = '\hypertarget{%s}{%s\label{%s}}' % (link, latextitle, link)
# return
return RawBlock('latex', latextitle)
if __name__ == '__main__':
toJSONFilter(f)