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

Source Code for Module doconce.rst

  1  import re, os, sys 
  2  from common import remove_code_and_tex, insert_code_and_tex, indent_lines, \ 
  3      table_analysis, plain_exercise 
  4  from html import html_movie 
  5   
  6  # replacement patterns for substitutions of inline tags 
7 -def rst_figure(m):
8 result = '' 9 # m is a MatchObject 10 11 caption = m.group('caption').strip() 12 13 # Stubstitute Doconce label by rst label in caption 14 # (also, remove final period in caption since caption is used as hyperlink 15 # text to figures). 16 17 m_label = re.search(r'label\{(.+?)\}', caption) 18 if m_label: 19 label = m_label.group(1) 20 result += '\n.. _%s:\n' % label 21 # remove . at the end of the caption text 22 parts = caption.split('label') 23 parts[0] = parts[0].rstrip() 24 if parts[0] and parts[0][-1] == '.': 25 parts[0] = parts[0][:-1] 26 # insert emphasize marks 27 parts[0] = '*' + parts[0].strip() + '*' 28 caption = ' label'.join(parts) 29 caption = re.sub(r'label\{(.+?)\}', '(\g<1>)', caption) 30 else: 31 if caption and caption[-1] == '.': 32 caption = caption[:-1] 33 34 35 filename = m.group('filename') 36 if not os.path.isfile(filename): 37 #raise IOError('No figure file %s' % filename) 38 print 'No figure file %s' % filename 39 sys.exit(1) 40 41 result += '\n.. figure:: ' + filename + '\n' # utilize flexibility 42 opts = m.group('options') 43 if opts: 44 info = [s.split('=') for s in opts.split()] 45 rst_info = [' :%s: %s' % (option, value) 46 for option, value in info if option not in ['frac']] 47 result += '\n'.join(rst_info) 48 # remove final period in caption since caption is used as hyperlink 49 # text to figures 50 if caption and caption[-1] == '.': 51 caption = caption[:-1] 52 if caption: 53 result += '\n\n ' + caption + '\n' 54 else: 55 result += '\n\n' 56 return result
57
58 -def rst_movie(m):
59 html_text = html_movie(m) 60 html_text = indent_lines(html_text, 'sphinx') 61 rst_text = '.. raw:: html\n' + html_text + '\n\n' 62 return rst_text
63 64 # these global patterns are used in st, epytext, plaintext as well: 65 bc_regex_pattern = r'([a-zA-Z0-9)"`.*_}=-^~])[\n:.?!, ]\s*?^!bc.*?$' 66 bt_regex_pattern = r'([a-zA-Z0-9)"`.*_}=-^~])[\n:.?!, ]\s*?^!bt.*?$' 67
68 -def rst_code(filestr, format):
69 # In rst syntax, code blocks are typeset with :: (verbatim) 70 # followed by intended blocks. This function indents everything 71 # inside code (or TeX) blocks. 72 73 # first indent all code/tex blocks: 74 filestr, code_blocks, tex_blocks = remove_code_and_tex(filestr) 75 76 for i in range(len(code_blocks)): 77 code_blocks[i] = indent_lines(code_blocks[i], format) 78 for i in range(len(tex_blocks)): 79 tex_blocks[i] = indent_lines(tex_blocks[i], format) 80 filestr = insert_code_and_tex(filestr, code_blocks, tex_blocks, 'rst') 81 82 # substitute !bc and !ec appropriately: 83 # the line before the !bc block must end in [a-zA-z0-9)"] 84 # followed by [\n:.?!,] see the bc_regex_pattern global variable above 85 # (problems with substituting !bc and !bt may be caused by 86 # missing characters in these two families) 87 #c = re.compile(bc_regex_pattern, re.DOTALL) 88 c = re.compile(bc_regex_pattern, re.MULTILINE) 89 filestr = c.sub(r'\g<1>::\n\n', filestr) 90 filestr = re.sub(r'!ec\n', '\n\n', filestr) 91 #filestr = re.sub(r'!ec\n', '\n', filestr) 92 #filestr = re.sub(r'!ec\n', '', filestr) 93 94 #c = re.compile(r'([a-zA-Z0-9)"])[:.]?\s*?!bt\n', re.DOTALL) 95 #filestr = c.sub(r'\g<1>:\n\n', filestr) 96 #filestr = re.sub(r'!bt\n', '.. latex-math::\n\n', filestr) 97 #filestr = re.sub(r'!bt\n', '.. latex::\n\n', filestr) 98 99 # just use the same substitution as for code blocks: 100 c = re.compile(bt_regex_pattern, re.MULTILINE) 101 #filestr = c.sub(r'\g<1>::\n\n', filestr) 102 filestr = c.sub(r'\g<1>::\n', filestr) 103 #filestr = re.sub(r'!et *\n', '\n\n', filestr) 104 filestr = re.sub(r'!et *\n', '\n\n', filestr) 105 106 # sphinx math: 107 #filestr = re.sub(r'!bt\n', '\n.. math::\n\n', filestr) 108 #filestr = re.sub(r'!et\n', '\n\n', filestr) 109 110 #filestr = re.sub(r'!et\n', '\n', filestr) 111 #filestr = re.sub(r'!et\n', '', filestr) 112 113 # Fix: if there are !bc-!ec or !bt-!et environments after each 114 # other without text in between, there is a difficulty with the 115 # :: symbol before the code block. In these cases, we get 116 # !ec:: and !et:: from the above substitutions. We just replace 117 # these by empty text. 118 filestr = filestr.replace('!ec::', '') 119 filestr = filestr.replace('!et::', '') 120 121 return filestr
122 123
124 -def rst_table(table):
125 # Note: rst and sphinx do not offer alignment of cell 126 # entries, everything is always left-adjusted (Nov. 2011) 127 column_width = table_analysis(table['rows']) 128 ncolumns = len(column_width) 129 column_spec = table.get('columns_align', 'c'*ncolumns).replace('|', '') 130 heading_spec = table.get('headings_align', 'c'*ncolumns).replace('|', '') 131 a2py = {'r': 'rjust', 'l': 'ljust', 'c': 'center'} 132 s = '' # '\n' 133 for i, row in enumerate(table['rows']): 134 #s += ' ' # indentation of tables 135 if row == ['horizontal rule']: 136 for w in column_width: 137 s += '='*w + ' ' 138 else: 139 # check if this is a headline between two horizontal rules: 140 if i == 1 and \ 141 table['rows'][i-1] == ['horizontal rule'] and \ 142 table['rows'][i+1] == ['horizontal rule']: 143 headline = True 144 else: 145 headline = False 146 147 for w, c, ha, ca in \ 148 zip(column_width, row, heading_spec, column_spec): 149 if headline: 150 s += getattr(c, a2py[ha])(w) + ' ' 151 else: 152 s += getattr(c, a2py[ca])(w) + ' ' 153 s += '\n' 154 s += '\n' 155 return s
156
157 -def rst_author(authors_and_institutions, auth2index, 158 inst2index, index2inst, auth2email):
159 authors = [] 160 for author, i, email in authors_and_institutions: 161 if email: 162 email = email.replace('@', ' at ') 163 authors.append(author + ' (%s)' % email) 164 else: 165 authors.append(author) 166 167 text = ':Author: ' + ', '.join(authors) + '\n\n' 168 # we skip institutions in rst 169 return text
170
171 -def ref_and_label_commoncode(section_label2title, format, filestr):
172 # .... see section ref{my:sec} is replaced by 173 # see the section "...section heading..." 174 pattern = r'[Ss]ection(s?)\s+ref\{' 175 replacement = r'the section\g<1> ref{' 176 filestr = re.sub(pattern, replacement, filestr) 177 pattern = r'[Cc]hapter(s?)\s+ref\{' 178 replacement = r'the chapter\g<1> ref{' 179 filestr = re.sub(pattern, replacement, filestr) 180 # Need special adjustment to handle start of sentence (capital) or not. 181 pattern = r'([.?!])\s+the (sections?|captions?)\s+ref' 182 replacement = r'\g<1> The \g<2> ref' 183 filestr = re.sub(pattern, replacement, filestr) 184 185 186 # Deal with the problem of identical titles, which makes problem 187 # with non-unique links in reST: add a counter to the title 188 title2label = {} 189 for label in section_label2title: 190 title = section_label2title[label] 191 if title in title2label: 192 title2label[title].append(label) 193 else: 194 title2label[title] = [label] 195 problematic_titles = [title for title in title2label \ 196 if len(title2label[title]) > 1] 197 adjusted_titles = {} 198 for title in problematic_titles: 199 counter = 1 200 for label in title2label[title]: 201 # Add counter to non-unique titles (only for rst and sphinx) 202 adjusted_titles[(title,label)] = title + ' (%d)' % counter 203 counter += 1 204 debugtext = '\nProblematic multiple titles:\n%s\nAdjusted titles:\n%s' %\ 205 (problematic_titles, adjusted_titles) 206 207 # Insert labels before all section headings: (not necessary, but ok) 208 for label in section_label2title: 209 title = section_label2title[label] 210 # Problem: one title can be common to many sections and different 211 # labels, making this first regex 212 #pattern = r'(_{3,7}|={3,7})(\s*%s\s*)(_{3,7}|={3,7})' % title 213 # lead to several rst labels for a title. The remedy consists of 214 # two steps: a pattern regex that matches the label too, and 215 # adding a counter to titles with the same name (done above) 216 pattern = r'(_{3,7}|={3,7})(\s*%s\s*)(_{3,7}|={3,7})\s*label\{%s\}' \ 217 % (re.escape(title), label) 218 # (title may contain ? () etc., that's why we take re.escape) 219 try: 220 new_title = adjusted_titles[(title,label)] 221 debugtext += 'Found an adjusted title: %s\n' % new_title 222 except KeyError: 223 new_title = title 224 replacement = '.. _%s:\n\n' % label + r'\g<1> %s \g<3>' % \ 225 new_title 226 filestr, n = re.subn(pattern, replacement, filestr) 227 if n == 0: 228 raise Exception('problem with substituting "%s"' % title) 229 # Update label2title mapping with new titles 230 for title, label in adjusted_titles: 231 section_label2title[label] = adjusted_titles[(title,label)] 232 233 # remove label{...} from output 234 #filestr = re.sub(r'^label\{.+?\}\s*$', '', filestr, flags=re.MULTILINE) 235 cpattern = re.compile(r'^label\{[^}]+?\}\s*$', flags=re.MULTILINE) 236 filestr = cpattern.sub('', filestr) 237 filestr = re.sub(r'label\{[^}]+?\}', '', filestr) # all the remaining 238 239 import doconce 240 doconce.debugpr(debugtext) 241 242 return filestr
243 244
245 -def rst_ref_and_label(section_label2title, format, filestr):
246 filestr = ref_and_label_commoncode(section_label2title, format, filestr) 247 248 # replace all references to sections: 249 for label in section_label2title: 250 filestr = filestr.replace('ref{%s}' % label, 251 '`%s`_' % section_label2title[label]) 252 253 from common import ref2equations 254 filestr = ref2equations(filestr) 255 # replace remaining ref{x} as x_ 256 filestr = re.sub(r'ref\{(.+?)\}', '`\g<1>`_', filestr) 257 258 return filestr
259
260 -def rst_bib(filestr, citations, bibfile):
261 for label in citations: 262 filestr = filestr.replace('cite{%s}' % label, '[%s]_' % label) 263 if 'rst' in bibfile: 264 f = open(bibfile['rst'], 'r'); bibtext = f.read(); f.close() 265 #filestr = re.sub(r'^BIBFILE:.+$', bibtext, filestr, flags=re.MULTILINE) 266 cpattern = re.compile(r'^BIBFILE:.+$', re.MULTILINE) 267 filestr = cpattern.sub(bibtext, filestr) 268 return filestr
269
270 -def rst_index_bib(filestr, index, citations, bibfile):
271 filestr = rst_bib(filestr, citations, bibfile) 272 273 # reStructuredText does not have index/glossary 274 filestr = re.sub(r'idx\{.+?\}\n?', '', filestr) 275 276 return filestr
277 278 279
280 -def define(FILENAME_EXTENSION, 281 BLANKLINE, 282 INLINE_TAGS_SUBST, 283 CODE, 284 LIST, 285 ARGLIST, 286 TABLE, 287 EXERCISE, 288 FIGURE_EXT, 289 CROSS_REFS, 290 INDEX_BIB, 291 INTRO, 292 OUTRO):
293 # all arguments are dicts and accept in-place modifications (extensions) 294 295 FILENAME_EXTENSION['rst'] = '.rst' 296 BLANKLINE['rst'] = '\n' 297 298 INLINE_TAGS_SUBST['rst'] = { 299 'math': r'\g<begin>\g<subst>\g<end>', 300 'math2': r'\g<begin>\g<puretext>\g<end>', 301 #'math': r'\g<begin>:math:`\g<subst>`\g<end>', # sphinx 302 #'math2': r'\g<begin>:math:`\g<latexmath>`\g<end>', 303 'emphasize': None, # => just use doconce markup (*emphasized words*) 304 'bold': r'\g<begin>**\g<subst>**\g<end>', 305 'verbatim': r'\g<begin>``\g<subst>``\g<end>', 306 'label': r'\g<subst>', # should be improved, rst has cross ref 307 'reference': r'\g<subst>', 308 'linkURL': r'\g<begin>`\g<link> <\g<url>>`_\g<end>', 309 #'linkURL': r'\g<begin>`\g<link>`_\g<end>' + '\n\n.. ' + r'_\g<link>: \g<url>' + '\n\n', # better (?): make function instead that stacks up the URLs and dumps them at the end; can be used for citations as well 310 'linkURL2': r'`\g<link> <\g<url>>`_', 311 'linkURL3': r'`\g<link> <\g<url>>`_', 312 'linkURL2v': r'`\g<link> <\g<url>>`_', # no verbatim, does not work well 313 'linkURL3v': r'`\g<link> <\g<url>>`_', # with triple backticks... 314 'plainURL': r'`<\g<url>>`_', 315 'inlinecomment': r'(**\g<name>**: \g<comment>)', 316 # the replacement string differs, depending on the match object m: 317 # (note len(m.group('subst')) gives wrong length for non-ascii strings, 318 # better with m.group('subst').decode('utf-8')) or latin-1 319 #'section': lambda m: r'\g<subst>' + '\n%s' % ('-'*len(m.group('subst').decode('utf-8'))), 320 # note: r'\g<subst>\n%s' also works fine ?), despite being different... 321 # (it just works in substitution...) 322 'chapter': lambda m: r'\g<subst>\n%s' % ('%'*len(m.group('subst').decode('latin-1'))), 323 'section': lambda m: r'\g<subst>\n%s' % ('='*len(m.group('subst').decode('latin-1'))), 324 #'section': lambda m: r'\g<subst>\n%s' % ('='*len(m.group('subst').decode('latin-1'))), 325 'subsection': lambda m: r'\g<subst>\n%s' % ('-'*len(m.group('subst').decode('latin-1'))), 326 'subsubsection': lambda m: r'\g<subst>\n%s' % ('~'*len(m.group('subst').decode('latin-1'))), 327 'paragraph': r'*\g<subst>* ', # extra blank 328 'abstract': r'\n*\g<type>.* \g<text>\n\g<rest>', 329 'title': r'======= \g<subst> =======\n', # doconce top section, is later replaced 330 'date': r':Date: \g<subst>\n', 331 'author': rst_author, 332 'figure': rst_figure, 333 'movie': rst_movie, 334 #'comment': '.. %s', # rst does not like empty comment lines: 335 # so therefore we introduce a function to remove empty comment lines 336 'comment': lambda c: '' if c.isspace() or c == '' else '.. %s\n' % c 337 } 338 339 CODE['rst'] = rst_code # function for typesetting code 340 341 LIST['rst'] = { 342 'itemize': 343 {'begin': '', 'item': '*', 'end': '\n'}, 344 # lists must end with a blank line - we insert one extra, 345 346 'enumerate': 347 {'begin': '', 'item': '%d.', 'end': '\n'}, 348 349 'description': 350 {'begin': '', 'item': '%s', 'end': '\n'}, 351 352 'separator': '\n', 353 } 354 from common import DEFAULT_ARGLIST 355 ARGLIST['rst'] = DEFAULT_ARGLIST 356 FIGURE_EXT['rst'] = ('.png', '.gif', '.jpg', '.jpeg', '.eps', '.ps') 357 CROSS_REFS['rst'] = rst_ref_and_label 358 INDEX_BIB['rst'] = rst_index_bib 359 360 TABLE['rst'] = rst_table 361 EXERCISE['rst'] = plain_exercise 362 INTRO['rst'] = """\ 363 .. Automatically generated reST file from Doconce source 364 (http://code.google.com/p/doconce/) 365 366 """
367