Package doconce :: Module doconce
[hide private]
[frames] | no frames]

Source Code for Module doconce.doconce

   1  #!/usr/bin/env python 
   2  import re, os, sys, shutil, commands, pprint, time, glob, codecs 
   3  try: 
   4      from collections import OrderedDict   # v2.7 and v3.1 
   5  except ImportError: 
   6      # use standard arbitrary-ordered dict instead (original order of 
   7      # citations is then lost) 
   8      OrderedDict = dict 
   9   
  10  global debug 
  11  debug = False  # can be reset in main() 
12 -def debugpr(out):
13 if debug: 14 #print out 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 #print 'calling define function in', module.__name__ 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
39 -def supported_format_names():
40 return 'html', 'latex', 'pdflatex', 'rst', 'sphinx', 'st', 'epytext', 'plain', 'gwiki', 'mwiki', 'cwiki', 'pandoc'
41 42 #---------------------------------------------------------------------------- 43 # Translators: (do not include, use import as shown above) 44 # include "common.py" 45 # include "html.py" 46 # include "latex.py" 47 #---------------------------------------------------------------------------- 48
49 -def syntax_check(filestr, format):
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 # Code blocks cannot come directly after tables or headings. 66 # Remove idx{} and label{} since these will be move for rst. 67 # Also remove all comments since these are also "invisible" 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'-\|', '__': # section, table, paragraph 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 # Code/latex blocks cannot have a comment, table, figure, etc. 83 # right before them 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 #and (format == 'rst' or format == 'sphinx'): 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 # There should only be ref and label *without* the latex-ish backslash 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 # consistency check between label{} and ref{}: 128 # (does not work well without labels from the !bt environments) 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 # Double quotes and not double single quotes in *plain text*: 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 #print '''\nWarning: Double forward-quotes '' found in file - should be "\n(unless derivatives in math)''' 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 # some common abbreviations (newcommands): 182 'beqan', 183 'eeqan', 184 'beqa', 185 'eeqa', 186 'balnn', 187 'ealnn', 188 'baln', 189 'ealn', 190 'beq', 191 'eeq', # the simplest, contained in others, must come last... 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 # begin math, do we have !bt at the line before? 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 # Must have !bt unless !bc block 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 # actually, the end part is never reached, because 211 # if the begin part is missing, program stops, and 212 # if the begin part is there, the whole block, incl 213 # an erroneous end part, is removed when this syntax 214 # check is performed... 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 # Cannot check on these since doconce documents about ptex2tex and 250 # latex writings may contain these expressions in inline verbatim or 251 # block verbatim 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 # Figure without comma between filename and options? Or initial spaces? 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 # Movie without comma between filename and options? Or initial spaces? 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 # Keywords at the beginning of the lines: 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 # Keywords without colon: 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 # if TITLE is given, AUTHOR and DATE must also be present 326 #md = re.search(r'^DATE:', filestr, flags=re.MULTILINE) 327 #mt = re.search(r'^TITLE:', filestr, flags=re.MULTILINE) 328 #ma = re.search(r'^AUTHOR:', filestr, flags=re.MULTILINE) 329 cdate = re.compile(r'^DATE:', re.MULTILINE) # v2.6 way of doing it 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
348 -def make_one_line_paragraphs(filestr, format):
349 # THIS FUNCTION DOES NOT WORK WELL - it's difficult to make 350 # one-line paragraphs... 351 print 'make_one_line_paragraphs: this function does not work well' 352 print 'drop oneline_paragraphs option on the command line...' 353 # make double linebreaks to triple 354 filestr = re.sub('\n *\n', '[[[[[DOUBLE_NEWLINE]]]]]', filestr) 355 # save some single linebreaks 356 # section headings 357 filestr = re.sub('(===+)\n', r'\g<1>[[[[[SINGLE_NEWLINE]]]]]\n', filestr) 358 # tables 359 filestr = re.sub('(\\|\\s*)\n', r'\g<1>[[[[[SINGLE_NEWLINE]]]]]\n', filestr) 360 # idx/label/ref{} 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 # then remove all single linebreaks + following indentation 366 filestr = re.sub('\n *', ' ', filestr) 367 debugpr('\n\n\n**** ONELINE2:\n\n%s\n\n' % filestr) 368 # finally insert single and double linebreaks 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
377 -def insert_code_from_file(filestr, format):
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 # detect if we are inside verbatim blocks: 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 # Determine code environment from filename extension 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': # Cython code is called cy 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 # no from-to or fromto 435 fromto = 'fromto:' # default 436 437 #print index, words 438 if index == -1 and len(words) < 3: 439 # no from/to regex, read the whole file: 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 # fromto: was not found, that is okay, use the 451 # remaining words as patterns 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 # Note that from_ and to_ are regular expressions 463 # and to_ might be empty 464 cfrom = re.compile(from_) 465 cto = re.compile(to_) 466 467 # Task: copy from the line with from_ if fromto is 'fromto:', 468 # or copy from the line after the with from_ if fromto 469 # is 'from-to:', and copy all lines up to, but not including, 470 # the line matching to_ 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 # The test on not to_found ensures that 483 # we cannot get a second match for from_ 484 # (which copies to the end if there are no 485 # following matches for to_!) 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 # now the to_ line is not included 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 # Insert extra space to preserve 503 # continuation line 504 codeline = codeline[:-2] + '\\ \n' 505 codelines.append(codeline) 506 507 if mf and fromto == 'from-to:' and not from_found: 508 copy = True # start copy from next codeline 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() # remove trailing whitespace 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 #if format == 'latex' or format == 'pdflatex' or format == 'sphinx': 528 # Insert a cod or pro directive for ptex2tex and sphinx. 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
545 -def exercises(filestr, format):
546 # Exercise: ===== Exercise: title ===== (starts with at least 3 =, max 5) 547 # label{some:label} file=thisfile.py solution=somefile.do.txt or file.py 548 # __Hint 1.__ some paragraph..., 549 # __Hint 2.__ ... 550 551 debugpr('\n\n\n***** Interpreting exercises *****\n\n') 552 553 all_exer = [] # collection of all exercises 554 exer = {} # data for one exercise 555 inside_exer = False 556 exer_end = False 557 exer_counter = 0 558 lines = filestr.splitlines() 559 newlines = [] # lines in resulting file 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 = {} # data in the exercise 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 # Hints have to come at the end of the text. 597 # Only __Hint marks the beginning of a new hint. 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: # outside exercise 615 newlines.append(lines[i]) 616 617 # End of exercise? Either new (sub)section with at least === 618 # or end of file 619 if i == len(lines) - 1: # last line? 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
662 -def parse_keyword(keyword, format):
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] == ':': # strip off trailing colon 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: # part of function argument++ explanation? 680 parse = True 681 break 682 if not parse: 683 # no need to parse for variable type and name 684 if format == 'epytext': 685 # epytext does not have description lists, add a "bullet" - 686 keyword = '- ' + keyword 687 return keyword 688 689 # parse: 690 if 'return' in keyword: 691 type = 'return' 692 varname = None 693 type = ARGLIST[format][type] # formatting of keyword 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 # probably not a list of variable explanations 711 # construct "type varname" string, where varname is typeset in 712 # inline verbatim: 713 pattern = r'(?P<begin>^)(?P<subst>%s)(?P<end>$)' % varname 714 #varname = re.sub(pattern, INLINE_TAGS_SUBST[format]['verbatim'], varname) 715 keyword = ARGLIST[format][type] + ' ' + varname 716 return keyword
717 718
719 -def typeset_tables(filestr, format):
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 # table is a dict with keys rows, headings_align, columns_align 730 table = {'rows': []} # init new table 731 inside_table = False 732 for line in filestr.splitlines(): 733 lin = line.lstrip() 734 # horisontal table rule? 735 if lin.startswith('|--') and lin.endswith('-|'): 736 table['rows'].append(['horizontal rule']) 737 # see if there is c-l-r alignments: 738 align = lin[1:-1].replace('-', '') # keep | in align spec. 739 if align: 740 if align == '|'*len(align): # Just '|||'? 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 # first horizontal rule, align concern headings 752 table['headings_align'] = align 753 else: 754 # align concerns column alignment 755 table['columns_align'] = align 756 continue # continue with next line 757 if lin.startswith('|') and not lin.startswith('|--'): 758 # row in table: 759 if not inside_table: 760 inside_table = True 761 columns = line.strip().split('|') 762 # remove empty columns and extra white space: 763 #columns = [c.strip() for c in columns if c] 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 # just skip commented table lines 768 else: 769 if inside_table: 770 # not a table line anymore, but we were just inside a table 771 # so the table is ended 772 inside_table = False 773 result.write(TABLE[format](table)) # typeset table 774 table = {'rows': []} # init new table 775 else: 776 result.write(line + '\n') 777 return result.getvalue()
778
779 -def typeset_lists(filestr, format, debug_info=[]):
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 # for debugging only: 795 _code_block_no = 0; _tex_block_no = 0 796 797 for line in lines: 798 debugpr('\n------------------------\nsource line=[%s]' % line) 799 # do a syntax check: 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(): # blank line? 810 if not lists: 811 result.write(BLANKLINE[format]) 812 # else: drop writing out blank line inside lists 813 debugpr(' > This is a blank line') 814 lastline = line 815 continue 816 817 if line.startswith('#'): 818 819 # first do some debug output: 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 # the comment can be propagated to some formats 834 # (rst, latex, html): 835 line = line[1:] # strip off initial # 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 # structure of a line: 848 linescan = re.compile( 849 r"(?P<indent> *(?P<listtype>[*o-] )? *)" + 850 r"(?P<keyword>.+?:\s+)?(?P<text>.*)\s?") 851 #r"(?P<keyword>[^:]+?:)?(?P<text>.*)\s?") 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 # new (sub)section makes end of any indent (we could demand 864 # (sub)sections to start in column 1, but we have later relaxed 865 # such a requirement; it is easier to just test for ___ or === and 866 # set indent=0 here): 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 # begin a new list or sublist: 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 # inside a list, but not in the beginning 884 # (we don't write out blank lines inside lists anymore!) 885 # write a possible blank line if the format wants that between items 886 result.write(LIST[format]['separator']) 887 888 if indent < lastindent: 889 # end a list or sublist, nest back all list 890 # environments on the lists stack: 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 # (a separator (blank line) is written above because we need 904 # to ensure that the separator is not written in the top of 905 # an entire new list) 906 907 # first write the list item identifier: 908 itemformat = LIST[format][listtype]['item'] 909 if format == 'cwiki' or format == 'mwiki': 910 itemformat = itemformat*len(lists) # *, **, #, ## etc. for sublists 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 # indent here counts with '3. ': 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 # empty keyword, the regex has a bad problem: when only 924 # keyword on the line, keyword is None and text 925 # is keyword - make a fix here 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 = '' # to avoid adding keyword up in 935 # below (ugly hack, but easy linescan parsing...) 936 else: 937 debugpr(' > This is an item in a description list, but empty keyword, serious error....') 938 result.write(' '*(indent-2)) # indent here counts with '- ' 939 result.write(item) 940 if not (text.isspace() or text == ''): 941 #result.write('\n' + ' '*(indent-1)) 942 # Need special treatment if type specifications in 943 # descrption lists for sphinx API doc 944 if format == 'sphinx' and text.lstrip().startswith('type:'): 945 text = text.lstrip()[5:].lstrip() 946 # no newline for type info 947 else: 948 result.write('\n' + ' '*(indent)) 949 else: 950 debugpr(' > This is an item in a bullet list') 951 result.write(' '*(indent-2)) # indent here counts with '* ' 952 result.write(item + ' ') 953 954 else: 955 debugpr(' > This line is some ordinary line, no special list syntax involved') 956 # should check emph, verbatim, etc., syntax check and common errors 957 result.write(' '*indent) # ordinary line 958 959 # this is not a list definition line and therefore we must 960 # add keyword + text because these two items make up the 961 # line if a : present in an ordinary line 962 if keyword: 963 text = keyword + text 964 debugpr('text=[%s]' % text) 965 966 # hack to make wiki have all text in an item on a single line: 967 newline = '' if lists and (format == 'gwiki' or format == 'mwiki' or format == 'cwiki') \ 968 else '\n' # hack... 969 #newline = '\n' 970 result.write(text + newline) 971 lastindent = indent 972 lastline = line 973 974 # end lists if any are left: 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
983 -def handle_figures(filestr, format):
984 if not format in FIGURE_EXT: 985 # no special handling of figures: 986 return filestr 987 988 pattern = INLINE_TAGS['figure'] 989 c = re.compile(pattern, re.MULTILINE) 990 991 # First check if the figure files are of right type, then 992 # call format-specific functions for how to format the figures. 993 994 files = [filename for filename, options, caption in c.findall(filestr)] 995 if type(FIGURE_EXT[format]) is str: 996 extensions = [FIGURE_EXT[format]] # wrap in list 997 else: 998 extensions = FIGURE_EXT[format] 999 import sets; files = sets.Set(files) # remove multiple occurences 1000 for figfile in files: 1001 file_found = False 1002 if not os.path.isfile(figfile): 1003 basepath, ext = os.path.splitext(figfile) 1004 if not ext: # no extension? 1005 # try to see if f + ext exists: 1006 for ext in extensions: 1007 newname = figfile + ext 1008 if os.path.isfile(newname): 1009 print 'Figure file %s:\n can use %s for format %s' % \ 1010 (figfile, newname, format) 1011 filestr = filestr.replace(figfile, newname) 1012 figfile = newname 1013 file_found = True 1014 break 1015 # try to see if other extensions exist: 1016 if not file_found: 1017 candidate_files = glob.glob(figfile + '.*') 1018 for newname in candidate_files: 1019 if os.path.isfile(newname): 1020 print 'Found', newname 1021 filestr = filestr.replace(figfile, newname) 1022 figfile = newname 1023 file_found = True 1024 break 1025 if not os.path.isfile(figfile): 1026 #raise ValueError('file %s does not exist' % figfile) 1027 print 'Figure file %s does not exist' % figfile 1028 sys.exit(1) 1029 1030 basepath, ext = os.path.splitext(figfile) 1031 if not ext in extensions: 1032 # use convert from ImageMagick to convert to proper format: 1033 for e in extensions: 1034 converted_file = basepath + e 1035 if not os.path.isfile(converted_file): 1036 # ext might be empty, in that case we cannot convert 1037 # anything: 1038 if ext: 1039 failure = os.system('convert %s %s' % (figfile, converted_file)) 1040 if not failure: 1041 print 'Figure', figfile, 'must have extension(s)', extensions 1042 print '....converted %s to %s' % (figfile, converted_file) 1043 filestr = filestr.replace(figfile, converted_file) 1044 break # jump out of inner e loop 1045 else: # right file exists: 1046 #print '....ok, ', converted_file, 'exists' 1047 filestr = filestr.replace(figfile, converted_file) 1048 break 1049 1050 # replace FIGURE... by format specific syntax: 1051 try: 1052 replacement = INLINE_TAGS_SUBST[format]['figure'] 1053 filestr = c.sub(replacement, filestr) 1054 except KeyError: 1055 pass 1056 return filestr
1057 1058
1059 -def handle_cross_referencing(filestr, format):
1060 # 1. find all section/chapter titles and corresponding labels 1061 #section_pattern = r'(_+|=+)([A-Za-z !.,;0-9]+)(_+|=+)\s*label\{(.+?)\}' 1062 section_pattern = r'(_{3,7}|={3,7})(.+?)(_{3,7}|={3,7})\s*label\{(.+?)\}' 1063 m = re.findall(section_pattern, filestr) 1064 #pprint.pprint(m) 1065 # Make sure sections appear in the right order 1066 # (in case rst.ref_and_label_commoncode has to assign numbers 1067 # to section titles that are identical) 1068 section_label2title = OrderedDict() 1069 for dummy1, title, dummy2, label in m: 1070 section_label2title[label] = title.strip() 1071 #pprint.pprint(section_label2title) 1072 1073 # 2. perform format-specific editing of ref{...} and label{...} 1074 filestr = CROSS_REFS[format](section_label2title, format, filestr) 1075 return filestr
1076 1077
1078 -def handle_index_and_bib(filestr, format, has_title):
1079 """Process idx{...} and cite{...} instructions.""" 1080 index = {} # index[word] = lineno 1081 citations = OrderedDict() # citations[label] = no_in_list (1,2,3,...) 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 # note: line numbers in the .do.txt file are of very limited 1110 # value for the end format file...anyway, we make them... 1111 1112 cite_args = re.findall(r'cite\{(.+?)\}', line) 1113 if cite_args: 1114 # multiple labels can be separated by comma: 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 # new citation label 1122 citations[label] = cite_counter 1123 # Replace cite{label1,label2,...} by individual cite{label1} 1124 # cite{label2}, etc. if not latex or pandoc format 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 # prefix labels with @ and substitute , by ; 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 # version < 2.7 warning 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
1146 -def interpret_authors(filestr, format):
1147 debugpr('\n*** Dealing with authors and institutions ***') 1148 # first deal with AUTHOR as there can be several such lines 1149 author_lines = re.findall(r'^AUTHOR:\s*(?P<author>.+)\s*$', filestr, 1150 re.MULTILINE) 1151 #filestr = re.sub(r'^AUTHOR:.+$', 'XXXAUTHOR', filestr, flags=re.MULTILINE) 1152 cpattern = re.compile(r'^AUTHOR:.+$', re.MULTILINE) 1153 filestr = cpattern.sub('XXXAUTHOR', filestr) # v2.6 way of doing it 1154 # contract multiple AUTHOR lines to one single: 1155 filestr = re.sub('(XXXAUTHOR\n)+', 'XXXAUTHOR', filestr) 1156 1157 # (author, (inst1, inst2, ...) or (author, None) 1158 authors_and_institutions = [] 1159 for line in author_lines: 1160 if ' at ' in line: 1161 # author and institution(s) given 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: # just author's name 1173 a = line.strip() 1174 i = None 1175 if 'mail:' in a: # email? 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 # get unique institutions: 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] = '' # leads to empty address 1202 auth2email[a] = e 1203 1204 # version < 2.7 warning: 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
1209 -def typeset_authors(filestr, format):
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
1219 -def inline_tag_subst(filestr, format):
1220 """Deal with all inline tags by substitution.""" 1221 # Note that all tags are *substituted* so that the sequence of 1222 # operations are not important for the contents of the document - we 1223 # choose a sequence that is appropriate from a substitution point 1224 # of view 1225 1226 filestr = typeset_authors(filestr, format) 1227 1228 # deal with DATE: today (i.e., find today's date) 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 #'figure', # done separately 1242 'abstract', # must become before sections since it tests on === 1243 # important to do section, subsection, etc. BEFORE paragraph and bold: 1244 'emphasize', 'math2', 'math', 1245 'chapter', 'section', 'subsection', 'subsubsection', 1246 'bold', 1247 'inlinecomment', 1248 'verbatim', 1249 'citation', 1250 'paragraph', # after bold and emphasize 1251 'plainURL', # before linkURL2 to avoid "URL" as link name 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 #print 'working with tag "%s" = "%s"' % (tag, tag_pattern) 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 # just ignore missing tags in current format 1270 if replacement is None: 1271 continue # no substitution 1272 1273 if isinstance(replacement, basestring): 1274 # first some info for debug output: 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 # treat line by line because replacement string depends 1288 # on the match object for each occurence 1289 # (this is mainly for headlines in rst format) 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 #raise Exception(e) 1302 # Raising exception is misleading since the 1303 # error occured in the replacement function 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
1316 -def subst_away_inline_comments(filestr):
1317 # inline comments: [hpl: this is a comment] 1318 pattern = r'\[(?P<name>[A-Za-z0-9_ ,.@]+?):(?P<comment>[^\]]*?)\]\s*' 1319 filestr = re.sub(pattern, '', filestr) 1320 return filestr
1321
1322 -def subst_class_func_mod(filestr, format):
1323 if format == 'sphinx' or format == 'rst': 1324 return filestr 1325 1326 # Replace :mod:`~my.pack.mod` by `my.pack.mod` 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 # if trouble with encoding: 1346 # Unix> doconce guess_encoding myfile.do.txt 1347 # Unix> doconce change_encoding utf-8 latin1 myfile.do.txt 1348 # or plain Unix: 1349 # Unix> file myfile.do.txt 1350 # myfile.do.txt: UTF-8 Unicode English text 1351 # Unix> # convert to latin-1: 1352 # Unix> iconv -f utf-8 -t LATIN1 myfile.do.txt --output newfile 1353 if encoding: # global variable 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
1374 -def doconce2format4docstrings(filestr, format):
1375 """Run doconce2format on all doc strings in a Python file.""" 1376 1377 c1 = re.compile(r'^\s*(class|def)\s+[A-Za-z0-9_,() =]+:\s+(""".+?""")', 1378 re.DOTALL|re.MULTILINE) 1379 c2 = re.compile(r"^\s*(class|def)\s+[A-Za-z0-9_,() =]+:\s+('''.+?''')", 1380 re.DOTALL|re.MULTILINE) 1381 doc_strings = [doc_string for dummy, doc_string in c1.findall(filestr)] + \ 1382 [doc_string for dummy, doc_string in c2.findall(filestr)] 1383 lines = filestr.splitlines() 1384 for i, line in enumerate(lines): 1385 if not line.lstrip().startswith('#'): 1386 break 1387 filestr2 = '\n'.join(lines[i:]) 1388 c3 = re.compile(r'^\s*""".+?"""', re.DOTALL) # ^ is the very start 1389 c4 = re.compile(r"^\s*'''.+?'''", re.DOTALL) # ^ is the very start 1390 doc_strings = c3.findall(filestr2) + c4.findall(filestr2) + doc_strings 1391 1392 # Find and remove indentation 1393 all = [] 1394 for doc_string in doc_strings: 1395 lines = doc_string.splitlines() 1396 if len(lines) > 1: 1397 indent = 0 1398 line1 = lines[1] 1399 while line1[indent] == ' ': 1400 indent += 1 1401 for i in range(1, len(lines)): 1402 lines[i] = lines[i][indent:] 1403 all.append(('\n'.join(lines), indent)) 1404 else: 1405 all.append((doc_string, None)) 1406 1407 for doc_string, indent in all: 1408 new_doc_string = doconce2format(doc_string, format) 1409 if indent is not None: 1410 lines = new_doc_string.splitlines() 1411 for i in range(1, len(lines)): 1412 lines[i] = ' '*indent + lines[i] 1413 new_doc_string = '\n'.join(lines) 1414 lines = doc_string.splitlines() 1415 for i in range(1, len(lines)): 1416 if lines[i].isspace() or lines[i] == '': 1417 pass # don't indent blank lines 1418 else: 1419 lines[i] = ' '*indent + lines[i] 1420 doc_string = '\n'.join(lines) 1421 1422 filestr = filestr.replace(doc_string, new_doc_string) 1423 1424 return filestr
1425
1426 -def doconce2format(filestr, format):
1427 # A special case: `!bc`, `!bt`, `!ec`, and `!et` at the beginning 1428 # of a line gives wrong consistency checks for plaintext format, 1429 # so we avoid having these at the beginning of a line. 1430 if format == 'plain': 1431 for directive in 'bc', 'ec', 'bt', 'et': 1432 cpattern = re.compile(r'^`!%s' % directive, re.MULTILINE) 1433 filestr = cpattern.sub(' `!%s' % directive, 1434 filestr) # space avoids beg.of line 1435 syntax_check(filestr, format) 1436 1437 1438 # ----------------------------------------------------------------- 1439 1440 # Step: check if ^#?TITLE: is present, and if so, header and footer 1441 # are to be included (later below): 1442 if re.search(r'^#?TITLE:', filestr, re.MULTILINE): 1443 has_title = True 1444 else: 1445 has_title = False 1446 1447 # Next step: insert verbatim code from other (source code) files: 1448 # (if the format is latex, we could let ptex2tex do this, but 1449 # the CODE start@stop specifications may contain uderscores and 1450 # asterix, which will be replaced later and hence destroyed) 1451 #if format != 'latex': 1452 filestr = insert_code_from_file(filestr, format) 1453 debugpr('%s\n**** The file after inserting @@@CODE (from file):\n\n%s\n\n' % \ 1454 ('*'*80, filestr)) 1455 1456 # hack to fix a bug with !ec/!et at the end of files, which is not 1457 # correctly substituted by '' in rst, sphinx, st, epytext, plain 1458 # (the fix is to add "enough" blank lines) 1459 if format in ('rst', 'sphinx', 'st', 'epytext', 'plain'): 1460 filestr = filestr.rstrip() 1461 if filestr.endswith('!ec') or filestr.endswith('!et'): 1462 filestr += '\n'*10 1463 1464 # Next step: remove all verbatim and math blocks 1465 1466 filestr, code_blocks, tex_blocks = remove_code_and_tex(filestr) 1467 1468 # for html we should make replacements of < and > in code_blocks, 1469 # since these can be interpreted as tags, and we must 1470 # handle latin-1 characters 1471 if format == 'html': # fix 1472 for i in range(len(code_blocks)): 1473 # This does not catch things like '<x ...<y>' 1474 #code_blocks[i] = re.sub(r'(<)([^>]*?)(>)', 1475 # '&lt;\g<2>&gt;', code_blocks[i]) 1476 code_blocks[i] = code_blocks[i].replace('<', '&lt;') 1477 code_blocks[i] = code_blocks[i].replace('>', '&gt;') 1478 1479 # This special character transformation is easier done 1480 # with encoding="utf-8" in the first line in the html file: 1481 # (but we do it explicitly to make it robust) 1482 filestr = html.latin2html(filestr) 1483 elif format == 'latex' or format == 'pdflatex': # fix 1484 # labels inside tex envirs must have backslash \label: 1485 for i in range(len(tex_blocks)): 1486 tex_blocks[i] = re.sub(r'([^\\])label', r'\g<1>\\label', 1487 tex_blocks[i]) 1488 1489 debugpr('%s\n**** The file after removal of code/tex blocks:\n\n%s\n\n' % \ 1490 ('*'*80, filestr)) 1491 debugpr('%s\n**** The code blocks:\n\n%s\n\n' % \ 1492 ('*'*80, pprint.pformat(code_blocks))) 1493 debugpr('%s\n**** The tex blocks:\n\n%s\n\n' % \ 1494 ('*'*80, pprint.pformat(tex_blocks))) 1495 1496 # remove linebreaks within paragraphs: 1497 if oneline_paragraphs: # (does not yet work well) 1498 filestr = make_one_line_paragraphs(filestr, format) 1499 1500 if skip_inline_comments: 1501 filestr = subst_away_inline_comments(filestr) 1502 1503 # Next step: deal with exercises 1504 filestr = exercises(filestr, format) 1505 1506 # Next step: deal with figures 1507 filestr = handle_figures(filestr, format) 1508 1509 # Next step: deal with cross referencing (must occur before other format subst) 1510 filestr = handle_cross_referencing(filestr, format) 1511 1512 debugpr('%s\n**** The file after handling ref and label cross referencing\n\n%s\n\n' % ('*'*80, filestr)) 1513 1514 # Next step: deal with index and bibliography (must be done before lists): 1515 filestr = handle_index_and_bib(filestr, format, has_title) 1516 1517 debugpr('%s\n**** The file after handling index and bibliography\n\n%s\n\n' % ('*'*80, filestr)) 1518 1519 # Next step: deal with lists 1520 filestr = typeset_lists(filestr, format, 1521 debug_info=[code_blocks, tex_blocks]) 1522 debugpr('%s\n**** The file after typesetting of list:\n\n%s\n\n' % \ 1523 ('*'*80, filestr)) 1524 1525 # Next step: deal with tables 1526 filestr = typeset_tables(filestr, format) 1527 debugpr('%s\n**** The file after typesetting of tables:\n\n%s\n\n' % \ 1528 ('*'*80, filestr)) 1529 1530 # Next step: do substitutions: 1531 filestr = inline_tag_subst(filestr, format) 1532 1533 debugpr('%s\n**** The file after all inline substitutions:\n\n%s\n\n' % ('*'*80, filestr)) 1534 1535 # Next step: substitute latex-style newcommands in filestr and tex_blocks 1536 # (not in code_blocks) 1537 from expand_newcommands import expand_newcommands 1538 if format != 'latex' and format != 'pdflatex' and format != 'pandoc': 1539 newcommand_files = ['newcommands_replace.tex'] 1540 if format == 'sphinx': # replace all newcommands in sphinx 1541 newcommand_files.extend(['newcommands.tex', 'newcommands_keep.tex']) 1542 # note: could use substitutions (|newcommand|) in rst/sphinx, 1543 # but they don't allow arguments so expansion of \newcommand 1544 # is probably a better solution 1545 filestr = expand_newcommands(newcommand_files, filestr) 1546 for i in range(len(tex_blocks)): 1547 tex_blocks[i] = expand_newcommands(newcommand_files, tex_blocks[i]) 1548 1549 # Next step: subst :class:`ClassName` by `ClassName` for 1550 # non-rst/sphinx formats: 1551 filestr = subst_class_func_mod(filestr, format) 1552 1553 # Next step: insert verbatim and math code blocks again: 1554 filestr = insert_code_and_tex(filestr, code_blocks, tex_blocks, format) 1555 filestr += '\n' 1556 1557 # Next step: substitute code and tex environments: 1558 filestr = CODE[format](filestr, format) 1559 debugpr('%s\n**** The file after inserting tex/code blocks:\n\n%s\n\n' % \ 1560 ('*'*80, filestr)) 1561 1562 if has_title: 1563 if format in INTRO: 1564 filestr = INTRO[format] + filestr 1565 if format in OUTRO: 1566 filestr = filestr + OUTRO[format] 1567 1568 if format == 'latex' or format == 'pdflatex': 1569 if r'\includemovie[' not in filestr: 1570 # avoid the need for movie15 package in latex file 1571 filestr = filestr.replace('define MOVIE', 'undef MOVIE') 1572 1573 return filestr
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 # First guess if preprocess or mako is used 1589 preprocess_commands = r'^#\s*#(if|define|include)' 1590 mako_commands = r'^\s*<?%' 1591 if re.search(preprocess_commands, filestr, re.MULTILINE): 1592 #print 'run preprocess on', filename, 'to make', resultfile 1593 preprocessor = 'preprocess' 1594 # Add -D to name=value options (mako style parameters) 1595 preprocess_options = preprocessor_options[:] # copy 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 # Syntax check: preprocess directives without leading #? 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 # Make filestr the result of preprocess in case mako shall be run 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: # already found preprocess commands? 1640 # The output is in resultfile, preprocess is run on that 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 # add a space after \\ at the end of lines (otherwise mako 1658 # eats one of the backslashes in tex blocks) 1659 # same for a single \ before newline 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 # Try eval(value), if it fails, assume string 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 # no preprocessor syntax detected 1707 resultfile = filename 1708 1709 return resultfile
1710
1711 -def main():
1712 # doconce format accepts special command-line arguments: 1713 # - debug (for debugging in file _doconce_debugging.log) or 1714 # - skip_inline_comments 1715 # - oneline (for removal of newlines/linebreaks within paragraphs) 1716 # - encoding utf-8 (e.g.) 1717 # - preprocessor options (-DVAR etc. for preprocess) 1718 1719 # oneline is inactive (doesn't work well yet) 1720 1721 options = ['debug', 'skip_inline_comments', 'encoding=', 1722 'oneline_paragraphs',] # 'tmp1'] 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 #print '\n----- doconce format %s %s' % (format, filename) 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) # clean up 1808 #print '----- successful run: %s filtered to %s\n' % (filename, out_filename) 1809 print 'output in', out_filename
1810 1811 if __name__ == '__main__': 1812 main() 1813