1
2
3 import os, commands, re, sys
4 from common import plain_exercise, table_analysis
5 additional_packages = ''
6
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
14
15
16
17 lines[i] = re.sub(r'^!bc\s*$', r'!bc ccq', lines[i])
18
19
20
21 m = bc_arg.search(lines[i])
22 if m:
23 arg = m.group(1)
24
25
26 lines[i] = bc_arg.sub(r'\\b' + arg, lines[i])
27
28
29 m = ec.search(lines[i])
30 if m:
31
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
39 arg = None
40 filestr = '\n'.join(lines)
41 c = re.compile(r'^!bt\n', re.MULTILINE)
42
43 filestr = c.sub('', filestr)
44 filestr = re.sub(r'!et\n', '', filestr)
45 return filestr
46
101
103 from plaintext import default_movie
104 text = default_movie(m)
105
106
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
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
158 column_width = table_analysis(table['rows'])
159
160
161 ncolumns = len(column_width)
162
163 column_spec = table.get('columns_align', 'c'*ncolumns)
164 column_spec = column_spec.replace('|', '')
165 if len(column_spec) != ncolumns:
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
172
173
174 heading_spec = table.get('headings_align', 'c'*ncolumns)
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
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
206 title = m.group('subst')
207
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
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
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:
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:
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
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:
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
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
338 filestr = filestr.replace('label{', r'\label{')
339
340 pattern = r'([Ss]ection|[Cc]hapter)(s?)\s+ref\{'
341
342
343 replacement = r'\g<1>\g<2>~\\ref{'
344
345 cpattern = re.compile(pattern, flags=re.IGNORECASE)
346 filestr = cpattern.sub(replacement, filestr)
347
348 filestr = re.sub(r'-ref\{', r'-\\ref{', filestr)
349
350 filestr = re.sub(r'\sref\{', r'~\\ref{', filestr)
351 filestr = re.sub(r'\(ref\{', r'(\\ref{', filestr)
352
353
354
355
356 filestr = re.sub(fix_latex_command_regex(r'\LaTeX({})?',
357 application='match'), 'LaTeX', filestr)
358
359
360 filestr = re.sub(r'''([^"'`*-])\bLaTeX\b([^"'`*-])''',
361 r'\g<1>{\LaTeX}\g<2>', filestr)
362
363
364
365
366 filestr = re.sub(r'([A-Za-z])\s*&\s*([A-Za-z])', r'\g<1>{\&}\g<2>', filestr)
367
368
369 chars = {'æ': r'{\ae}', 'ø': r'{\o}', 'å': r'{\aa}',
370 'Æ': r'{\AE}', 'Ø': r'{\O}', 'Å': r'{\AA}',
371 }
372
373
374
375
376
377
378
379 filestr = re.sub(r'([0-9]{1,3})%', r'\g<1>\%', filestr)
380
381
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
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
394
395
396 filestr = filestr.replace('cite{', r'\cite{')
397 for word in index:
398 pattern = 'idx{%s}' % word
399 if '`' in word:
400
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
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
415
416 cpattern = re.compile(r'^BIBFILE:.+$', re.MULTILINE)
417 filestr = cpattern.sub(bibtext, filestr)
418 return filestr
419
420
422 s = ''
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
429
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
438 if 'file' in exer:
439
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
462
463 FILENAME_EXTENSION['latex'] = '.p.tex'
464 BLANKLINE['latex'] = '\n'
465
466 INLINE_TAGS_SUBST['latex'] = {
467
468
469
470
471
472 'math': None,
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>',
476 'verbatim': r'\g<begin>\code{\g<subst>}\g<end>',
477
478
479
480
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>}}',
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
493 'subsubsection': r'\n\paragraph{\g<subst>.}',
494 'paragraph': r'\paragraph{\g<subst>}\n',
495
496 'abstract': r'\n\n\\begin{abstract}\n\g<text>\n\end{abstract}\n\n\g<rest>',
497
498
499 'title': latex_title,
500 'author': latex_author,
501
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
533
534
535
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
558
559
560
561
562
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
630
631
632
633 else:
634
635 pass
636
637
638 OUTRO['latex'] = r"""
639
640 \printindex
641
642 \end{document}
643 """
644
645
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
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