1 """
2 This module contains data structures used in translation of the
3 Doconce format to other formats. Some convenience functions used in
4 translation modules (latex.py, html.py, etc.) are also included in
5 here.
6 """
7 import re, sys
8
9
10 _CODE_BLOCK = '<<<!!CODE_BLOCK'
11 _MATH_BLOCK = '<<<!!MATH_BLOCK'
12
14 """
15 Return the location where the doconce package is installed.
16 """
17
18 import os
19 return os.path.dirname(__file__)
20
22 """
23 Indent each line in the string text, provided in a format for
24 HTML, LaTeX, epytext, ..., by the blank string indentation.
25 Return new version of text.
26 """
27 if format == 'epytext':
28
29
30
31
32 if re.search(r'\\n', text):
33 comment_out = True
34 text = """\
35
36 NOTE: A verbatim block has been removed because
37 it causes problems for Epytext.
38 """
39 return text
40
41
42 text = '\n'.join([indentation + line for line in text.splitlines()])
43 return text
44
45
47 """Return max width of each column."""
48 column_list = []
49 for i, row in enumerate(table):
50 if row != ['horizontal rule']:
51 if not column_list:
52 column_list = [[]]*len(row)
53 for j, column in enumerate(row):
54 column_list[j].append(len(column))
55 return [max(c) for c in column_list]
56
57
59 """
60 Replace references to equations:
61 (ref{my:label}) -> Equation (my:label)
62 (ref{my:label1})-(ref{my:label2}) -> Equations (my:label1)-(my:label2)
63 (ref{my:label1}) and (ref{my:label2}) -> Equations (my:label1) and (my:label2)
64 (ref{my:label1}), (ref{my:label2}) and (ref{my:label3}) -> Equations (my:label1), (my:label2) and (ref{my:label2})
65 """
66 filestr = re.sub(r'\(ref\{(.+?)\}\)-\(ref\{(.+?)\}\)',
67 r'Equations (\g<1>)-(\g<2>)', filestr)
68 filestr = re.sub(r'\(ref\{(.+?)\}\)\s+and\s+\(ref\{(.+?)\}\)',
69 r'Equations (\g<1>) and (\g<2>)', filestr)
70 filestr = re.sub(r'\(ref\{(.+?)\}\),\s*\(ref\{(.+?)\}\)(,?)\s+and\s+\(ref\{(.+?)\}\)',
71 r'Equations (\g<1>), (\g<2>)\g<3> and (\g<4>)', filestr)
72 filestr = re.sub(r'\(ref\{(.+?)\}\)',
73 r'Equation (\g<1>)', filestr)
74 return filestr
75
77 """Replace a movie entry by a proper URL with text."""
78
79 import os, glob
80 filename = m.group('filename')
81 options = m.group('options')
82 caption = m.group('caption')
83
84
85 if ',' in options:
86 options = options.split(',')
87 else:
88 options = options.split()
89 kwargs = {}
90 for opt in options:
91 if opt.startswith('width') or opt.startswith('WIDTH'):
92 kwargs['width'] = int(opt.split('=')[1])
93 if opt.startswith('height') or opt.startswith('HEIGHT'):
94 kwargs['height'] = int(opt.split('=')[1])
95
96 if '*' in filename:
97
98
99 plotfiles = sorted(glob.glob(filename))
100 if not plotfiles:
101 print 'No plotfiles on the form', filename
102 sys.exit(1)
103 basename = os.path.basename(plotfiles[0])
104 stem, ext = os.path.splitext(basename)
105 kwargs['casename'] = stem
106 import DocWriter
107 header, jscode, form, footer = DocWriter.html_movie(plotfiles, **kwargs)
108
109 moviehtml = stem + '.html'
110 f = open(moviehtml, 'w')
111 f.write(header + jscode + form + footer)
112 f.close()
113 text = """\n%s (Movie of files `%s` in URL:"%s")\n""" % \
114 (caption, filename, moviehtml)
115 elif 'youtube.com' in filename:
116
117 filename = filename.replace('embed/', 'watch?v=')
118 text = '%s: URL:"%s"' % (caption, filename)
119 else:
120
121
122 stem = os.path.splitext(os.path.basename(filename))[0]
123 moviehtml = stem + '.html'
124 f = open(moviehtml, 'w')
125 f.write("""
126 <HTML>
127 <BODY>
128 <TITLE>Embedding movie %s in HTML</TITLE>
129 <EMBED SRC="%s" %s AUTOPLAY="TRUE" LOOP="TRUE"></EMBED>
130 <P>
131 <EM>%s</EM>
132 </P>
133 </BODY>
134 </HTML>
135 """ % (filename, filename, ' '.join(options), caption))
136 text = '%s (Movie %s: play URL:"%s")' % (caption, filename, moviehtml)
137 return text
138
140 """
141 Remove verbatim and latex (math) code blocks from the file and
142 store separately in lists (code_blocks and tex_blocks).
143 The function insert_code_and_tex will insert these blocks again.
144 """
145
146
147
148
149
150
151
152
153 code = re.compile(r'^!bc(.*?)\n(.*?)^!ec *\n', re.DOTALL|re.MULTILINE)
154
155
156
157
158 if filestr[-1] != '\n':
159 filestr = filestr + '\n'
160
161 code_blocks = [c for opt, c in code.findall(filestr)]
162
163 tex = re.compile(r'^!bt\n(.*?)^!et *\n', re.DOTALL|re.MULTILINE)
164 tex_blocks = tex.findall(filestr)
165
166
167 nbc = len(re.compile(r'^!bc', re.MULTILINE).findall(filestr))
168 nec = len(re.compile(r'^!ec', re.MULTILINE).findall(filestr))
169 nbt = len(re.compile(r'^!bt', re.MULTILINE).findall(filestr))
170 net = len(re.compile(r'^!et', re.MULTILINE).findall(filestr))
171
172 def find2(filestr, begin_pattern, end_pattern):
173 lines = filestr.splitlines()
174 begin_ends = []
175 for i, line in enumerate(lines):
176 if line.startswith(begin_pattern):
177 begin_ends.append((begin_pattern, i))
178 if line.startswith(end_pattern):
179 begin_ends.append((end_pattern, i))
180 for k in range(1, len(begin_ends)):
181 pattern, i = begin_ends[k]
182 if pattern == begin_ends[k-1][0]:
183 print '\n\nTwo', pattern, 'after each other!\n'
184 for j in range(begin_ends[k-1][1], begin_ends[k][1]+1):
185 print lines[j]
186 sys.exit(1)
187
188 if nbc != nec:
189 print '%d !bc do not match %d !ec directives' % (nbc, nec)
190 find2(filestr, '!bc', '!ec')
191 sys.exit(1)
192 if nbt != net:
193 print '%d !bt do not match %d !et directives' % (nbt, net)
194 find2(filestr, '!bt', '!et')
195 sys.exit(1)
196 if nbc != len(code_blocks):
197 print '%d !bc and %d extracted code blocks - BUG!!!' % \
198 (nbc, len(code_blocks))
199 if nbt != len(tex_blocks):
200 print '%d !bt and %d extracted tex blocks - BUG!!!' % \
201 (nbt, len(tex_blocks))
202
203
204 filestr = code.sub('%s \g<1>\n' % _CODE_BLOCK, filestr)
205 filestr = tex.sub('%s\n' % _MATH_BLOCK, filestr)
206
207
208
209
210
211 return filestr, code_blocks, tex_blocks
212
213
215 lines = filestr.splitlines()
216 for code in code_blocks:
217
218
219
220
221
222
223 for i in range(len(lines)):
224 if _CODE_BLOCK in lines[i]:
225
226 lines[i] = re.sub('%s(.*)' % _CODE_BLOCK,
227 '!bc\g<1>\n!XX&XX', lines[i])
228
229 try:
230
231
232 lines[i] = lines[i].replace('!XX&XX', '%s!ec' % code)
233 except UnicodeDecodeError, e:
234 raise UnicodeDecodeError(e + '\nproblem with code block:\n' + code)
235 break
236 for tex in tex_blocks:
237
238
239
240
241
242 if format == 'latex' or format == 'pdflatex':
243
244
245
246
247 filestr = re.sub(r'([^\\])label\{', r'\g<1>\label{', filestr)
248 filestr = re.sub(r'([^\\])ref\{', r'\g<1>\\ref{', filestr)
249
250 for i in range(len(lines)):
251 if _MATH_BLOCK in lines[i]:
252 lines[i] = lines[i].replace(_MATH_BLOCK,
253 '!bt\n%s!et' % tex)
254 break
255 filestr = '\n'.join(lines)
256 return filestr
257
259 s = ''
260 if not 'heading' in exer:
261 print 'Wrong formatting of exercise, not a 3/5 === type heading'
262 print exer
263 sys.exit(1)
264
265
266 s += exer['heading'] + ' ' + exer['title'] + ' ' + exer['heading'] + '\n'
267
268 if 'label' in exer:
269 s += 'label{%s}' % exer['label'] + '\n'
270 s += '\n' + exer['text'] + '\n'
271 for hint_no in sorted(exer['hint']):
272 s += '\n' + exer['hint'][hint_no] + '\n'
273 if 'file' in exer:
274 s += '*Filename*: `%s`' % exer['file'] + '\n'
275
276 if 'solution' in exer:
277 pass
278 if 'comments' in exer:
279 s += '\n' + exer['comments']
280 return s
281
282
283
284 BLANKLINE = {}
285 FILENAME_EXTENSION = {}
286 LIST = {}
287 CODE = {}
288
289 ARGLIST = {}
290 DEFAULT_ARGLIST = {
291 'parameter': 'argument',
292 'keyword': 'keyword argument',
293 'return': 'return value(s)',
294 'instance variable': 'instance variable',
295 'class variable': 'class variable',
296 'module variable': 'module variable',
297 }
298 TABLE = {}
299 FIGURE_EXT = {}
300 CROSS_REFS = {}
301 INDEX_BIB = {}
302 INTRO = {}
303 OUTRO = {}
304 EXERCISE = {}
305
306
307
308 inline_tag_begin = r"""(?P<begin>(^|[(\s]))"""
309 inline_tag_end = r"""(?P<end>($|[.,?!;:)\s]))"""
310
311 inline_tag_before = r"""(?<=^(|[(\s])))"""
312 inline_tag_after = r"""(?=($|[.,?!;:)\s]))"""
313 _linked_files = '''\s*"(?P<url>([^"]+?\.html?|[^"]+?\.txt|[^"]+?\.pdf|[^"]+?\.f|[^"]+?\.c|[^"]+?\.cpp|[^"]+?\.cxx|[^"]+?\.py|[^"]+?\.java|[^"]+?\.pl|[^"]+?\.sh|[^"]+?\.csh|[^"]+?\.zsh|[^"]+?\.ksh|[^"]+?\.tar\.gz|[^"]+?\.tar|[^"]+?\.f77|[^"]+?\.f90|[^"]+?\.f95))"'''
314
315 INLINE_TAGS = {
316
317
318
319 'math':
320 r'%s\$(?P<subst>[^ `][^$`]*)\$%s' % \
321 (inline_tag_begin, inline_tag_end),
322
323
324 'math2':
325 r'%s\$(?P<latexmath>[^ `][^$`]*)\$\|\$(?P<puretext>[^ `][^$`]*)\$%s' % \
326 (inline_tag_begin, inline_tag_end),
327
328
329
330
331
332 'emphasize':
333 r'%s\*(?P<subst>[^ `][^*`]*)\*%s' % \
334 (inline_tag_begin, inline_tag_end),
335
336
337 'verbatim':
338 r'%s`(?P<subst>[^ ][^`]*)`%s' % \
339 (inline_tag_begin, inline_tag_end),
340
341
342 'bold':
343 r'%s_(?P<subst>[^ `][^\]_`]*)_%s' % \
344 (inline_tag_begin, inline_tag_end),
345
346
347 'citation':
348 r' cite\{(?P<subst>[^}]+)\}',
349
350
351 'linkURL':
352 r'%s(?P<url>https?://[^<\n]+)<(?P<link>[^>]+)>%s' % \
353 (inline_tag_begin, inline_tag_end),
354
355 'linkURL2':
356 r'''"(?P<link>[^"]+?)" ?:\s*"(?P<url>(file:/|https?:)//.+?)"''',
357
358
359 'linkURL2v':
360 r'''"`(?P<link>[^"]+?)`" ?:\s*"(?P<url>(file:/|https?:)//.+?)"''',
361
362 'linkURL3':
363
364 r'''"(?P<link>[^"]+?)" ?:''' + _linked_files,
365
366 'linkURL3v':
367 r'''"`(?P<link>[^"]+?)`" ?:''' + _linked_files,
368
369 'plainURL':
370
371
372 r'("URL"|"url"|URL|url) ?:\s*"(?P<url>.+?)"',
373
374 'inlinecomment':
375 r'''\[(?P<name>[A-Za-z0-9_'-]+?):\s+(?P<comment>[^\]]*?)\]''',
376
377 'abstract':
378 r"""^\s*__(?P<type>Abstract|Summary).__\s*(?P<text>.+?)(?P<rest>\s*[_=]{3,9})""",
379
380
381
382 'section':
383
384
385
386 r'^\s*[_=]{7}\s*(?P<subst>[^ =-].+?)\s*[_=]+\s*$',
387
388 'chapter':
389 r'^\s*[_=]{9}\s*(?P<subst>[^ =-].+?)\s*[_=]+\s*$',
390
391 'subsection':
392
393
394 r'^\s*[_=]{5}\s*(?P<subst>[^ =-].+?)\s*[_=]+\s*$',
395
396 'subsubsection':
397
398
399 r'^\s*[_=]{3}\s*(?P<subst>[^ =-].+?)\s*[_=]+\s*$',
400
401
402 'paragraph':
403 r'(?P<begin>^)__(?P<subst>.+?)__\s+',
404
405
406
407 'title':
408 r'^TITLE:\s*(?P<subst>.+)\s*$',
409
410
411 'author':
412
413
414 r'^AUTHOR:\s*(?P<name>.+?)(,|\s+at\s+)(?P<institution>.+)\s*$',
415
416
417 'date':
418 r'^DATE:\s*(?P<subst>.+)\s*$',
419
420
421 'figure':
422 r'^FIGURE:\s*\[(?P<filename>[^,\]]+),?(?P<options>[^\]]*)\]\s*?(?P<caption>.*)$',
423
424 'movie':
425 r'^MOVIE:\s*\[(?P<filename>[^,\]]+),?(?P<options>[^\]]*)\]\s*?(?P<caption>.*)$',
426 }
427 INLINE_TAGS_SUBST = {}
428
429
430 heading_error = (r'(^ [_=]+[^_=]*|^[_=]+[^ _=]*$)',
431 'Initial spaces or missing underscore(s) or = at the end')
432 INLINE_TAGS_BUGS = {
433
434 'math': (r'%s(?P<subst>\$ [^$]*\$)%s' % (inline_tag_begin, inline_tag_end),
435 'Space after first $ in inline math expressions'),
436 'emphasize': None,
437 'verbatim': (r'%s(?P<subst>` [^`]*`)%s' % \
438 (inline_tag_begin, inline_tag_end),
439 'Space after first ` in inline verbatim expressions'),
440 'bold': (r'%s(?P<subst>_ [^_]*_)%s' % \
441 (inline_tag_begin, inline_tag_end),
442 'Space after first _ in inline boldface expressions'),
443 'section': heading_error,
444 'subsection': heading_error,
445 'subsubsection': heading_error,
446 'paragraph': heading_error,
447 }
448
449 LIST_SYMBOL = {'*': 'itemize', 'o': 'enumerate', '-': 'description'}
450