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

Source Code for Module doconce.latex

  1  # -*- coding: iso-8859-15 -*- 
  2   
  3  import os, commands, re, sys 
  4  from common import plain_exercise, table_analysis 
  5  additional_packages = ''  # comma-sep. list of packages for \usepackage{} 
  6   
7 -def latex_code(filestr, format):
8 lines = filestr.splitlines() 9 arg = None 10 bc_arg = re.compile(r'^!bc\s+([^ ]+?)$') 11 ec = re.compile(r'^!ec\s*$') 12 for i in range(len(lines)): 13 #if re.search(r'^![be]c', lines[i]):a 14 # print 'latex_code treats line\n', lines[i] 15 16 # !bc without argument is substituted as !bc ccq: 17 lines[i] = re.sub(r'^!bc\s*$', r'!bc ccq', lines[i]) 18 #print 'after mod:', lines[i] 19 20 # treat a line !bc arg: 21 m = bc_arg.search(lines[i]) 22 if m: 23 arg = m.group(1) 24 #print 'yes, this is a !bc line with arg =', arg 25 # add \b to arg, e.g., if arg is cod, make \bcod (ptex2tex) 26 lines[i] = bc_arg.sub(r'\\b' + arg, lines[i]) 27 #print 'new b envir:', lines[i] 28 # treat a line !ec: 29 m = ec.search(lines[i]) 30 if m: 31 #print 'yes, this is a !ec line with arg =', arg 32 if arg == None: 33 print '\n'.join(lines[:i+1]) 34 print '\n\nError: !ec with a non-matching !bc before, '\ 35 'see print out above, up to the problematic line.' 36 sys.exit(1) 37 lines[i] = ec.sub(r'\\e' + arg, lines[i]) 38 #print 'new e envir:', lines[i] 39 arg = None 40 filestr = '\n'.join(lines) 41 c = re.compile(r'^!bt\n', re.MULTILINE) 42 #filestr = c.sub('\n', filestr) # why an extra \n? 43 filestr = c.sub('', filestr) 44 filestr = re.sub(r'!et\n', '', filestr) 45 return filestr
46
47 -def latex_figure(m, includegraphics=True):
48 filename = m.group('filename') 49 basename = os.path.basename(filename) 50 stem, ext = os.path.splitext(basename) 51 #root, ext = os.path.splitext(filename) 52 # doconce.py ensures that images are transformed to .ps or .eps 53 54 # note that label{...} are substituted by \label{...} (inline 55 # label tag) so we write just label and not \label below: 56 57 frac = 0.9 58 opts = m.group('options') 59 if opts: 60 info = [s.split('=') for s in opts.split()] 61 for option, value in info: 62 if option == 'frac': 63 frac = float(value) 64 if includegraphics: 65 includeline = r'\centerline{\includegraphics[width=%s\linewidth]{%s}}' % (frac, filename) 66 else: 67 includeline = r'\centerline{\psfig{figure=%s,width=%s\linewidth}}' % (filename, frac) 68 69 caption = m.group('caption').strip() 70 # `verbatim text` in backquotes does not work so we need to substitute 71 # by \texttt{}, and underscores need a backslash 72 verbatim_text = re.findall(r'(`[^`]+?`)', caption) 73 verbatim_text_new = [] 74 for words in verbatim_text: 75 new_words = words 76 if '_' in new_words: 77 new_words = new_words.replace('_', r'\_') 78 # Replace backquotes by {\rm\texttt{}} 79 new_words = r'{\rm\texttt{' + new_words[1:-1] + '}}' 80 verbatim_text_new.append(new_words) 81 for from_, to_ in zip(verbatim_text, verbatim_text_new): 82 caption = caption.replace(from_, to_) 83 if caption: 84 result = r""" 85 \begin{figure} 86 %s 87 \caption{ 88 %s 89 } 90 \end{figure} 91 """ % (includeline, caption) 92 else: 93 # drop caption 94 result = r""" 95 \begin{figure} 96 %s 97 %%\caption{} 98 \end{figure} 99 """ % (includeline) 100 return result
101
102 -def latex_movie(m):
103 from plaintext import default_movie 104 text = default_movie(m) 105 106 # URL to HTML viewer file must have absolute path in \href 107 html_viewer_file_pattern = r'Movie of files `.+` in URL:"(.+)"' 108 m2 = re.search(html_viewer_file_pattern, text) 109 if m2: 110 html_viewer_file = m2.group(1) 111 if os.path.isfile(html_viewer_file): 112 html_viewer_file_abs = os.path.abspath(html_viewer_file) 113 text = text.replace('URL:"%s"' % html_viewer_file, 114 'URL:"file://%s"' % html_viewer_file_abs) 115 116 117 if ': play URL:' in text: 118 # Drop default_movie, embed in PDF instead using the movie15 package 119 text = r""" 120 \\begin{figure}[ht] 121 \\begin{center} 122 123 % #ifdef MOVIE15 124 \includemovie[poster, 125 label=\g<filename>, 126 autoplay, 127 %controls, 128 %toolbar, 129 % #ifdef EXTERNAL_MOVIE_VIEWER 130 externalviewer, 131 % #endif 132 text={\small (Loading \g<filename>)}, 133 repeat, 134 ]{0.9\linewidth}{0.9\linewidth}{\g<filename>} % requires \usepackage{movie15} 135 % #ifndef EXTERNAL_MOVIE_VIEWER 136 \movieref[rate=0.5]{\g<filename>}{Slower} 137 \movieref[rate=2]{\g<filename>}{Faster} 138 \movieref[default]{\g<filename>}{Normal} 139 \movieref[pause]{\g<filename>}{Play/Pause} 140 \movieref[stop]{\g<filename>}{Stop} 141 % #else 142 \href{run:\g<filename>}{\g<filename>} 143 % #endif 144 145 % #else 146 \href{run:\g<filename>}{\g<filename>} 147 148 % alternative: \movie command that comes with beamer 149 % \movie[options]{\g<filename>}{\g<filename>} 150 % #endif 151 \end{center} 152 \caption{\g<caption>} 153 \end{figure} 154 """ 155 return text
156
157 -def latex_table(table):
158 column_width = table_analysis(table['rows']) 159 160 #ncolumns = max(len(row) for row in table['rows']) 161 ncolumns = len(column_width) 162 #import pprint; pprint.pprint(table) 163 column_spec = table.get('columns_align', 'c'*ncolumns) 164 column_spec = column_spec.replace('|', '') 165 if len(column_spec) != ncolumns: # (allow | separators) 166 print 'Table has column alignment specification: %s, but %d columns' \ 167 % (column_spec, ncolumns) 168 print 'Table with rows', table['rows'] 169 sys.exit(1) 170 171 # we do not support | in headings alignments (could be fixed, 172 # by making column_spec not a string but a list so the 173 # right elements are picked in the zip-based loop) 174 heading_spec = table.get('headings_align', 'c'*ncolumns)#.replace('|', '') 175 if len(heading_spec) != ncolumns: 176 print 'Table has headings alignment specification: %s, '\ 177 'but %d columns' % (heading_spec, ncolumns) 178 print 'Table with rows', table['rows'] 179 sys.exit(1) 180 181 s = '\n' + r'\begin{quote}\begin{tabular}{%s}' % column_spec + '\n' 182 for i, row in enumerate(table['rows']): 183 if row == ['horizontal rule']: 184 s += r'\hline' + '\n' 185 else: 186 # check if this is a headline between two horizontal rules: 187 if i == 1 and \ 188 table['rows'][i-1] == ['horizontal rule'] and \ 189 table['rows'][i+1] == ['horizontal rule']: 190 headline = True 191 else: 192 headline = False 193 194 if headline: 195 row = [r'\multicolumn{1}{%s}{%s}' % (a, r) \ 196 for r, a in zip(row, heading_spec)] 197 else: 198 row = [r.ljust(w) for r, w in zip(row, column_width)] 199 200 s += ' & '.join(row) + ' \\\\\n' 201 202 s += r'\end{tabular}\end{quote}' + '\n\n' + r'\noindent' + '\n' 203 return s
204
205 -def latex_title(m):
206 title = m.group('subst') 207 # Make appropriate linebreaks for the default typesetting 208 import textwrap 209 default_title = r' \\\\ [1.5mm] '.join(textwrap.wrap(title, width=38)) 210 211 text = fix_latex_command_regex(pattern=r""" 212 213 %% #ifndef LATEX_HEADING 214 %% #define LATEX_HEADING 215 %% #endif 216 217 %% ----------------- Title ------------------------- 218 %% #if LATEX_HEADING == "traditional" 219 220 \title{%s} 221 222 %% #elif LATEX_HEADING == "titlepage" 223 224 \thispagestyle{empty} 225 \hbox{\ \ } 226 \vfill 227 \begin{center} 228 {\huge{\bfseries{%s}}} 229 230 %% #else 231 232 \begin{center} 233 {\LARGE\bf %s} 234 \end{center} 235 236 %% #endif 237 """ % (title, title, default_title), application='replacement') 238 return text
239
240 -def latex_author(authors_and_institutions, auth2index, 241 inst2index, index2inst, auth2email):
242 text = r""" 243 244 % ----------------- Author(s) ------------------------- 245 % #if LATEX_HEADING == "traditional" 246 \author{""" 247 248 # Traditional latex heading 249 author_command = [] 250 for a, i, e in authors_and_institutions: 251 a_text = a 252 if e is not None: 253 e = e.replace('_', r'\_') 254 name, adr = e.split('@') 255 #e_text = r'Email: \texttt{%s} at \texttt{%s}' % (name, adr) 256 e_text = r'Email: \texttt{%s@%s}' % (name, adr) 257 else: 258 e_text = '' 259 if i is not None: 260 a_text += r'\footnote{' 261 if len(i) == 1: 262 i_text = i[0] 263 elif len(i) == 2: 264 i_text = ' and '.join(i) 265 else: 266 i[-1] = 'and ' + i[-1] 267 i_text = '; '.join(i) 268 if e_text: 269 a_text += e_text + '. ' + i_text 270 else: 271 a_text += i_text 272 a_text += '.}' 273 else: # Just email 274 if e_text: 275 a_text += r'\footnote{%s.}' % e_text 276 author_command.append(a_text) 277 author_command = '\n\\and '.join(author_command) 278 279 text += author_command + '}\n' 280 281 text += r""" 282 % #elif LATEX_HEADING == "titlepage" 283 \vspace{1.3cm} 284 """ 285 for author in auth2index: # correct order of authors 286 email = auth2email[author] 287 if email is None: 288 email_text = '' 289 else: 290 email = email.replace('_', r'\_') 291 name, adr = email.split('@') 292 #email_text = r' (\texttt{%s} at \texttt{%s})' % (name, adr) 293 email_text = r' (\texttt{%s@%s})' % (name, adr) 294 text += r""" 295 {\Large\textsf{%s${}^{%s}$%s}}\\ [3mm] 296 """ % (author, str(auth2index[author])[1:-1], email_text) 297 text += r""" 298 \ \\ [2mm] 299 """ 300 for index in index2inst: 301 text += r""" 302 {\large\textsf{${}^%d$%s} \\ [1.5mm]}""" % \ 303 (index, index2inst[index]) 304 305 text += r""" 306 307 % #else 308 """ 309 for author in auth2index: # correct order of authors 310 email = auth2email[author] 311 if email is None: 312 email_text = '' 313 else: 314 email = email.replace('_', r'\_') 315 name, adr = email.split('@') 316 #email_text = r' (\texttt{%s} \emph{at} \texttt{%s})' % (name, adr) 317 email_text = r' (\texttt{%s@%s})' % (name, adr) 318 text += r""" 319 \begin{center} 320 {\bf %s${}^{%s}$%s} \\ [0mm] 321 \end{center} 322 323 """ % (author, str(auth2index[author])[1:-1], email_text) 324 325 text += r'\begin{center}' + '\n' + '% List of all institutions:\n' 326 for index in index2inst: 327 text += r"""\centerline{{\small ${}^%d$%s}}""" % \ 328 (index, index2inst[index]) + '\n' 329 330 text += r"""\end{center} 331 % #endif 332 % ----------------- End of author(s) ------------------------- 333 334 """ 335 return text
336
337 -def latex_ref_and_label(section_label2title, format, filestr):
338 filestr = filestr.replace('label{', r'\label{') 339 # add ~\ between chapter/section and the reference 340 pattern = r'([Ss]ection|[Cc]hapter)(s?)\s+ref\{' # no \[A-Za-z] pattern => no fix 341 # recall \r is special character so it needs \\r 342 # (could call fix_latex_command_regex for the replacement) 343 replacement = r'\g<1>\g<2>~\\ref{' 344 #filestr = re.sub(pattern, replacement, filestr, flags=re.IGNORECASE) 345 cpattern = re.compile(pattern, flags=re.IGNORECASE) 346 filestr = cpattern.sub(replacement, filestr) 347 # range ref: 348 filestr = re.sub(r'-ref\{', r'-\\ref{', filestr) 349 # the rest of the ' ref{}' (single refs should have ~ in front): 350 filestr = re.sub(r'\sref\{', r'~\\ref{', filestr) 351 filestr = re.sub(r'\(ref\{', r'(\\ref{', filestr) 352 353 # equations are ok in the doconce markup 354 355 # perform a substitution of "LaTeX" (and ensure \LaTeX is not there): 356 filestr = re.sub(fix_latex_command_regex(r'\LaTeX({})?', 357 application='match'), 'LaTeX', filestr) 358 #filestr = re.sub('''([^"'`*_A-Za-z0-9-])LaTeX([^"'`*_A-Za-z0-9-])''', 359 # r'\g<1>{\LaTeX}\g<2>', filestr) 360 filestr = re.sub(r'''([^"'`*-])\bLaTeX\b([^"'`*-])''', 361 r'\g<1>{\LaTeX}\g<2>', filestr) 362 # This one is not good enough for verbatim `LaTeX`: 363 #filestr = re.sub(r'\bLaTeX\b', r'{\LaTeX}', filestr) 364 365 # handle & (Texas A&M -> Texas A{\&}M): 366 filestr = re.sub(r'([A-Za-z])\s*&\s*([A-Za-z])', r'\g<1>{\&}\g<2>', filestr) 367 368 # handle non-English characters: 369 chars = {'æ': r'{\ae}', 'ø': r'{\o}', 'å': r'{\aa}', 370 'Æ': r'{\AE}', 'Ø': r'{\O}', 'Å': r'{\AA}', 371 } 372 # Not implemented 373 #for c in chars: 374 # filestr, n = re.subn(c, chars[c], filestr) 375 # print '%d subst of %s' % (n, c) 376 # #filestr = filestr.replace(c, chars[c]) 377 378 # Handle 50% and similar 379 filestr = re.sub(r'([0-9]{1,3})%', r'\g<1>\%', filestr) 380 381 # fix periods followed by too long space: 382 prefix = r'Prof\.', r'Profs\.', r'prof\.', r'profs\.', r'Dr\.', \ 383 r'assoc\.', r'Assoc.', r'Assist.', r'Mr\.', r'Ms\.', 'Mss\.', \ 384 r'Fig\.', r'Tab\.', r'Univ\.', r'Dept\.', r'abbr\.', r'cf\.', \ 385 r'e\.g\.', r'E\.g\.', r'i\.e\.', r'Approx\.', r'approx\.' 386 # avoid r'assist\.' - matches too much 387 for p in prefix: 388 filestr = re.sub(r'(%s) +([\\A-Za-z0-9])' % p, r'\g<1>~\g<2>', 389 filestr) 390 391 return filestr
392
393 -def latex_index_bib(filestr, index, citations, bibfile):
394 #print 'index:', index 395 #print 'citations:', citations 396 filestr = filestr.replace('cite{', r'\cite{') 397 for word in index: 398 pattern = 'idx{%s}' % word 399 if '`' in word: 400 # verbatim typesetting: 401 word = re.sub(r'^(.*)`([^`]+)`(.*)$', 402 fix_latex_command_regex(r'\g<1>\g<2>@\g<1>{\rm\texttt{\g<2>}}\g<3>', 403 application='replacement'), word) 404 # fix underscores: 405 word = word.replace('_', r'\_') 406 replacement = r'\index{%s}' % word 407 filestr = filestr.replace(pattern, replacement) 408 if 'bib' in bibfile: 409 bibtext = fix_latex_command_regex(r""" 410 411 \bibliographystyle{plain} 412 \bibliography{%s} 413 """ % bibfile['bib'], application='replacement') 414 #filestr = re.sub(r'^BIBFILE:.+$', bibtext, filestr, 415 # flags=re.MULTILINE) 416 cpattern = re.compile(r'^BIBFILE:.+$', re.MULTILINE) 417 filestr = cpattern.sub(bibtext, filestr) 418 return filestr
419 420
421 -def latex_exercise(exer):
422 s = '' # result string 423 if not 'heading' in exer: 424 print 'Wrong formatting of exercise, not a 3/5 === type heading' 425 print exer 426 sys.exit(1) 427 428 # Reuse plan_exercise (std doconce formatting) where possible 429 # and just make a few adjustments 430 431 s += exer['heading'] + ' ' + exer['title'] + ' ' + exer['heading'] + '\n' 432 if 'label' in exer: 433 s += 'label{%s}' % exer['label'] + '\n' 434 s += '\n' + exer['text'] + '\n' 435 for hint_no in sorted(exer['hint']): 436 s += exer['hint'][hint_no] + '\n' 437 #s += '\n' + exer['hint'][hint_no] + '\n' 438 if 'file' in exer: 439 #s += '\n' + r'\noindent' + '\nFilename: ' + r'\code{%s}' % exer['file'] + '\n' 440 s += 'Filename: ' + r'\code{%s}' % exer['file'] + '.\n' 441 if 'comments' in exer: 442 s += '\n' + exer['comments'] 443 if 'solution' in exer: 444 pass 445 return s
446 447
448 -def define(FILENAME_EXTENSION, 449 BLANKLINE, 450 INLINE_TAGS_SUBST, 451 CODE, 452 LIST, 453 ARGLIST, 454 TABLE, 455 EXERCISE, 456 FIGURE_EXT, 457 CROSS_REFS, 458 INDEX_BIB, 459 INTRO, 460 OUTRO):
461 # all arguments are dicts and accept in-place modifications (extensions) 462 463 FILENAME_EXTENSION['latex'] = '.p.tex' 464 BLANKLINE['latex'] = '\n' 465 466 INLINE_TAGS_SUBST['latex'] = { 467 # Note: re.sub "eats" backslashes: \t and \b will not survive to 468 # latex if text goes through re.sub. Then we must write 469 # \\b and \\t etc. See the fix_latex_command_regex function below 470 # for the complete story. 471 472 'math': None, # indicates no substitution, leave as is 473 'math2': r'\g<begin>$\g<latexmath>$\g<end>', 474 'emphasize': r'\g<begin>\emph{\g<subst>}\g<end>', 475 'bold': r'\g<begin>\\textbf{\g<subst>}\g<end>', # (re.sub swallows a \) 476 'verbatim': r'\g<begin>\code{\g<subst>}\g<end>', 477 # The following verbatim is better if fixed fontsize is ok, since 478 # \code{\latexcommand{arg1}} style formatting does not work well 479 # with ptex2tex (the regex will not include the proper second } 480 #'verbatim': r'\g<begin>{\footnotesize{10pt}{10pt}\verb!\g<subst>!\g<end>', 481 'citation': r'~\\cite{\g<subst>}', 482 'linkURL': r'\g<begin>\href{\g<url>}{\g<link>}\g<end>', 483 'linkURL2': r'\href{{\g<url>}}{\g<link>}', 484 'linkURL3': r'\href{{\g<url>}}{\g<link>}', 485 'linkURL2v': r'\href{{\g<url>}}{\\nolinkurl{\g<link>}}', 486 'linkURL3v': r'\href{{\g<url>}}{\\nolinkurl{\g<link>}}', 487 'plainURL': r'\href{{\g<url>}}{\\nolinkurl{\g<url>}}', # cannot use \code inside \href, use \nolinkurl to handle _ and # etc. (implies verbatim font) 488 'inlinecomment': r'\inlinecomment{\g<name>}{\g<comment>}', 489 'chapter': r'\n\n\chapter{\g<subst>}\n', 490 'section': r'\n\n\section{\g<subst>}\n', 491 'subsection': r'\n\subsection{\g<subst>}\n', 492 #'subsubsection': '\n' + r'\subsubsection{\g<subst>}' + '\n', 493 'subsubsection': r'\n\paragraph{\g<subst>.}', 494 'paragraph': r'\paragraph{\g<subst>}\n', 495 #'abstract': '\n\n' + r'\\begin{abstract}' + '\n' + r'\g<text>' + '\n' + r'\end{abstract}' + '\n\n' + r'\g<rest>', 496 'abstract': r'\n\n\\begin{abstract}\n\g<text>\n\end{abstract}\n\n\g<rest>', 497 # recall that this is regex so latex commands must be treated carefully: 498 #'title': r'\\title{\g<subst>}' + '\n', # we don'e use maketitle 499 'title': latex_title, 500 'author': latex_author, 501 #'date': r'\\date{\g<subst>}' ' \n\\maketitle\n\n', 502 'date': fix_latex_command_regex(pattern=r""" 503 504 % ----------------- Date ------------------------- 505 506 % #if LATEX_HEADING == "traditional" 507 508 \date{\g<subst>} 509 \maketitle 510 511 % #elif LATEX_HEADING == "titlepage" 512 513 \ \\\\ [10mm] 514 {\large\textsf{\g<subst>}} 515 516 \end{center} 517 \vfill 518 \clearpage 519 520 % #else 521 522 \begin{center} 523 \g<subst> 524 \end{center} 525 526 % #endif 527 """, application='replacement'), 528 'figure': latex_figure, 529 'movie': latex_movie, 530 'comment': '%% %s', 531 } 532 # should be configureable: 533 # [tex] 534 # verbatim = \code{, } 535 # verbatim = \verb!, ! 536 537 ending = '\n' 538 ending = '\n\n\\noindent\n' 539 LIST['latex'] = { 540 'itemize': 541 {'begin': r'\begin{itemize}' + '\n', 542 'item': r'\item', 'end': r'\end{itemize}' + ending}, 543 544 'enumerate': 545 {'begin': r'\begin{enumerate}' + '\n', 'item': r'\item', 546 'end': r'\end{enumerate}' + ending}, 547 548 'description': 549 {'begin': r'\begin{description}' + '\n', 'item': r'\item[%s]', 550 'end': r'\end{description}' + ending}, 551 552 'separator': '\n', 553 } 554 555 CODE['latex'] = latex_code 556 ARGLIST['latex'] = { 557 # 'parameter': r'\textbf{argument}', 558 # 'keyword': r'\textbf{keyword argument}', 559 # 'return': r'\textbf{return value(s)}', 560 # 'instance variable': r'\textbf{instance variable}', 561 # 'class variable': r'\textbf{class variable}', 562 # 'module variable': r'\textbf{module variable}', 563 'parameter': r'argument', 564 'keyword': r'keyword argument', 565 'return': r'return value(s)', 566 'instance variable': r'instance variable', 567 'class variable': r'class variable', 568 'module variable': r'module variable', 569 } 570 571 FIGURE_EXT['latex'] = ('.eps', '.ps') 572 573 CROSS_REFS['latex'] = latex_ref_and_label 574 575 TABLE['latex'] = latex_table 576 EXERCISE['latex'] = latex_exercise 577 INDEX_BIB['latex'] = latex_index_bib 578 579 INTRO['latex'] = r"""%% 580 %% Automatically generated LaTeX file from Doconce source 581 %% http://code.google.com/p/doconce/ 582 %% 583 584 % #ifdef BOOK 585 \documentclass{book} 586 % #else 587 \documentclass{article} 588 % #endif 589 590 \usepackage{relsize,epsfig,makeidx,amsmath,amsfonts} 591 \usepackage[latin1]{inputenc} 592 \usepackage{ptex2tex} 593 % #ifdef MOVIE15 594 \usepackage{movie15} 595 % #endif 596 % #ifdef MINTED 597 \usepackage{minted} % requires latex -shell-escape (for Minted_* ptex2tex envirs) 598 % #endif 599 600 % #ifdef HELVETICA 601 % Set helvetica as the default font family: 602 \RequirePackage{helvet} 603 \renewcommand\familydefault{phv} 604 % #endif 605 606 \usepackage[% 607 colorlinks=true, 608 linkcolor=blue, 609 citecolor=black, 610 filecolor=blue, 611 urlcolor=blue]{hyperref} 612 %\hyperbaseurl{} % hyperlinks are relative to this root 613 614 \newcommand{\inlinecomment}[2]{ ({\bf #1}: \emph{#2}) } 615 %\newcommand{\inlinecomment}[2]{} % turn off inline comments 616 617 \makeindex 618 619 \begin{document} 620 621 """ 622 newcommands_files = 'newcommands.tex', 'newcommands_replace.tex', \ 623 'newcommands_keep.tex' 624 for filename in newcommands_files: 625 pfilename = filename[:-4] + '.p.tex' 626 if os.path.isfile(filename) or os.path.isfile(pfilename): 627 INTRO['latex'] += r"""\input{%s} 628 """ % (filename[:-4]) 629 #print '... found', filename 630 #elif os.path.isfile(pfilename): 631 # print '%s exists, but not %s - run ptex2tex first' % \ 632 # (pfilename, filename) 633 else: 634 #print '... did not find', filename 635 pass 636 637 638 OUTRO['latex'] = r""" 639 640 \printindex 641 642 \end{document} 643 """
644 645
646 -def fix_latex_command_regex(pattern, application='match'):
647 """ 648 Given a pattern for a regular expression match or substitution, 649 the function checks for problematic patterns commonly 650 encountered when working with LaTeX texts, namely commands 651 starting with a backslash. 652 653 For a pattern to be matched or substituted, and extra backslash is 654 always needed (either a special regex construction like ``\w`` leads 655 to wrong match, or ``\c`` leads to wrong substitution since ``\`` just 656 escapes ``c`` so only the ``c`` is replaced, leaving an undesired 657 backslash). For the replacement pattern in a substitutions, specified 658 by the ``application='replacement'`` argument, a backslash 659 before any of the characters ``abfgnrtv`` must be preceeded by an 660 additional backslash. 661 662 The application variable equals 'match' if `pattern` is used for 663 a match and 'replacement' if `pattern` defines a replacement 664 regex in a ``re.sub`` command. 665 666 Caveats: let `pattern` just contain LaTeX commands, not combination 667 of commands and other regular expressions (``\s``, ``\d``, etc.) as the 668 latter will end up with an extra undesired backslash. 669 670 Here are examples on failures. 671 672 >>> re.sub(r'\begin\{equation\}', r'\[', r'\begin{equation}') 673 '\\begin{equation}' 674 >>> # match of mbox, not \mbox, and wrong output 675 >>> re.sub(r'\mbox\{(.+?)\}', r'\fbox{\g<1>}', r'\mbox{not}') 676 '\\\x0cbox{not}' 677 678 Here are examples on using this function. 679 680 >>> from doconce.latex import fix_latex_command_regex as fix 681 >>> pattern = fix(r'\begin\{equation\}', application='match') 682 >>> re.sub(pattern, r'\[', r'\begin{equation}') 683 '\\[' 684 >>> pattern = fix(r'\mbox\{(.+?)\}', application='match') 685 >>> replacement = fix(r'\fbox{\g<1>}', application='replacement') 686 >>> re.sub(pattern, replacement, r'\mbox{not}') 687 '\\fbox{not}' 688 689 Avoid mixing LaTeX commands and ordinary regular expression 690 commands, e.g., 691 692 >>> pattern = fix(r'\mbox\{(\d+)\}', application='match') 693 >>> pattern 694 '\\\\mbox\\{(\\\\d+)\\}' 695 >>> re.sub(pattern, replacement, r'\mbox{987}') 696 '\\mbox{987}' # no substitution, no match 697 698 """ 699 import string 700 problematic_letters = string.ascii_letters if application == 'match' \ 701 else 'abfgnrtv' 702 703 for letter in problematic_letters: 704 problematic_pattern = '\\' + letter 705 706 if letter == 'g' and application == 'replacement': 707 # no extra \ for \g<...> in pattern 708 if r'\g<' in pattern: 709 continue 710 711 ok_pattern = '\\\\' + letter 712 if problematic_pattern in pattern and not ok_pattern in pattern: 713 pattern = pattern.replace(problematic_pattern, ok_pattern) 714 return pattern
715