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

Source Code for Module doconce.common

  1  """ 
  2  This module contains data structures used in translation of the 
  3  Doconce format to other formats.  Some convenience functions used in 
  4  translation modules (latex.py, html.py, etc.) are also included in 
  5  here. 
  6  """ 
  7  import re, sys 
  8   
  9  # Identifiers in the text used to identify code and math blocks 
 10  _CODE_BLOCK = '<<<!!CODE_BLOCK' 
 11  _MATH_BLOCK = '<<<!!MATH_BLOCK' 
 12   
13 -def where():
14 """ 15 Return the location where the doconce package is installed. 16 """ 17 # Technique: find the directory where this common.py file resides 18 import os 19 return os.path.dirname(__file__)
20
21 -def indent_lines(text, format, indentation=' '*8):
22 """ 23 Indent each line in the string text, provided in a format for 24 HTML, LaTeX, epytext, ..., by the blank string indentation. 25 Return new version of text. 26 """ 27 if format == 'epytext': 28 # some formats (Epytext) give wrong behavior if there is a \n 29 # in code or tex blocks (\nabla is one example), hence we 30 # comment out the block in those cases: (\b also gives problems... 31 # it seems that Epytext is not capable of doing raw strings here) 32 if re.search(r'\\n', text): 33 comment_out = True 34 text = """\ 35 36 NOTE: A verbatim block has been removed because 37 it causes problems for Epytext. 38 """ 39 return text 40 41 # indent X chars (choose X=6 for sufficient indent in lists) 42 text = '\n'.join([indentation + line for line in text.splitlines()]) 43 return text
44 45
46 -def table_analysis(table):
47 """Return max width of each column.""" 48 column_list = [] 49 for i, row in enumerate(table): 50 if row != ['horizontal rule']: 51 if not column_list: 52 column_list = [[]]*len(row) 53 for j, column in enumerate(row): 54 column_list[j].append(len(column)) 55 return [max(c) for c in column_list]
56 57
58 -def ref2equations(filestr):
59 """ 60 Replace references to equations: 61 (ref{my:label}) -> Equation (my:label) 62 (ref{my:label1})-(ref{my:label2}) -> Equations (my:label1)-(my:label2) 63 (ref{my:label1}) and (ref{my:label2}) -> Equations (my:label1) and (my:label2) 64 (ref{my:label1}), (ref{my:label2}) and (ref{my:label3}) -> Equations (my:label1), (my:label2) and (ref{my:label2}) 65 """ 66 filestr = re.sub(r'\(ref\{(.+?)\}\)-\(ref\{(.+?)\}\)', 67 r'Equations (\g<1>)-(\g<2>)', filestr) 68 filestr = re.sub(r'\(ref\{(.+?)\}\)\s+and\s+\(ref\{(.+?)\}\)', 69 r'Equations (\g<1>) and (\g<2>)', filestr) 70 filestr = re.sub(r'\(ref\{(.+?)\}\),\s*\(ref\{(.+?)\}\)(,?)\s+and\s+\(ref\{(.+?)\}\)', 71 r'Equations (\g<1>), (\g<2>)\g<3> and (\g<4>)', filestr) 72 filestr = re.sub(r'\(ref\{(.+?)\}\)', 73 r'Equation (\g<1>)', filestr) 74 return filestr
75
76 -def default_movie(m):
77 """Replace a movie entry by a proper URL with text.""" 78 # Note: essentially same code as html_movie 79 import os, glob 80 filename = m.group('filename') 81 options = m.group('options') 82 caption = m.group('caption') 83 84 # Turn options to dictionary 85 if ',' in options: 86 options = options.split(',') 87 else: 88 options = options.split() 89 kwargs = {} 90 for opt in options: 91 if opt.startswith('width') or opt.startswith('WIDTH'): 92 kwargs['width'] = int(opt.split('=')[1]) 93 if opt.startswith('height') or opt.startswith('HEIGHT'): 94 kwargs['height'] = int(opt.split('=')[1]) 95 96 if '*' in filename: 97 # Glob files and use DocWriter.html_movie to make a separate 98 # HTML page for viewing the set of files 99 plotfiles = sorted(glob.glob(filename)) 100 if not plotfiles: 101 print 'No plotfiles on the form', filename 102 sys.exit(1) 103 basename = os.path.basename(plotfiles[0]) 104 stem, ext = os.path.splitext(basename) 105 kwargs['casename'] = stem 106 import DocWriter 107 header, jscode, form, footer = DocWriter.html_movie(plotfiles, **kwargs) 108 #text = jscode + form # does not work well with several movies 109 moviehtml = stem + '.html' 110 f = open(moviehtml, 'w') 111 f.write(header + jscode + form + footer) 112 f.close() 113 text = """\n%s (Movie of files `%s` in URL:"%s")\n""" % \ 114 (caption, filename, moviehtml) 115 elif 'youtube.com' in filename: 116 # Rename embedded files to ordinary YouTube 117 filename = filename.replace('embed/', 'watch?v=') 118 text = '%s: URL:"%s"' % (caption, filename) 119 else: 120 # Make an HTML file where the movie file can be played 121 # (alternative to launching a player manually) 122 stem = os.path.splitext(os.path.basename(filename))[0] 123 moviehtml = stem + '.html' 124 f = open(moviehtml, 'w') 125 f.write(""" 126 <HTML> 127 <BODY> 128 <TITLE>Embedding movie %s in HTML</TITLE> 129 <EMBED SRC="%s" %s AUTOPLAY="TRUE" LOOP="TRUE"></EMBED> 130 <P> 131 <EM>%s</EM> 132 </P> 133 </BODY> 134 </HTML> 135 """ % (filename, filename, ' '.join(options), caption)) 136 text = '%s (Movie %s: play URL:"%s")' % (caption, filename, moviehtml) 137 return text
138
139 -def remove_code_and_tex(filestr):
140 """ 141 Remove verbatim and latex (math) code blocks from the file and 142 store separately in lists (code_blocks and tex_blocks). 143 The function insert_code_and_tex will insert these blocks again. 144 """ 145 # Method: 146 # store code and tex blocks in lists and substitute these blocks 147 # by the contents of _CODE_BLOCK and _MATH_BLOCK (arguments after 148 # !bc must be copied after _CODE_BLOCK). 149 # later we replace _CODE_BLOCK by !bc and !ec and the code block again 150 # (similarly for the tex/math block). 151 152 # (recall that !bc can be followed by extra information that we must keep:) 153 code = re.compile(r'^!bc(.*?)\n(.*?)^!ec *\n', re.DOTALL|re.MULTILINE) 154 155 # Note: final \n is required and may be missing if there is a block 156 # at the end of the file, so let us ensure that a blank final 157 # line is appended to the text: 158 if filestr[-1] != '\n': 159 filestr = filestr + '\n' 160 161 code_blocks = [c for opt, c in code.findall(filestr)] 162 163 tex = re.compile(r'^!bt\n(.*?)^!et *\n', re.DOTALL|re.MULTILINE) 164 tex_blocks = tex.findall(filestr) 165 166 # Record for consistency check 167 nbc = len(re.compile(r'^!bc', re.MULTILINE).findall(filestr)) 168 nec = len(re.compile(r'^!ec', re.MULTILINE).findall(filestr)) 169 nbt = len(re.compile(r'^!bt', re.MULTILINE).findall(filestr)) 170 net = len(re.compile(r'^!et', re.MULTILINE).findall(filestr)) 171 #nbc2 = sum(1 for line in filestr.splitlines() if line.startswith('!bc')) 172 def find2(filestr, begin_pattern, end_pattern): 173 lines = filestr.splitlines() 174 begin_ends = [] 175 for i, line in enumerate(lines): 176 if line.startswith(begin_pattern): 177 begin_ends.append((begin_pattern, i)) 178 if line.startswith(end_pattern): 179 begin_ends.append((end_pattern, i)) 180 for k in range(1, len(begin_ends)): 181 pattern, i = begin_ends[k] 182 if pattern == begin_ends[k-1][0]: 183 print '\n\nTwo', pattern, 'after each other!\n' 184 for j in range(begin_ends[k-1][1], begin_ends[k][1]+1): 185 print lines[j] 186 sys.exit(1)
187 188 if nbc != nec: 189 print '%d !bc do not match %d !ec directives' % (nbc, nec) 190 find2(filestr, '!bc', '!ec') 191 sys.exit(1) 192 if nbt != net: 193 print '%d !bt do not match %d !et directives' % (nbt, net) 194 find2(filestr, '!bt', '!et') 195 sys.exit(1) 196 if nbc != len(code_blocks): 197 print '%d !bc and %d extracted code blocks - BUG!!!' % \ 198 (nbc, len(code_blocks)) 199 if nbt != len(tex_blocks): 200 print '%d !bt and %d extracted tex blocks - BUG!!!' % \ 201 (nbt, len(tex_blocks)) 202 203 # Remove blocks and substitute by a one-line sign 204 filestr = code.sub('%s \g<1>\n' % _CODE_BLOCK, filestr) 205 filestr = tex.sub('%s\n' % _MATH_BLOCK, filestr) 206 207 # could leave @@@CODE blocks to ptex2tex, but then these lines must be 208 # removed since they may contain underscores and asterix and hence 209 # be destroyed by substutitions of inline tags 210 211 return filestr, code_blocks, tex_blocks 212 213
214 -def insert_code_and_tex(filestr, code_blocks, tex_blocks, format):
215 lines = filestr.splitlines() 216 for code in code_blocks: 217 # this construction does not handle newlines in regex and 218 # similar verbatim environments properly: 219 #filestr = re.sub(r'%s (.*?)\n' % _CODE_BLOCK, 220 # '!bc\g<1>\n%s!ec\n' % code, filestr, 1) 221 # use string.replace instead 222 223 for i in range(len(lines)): 224 if _CODE_BLOCK in lines[i]: 225 # use re.sub for the heading when we need a group: 226 lines[i] = re.sub('%s(.*)' % _CODE_BLOCK, 227 '!bc\g<1>\n!XX&XX', lines[i]) 228 # use string.replace to deal correctly with \n: 229 try: 230 #lines[i] = lines[i].replace('!XX&XX', '%s\n!ec' % code) 231 # the \n should not be there (gives extra newline) 232 lines[i] = lines[i].replace('!XX&XX', '%s!ec' % code) 233 except UnicodeDecodeError, e: 234 raise UnicodeDecodeError(e + '\nproblem with code block:\n' + code) 235 break 236 for tex in tex_blocks: 237 # Also here problems with this: (\nabla becomes \n (newline) and abla) 238 # which means that 239 # filestr = re.sub(_MATH_BLOCK, '!bt\n%s!et' % tex, filestr, 1) 240 # does not work properly. Instead, we use str.replace 241 242 if format == 'latex' or format == 'pdflatex': # fix 243 # ref/label is ok outside tex environments (see test in 244 # cross_referencing), but inside !bt/!et environments the user 245 # is allowed to have ref and label without backslashes 246 # and these must be equipped by backslashes in LaTeX format 247 filestr = re.sub(r'([^\\])label\{', r'\g<1>\label{', filestr) 248 filestr = re.sub(r'([^\\])ref\{', r'\g<1>\\ref{', filestr) 249 250 for i in range(len(lines)): 251 if _MATH_BLOCK in lines[i]: 252 lines[i] = lines[i].replace(_MATH_BLOCK, 253 '!bt\n%s!et' % tex) 254 break 255 filestr = '\n'.join(lines) 256 return filestr
257
258 -def plain_exercise(exer):
259 s = '' # result string 260 if not 'heading' in exer: 261 print 'Wrong formatting of exercise, not a 3/5 === type heading' 262 print exer 263 sys.exit(1) 264 265 #s += exer['heading'] + ' ' + exer['type'] + ' ' + exer['no'] + ': ' + exer['title'] + ' ' + exer['heading'] + '\n' 266 s += exer['heading'] + ' ' + exer['title'] + ' ' + exer['heading'] + '\n' 267 # Write out label - it will be treated right in all formats 268 if 'label' in exer: 269 s += 'label{%s}' % exer['label'] + '\n' 270 s += '\n' + exer['text'] + '\n' 271 for hint_no in sorted(exer['hint']): 272 s += '\n' + exer['hint'][hint_no] + '\n' 273 if 'file' in exer: 274 s += '*Filename*: `%s`' % exer['file'] + '\n' 275 #s += '\n' + '*Filename*: `%s`' % exer['file'] + '\n' 276 if 'solution' in exer: 277 pass 278 if 'comments' in exer: 279 s += '\n' + exer['comments'] 280 return s
281 282 283 284 BLANKLINE = {} 285 FILENAME_EXTENSION = {} 286 LIST = {} 287 CODE = {} 288 # listing of function parameters/arguments and return values: 289 ARGLIST = {} 290 DEFAULT_ARGLIST = { 291 'parameter': 'argument', 292 'keyword': 'keyword argument', 293 'return': 'return value(s)', 294 'instance variable': 'instance variable', 295 'class variable': 'class variable', 296 'module variable': 'module variable', 297 } 298 TABLE = {} 299 FIGURE_EXT = {} 300 CROSS_REFS = {} 301 INDEX_BIB = {} 302 INTRO = {} 303 OUTRO = {} 304 EXERCISE = {} 305 306 307 # regular expressions for inline tags: 308 inline_tag_begin = r"""(?P<begin>(^|[(\s]))""" 309 inline_tag_end = r"""(?P<end>($|[.,?!;:)\s]))""" 310 # alternatives using positive lookbehind and lookahead (not tested!): 311 inline_tag_before = r"""(?<=^(|[(\s])))""" 312 inline_tag_after = r"""(?=($|[.,?!;:)\s]))""" 313 _linked_files = '''\s*"(?P<url>([^"]+?\.html?|[^"]+?\.txt|[^"]+?\.pdf|[^"]+?\.f|[^"]+?\.c|[^"]+?\.cpp|[^"]+?\.cxx|[^"]+?\.py|[^"]+?\.java|[^"]+?\.pl|[^"]+?\.sh|[^"]+?\.csh|[^"]+?\.zsh|[^"]+?\.ksh|[^"]+?\.tar\.gz|[^"]+?\.tar|[^"]+?\.f77|[^"]+?\.f90|[^"]+?\.f95))"''' 314 315 INLINE_TAGS = { 316 # math: text inside $ signs, as in $a = b$, with space before the 317 # first $ and space, comma, period, colon, semicolon, or question 318 # mark after the enclosing $. 319 'math': 320 r'%s\$(?P<subst>[^ `][^$`]*)\$%s' % \ 321 (inline_tag_begin, inline_tag_end), 322 323 # $latex text$|$pure text alternative$ 324 'math2': 325 r'%s\$(?P<latexmath>[^ `][^$`]*)\$\|\$(?P<puretext>[^ `][^$`]*)\$%s' % \ 326 (inline_tag_begin, inline_tag_end), 327 # simpler (not tested): 328 #r'%s\$(?P<latexmath>[^$]+?)\$\|\$(?P<puretext>[^$]+)\$%s' % \ 329 #(inline_tag_begin, inline_tag_end), 330 331 # *emphasized words* 332 'emphasize': 333 r'%s\*(?P<subst>[^ `][^*`]*)\*%s' % \ 334 (inline_tag_begin, inline_tag_end), 335 336 # `verbatim inline text is enclosed in back quotes` 337 'verbatim': 338 r'%s`(?P<subst>[^ ][^`]*)`%s' % \ 339 (inline_tag_begin, inline_tag_end), 340 341 # _underscore before and after signifies bold_ 342 'bold': 343 r'%s_(?P<subst>[^ `][^\]_`]*)_%s' % \ 344 (inline_tag_begin, inline_tag_end), 345 346 # cite{labelname} 347 'citation': 348 r' cite\{(?P<subst>[^}]+)\}', 349 350 # http://some.where.org/mypage<link text> # old outdated syntax 351 'linkURL': 352 r'%s(?P<url>https?://[^<\n]+)<(?P<link>[^>]+)>%s' % \ 353 (inline_tag_begin, inline_tag_end), 354 355 'linkURL2': # "some link": "https://bla-bla" 356 r'''"(?P<link>[^"]+?)" ?:\s*"(?P<url>(file:/|https?:)//.+?)"''', 357 #r'"(?P<link>[^>]+)" ?: ?"(?P<url>https?://[^<]+?)"' 358 359 'linkURL2v': # "`filelink`": "https://bla-bla" 360 r'''"`(?P<link>[^"]+?)`" ?:\s*"(?P<url>(file:/|https?:)//.+?)"''', 361 362 'linkURL3': # "some link": "some/local/file/name.html" or .txt/.pdf/.py/.c/.cpp/.cxx/.f/.java/.pl files 363 #r'''"(?P<link>[^"]+?)" ?:\s*"(?P<url>([^"]+?\.html?|[^"]+?\.txt|[^"]+?.pdf))"''', 364 r'''"(?P<link>[^"]+?)" ?:''' + _linked_files, 365 #r'"(?P<link>[^>]+)" ?: ?"(?P<url>https?://[^<]+?)"' 366 'linkURL3v': # "`somefile`": "some/local/file/name.html" or .txt/.pdf/.py/.c/.cpp/.cxx/.f/.java/.pl files 367 r'''"`(?P<link>[^"]+?)`" ?:''' + _linked_files, 368 369 'plainURL': 370 #r'"URL" ?: ?"(?P<url>.+?)"', 371 #r'"?(URL|url)"? ?: ?"(?P<url>.+?)"', 372 r'("URL"|"url"|URL|url) ?:\s*"(?P<url>.+?)"', 373 374 'inlinecomment': 375 r'''\[(?P<name>[A-Za-z0-9_'-]+?):\s+(?P<comment>[^\]]*?)\]''', 376 377 'abstract': # __Abstract.__ Any text up to a headline === 378 r"""^\s*__(?P<type>Abstract|Summary).__\s*(?P<text>.+?)(?P<rest>\s*[_=]{3,9})""", 379 380 # ======= Seven Equality Signs for Headline ======= 381 # (the old underscores instead of = are still allowed) 382 'section': 383 #r'^_{7}(?P<subst>[^ ].*)_{7}\s*$', 384 # previous: r'^\s*_{7}(?P<subst>[^ ].*?)_+\s*$', 385 #r'^\s*[_=]{7}\s*(?P<subst>[^ ].*?)\s*[_=]+\s*$', 386 r'^\s*[_=]{7}\s*(?P<subst>[^ =-].+?)\s*[_=]+\s*$', 387 388 'chapter': 389 r'^\s*[_=]{9}\s*(?P<subst>[^ =-].+?)\s*[_=]+\s*$', 390 391 'subsection': 392 #r'^\s*_{5}(?P<subst>[^ ].*?)_+\s*$', 393 #r'^\s*[_=]{5}\s*(?P<subst>[^ ].*?)\s*[_=]+\s*$', 394 r'^\s*[_=]{5}\s*(?P<subst>[^ =-].+?)\s*[_=]+\s*$', 395 396 'subsubsection': 397 #r'^\s*_{3}(?P<subst>[^ ].*?)_+\s*$', 398 #r'^\s*[_=]{3}\s*(?P<subst>[^ ].*?)\s*[_=]+\s*$', 399 r'^\s*[_=]{3}\s*(?P<subst>[^ =-].+?)\s*[_=]+\s*$', 400 401 # __Two underscores for Inline Paragraph Title.__ 402 'paragraph': 403 r'(?P<begin>^)__(?P<subst>.+?)__\s+', 404 #r'(?P<begin>^)[_=]{2}\s*(?P<subst>[^ =-].+?)[_=]{2}\s+', 405 406 # TITLE: My Document Title 407 'title': 408 r'^TITLE:\s*(?P<subst>.+)\s*$', 409 410 # AUTHOR: Some Name 411 'author': 412 #r'^AUTHOR:\s*(?P<name>.+?)\s+at\s+(?P<institution>.+)\s*$', 413 # for backward compatibility (comma or at as separator): 414 r'^AUTHOR:\s*(?P<name>.+?)(,|\s+at\s+)(?P<institution>.+)\s*$', 415 416 # DATE: Jan 27, 2010 417 'date': 418 r'^DATE:\s*(?P<subst>.+)\s*$', 419 420 # FIGURE:[filename, options] some caption text label{some:label} 421 'figure': 422 r'^FIGURE:\s*\[(?P<filename>[^,\]]+),?(?P<options>[^\]]*)\]\s*?(?P<caption>.*)$', 423 # MOVIE:[filename, options] some caption text label{some:label} 424 'movie': 425 r'^MOVIE:\s*\[(?P<filename>[^,\]]+),?(?P<options>[^\]]*)\]\s*?(?P<caption>.*)$', 426 } 427 INLINE_TAGS_SUBST = {} 428 429 # frequent syntax errors that we can test for: (not yet used) 430 heading_error = (r'(^ [_=]+[^_=]*|^[_=]+[^ _=]*$)', 431 'Initial spaces or missing underscore(s) or = at the end') 432 INLINE_TAGS_BUGS = { 433 # look for space after first special character ($ ` _ etc) 434 'math': (r'%s(?P<subst>\$ [^$]*\$)%s' % (inline_tag_begin, inline_tag_end), 435 'Space after first $ in inline math expressions'), 436 'emphasize': None, # *item with *emph* word is legal (no error) 437 'verbatim': (r'%s(?P<subst>` [^`]*`)%s' % \ 438 (inline_tag_begin, inline_tag_end), 439 'Space after first ` in inline verbatim expressions'), 440 'bold': (r'%s(?P<subst>_ [^_]*_)%s' % \ 441 (inline_tag_begin, inline_tag_end), 442 'Space after first _ in inline boldface expressions'), 443 'section': heading_error, 444 'subsection': heading_error, 445 'subsubsection': heading_error, 446 'paragraph': heading_error, 447 } 448 449 LIST_SYMBOL = {'*': 'itemize', 'o': 'enumerate', '-': 'description'} 450