1
2 import re, os, sys, shutil, commands, pprint, time, glob, codecs
3 try:
4 from collections import OrderedDict
5 except ImportError:
6
7
8 OrderedDict = dict
9
10 global debug
11 debug = False
13 if debug:
14
15 global _log
16 _log = open('_doconce_debugging.log','a')
17 _log.write(out + '\n')
18 _log.close()
19
20
21 from common import *
22 import html, latex, pdflatex, rst, sphinx, st, epytext, plaintext, gwiki, mwiki, cwiki, pandoc
23 for module in html, latex, pdflatex, rst, sphinx, st, epytext, plaintext, gwiki, mwiki, cwiki, pandoc:
24
25 module.define(FILENAME_EXTENSION,
26 BLANKLINE,
27 INLINE_TAGS_SUBST,
28 CODE,
29 LIST,
30 ARGLIST,
31 TABLE,
32 EXERCISE,
33 FIGURE_EXT,
34 CROSS_REFS,
35 INDEX_BIB,
36 INTRO,
37 OUTRO)
38
41
42
43
44
45
46
47
48
50
51 pattern = re.compile(r'^ +![eb][ct]', re.MULTILINE)
52 m = pattern.search(filestr)
53 if m:
54 print '\nSyntax error: !bc/!bt/!ec/!et does not start at the beginning of the line'
55 print repr(filestr[m.start():m.start()+80])
56 sys.exit(1)
57
58 pattern = re.compile(r'[^\n:.?!,]^(!b[ct]|@@@CODE)', re.MULTILINE)
59 m = pattern.search(filestr)
60 if m:
61 print '\nSyntax error: Line before !bc/!bt/@@@CODE block\nends with wrong character (must be among [\\n:.?!, ]):'
62 print repr(filestr[m.start():m.start()+80])
63 sys.exit(1)
64
65
66
67
68 filestr2 = filestr
69 for tag in 'label', 'idx':
70 filestr2 = re.sub('%s\{.+?\}' % tag, '', filestr2)
71 pattern = re.compile(r'^#.*$', re.MULTILINE)
72 filestr2 = pattern.sub('', filestr2)
73 for linetp in '===', r'-\|', '__':
74 pattern = re.compile(r'%s\s+^(!b[ct]|@@@CODE)' % linetp,
75 re.MULTILINE)
76 m = pattern.search(filestr2)
77 if m and format in ('rst', 'plain', 'epytext', 'st'):
78 print '\nSyntax error: Must have a plain sentence before\na code block like !bc/!bt/@@@CODE, not a section/paragraph heading,\ntable, or comment:'
79 print filestr2[m.start():m.start()+80]
80 sys.exit(1)
81
82
83
84 constructions = {'comment': r'^\s*#.*?$',
85 'table': r'-\|\s*$',
86 'figure': r'^\s*FIGURE:.+$',
87 'movie': r'^\s*MOVIE:.+$',
88 }
89 for construction in constructions:
90 pattern = re.compile(r'%s\s*^(!b[ct]|@@@CODE|\s*\*)' % \
91 constructions[construction],
92 re.MULTILINE)
93 m = pattern.search(filestr)
94 if m:
95
96 print '\nSyntax error: Line before list or !bc/!bt/@@@CODE block is a %s line\nwhich will "swallow" the block in reST format.\nInsert some extra line (text) to separate the two elements.' % construction
97 print filestr[m.start():m.start()+80]
98 sys.exit(1)
99
100 matches = re.findall(r'\\cite\{.+?\}', filestr)
101 if matches:
102 print '\nWarning: found \\cite{...} (cite{...} has no backslash)'
103 print '\n'.join(matches)
104
105 matches = re.findall(r'\\idx\{.+?\}', filestr)
106 if matches:
107 print '\nWarning: found \\idx{...} (indx{...} has no backslash)'
108 print '\n'.join(matches)
109 sys.exit(1)
110
111 matches = re.findall(r'\\index\{.+?\}', filestr)
112 if matches:
113 print '\nWarning: found \\index{...} (index is written idx{...})'
114 print '\n'.join(matches)
115
116
117 matches = re.findall(r'\\label\{.+?\}', filestr)
118 if matches:
119 print '\nWarning: found \\label{...} (label{...} has no backslash)'
120 print '\n'.join(matches)
121
122 matches = re.findall(r'\\ref\{.+?\}', filestr)
123 if matches:
124 print '\nWarning: found \\ref{...} (ref{...} has no backslash)'
125 print '\n'.join(matches)
126
127
128
129 """
130 labels = re.findall(r'label\{(.+?)\}', filestr)
131 refs = re.findall(r'ref\{(.+?)\}', filestr)
132 for ref in refs:
133 if not ref in labels:
134 print '...ref{%s} has no corresponding label{%s} (within this file)' % \
135 (ref, ref)
136 """
137
138
139 inside_code = False
140 inside_math = False
141 for line in filestr.splitlines():
142 if line.startswith('!bc'):
143 inside_code = True
144 if line.startswith('!bt'):
145 inside_math = True
146 if line.startswith('!ec'):
147 inside_code = False
148 if line.startswith('!et'):
149 inside_math = False
150
151 if not inside_code:
152 if "``" in line:
153 print '''\nWarning: Double back-quotes `` found in file - should be "?'''
154 print 'Line:', line
155 if not inside_math:
156 if "''" in line:
157
158 pass
159
160 commands = [
161 'begin{equation}',
162 'end{equation}',
163 'begin{equation*}',
164 'end{equation*}',
165 'begin{eqnarray}',
166 'end{eqnarray}',
167 'begin{eqnarray*}',
168 'end{eqnarray*}',
169 'begin{align}',
170 'end{align}',
171 'begin{align*}',
172 'end{align*}',
173 'begin{multline}',
174 'end{multline}',
175 'begin{multline*}',
176 'end{multline*}',
177 'begin{gather}',
178 'end{gather}',
179 'begin{gather*}',
180 'end{gather*}',
181
182 'beqan',
183 'eeqan',
184 'beqa',
185 'eeqa',
186 'balnn',
187 'ealnn',
188 'baln',
189 'ealn',
190 'beq',
191 'eeq',
192 ]
193 lines = filestr.splitlines()
194 for i in range(len(lines)):
195 for c in commands:
196 if c[0] == 'b':
197 if (c in lines[i] or r'\[' in lines[i]) and '`' not in lines[i]:
198
199 prev_line = i-1
200 while prev_line >= 0 and lines[prev_line].isspace():
201 prev_line -= 1
202 if not lines[prev_line].startswith('!bt'):
203
204 if not lines[prev_line].startswith('!bc'):
205 print '\nWarning: forgot to precede math (%s) by !bt:' % c
206 stop_line = i+2 if i+2 <+ len(lines)-1 else len(lines)-1
207 for k in range(prev_line, stop_line):
208 print lines[k]
209 elif c[0] == 'e':
210
211
212
213
214
215 pass
216 """
217 if c in lines[i] or r'\]' in lines[i]:
218 # end math, do we have !et at the line after?
219 ...
220 """
221 """
222 # This is better done in sphinx.py, or should we provide warnings
223 # to enforce writers to stay away from a range of latex
224 # constructions even if sphinx.py can substitute them away?
225 """
226 not_for_sphinx = [
227 '{eqnarray}',
228 '{eqnarray*}',
229 '{multline}',
230 '{multline*}',
231 '{gather}',
232 '{gather*}',
233 'beqan',
234 'beqa',
235 ]
236 warning_given = False
237 if format == 'sphinx':
238 for command in not_for_sphinx:
239 if command in filestr:
240 if not warning_given:
241 print '\nWarning:'
242 print 'Not recommended for sphinx output: math environment %s' % command
243 if not warning_given:
244 print '(use equation, \[ \], or align/align*)'
245 warning_given = True
246 """
247 """
248
249
250
251
252 """
253 patterns = r'\\[be]cod', r'\\begin{[Vv]erbatim', r'\\end{[Vv]erbatim', r'\\[be]sys', r'\\[be]py',
254 for pattern in patterns:
255 matches = re.findall(pattern, filestr)
256 if matches:
257 print '\nSyntax error: Wrong syntax (latex!)'
258 print '\n'.join(matches)
259 sys.exit(1)
260 """
261
262 pattern = r'__[A-Z][A-Za-z0-9,:` ]+__\.'
263 matches = re.findall(pattern, filestr)
264 if matches:
265 print '\nSyntax error: Wrong paragraphs'
266 print '\n'.join(matches)
267 sys.exit(1)
268
269 pattern = re.compile(r'^__[A-Za-z0-9,: ]+?__', re.MULTILINE)
270 matches = pattern.findall(filestr)
271 if matches:
272 print 'Warning: Missing period or similar after paragraph heading'
273 print '\n'.join(matches)
274
275 pattern = r'idx\{[^}]*?\\_[^}]*?\}'
276 matches = re.findall(pattern, filestr)
277 if matches:
278 print 'Warning: Backslash before underscore(s) in idx'
279 print matches
280
281
282 pattern = r'^FIGURE:\s*\[[^,\]]+ +[^\]]*\]'
283 cpattern = re.compile(pattern, re.MULTILINE)
284 matches = cpattern.findall(filestr)
285 if matches:
286 print '\nSyntax error in FIGURE specification'\
287 '\nmissing comma after filename, before options'
288 print '\n'.join(matches)
289 sys.exit(1)
290
291
292 pattern = r'^MOVIE:\s*\[[^,\]]+ +[^\]]*\]'
293 cpattern = re.compile(pattern, re.MULTILINE)
294 matches = cpattern.findall(filestr)
295 if matches:
296 print '\nSyntax error in MOVIE specification'\
297 '\nmissing comma after filename, before options'
298 print '\n'.join(matches)
299 sys.exit(1)
300
301
302 keywords = 'AUTHOR', 'TITLE', 'DATE', 'FIGURE', 'BIBFILE', 'MOVIE'
303 for kw in keywords:
304 pattern = '^ +' + kw
305 cpattern = re.compile(pattern, re.MULTILINE)
306 matches = cpattern.findall(filestr)
307 if matches:
308 print '\nSyntax error in %s specification'\
309 '\ninitial space(s) online before keyword' % kw
310 print '\n'.join(matches)
311 sys.exit(1)
312
313
314 for kw in keywords:
315 pattern = '^' + kw + ' +'
316 cpattern = re.compile(pattern, re.MULTILINE)
317 matches = cpattern.findall(filestr)
318 if matches:
319 print '\nSyntax error in %s: specification'\
320 '\nmissing colon after keyword' % kw
321 print '\n'.join(matches)
322 sys.exit(1)
323
324 if format == "latex":
325
326
327
328
329 cdate = re.compile(r'^DATE:', re.MULTILINE)
330 ctitle = re.compile(r'^TITLE:', re.MULTILINE)
331 cauthor = re.compile(r'^AUTHOR:', re.MULTILINE)
332 md = cdate.search(filestr)
333 mt = ctitle.search(filestr)
334 ma = cauthor.search(filestr)
335 if md or mt or ma:
336 if not (md and mt and ma):
337 print """
338 Syntax error: latex format requires TITLE, AUTHOR and DATE to be
339 specified if one of them is present."""
340 if not md:
341 print 'DATE is missing'
342 if not mt:
343 print 'TITLE is missing'
344 if not ma:
345 print 'AUTHOR is missing'
346 sys.exit(1)
347
349
350
351 print 'make_one_line_paragraphs: this function does not work well'
352 print 'drop oneline_paragraphs option on the command line...'
353
354 filestr = re.sub('\n *\n', '[[[[[DOUBLE_NEWLINE]]]]]', filestr)
355
356
357 filestr = re.sub('(===+)\n', r'\g<1>[[[[[SINGLE_NEWLINE]]]]]\n', filestr)
358
359 filestr = re.sub('(\\|\\s*)\n', r'\g<1>[[[[[SINGLE_NEWLINE]]]]]\n', filestr)
360
361 filestr = re.sub('(\\}\\s*)\n', r'\g<1>[[[[[SINGLE_NEWLINE]]]]]\n', filestr)
362 filestr = re.sub('\n(AUTHOR|TITLE|DATE|FIGURE)', r'\n[[[[[SINGLE_NEWLINE]]]]]\g<1>', filestr)
363 debugpr('\n\n\n**** ONELINE1:\n\n%s\n\n' % filestr)
364
365
366 filestr = re.sub('\n *', ' ', filestr)
367 debugpr('\n\n\n**** ONELINE2:\n\n%s\n\n' % filestr)
368
369 filestr = filestr.replace('[[[[[SINGLE_NEWLINE]]]]] ', '\n')
370 filestr = filestr.replace('[[[[[SINGLE_NEWLINE]]]]]', '\n')
371 debugpr('\n\n\n**** ONELINE3:\n\n%s\n\n' % filestr)
372 filestr = filestr.replace('[[[[[DOUBLE_NEWLINE]]]]] ', '\n\n')
373 filestr = filestr.replace('[[[[[DOUBLE_NEWLINE]]]]]', '\n\n')
374 debugpr('\n\n\n**** ONELINE4:\n\n%s\n\n' % filestr)
375 return filestr
376
378 lines = filestr.splitlines()
379 inside_verbatim = False
380 for i in range(len(lines)):
381 line = lines[i]
382 line = line.lstrip()
383
384
385 if line.startswith('!bc'):
386 inside_verbatim = True
387 if line.startswith('!ec'):
388 inside_verbatim = False
389 if inside_verbatim:
390 continue
391
392 if line.startswith('@@@CODE'):
393 debugpr('\nFound verbatim copy (line %d):\n%s\n' % (i+1, line))
394 words = line.split()
395 try:
396 filename = words[1]
397 except IndexError:
398 raise SyntaxError, \
399 'Syntax error: missing filename in line\n %s' % line
400 try:
401 codefile = open(filename, 'r')
402 except IOError, e:
403 print 'Could not open the file %s used in @@@CODE instruction' % filename
404 if 'No such file or directory' in str(e):
405 print ' No such file or directory!'
406 print ' A dummy file %s is generated...' % filename
407 dummyfile = open(filename, 'w')
408 dummyfile.write(
409 'File %s missing - made this dummy file...\n'
410 % filename)
411 dummyfile.close()
412 codefile = open(filename, 'r')
413 else:
414 print e
415 sys.exit(1)
416
417
418 filename_ext = os.path.splitext(filename)[1]
419 if filename_ext == '.cxx' or filename_ext == '.C':
420 filename_ext = '.cpp'
421 if filename_ext == '.pyx':
422 filename_ext = '.cy'
423 if filename_ext in ('.py', '.f', '.c', '.cpp', '.sh',
424 '.m', '.pl', '.cy'):
425 code_envir = filename_ext[1:]
426 else:
427 code_envir = ''
428
429 m = re.search(r'from-?to:', line)
430 if m:
431 index = m.start()
432 fromto = m.group()
433 else:
434 index = -1
435 fromto = 'fromto:'
436
437
438 if index == -1 and len(words) < 3:
439
440 print 'copy complete file %s' % filename,
441 complete_file = True
442 code = codefile.read().strip()
443 debugpr('copy the whole file "%s" into a verbatim block\n' % filename)
444
445 else:
446 complete_file = False
447 if index >= 0:
448 patterns = line[index+len(fromto):].strip()
449 else:
450
451
452 patterns = ' '.join(words[2:]).strip()
453 try:
454 from_, to_ = patterns.split('@')
455 except:
456 raise SyntaxError, \
457 'Syntax error: missing @ in regex in line\n %s' % line
458
459 print 'copy %s regex "%s" until "%s"\n file: %s,' % \
460 ('after' if fromto == 'from-to:' else 'from',
461 from_, to_, filename),
462
463
464 cfrom = re.compile(from_)
465 cto = re.compile(to_)
466
467
468
469
470
471
472 codefile_lines = codefile.readlines()
473 from_found = False
474 to_found = False
475 from_line = -1
476 to_line = len(codefile_lines)
477 codelines = []
478 copy = False
479 for line_no, codeline in enumerate(codefile_lines):
480 mf = cfrom.search(codeline)
481 if mf and fromto == 'fromto:' and not from_found:
482
483
484
485
486 copy = True
487 from_found = True
488 from_line = line_no+1
489 debugpr('hit (fromto:) start "%s" (as "%s") in line no. %d\n%s\ncode environment: %s' % (from_, codeline[mf.start():mf.end()], line_no+1, codeline, code_envir if code_envir else 'none'))
490
491 if to_:
492 mt = cto.search(codeline)
493 if mt:
494 copy = False
495 to_found = True
496 to_line = line_no+1
497
498 debugpr('hit end "%s" (as "%s") in line no. %d\n%s' % (to_, codeline[mt.start():mt.end()], line_no+1, codeline))
499 if copy:
500 debugpr('copy: %s' % codeline.rstrip())
501 if codeline[-2:] == '\\\n':
502
503
504 codeline = codeline[:-2] + '\\ \n'
505 codelines.append(codeline)
506
507 if mf and fromto == 'from-to:' and not from_found:
508 copy = True
509 from_found = True
510 from_line = line_no+2
511 debugpr('hit (from-to:) start "%s" (as "%s") in line no. %d\n%s\ncode environment: %s' % (from_, codeline[mf.start():mf.end()], line_no+1, codeline, code_envir if code_envir else 'none'))
512
513 code = ''.join(codelines)
514 code = code.rstrip()
515 if code == '' or code.isspace():
516 if not from_found:
517 print 'Could not find regex "%s".' % from_,
518 if not to_found:
519 print 'Could not find regex "%s".' % to_,
520 if from_found and to_found:
521 print '"From" and "to" regex match at the same line - empty text.',
522 print '\nAbort!'
523 sys.exit(1)
524 print ' lines %d-%d' % (from_line, to_line),
525 codefile.close()
526
527
528
529 if True:
530 if complete_file:
531 code = "!bc %spro\n%s\n!ec" % (code_envir, code)
532 print ' (format: %spro)' % code_envir
533 else:
534 code = "!bc %scod\n%s\n!ec" % (code_envir, code)
535 print ' (format: %scod)' % code_envir
536 else:
537 code = "!bc\n%s\n!ec" % code
538 print
539 lines[i] = code
540
541 filestr = '\n'.join(lines)
542 return filestr
543
544
546
547
548
549
550
551 debugpr('\n\n\n***** Interpreting exercises *****\n\n')
552
553 all_exer = []
554 exer = {}
555 inside_exer = False
556 exer_end = False
557 exer_counter = 0
558 lines = filestr.splitlines()
559 newlines = []
560 exer_line_pattern = re.compile(r'^\s*([_=]{3,5})\s*([Ee]xercise|[Pp]roblem|[Pp]roject):\s*(?P<title>[^ =-].+?)\s*[_=]+')
561 label_pattern = re.compile(r'label\{(.+?)\}')
562 file_pattern = re.compile(r'file\s*=\s*([^\s]+)')
563 solution_pattern = re.compile(r'solution\s*=\s*([^\s]+)')
564 for i in range(len(lines)):
565 m = exer_line_pattern.search(lines[i])
566 if m:
567 exer = {}
568 exer['title'] = m.group('title')
569 exer['heading'] = m.group(1)
570 exer['type'] = m.group(2)
571 inside_exer = True
572 exer['text'] = []
573 exer['hint'] = {}
574 exer['comments'] = []
575 exer_counter += 1
576 exer['no'] = exer_counter
577 hint_counter = 0
578 inside_hint = False
579 exer_end = False
580 text_line = True
581 elif inside_exer:
582 label_info_line = False
583 m = label_pattern.search(lines[i])
584 if m:
585 exer['label'] = m.group(1)
586 label_info_line = True
587 m = file_pattern.search(lines[i])
588 if m:
589 exer['file'] = m.group(1)
590 label_info_line = True
591 m = solution_pattern.search(lines[i])
592 if m:
593 exer['solution'] = m.group(1)
594 label_info_line = True
595
596
597
598 if '__Hint' in lines[i]:
599 hint_counter += 1
600 exer['hint'][hint_counter] = []
601 inside_hint = True
602 text_line = False
603 if inside_hint:
604 if lines[i].startswith('#'):
605 exer['comments'].append(lines[i])
606 else:
607 exer['hint'][hint_counter].append(lines[i])
608
609 if text_line and not label_info_line:
610 if lines[i].startswith('#'):
611 exer['comments'].append(lines[i])
612 else:
613 exer['text'].append(lines[i])
614 else:
615 newlines.append(lines[i])
616
617
618
619 if i == len(lines) - 1:
620 exer_end = True
621 elif inside_exer and lines[i+1].startswith('==='):
622 exer_end = True
623
624 if exer and exer_end:
625 exer['text'] = '\n'.join(exer['text']).strip()
626 for hint_no in exer['hint']:
627 exer['hint'][hint_no] = '\n'.join(exer['hint'][hint_no]).strip()
628 exer['comments'] = '\n'.join(exer['comments']).strip()
629
630 debugpr(pprint.pformat(exer))
631 formatted_exercise = EXERCISE[format](exer)
632 newlines.append(formatted_exercise)
633 all_exer.append(exer)
634 inside_exer = False
635 exer_end = False
636 exer = {}
637
638 filestr = '\n'.join(newlines)
639 if all_exer:
640 exer_filename = filename.replace('.do.txt', '')
641 exer_filename = '.%s.exerinfo' % exer_filename
642 f = open(exer_filename, 'w')
643 f.write("""
644 # Information about all exercises in the file %s.
645 # The information can be loaded into a Python list of dicts
646 # by the code (f is an open filehandle to the current file):
647 #
648 # for i in range(7): f.readline() # skip comments in the top
649 # exer = eval(f.read())
650 #
651 """ % filename)
652 f.write(pprint.pformat(all_exer))
653 f.close()
654 print 'Info about %d exercises written to %s' % \
655 (len(all_exer), exer_filename)
656 else:
657 debugpr('No exercises found.\n')
658
659 return filestr
660
661
663 """
664 Parse a keyword for a description list when the keyword may
665 represent information about an argument to a function or a
666 variable in a program::
667
668 - argument x: x coordinate (float).
669 - keyword argument tolerance: error tolerance (float).
670 - return: corresponding y coordinate (float).
671 """
672 keyword = keyword.strip()
673 if keyword[-1] == ':':
674 keyword = keyword[:-1]
675
676 typical_words = ('argument', 'keyword argument', 'return', 'variable')
677 parse = False
678 for w in typical_words:
679 if w in keyword:
680 parse = True
681 break
682 if not parse:
683
684 if format == 'epytext':
685
686 keyword = '- ' + keyword
687 return keyword
688
689
690 if 'return' in keyword:
691 type = 'return'
692 varname = None
693 type = ARGLIST[format][type]
694 return type
695 else:
696 words = keyword.split()
697 varname = words[-1]
698 type = ' '.join(words[:-1])
699 if type == 'argument':
700 type = 'parameter'
701 elif type == 'keyword argument':
702 type = 'keyword'
703 elif type == 'instance variable':
704 type = 'instance variable'
705 elif type == 'class variable':
706 type = 'class variable'
707 elif type == 'module variable':
708 type = 'module variable'
709 else:
710 return keyword
711
712
713 pattern = r'(?P<begin>^)(?P<subst>%s)(?P<end>$)' % varname
714
715 keyword = ARGLIST[format][type] + ' ' + varname
716 return keyword
717
718
720 """
721 Translate tables with pipes and dashes to a list of
722 row-column values. Horizontal rules become a row
723 ['horizontal rule'] in the list.
724 The list is easily translated to various output formats
725 by other modules.
726 """
727 from StringIO import StringIO
728 result = StringIO()
729
730 table = {'rows': []}
731 inside_table = False
732 for line in filestr.splitlines():
733 lin = line.lstrip()
734
735 if lin.startswith('|--') and lin.endswith('-|'):
736 table['rows'].append(['horizontal rule'])
737
738 align = lin[1:-1].replace('-', '')
739 if align:
740 if align == '|'*len(align):
741 print 'Syntax error: horizontal rule in table '\
742 'contains | between columns - remove these.'
743 print line
744 sys.exit(1)
745 for char in align:
746 if char not in ('|', 'r', 'l', 'c'):
747 print 'illegal alignment character in table:', char
748 sys.exit(1)
749
750 if len(table['rows']) == 0:
751
752 table['headings_align'] = align
753 else:
754
755 table['columns_align'] = align
756 continue
757 if lin.startswith('|') and not lin.startswith('|--'):
758
759 if not inside_table:
760 inside_table = True
761 columns = line.strip().split('|')
762
763
764 columns = [c.strip() for c in columns if c.strip()]
765 table['rows'].append(columns)
766 elif lin.startswith('#') and inside_table:
767 continue
768 else:
769 if inside_table:
770
771
772 inside_table = False
773 result.write(TABLE[format](table))
774 table = {'rows': []}
775 else:
776 result.write(line + '\n')
777 return result.getvalue()
778
780 """
781 Go through filestr and parse all lists and typeset them correctly.
782 This function must be called after all (verbatim) code and tex blocks
783 have been removed from the file.
784 This function also treats comment lines and blank lines.
785 """
786 debugpr('*** List typesetting phase + comments and blank lines ***')
787 from StringIO import StringIO
788 result = StringIO()
789 lastindent = 0
790 lists = []
791 inside_description_environment = False
792 lines = filestr.splitlines()
793 lastline = lines[0]
794
795 _code_block_no = 0; _tex_block_no = 0
796
797 for line in lines:
798 debugpr('\n------------------------\nsource line=[%s]' % line)
799
800 for tag in INLINE_TAGS_BUGS:
801 bug = INLINE_TAGS_BUGS[tag]
802 if bug:
803 m = re.search(bug[0], line)
804 if m:
805 print '>>> Syntax ERROR? "%s"\n %s!' % \
806 (m.group(0), bug[1])
807 print ' In line\n', line
808
809 if not line or line.isspace():
810 if not lists:
811 result.write(BLANKLINE[format])
812
813 debugpr(' > This is a blank line')
814 lastline = line
815 continue
816
817 if line.startswith('#'):
818
819
820 if line.startswith('#!!CODE') and len(debug_info) >= 1:
821 result.write(line + '\n')
822 debugpr(' > Here is a code block:\n%s\n--------' % \
823 debug_info[0][_code_block_no])
824 _code_block_no += 1
825 elif line.startswith('#!!TEX') and len(debug_info) >= 2:
826 result.write(line + '\n')
827 debugpr(' > Here is a latex block:\n%s\n--------' % \
828 debug_info[1][_tex_block_no])
829 _tex_block_no += 1
830
831 else:
832 debugpr(' > This is just a comment line')
833
834
835 line = line[1:]
836 if 'comment' in INLINE_TAGS_SUBST[format]:
837 comment_action = INLINE_TAGS_SUBST[format]['comment']
838 if isinstance(comment_action, str):
839 new_comment = comment_action % line.strip()
840 elif callable(comment_action):
841 new_comment = comment_action(line.strip())
842 result.write(new_comment + '\n')
843
844 lastline = line
845 continue
846
847
848 linescan = re.compile(
849 r"(?P<indent> *(?P<listtype>[*o-] )? *)" +
850 r"(?P<keyword>.+?:\s+)?(?P<text>.*)\s?")
851
852
853 m = linescan.match(line)
854 indent = len(m.group('indent'))
855 listtype = m.group('listtype')
856 if listtype:
857 listtype = listtype.strip()
858 listtype = LIST_SYMBOL[listtype]
859 keyword = m.group('keyword')
860 text = m.group('text')
861 debugpr(' > indent=%d (previous indent=%d), keyword=[%s], text=[%s]' % (indent, lastindent, keyword, text))
862
863
864
865
866
867 if line.lstrip().startswith('___') or line.lstrip().startswith('==='):
868 indent = 0
869
870
871 if indent > lastindent and listtype:
872 debugpr(' > This is a new list of type "%s"' % listtype)
873
874 lists.append({'listtype': listtype, 'indent': indent})
875 result.write(LIST[format][listtype]['begin'])
876 if len(lists) > 1:
877 result.write(LIST[format]['separator'])
878
879 lastindent = indent
880 if listtype == 'enumerate':
881 enumerate_counter = 0
882 elif listtype:
883
884
885
886 result.write(LIST[format]['separator'])
887
888 if indent < lastindent:
889
890
891 while lists and lists[-1]['indent'] > indent:
892 debugpr(' > This is the end of a %s list' % \
893 lists[-1]['listtype'])
894 result.write(LIST[format][lists[-1]['listtype']]['end'])
895 del lists[-1]
896 lastindent = indent
897
898 if indent == lastindent:
899 debugpr(' > This line belongs to the previous block since it has '\
900 'the same indent (%d blanks)' % indent)
901
902 if listtype:
903
904
905
906
907
908 itemformat = LIST[format][listtype]['item']
909 if format == 'cwiki' or format == 'mwiki':
910 itemformat = itemformat*len(lists)
911 item = itemformat
912 if listtype == 'enumerate':
913 debugpr(' > This is an item in an enumerate list')
914 enumerate_counter += 1
915 if '%d' in itemformat:
916 item = itemformat % enumerate_counter
917
918 result.write(' '*(indent - 2 - enumerate_counter//10 - 1))
919 result.write(item + ' ')
920 elif listtype == 'description':
921 if '%s' in itemformat:
922 if not keyword:
923
924
925
926 if text[-1] == ':':
927 keyword = text
928 text = ''
929 if keyword:
930 keyword = parse_keyword(keyword, format) + ':'
931 item = itemformat % keyword + ' '
932 debugpr(' > This is an item in a description list '\
933 'with parsed keyword=[%s]' % keyword)
934 keyword = ''
935
936 else:
937 debugpr(' > This is an item in a description list, but empty keyword, serious error....')
938 result.write(' '*(indent-2))
939 result.write(item)
940 if not (text.isspace() or text == ''):
941
942
943
944 if format == 'sphinx' and text.lstrip().startswith('type:'):
945 text = text.lstrip()[5:].lstrip()
946
947 else:
948 result.write('\n' + ' '*(indent))
949 else:
950 debugpr(' > This is an item in a bullet list')
951 result.write(' '*(indent-2))
952 result.write(item + ' ')
953
954 else:
955 debugpr(' > This line is some ordinary line, no special list syntax involved')
956
957 result.write(' '*indent)
958
959
960
961
962 if keyword:
963 text = keyword + text
964 debugpr('text=[%s]' % text)
965
966
967 newline = '' if lists and (format == 'gwiki' or format == 'mwiki' or format == 'cwiki') \
968 else '\n'
969
970 result.write(text + newline)
971 lastindent = indent
972 lastline = line
973
974
975 while lists:
976 debugpr(' > This is the end of a %s list' % lists[-1]['listtype'])
977 result.write(LIST[format][lists[-1]['listtype']]['end'])
978 del lists[-1]
979
980 return result.getvalue()
981
982
1057
1058
1060
1061
1062 section_pattern = r'(_{3,7}|={3,7})(.+?)(_{3,7}|={3,7})\s*label\{(.+?)\}'
1063 m = re.findall(section_pattern, filestr)
1064
1065
1066
1067
1068 section_label2title = OrderedDict()
1069 for dummy1, title, dummy2, label in m:
1070 section_label2title[label] = title.strip()
1071
1072
1073
1074 filestr = CROSS_REFS[format](section_label2title, format, filestr)
1075 return filestr
1076
1077
1079 """Process idx{...} and cite{...} instructions."""
1080 index = {}
1081 citations = OrderedDict()
1082 line_counter = 0
1083 cite_counter = 0
1084 bibfile = {}
1085 for line in filestr.splitlines():
1086 line_counter += 1
1087 line = line.strip()
1088 if line.startswith('BIBFILE:'):
1089 files = re.split(r'\s*,\s*', line[8:].strip())
1090 for filename in files:
1091 stem, ext = os.path.splitext(filename)
1092 if ext == '.bib':
1093 bibfile['bib'] = stem
1094 elif ext == '.rst':
1095 bibfile['rst'] = filename
1096 elif ext == '.py':
1097 bibfile['py'] = filename
1098 else:
1099 print '\nUnknown extension of BIBFILE:', filename
1100 sys.exit(1)
1101 else:
1102 index_words = re.findall(r'idx\{(.+?)\}', line)
1103 if index_words:
1104 for word in index_words:
1105 if word in index:
1106 index[word].append(line_counter)
1107 else:
1108 index[word] = [line_counter]
1109
1110
1111
1112 cite_args = re.findall(r'cite\{(.+?)\}', line)
1113 if cite_args:
1114
1115 cite_labels = []
1116 for arg in cite_args:
1117 for c in arg.split(','):
1118 cite_labels.append(c.strip())
1119 for label in cite_labels:
1120 if not label in citations:
1121 cite_counter += 1
1122 citations[label] = cite_counter
1123
1124
1125 if format != 'latex' and format != 'pdflatex' and \
1126 format != 'pandoc':
1127 for arg in cite_args:
1128 replacement = ' '.join(['cite{%s}' % label.strip() \
1129 for label in arg.split(',')])
1130 filestr = filestr.replace('cite{%s}' % arg,
1131 replacement)
1132 elif format == 'pandoc':
1133
1134 for arg in cite_args:
1135 replacement = ';'.join(
1136 ['@' + label for label in arg.split(',')])
1137 filestr = filestr.replace('cite{%s}' % arg,
1138 replacement)
1139
1140
1141 if len(citations) > 0 and OrderedDict is dict:
1142 print 'Warning: citations may appear in random order unless you upgrade to Python version 2.7 or 3.1'
1143 filestr = INDEX_BIB[format](filestr, index, citations, bibfile)
1144 return filestr
1145
1147 debugpr('\n*** Dealing with authors and institutions ***')
1148
1149 author_lines = re.findall(r'^AUTHOR:\s*(?P<author>.+)\s*$', filestr,
1150 re.MULTILINE)
1151
1152 cpattern = re.compile(r'^AUTHOR:.+$', re.MULTILINE)
1153 filestr = cpattern.sub('XXXAUTHOR', filestr)
1154
1155 filestr = re.sub('(XXXAUTHOR\n)+', 'XXXAUTHOR', filestr)
1156
1157
1158 authors_and_institutions = []
1159 for line in author_lines:
1160 if ' at ' in line:
1161
1162 try:
1163 a, i = line.split(' at ')
1164 except ValueError:
1165 print 'Wrong syntax of author(s) and institution(s): too many "at":\n', line, '\nauthor at inst1, adr1 and inst2, adr2a, adr2b and inst3, adr3'
1166 sys.exit(1)
1167 a = a.strip()
1168 if ' and ' in i:
1169 i = [w.strip() for w in i.split(' and ')]
1170 else:
1171 i = (i.strip(),)
1172 else:
1173 a = line.strip()
1174 i = None
1175 if 'mail:' in a:
1176 a, e = re.split(r'[Ee]?mail:\s*', a)
1177 a = a.strip()
1178 e = e.strip()
1179 if not '@' in e:
1180 print 'Syntax error: wrong email specification in AUTHOR line: "%s" (no @)' % e
1181 else:
1182 e = None
1183 authors_and_institutions.append((a, i, e))
1184
1185 inst2index = OrderedDict()
1186 index2inst = {}
1187 auth2index = OrderedDict()
1188 auth2email = OrderedDict()
1189
1190 for a, institutions, e in authors_and_institutions:
1191 if institutions is not None:
1192 for i in institutions:
1193 inst2index[i] = None
1194 for index, i in enumerate(inst2index):
1195 inst2index[i] = index+1
1196 index2inst[index+1] = i
1197 for a, institutions, e in authors_and_institutions:
1198 if institutions is not None:
1199 auth2index[a] = [inst2index[i] for i in institutions]
1200 else:
1201 auth2index[a] = ''
1202 auth2email[a] = e
1203
1204
1205 if len(auth2index) > 1 and OrderedDict is dict:
1206 print 'Warning: multiple authors\n - correct order of authors requires Python version 2.7 or 3.1 (or higher)'
1207 return authors_and_institutions, auth2index, inst2index, index2inst, auth2email, filestr
1208
1210 authors_and_institutions, auth2index, inst2index, \
1211 index2inst, auth2email, filestr = interpret_authors(filestr, format)
1212 author_block = INLINE_TAGS_SUBST[format]['author']\
1213 (authors_and_institutions, auth2index, inst2index,
1214 index2inst, auth2email)
1215 filestr = filestr.replace('XXXAUTHOR', author_block)
1216 return filestr
1217
1218
1220 """Deal with all inline tags by substitution."""
1221
1222
1223
1224
1225
1226 filestr = typeset_authors(filestr, format)
1227
1228
1229 m = re.search(r'^(DATE:\s*[Tt]oday)', filestr, re.MULTILINE)
1230 if m:
1231 origstr = m.group(1)
1232 w = time.asctime().split()
1233 date = w[1] + ' ' + w[2] + ', ' + w[4]
1234 filestr = filestr.replace(origstr, 'DATE: ' + date)
1235
1236 debugpr('\n*** Inline tags substitution phase ***')
1237
1238 ordered_tags = (
1239 'title', 'date',
1240 'movie',
1241
1242 'abstract',
1243
1244 'emphasize', 'math2', 'math',
1245 'chapter', 'section', 'subsection', 'subsubsection',
1246 'bold',
1247 'inlinecomment',
1248 'verbatim',
1249 'citation',
1250 'paragraph',
1251 'plainURL',
1252 'linkURL2v',
1253 'linkURL3v',
1254 'linkURL2',
1255 'linkURL3',
1256 'linkURL',
1257 )
1258 for tag in ordered_tags:
1259 debugpr('\n*************** Working with tag "%s"' % tag)
1260 tag_pattern = INLINE_TAGS[tag]
1261
1262 if tag in ('abstract',):
1263 c = re.compile(tag_pattern, re.MULTILINE|re.DOTALL)
1264 else:
1265 c = re.compile(tag_pattern, re.MULTILINE)
1266 try:
1267 replacement = INLINE_TAGS_SUBST[format][tag]
1268 except KeyError:
1269 continue
1270 if replacement is None:
1271 continue
1272
1273 if isinstance(replacement, basestring):
1274
1275 findlist = c.findall(filestr)
1276 occurences = len(findlist)
1277 findlist = pprint.pformat(findlist)
1278 if occurences > 0:
1279 debugpr('Found %d occurences of "%s":\nfindall list: %s' % (occurences, tag, findlist))
1280 debugpr('%s is to be replaced using %s' % (tag, replacement))
1281 m = c.search(filestr)
1282 if m:
1283 debugpr('First occurence: "%s"\ngroups: %s\nnamed groups: %s' % (m.group(0), m.groups(), m.groupdict()))
1284
1285 filestr = c.sub(replacement, filestr)
1286 elif callable(replacement):
1287
1288
1289
1290 lines = filestr.splitlines()
1291 occurences = 0
1292 for i in range(len(lines)):
1293 m = re.search(tag_pattern, lines[i])
1294 if m:
1295 try:
1296 replacement_str = replacement(m)
1297 except Exception, e:
1298 print 'Problem at line\n ', lines[i], \
1299 '\nException:\n', e
1300 print 'occured while replacing inline tag "%s" (%s) with aid of function %s' % (tag, tag_pattern, replacement.__name__)
1301
1302
1303
1304 sys.exit(1)
1305 lines[i] = re.sub(tag_pattern, replacement_str, lines[i])
1306 occurences += 1
1307 filestr = '\n'.join(lines)
1308
1309 else:
1310 raise ValueError, 'replacement is of type %s' % type(replacement)
1311 if occurences > 0:
1312 debugpr('\n**** The file after %d "%s" substitutions ***\n%s\n%s\n\n' % \
1313 (occurences, tag, filestr, '-'*80))
1314 return filestr
1315
1321
1323 if format == 'sphinx' or format == 'rst':
1324 return filestr
1325
1326
1327 tp = 'class', 'func', 'mod'
1328 for t in tp:
1329 filestr = re.sub(r':%s:`~?([A-Za-z0-9_.]+?)`' % t,
1330 r'`\g<1>`', filestr)
1331 return filestr
1332
1333
1334 -def file2file(in_filename, format, out_filename):
1335 """
1336 Perform the transformation of a doconce file, stored in in_filename,
1337 to a given format (html, latex, etc.), written to out_filename.
1338 This is the "main" function in the module.
1339 """
1340 if in_filename.startswith('__'):
1341 print 'translate preprocessed doconce text in', in_filename
1342 else:
1343 print 'translate doconce text in', in_filename
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353 if encoding:
1354 print 'Open file with encoding', encoding
1355 f = codecs.open(in_filename, 'r', encoding)
1356 else:
1357 f = open(in_filename, 'r')
1358 filestr = f.read()
1359 f.close()
1360
1361 if in_filename.endswith('.py') or in_filename.endswith('.py.do.txt'):
1362 filestr = doconce2format4docstrings(filestr, format)
1363 else:
1364 filestr = doconce2format(filestr, format)
1365
1366 if encoding:
1367 f = codecs.open(out_filename, 'w', encoding)
1368 else:
1369 f = open(out_filename, 'w')
1370 f.write(filestr)
1371 f.close()
1372
1373
1425
1574
1575
1576 -def preprocess(filename, format, preprocessor_options=[]):
1577 """
1578 Run mako or the preprocess script on filename and return the name
1579 of the resulting file. The preprocessor_options list contains
1580 the preprocessor options given on the command line.
1581 In addition, the preprocessor option FORMAT (=format) is
1582 always defined.
1583 """
1584
1585 f = open(filename, 'r'); filestr = f.read(); f.close()
1586 preprocessor = None
1587
1588
1589 preprocess_commands = r'^#\s*#(if|define|include)'
1590 mako_commands = r'^\s*<?%'
1591 if re.search(preprocess_commands, filestr, re.MULTILINE):
1592
1593 preprocessor = 'preprocess'
1594
1595 preprocess_options = preprocessor_options[:]
1596 for i in range(len(preprocess_options)):
1597 if preprocess_options[i][:2] != '-U' and \
1598 preprocess_options[i][:2] != '-D':
1599 preprocess_options[i] = '-D' + preprocess_options[i]
1600 preprocess_options = ' '.join(preprocess_options)
1601 resultfile = '__tmp.do.txt'
1602
1603
1604 pattern1 = r'^#if.*'; pattern2 = r'^#else'
1605 pattern3 = r'^#elif'; pattern4 = r'^#endif'
1606 for pattern in pattern1, pattern2, pattern3, pattern4:
1607 cpattern = re.compile(pattern, re.MULTILINE)
1608 matches = cpattern.findall(filestr)
1609 if matches:
1610 print '\nSyntax error in preprocess directives: missing # '\
1611 'before directive'
1612 print pattern
1613 sys.exit(1)
1614
1615 try:
1616 import preprocess
1617 except ImportError:
1618 print """\
1619 %s makes use of preprocess directives and therefore requires
1620 the preprocess program to be installed (see code.google.com/p/preprocess).
1621 On Debian systems, preprocess can be installed through the
1622 preprocess package (sudo apt-get install preprocess).
1623 """ % filename
1624 sys.exit(1)
1625
1626 cmd = 'preprocess -DFORMAT=%s %s %s > %s' % \
1627 (format, preprocess_options, filename, resultfile)
1628 print 'run', cmd
1629 failure, outtext = commands.getstatusoutput(cmd)
1630 if failure:
1631 print 'Could not run preprocessor:\n%s' % cmd
1632 print outtext
1633 sys.exit(1)
1634
1635 f = open(resultfile, 'r'); filestr = f.read(); f.close()
1636
1637
1638 if re.search(mako_commands, filestr, re.MULTILINE):
1639 if preprocessor is not None:
1640
1641 filename = resultfile
1642 preprocessor = 'mako'
1643 resultfile = '__tmp.do.txt'
1644
1645 try:
1646 import mako
1647 except ImportError:
1648 print """\
1649 %s makes use of mako directives and therefore requires mako
1650 to be installed (www.makotemplates.org).
1651 On Debian systems, mako can easily be installed through the
1652 python-mako package (sudo apt-get install python-mako).
1653 """ % filename
1654 sys.exit(1)
1655
1656 print 'run mako on', filename, 'to make', resultfile
1657
1658
1659
1660 f = open(filename, 'r')
1661 filestr = f.read()
1662 f.close()
1663 filestr = filestr.replace('\\\\\n', '\\\\ \n')
1664 filestr = filestr.replace('\\\n', '\\ \n')
1665 f = open(resultfile, 'w')
1666 f.write(filestr)
1667 f.close()
1668
1669 from mako.template import Template
1670 from mako.lookup import TemplateLookup
1671 lookup = TemplateLookup(directories=[os.curdir])
1672 temp = Template(filename=resultfile, lookup=lookup)
1673 f = open(resultfile, 'w')
1674 kwargs = {'FORMAT': format}
1675 for option in preprocessor_options:
1676 try:
1677 key, value = option.split('=')
1678 except ValueError:
1679 print 'command line argument "%s" not recognized' % option
1680 sys.exit(1)
1681
1682 try:
1683 kwargs[key] = eval(value)
1684 except (NameError, SyntaxError):
1685 kwargs[key] = value
1686 debugpr('Keyword arguments to be sent to mako: %s' % \
1687 pprint.pformat(kwargs))
1688 try:
1689 f.write(temp.render(**kwargs))
1690 except TypeError, e:
1691 if "'Undefined' object is not callable" in str(e):
1692 calls = '\n'.join(re.findall(r'(\$\{[A-Za-z0-9_ ]+?\()[^}]+?\}', filestr))
1693 print '${func(...)} calls undefined function "func",\ncheck all ${...} calls in the file(s) for possible typos and lack of includes!\n%s' % calls
1694 sys.exit(1)
1695 except NameError, e:
1696 if "Undefined" in str(e):
1697 variables = '\n'.join(re.findall(r'\$\{[A-Za-z0-9_]+?\}', filestr))
1698 print 'One or more ${var} variables are undefined, check all!\n%s' % variables
1699 sys.exit(1)
1700
1701 f.close()
1702 if preprocessor_options:
1703 print 'mako variables:', kwargs
1704
1705 if preprocessor is None:
1706
1707 resultfile = filename
1708
1709 return resultfile
1710
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721 options = ['debug', 'skip_inline_comments', 'encoding=',
1722 'oneline_paragraphs',]
1723
1724 global debug, _log, oneline_paragraphs, \
1725 skip_inline_comments, encoding, filename
1726
1727 try:
1728 format = sys.argv[1]
1729 filename = sys.argv[2]
1730 del sys.argv[1:3]
1731 except IndexError:
1732 print 'Usage: %s format filename [%s] [preprocessor options]\n' \
1733 % (sys.argv[0], ' | '.join(options))
1734 if len(sys.argv) == 1:
1735 print 'Missing format specification!'
1736 print 'formats:', str(supported_format_names())[1:-1]
1737 print '\n-DFORMAT=format is always defined when running preprocess'
1738 print 'Other -Dvar preprocess options can be added'
1739 sys.exit(1)
1740
1741 names = supported_format_names()
1742 if format not in names:
1743 print '%s is not among the supported formats:\n%s' % (format, names)
1744 sys.exit(1)
1745
1746 debug = False
1747 if 'debug' in sys.argv[1:]:
1748 debug = True
1749 sys.argv.remove('debug')
1750 if '--debug' in sys.argv[1:]:
1751 debug = True
1752 sys.argv.remove('--debug')
1753
1754 oneline_paragraphs = False
1755 if 'oneline_paragraphs' in sys.argv[1:]:
1756 oneline_paragraphs = True
1757 sys.argv.remove('oneline_paragraphs')
1758 if '--oneline_paragraphs' in sys.argv[1:]:
1759 oneline_paragraphs = True
1760 sys.argv.remove('--oneline_paragraphs')
1761
1762 skip_inline_comments = False
1763 if 'skip_inline_comments' in sys.argv[1:]:
1764 skip_inline_comments = True
1765 sys.argv.remove('skip_inline_comments')
1766 if '--skip_inline_comments' in sys.argv[1:]:
1767 skip_inline_comments = True
1768 sys.argv.remove('--skip_inline_comments')
1769
1770 encoding = ''
1771 for arg in sys.argv[1:]:
1772 if arg.startswith('encoding=') or arg.startswith('--encoding='):
1773 dummy, encoding = arg.split('=')
1774 break
1775 if encoding:
1776 sys.argv.remove(arg)
1777
1778 if debug:
1779 _log_filename = '_doconce_debugging.log'
1780 _log = open(_log_filename,'w')
1781 _log.write("""
1782 This is a log file for the doconce script.
1783 Debugging is turned on by a 3rd command-line argument '--debug'
1784 to doconce format. Without that command-line argument,
1785 this file is not produced.
1786
1787 """)
1788 print 'debug output in', _log_filename
1789
1790
1791 debugpr('\n\n>>>>>>>>>>>>>>>>> %s >>>>>>>>>>>>>>>>>\n\n' % format)
1792
1793 if not os.path.isfile(filename):
1794 basename = filename
1795 filename = filename + '.do.txt'
1796 if not os.path.isfile(filename):
1797 print 'No such Doconce file: %s' % (filename[:-7])
1798 sys.exit(1)
1799 else:
1800 basename = filename[:-7]
1801
1802 out_filename = basename + FILENAME_EXTENSION[format]
1803
1804 filename_preprocessed = preprocess(filename, format, sys.argv[1:])
1805 file2file(filename_preprocessed, format, out_filename)
1806 if filename_preprocessed.startswith('__') and not debug:
1807 os.remove(filename_preprocessed)
1808
1809 print 'output in', out_filename
1810
1811 if __name__ == '__main__':
1812 main()
1813