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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
|
#!/usr/bin/python3
#
# Call pandoc to convert markdown to docbook, then expand gtk-doc
# abbreviations (|[ ]|, function(), #object, %constant, etc)
import sys
import re
import tempfile
import os.path
import subprocess
# The following code is taken from gtk-doc
def ExpandAbbreviations(symbol, text):
# Convert '@param()'
text = re.sub(r'(\A|[^\\])\@(\w+((\.|->)\w+)*)\s*\(\)', r'\1<parameter>\2()</parameter>', text)
# Convert 'function()' or 'macro()'.
# if there is abc_*_def() we don't want to make a link to _def()
# FIXME: also handle abc(def(....)) : but that would need to be done recursively :/
def f1(m):
return m.group(1) + MakeXRef(m.group(2), tagify(m.group(2) + "()", "function"))
text = re.sub(r'([^\*.\w])(\w+)\s*\(\)', f1, text)
# handle #Object.func()
text = re.sub(r'(\A|[^\\])#([\w\-:\.]+[\w]+)\s*\(\)', f1, text)
# Convert '@param', but not '\@param'.
text = re.sub(r'(\A|[^\\])\@(\w+((\.|->)\w+)*)', r'\1<parameter>\2</parameter>', text)
text = re.sub(r'/\\\@', r'\@', text)
# Convert '%constant', but not '\%constant'.
# Also allow negative numbers, e.g. %-1.
def f2(m):
return m.group(1) + MakeXRef(m.group(2), tagify(m.group(2), "literal"))
text = re.sub(r'(\A|[^\\])\%(-?\w+)', f2, text)
text = re.sub(r'\\\%', r'\%', text)
# Convert '#symbol', but not '\#symbol'.
# Only convert #foo after a space to avoid interfering with
# fragment identifiers in urls
def f3(m):
return m.group(1) + MakeHashXRef(m.group(2), "type")
text = re.sub(r'(\A|[ ])#([\w\-:\.]+[\w]+)', f3, text)
text = re.sub(r'\\#', '#', text)
return text
# Standard C preprocessor directives, which we ignore for '#' abbreviations.
PreProcessorDirectives = {
'assert', 'define', 'elif', 'else', 'endif', 'error', 'if', 'ifdef', 'ifndef',
'include', 'line', 'pragma', 'unassert', 'undef', 'warning'
}
def MakeHashXRef(symbol, tag):
text = symbol
# Check for things like '#include', '#define', and skip them.
if symbol in PreProcessorDirectives:
return "#%s" % symbol
# Get rid of special suffixes ('-struct','-enum').
text = re.sub(r'-struct$', '', text)
text = re.sub(r'-enum$', '', text)
# If the symbol is in the form "Object::signal", then change the symbol to
# "Object-signal" and use "signal" as the text.
if '::' in symbol:
o, s = symbol.split('::', 1)
symbol = '%s-%s' % (o, s)
text = u'“' + s + u'”'
# If the symbol is in the form "Object:property", then change the symbol to
# "Object--property" and use "property" as the text.
if ':' in symbol:
o, p = symbol.split(':', 1)
symbol = '%s--%s' % (o, p)
text = u'“' + p + u'”'
if tag != '':
text = tagify(text, tag)
return MakeXRef(symbol, text)
def MakeXRef(symbol, text=None):
"""This returns a cross-reference link to the given symbol.
Though it doesn't try to do this for a few standard C types that it knows
won't be in the documentation.
Args:
symbol (str): the symbol to try to create a XRef to.
text (str): text to put inside the XRef, defaults to symbol
Returns:
str: a docbook link
"""
symbol = symbol.strip()
if not text:
text = symbol
# Get rid of special suffixes ('-struct','-enum').
text = re.sub(r'-struct$', '', text)
text = re.sub(r'-enum$', '', text)
if ' ' in symbol:
return text
symbol_id = CreateValidSGMLID(symbol)
return "<link linkend=\"%s\">%s</link>" % (symbol_id, text)
def CreateValidSGMLID(xml_id):
"""Creates a valid SGML 'id' from the given string.
According to http://www.w3.org/TR/html4/types.html#type-id "ID and NAME
tokens must begin with a letter ([A-Za-z]) and may be followed by any number
of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"),
and periods (".")."
When creating SGML IDS, we append ":CAPS" to all all-caps identifiers to
prevent name clashes (SGML ids are case-insensitive). (It basically never is
the case that mixed-case identifiers would collide.)
Args:
id (str): The text to be converted into a valid SGML id.
Returns:
str: The converted id.
"""
# Special case, '_' would end up as '' so we use 'gettext-macro' instead.
if xml_id == '_':
return "gettext-macro"
xml_id = re.sub(r'[,;]', '', xml_id)
xml_id = re.sub(r'[_ ]', '-', xml_id)
xml_id = re.sub(r'^-+', '', xml_id)
xml_id = xml_id.replace('::', '-')
xml_id = xml_id.replace(':', '--')
# Append ":CAPS" to all all-caps identifiers
# FIXME: there are some inconsistencies here, we have index files containing e.g. TRUE--CAPS
if xml_id.isupper() and not xml_id.endswith('-CAPS'):
xml_id += ':CAPS'
return xml_id
def tagify(text, elem):
# Adds a tag around some text.
# e.g tagify("Text", "literal") => "<literal>Text</literal>".
return '<' + elem + '>' + text + '</' + elem + '>'
# End of gtk-doc excerpts
MarkdownExtensions = {
'-auto_identifiers', # we use explicit identifiers where needed
'+header_attributes', # for explicit identifiers
'+blank_before_header', # helps with gtk-doc #Object abbreviations
'+compact_definition_lists', # to replace <variablelist>
'+pipe_tables',
'+backtick_code_blocks', # to replace |[ ]|
'+fenced_code_attributes', # to add language annotations
'-raw_html', # to escape literal tags like <child> in input
'+startnum', # to have interrupted lists in the q&a part
}
def ConvertToDocbook(infile, outfile):
basename = os.path.basename(infile)
if basename.startswith('section'):
division='section'
else:
division='chapter'
input_format = "markdown" + "".join(MarkdownExtensions)
output_format = "docbook"
subprocess.check_call(["pandoc", infile, "-o", outfile,
"--from=" + input_format,
"--to=" + output_format,
"--standalone",
"--top-level-division=" + division])
def ExpandGtkDocAbbreviations(infile, outfile):
contents = open(infile, 'r', encoding='utf-8').read()
with open(outfile, 'w', encoding='utf-8') as out:
out.write(ExpandAbbreviations("file", contents))
if __name__ == '__main__':
tmp = tempfile.mktemp()
ConvertToDocbook(sys.argv[1], tmp)
ExpandGtkDocAbbreviations(tmp, sys.argv[2])
os.remove(tmp)
|