Debian Codegraph @

doc/mklatex.py

raw
1 # The script builds the LaTeX documentation.
2 # Testing:
3 # python mklatex.py latex .. 1.0
4
5 from docstructure import SITE_STRUCTURE, BASENAME_MAP
6 import os, shutil, re, sys, datetime
7
8 TARGET_FILE = "lxmldoc.tex"
9
10 RST2LATEX_OPTIONS = " ".join([
11 # "--no-toc-backlinks",
12 "--strip-comments",
13 "--language en",
14 # "--date",
15 # "--use-latex-footnotes",
16 "--use-latex-citations",
17 "--use-latex-toc",
18 "--font-encoding=T1",
19 "--output-encoding=utf-8",
20 "--input-encoding=utf-8",
21 "--graphicx-option=pdftex",
22 ])
23
24 htmlnsmap = {"h" : "http://www.w3.org/1999/xhtml"}
25
26 replace_invalid = re.compile(r'[-_/.\s\\]').sub
27 replace_content = re.compile(r"\{[^\}]*\}").sub
28
29 replace_epydoc_macros = re.compile(r'(,\s*amssymb|dvips\s*,\s*)').sub
30 replace_rst_macros = re.compile(r'(\\usepackage\{color}|\\usepackage\[[^]]*]\{hyperref})').sub
31
32 BASENAME_MAP = BASENAME_MAP.copy()
33 BASENAME_MAP.update({'api' : 'lxmlapi'})
34
35 # LaTeX snippets
36
37 DOCUMENT_CLASS = r"""
38 \documentclass[10pt,english]{report}
39 \usepackage[a4paper]{geometry}
40 \usepackage{tabularx}
41 \usepackage{ifthen}
42 \usepackage[pdftex]{graphicx}
43 \parindent0pt
44 \parskip1ex
45
46 %%% Fallback definitions for Docutils-specific commands
47
48 % providelength (provide a length variable and set default, if it is new)
49 \providecommand*{\DUprovidelength}[2]{
50 \ifthenelse{\isundefined{#1}}{\newlength{#1}\setlength{#1}{#2}}{}
51 }
52
53 % docinfo (width of docinfo table)
54 \DUprovidelength{\DUdocinfowidth}{0.9\textwidth}
55
56 % titlereference role
57 \providecommand*{\DUroletitlereference}[1]{\textsl{#1}}
58
59 """
60
61 PYGMENTS_IMPORT = r"""
62 \usepackage{fancyvrb}
63 \input{_part_pygments.tex}
64 """
65
66 EPYDOC_IMPORT = r"""
67 \input{_part_epydoc.tex}
68 """
69
70 def write_chapter(master, title, filename):
71 filename = os.path.join(os.path.dirname(filename),
72 "_part_%s" % os.path.basename(filename))
73 master.write(r"""
74 \chapter{%s}
75 \label{%s}
76 \input{%s}
77 """ % (title, filename, filename))
78
79
80 # the program ----
81
82 def rest2latex(script, source_path, dest_path):
83 command = ('%s %s %s %s > %s' %
84 (sys.executable, script, RST2LATEX_OPTIONS,
85 source_path, dest_path))
86 os.system(command)
87
88 def build_pygments_macros(filename):
89 from pygments.formatters import LatexFormatter
90 text = LatexFormatter().get_style_defs()
91 with open(filename, "w") as f:
92 f.write(text)
93 f.write('\n')
94
95 def copy_epydoc_macros(src, dest, existing_header_lines):
96 doc = open(src, 'r')
97 out = open(dest, "w")
98 for line in doc:
99 if line.startswith('%% generator') \
100 or line.startswith('% generated by ') \
101 or '\\begin{document}' in line \
102 or '\\makeindex' in line:
103 break
104 if line.startswith('%') or \
105 r'\documentclass' in line or \
106 r'\makeindex' in line or \
107 r'{inputenc}' in line:
108 continue
109 if line.startswith(r'\usepackage'):
110 if line in existing_header_lines:
111 continue
112 if '{hyperref}' in line:
113 line = line.replace('black', 'blue')
114 out.write( replace_epydoc_macros('', line) )
115 out.close()
116 doc.close()
117
118 def noop(input):
119 return input
120
121 counter_no = 0
122
123 def tex_postprocess(src_path, dest_path, want_header=False, process_line=noop):
124 """
125 Postprocessing of the LaTeX file generated from ReST.
126
127 Reads file src_path and saves to dest_path only the true content
128 (without the document header and final) - so it is suitable
129 to be used as part of the longer document.
130
131 Returns the title of document
132
133 If want_header is set, returns also the document header (as
134 the list of lines).
135 """
136 header = []
137 add_header_line = header.append
138 global counter_no
139 counter_no = counter_no + 1
140 counter_text = "listcnt%d" % counter_no
141
142 search_title = re.compile(r'\\title{([^{}]*(?:{[^}]*})*)}').search
143 skipping = re.compile(r'(\\end{document}|\\tableofcontents|^%)').search
144
145 with open(src_path) as src:
146 src_text = src.read()
147
148 dest = open(dest_path, "w")
149
150 title = search_title(src_text)
151 if title:
152 # remove any commands from the title
153 title = re.sub(r'\\\w+({[^}]*})?', '', title.group(1))
154
155 iter_lines = iter(src_text.splitlines())
156 for l in iter_lines:
157 l = process_line(l)
158 if not l:
159 continue
160 if want_header:
161 add_header_line(replace_rst_macros('', l))
162 if l.startswith("\\maketitle"):
163 break
164
165 for l in iter_lines:
166 l = process_line(l)
167 if skipping(l):
168 # To-Do minitoc instead of tableofcontents
169 continue
170 elif r"\hypertarget{old-versions}" in l:
171 break
172 elif "listcnt0" in l:
173 l = l.replace("listcnt0", counter_text)
174 dest.write(l + '\n')
175
176 dest.close()
177
178 if not title:
179 raise Exception("Bueee, no title in %s" % src_path)
180 return title, header
181
182 def publish(dirname, lxml_path, release):
183 if not os.path.exists(dirname):
184 os.mkdir(dirname)
185
186 book_title = "lxml %s" % release
187
188 doc_dir = os.path.join(lxml_path, 'doc')
189 script = os.path.join(doc_dir, 'rest2latex.py')
190 pubkey = os.path.join(doc_dir, 'pubkey.asc')
191
192 shutil.copy(pubkey, dirname)
193
194 # build pygments macros
195 build_pygments_macros(os.path.join(dirname, '_part_pygments.tex'))
196
197 # Used in postprocessing of generated LaTeX files
198 header = []
199 titles = {}
200
201 replace_interdoc_hyperrefs = re.compile(
202 r'\\href\{([^/}]+)[.]([^./}]+)\}').sub
203 replace_docinternal_hyperrefs = re.compile(
204 r'\\href\{\\#([^}]+)\}').sub
205 replace_image_paths = re.compile(
206 r'^(\\includegraphics{)').sub
207 def build_hyperref(match):
208 basename, extension = match.groups()
209 outname = BASENAME_MAP.get(basename, basename)
210 if '#' in extension:
211 anchor = extension.split('#')[-1]
212 return r"\hyperref[%s]" % anchor
213 elif extension != 'html':
214 return r'\href{https://lxml.de/%s.%s}' % (
215 outname, extension)
216 else:
217 return r"\hyperref[_part_%s.tex]" % outname
218 def fix_relative_hyperrefs(line):
219 line = replace_image_paths(r'\1../html/', line)
220 if r'\href' not in line:
221 return line
222 line = replace_interdoc_hyperrefs(build_hyperref, line)
223 return replace_docinternal_hyperrefs(r'\\hyperref[\1]', line)
224
225 # Building pages
226 for section, text_files in SITE_STRUCTURE:
227 for filename in text_files:
228 if filename.startswith('@'):
229 continue
230 #page_title = filename[1:]
231 #url = href_map[page_title]
232 #build_menu_entry(page_title, url, section_head)
233
234 basename = os.path.splitext(os.path.basename(filename))[0]
235 basename = BASENAME_MAP.get(basename, basename)
236 outname = basename + '.tex'
237 outpath = os.path.join(dirname, outname)
238 path = os.path.join(doc_dir, filename)
239
240 print("Creating %s" % outname)
241 rest2latex(script, path, outpath)
242
243 final_name = os.path.join(dirname, os.path.dirname(outname),
244 "_part_%s" % os.path.basename(outname))
245
246 title, hd = tex_postprocess(outpath, final_name,
247 want_header = not header,
248 process_line=fix_relative_hyperrefs)
249 if not header:
250 header = hd
251 titles[outname] = title
252
253 # integrate generated API docs
254
255 print("Integrating API docs")
256 apidocsname = 'lxmlapi.tex'
257 apipath = os.path.join(dirname, apidocsname)
258 tex_postprocess(apipath, os.path.join(dirname, "_part_%s" % apidocsname),
259 process_line=fix_relative_hyperrefs)
260 copy_epydoc_macros(apipath, os.path.join(dirname, '_part_epydoc.tex'),
261 set(header))
262
263 # convert CHANGES.txt
264
265 print("Integrating ChangeLog")
266 find_version_title = re.compile(
267 r'(.*\\section\{)([0-9][^\} ]*)\s+\(([^)]+)\)(\}.*)').search
268 def fix_changelog(line):
269 m = find_version_title(line)
270 if m:
271 line = "%sChanges in version %s, released %s%s" % m.groups()
272 else:
273 line = line.replace(r'\subsection{', r'\subsection*{')
274 return line
275
276 chgname = 'changes-%s.tex' % release
277 chgpath = os.path.join(dirname, chgname)
278 rest2latex(script,
279 os.path.join(lxml_path, 'CHANGES.txt'),
280 chgpath)
281 tex_postprocess(chgpath, os.path.join(dirname, "_part_%s" % chgname),
282 process_line=fix_changelog)
283
284 # Writing a master file
285 print("Building %s\n" % TARGET_FILE)
286 master = open( os.path.join(dirname, TARGET_FILE), "w")
287 for hln in header:
288 if hln.startswith(r"\documentclass"):
289 #hln = hln.replace('article', 'book')
290 hln = DOCUMENT_CLASS + EPYDOC_IMPORT
291 elif hln.startswith(r"\begin{document}"):
292 # pygments and epydoc support
293 master.write(PYGMENTS_IMPORT)
294 elif hln.startswith(r"\title{"):
295 hln = replace_content(
296 r'{%s\\\\\\vspace{1cm}\\includegraphics[width=2.5cm]{../html/tagpython-big.png}}' % book_title, hln)
297 elif hln.startswith(r"\date{"):
298 hln = replace_content(
299 r'{%s}' % datetime.date.today().isoformat(), hln)
300 elif hln.startswith("pdftitle"):
301 hln = replace_content(
302 r'{%s}' % book_title, hln)
303 master.write(hln + '\n')
304
305 master.write("\\setcounter{page}{2}\n")
306 master.write("\\tableofcontents\n")
307
308 for section, text_files in SITE_STRUCTURE:
309 master.write("\n\n\\part{%s}\n" % section)
310 for filename in text_files:
311 if filename.startswith('@'):
312 continue
313 #print "Not yet implemented: %s" % filename[1:]
314 #page_title = filename[1:]
315 #url = href_map[page_title]
316 #build_menu_entry(page_title, url, section_head)
317 else:
318 basename = os.path.splitext(os.path.basename(filename))[0]
319 basename = BASENAME_MAP.get(basename, basename)
320 outname = basename + '.tex'
321 write_chapter(master, titles[outname], outname)
322
323 master.write("\\appendix\n")
324 master.write("\\begin{appendix}\n")
325
326 write_chapter(master, "Changes", chgname)
327 write_chapter(master, "Generated API documentation", apidocsname)
328
329 master.write("\\end{appendix}\n")
330 master.write("\\end{document}\n")
331
332
333 if __name__ == '__main__':
334 publish(sys.argv[1], sys.argv[2], sys.argv[3])