def cwiki_figure(m): filename = m.group('filename') link = filename if filename.startswith('http') else None if not link and not os.path.isfile(filename): raise IOError('no figure file %s' % filename) basename = os.path.basename(filename) stem, ext = os.path.splitext(basename) root, ext = os.path.splitext(filename) if link is None: if not ext in '.png .gif .jpg .jpeg'.split(): # try to convert image file to PNG, using # convert from ImageMagick: cmd = 'convert %s png:%s' % (filename, root+'.png') failure, output = commands.getstatusoutput(cmd) if failure: print '\n**** Warning: could not run', cmd print 'Convert %s to PNG format manually' % filename _abort() filename = root + '.png' caption = m.group('caption') # keep label if it's there: caption = re.sub(r'label\{(.+?)\}', '(\g<1>)', caption) result = r"""{{%s|%s}}""" % (filename, caption) return result
def cwiki_figure(m): filename = m.group('filename') link = filename if filename.startswith('http') else None if not link and not os.path.isfile(filename): raise IOError('no figure file %s' % filename) basename = os.path.basename(filename) stem, ext = os.path.splitext(basename) root, ext = os.path.splitext(filename) if link is None: if not ext in '.png .gif .jpg .jpeg'.split(): # try to convert image file to PNG, using # convert from ImageMagick: cmd = 'convert %s png:%s' % (filename, root + '.png') failure, output = commands.getstatusoutput(cmd) if failure: print '\n**** Warning: could not run', cmd print 'Convert %s to PNG format manually' % filename _abort() filename = root + '.png' caption = m.group('caption') # keep label if it's there: caption = re.sub(r'label\{(.+?)\}', '(\g<1>)', caption) result = r"""{{%s|%s}}""" % (filename, caption) return result
def gwiki_figure(m): filename = m.group('filename') link = filename if filename.startswith('http') else None if not link and not os.path.isfile(filename): raise IOError('no figure file %s' % filename) basename = os.path.basename(filename) stem, ext = os.path.splitext(basename) root, ext = os.path.splitext(filename) if link is None: if not ext in '.png .gif .jpg .jpeg'.split(): # try to convert image file to PNG, using # convert from ImageMagick: cmd = 'convert %s png:%s' % (filename, root+'.png') failure, output = commands.getstatusoutput(cmd) if failure: print '\n**** Warning: could not run', cmd print 'Convert %s to PNG format manually' % filename _abort() filename = root + '.png' caption = m.group('caption') # keep label if it's there: caption = re.sub(r'label\{(.+?)\}', '(\g<1>)', caption) print """ NOTE: Place %s at some place on the web and edit the .gwiki page, either manually (seach for 'Figure: ') or use the doconce script: doconce gwiki_figsubst.py mydoc.gwiki URL """ % filename result = r""" --------------------------------------------------------------- Figure: %s (the URL of the image file %s must be inserted here) <wiki:comment> Put the figure file %s on the web (e.g., as part of the googlecode repository) and substitute the line above with the URL. </wiki:comment> --------------------------------------------------------------- """ % (caption, filename, filename) return result
def gwiki_figure(m): filename = m.group('filename') link = filename if filename.startswith('http') else None if not link and not os.path.isfile(filename): raise IOError('no figure file %s' % filename) basename = os.path.basename(filename) stem, ext = os.path.splitext(basename) root, ext = os.path.splitext(filename) if link is None: if not ext in '.png .gif .jpg .jpeg'.split(): # try to convert image file to PNG, using # convert from ImageMagick: cmd = 'convert %s png:%s' % (filename, root + '.png') failure, output = commands.getstatusoutput(cmd) if failure: print '\n**** Warning: could not run', cmd print 'Convert %s to PNG format manually' % filename _abort() filename = root + '.png' caption = m.group('caption') # keep label if it's there: caption = re.sub(r'label\{(.+?)\}', '(\g<1>)', caption) print """ NOTE: Place %s at some place on the web and edit the .gwiki page, either manually (seach for 'Figure: ') or use the doconce script: doconce gwiki_figsubst.py mydoc.gwiki URL """ % filename result = r""" --------------------------------------------------------------- Figure: %s (the URL of the image file %s must be inserted here) <wiki:comment> Put the figure file %s on the web (e.g., as part of the googlecode repository) and substitute the line above with the URL. </wiki:comment> --------------------------------------------------------------- """ % (caption, filename, filename) return result
def rst_code(filestr, code_blocks, code_block_types, tex_blocks, format): # In rst syntax, code blocks are typeset with :: (verbatim) # followed by intended blocks. This function indents everything # inside code (or TeX) blocks. for i in range(len(code_blocks)): code_blocks[i] = indent_lines(code_blocks[i], format) for i in range(len(tex_blocks)): tex_blocks[i] = indent_lines(tex_blocks[i], format) filestr = insert_code_and_tex(filestr, code_blocks, tex_blocks, 'rst') # substitute !bc and !ec appropriately: # the line before the !bc block must end in [a-zA-z0-9)"] # followed by [\n:.?!,] see the bc_regex_pattern global variable above # (problems with substituting !bc and !bt may be caused by # missing characters in these two families) #c = re.compile(bc_regex_pattern, re.DOTALL) filestr = re.sub(bc_regex_pattern, r'\g<1>::\n\n', filestr, flags=re.MULTILINE|re.DOTALL) filestr = re.sub(r'^!ec\n', '\n', filestr, flags=re.MULTILINE) #filestr = re.sub(r'^!ec\n', '', filestr, flags=re.MULTILINE) #c = re.compile(r'([a-zA-Z0-9)"])[:.]?\s*?!bt\n', re.DOTALL) #filestr = c.sub(r'\g<1>:\n\n', filestr) #filestr = re.sub(r'^!bt\n', '.. latex-math::\n\n', filestr, re.MULTILINE) #filestr = re.sub(r'^!bt\n', '.. latex::\n\n', filestr, re.MULTILINE) # just use the same substitution as for code blocks: filestr = re.sub(bt_regex_pattern, r'\g<1>::\n', filestr, flags=re.MULTILINE) #filestr = re.sub(r'^!et *\n', '\n\n', filestr, flags=re.MULTILINE) filestr = re.sub(r'^!et *\n', '\n', filestr, flags=re.MULTILINE) # Fix: if there are !bc-!ec or other environments after each # other without text in between, there is a difficulty with the # :: symbol before the code block. In these cases, we get # !ec::, !et::, !bbox:: etc. from the above substitutions. # We just replace these by empty text. filestr = re.sub(r'^(!(b|e)[a-z]+)::', r'\g<1>', filestr, flags=re.MULTILINE) # Check for pattern in '^!bt', '^!et': c = re.compile(pattern, re.MULTILINE) m = c.search(filestr) if m: print """ Still %s left after handling of code and tex blocks. Problem is probably that %s is not preceded by text which can be extended with :: (required). """ % (pattern, pattern) _abort() # Final fixes filestr = fix_underlines_in_headings(filestr) # Ensure blank line before and after comments filestr = re.sub(r'([.:;?!])\n^\.\. ', r'\g<1>\n\n.. ', filestr, flags=re.MULTILINE) filestr = re.sub(r'(^\.\. .+)\n([^ \n]+)', r'\g<1>\n\n\g<2>', filestr, flags=re.MULTILINE) # Line breaks interfer with tables and needs a final blank line too lines = filestr.splitlines() inside_block = False for i in range(len(lines)): if lines[i].startswith('<linebreakpipe>') and not inside_block: inside_block = True lines[i] = lines[i].replace('<linebreakpipe> ', '') + '\n' continue if lines[i].startswith('<linebreakpipe>') and inside_block: lines[i] = '|' + lines[i].replace('<linebreakpipe>', '') continue if inside_block and not lines[i].startswith('<linebreakpipe>'): inside_block = False lines[i] = '| ' + lines[i] + '\n' filestr = '\n'.join(lines) # Remove too much vertical space filestr = re.sub(r'\n\n\n+', '\n\n', filestr) return filestr
def define(FILENAME_EXTENSION, BLANKLINE, INLINE_TAGS_SUBST, CODE, LIST, ARGLIST, TABLE, EXERCISE, FIGURE_EXT, CROSS_REFS, INDEX_BIB, TOC, ENVIRS, QUIZ, INTRO, OUTRO, filestr): # all arguments are dicts and accept in-place modifications (extensions) FILENAME_EXTENSION['rst'] = '.rst' BLANKLINE['rst'] = '\n' INLINE_TAGS_SUBST['rst'] = { 'math': r'\g<begin>\g<subst>\g<end>', 'math2': r'\g<begin>\g<puretext>\g<end>', #'math': r'\g<begin>:math:`\g<subst>`\g<end>', # sphinx #'math2': r'\g<begin>:math:`\g<latexmath>`\g<end>', 'emphasize': None, # => just use doconce markup (*emphasized words*) 'bold': r'\g<begin>**\g<subst>**\g<end>', 'verbatim': r'\g<begin>``\g<subst>``\g<end>', 'label': r'\g<subst>', # should be improved, rst has cross ref 'reference': r'\g<subst>', #colortext works for HTML only. Can see here: http://stackoverflow.com/questions/4669689/how-to-use-color-in-text-with-restructured-text-rst2html-py-or-how-to-insert-h (but probably color is most relevant for HTML anyway) 'colortext': r'<font color="\g<color>">\g<text></font>', #'linkURL': r'\g<begin>`\g<link> <\g<url>>`_\g<end>', #'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 'linkURL2': r'`\g<link> <\g<url>>`_', 'linkURL3': r'`\g<link> <\g<url>>`_', 'linkURL2v': r'`\g<link> <\g<url>>`_', # no verbatim, does not work well 'linkURL3v': r'`\g<link> <\g<url>>`_', # same 'plainURL': r'`<\g<url>>`_', 'inlinecomment': r'(**\g<name>**: \g<comment>)', # the replacement string differs, depending on the match object m: # (note len(m.group('subst')) gives wrong length for non-ascii strings, # better with m.group('subst').decode('utf-8')) or latin-1 'chapter': lambda m: '%s\n%s' % (m.group('subst'), '%'*len(m.group('subst').decode('latin-1'))), 'section': lambda m: '%s\n%s' % (m.group('subst'), '='*len(m.group('subst').decode('latin-1'))), #'section': lambda m: '%s\n%s' % (m.group('subst'), '='*len(m.group('subst').decode('latin-1'))), 'subsection': lambda m: '%s\n%s' % (m.group('subst'), '-'*len(m.group('subst').decode('latin-1'))), 'subsubsection': lambda m: '%s\n%s\n' % (m.group('subst'), '~'*len(m.group('subst').decode('latin-1'))), 'paragraph': r'**\g<subst>**\n', # extra newline 'abstract': r'\n*\g<type>.* \g<text>\n\g<rest>', #'title': r'======= \g<subst> =======\n', # doconce top section, must be the highest section level (but no higher than others, need more code) 'title': None, # taken care of in ref_and_label_commoncode 'date': r':Date: \g<subst>\n', 'author': rst_author, 'figure': rst_figure, 'movie': rst_movie, #'comment': '.. %s', # rst does not like empty comment lines: # so therefore we introduce a function to remove empty comment lines 'comment': lambda c: '' if c.isspace() or c == '' else '.. %s\n' % c, #'linebreak': r'| \g<text>', # does not work: interfers with tables and requires a final blank line after block 'linebreak': r'<linebreakpipe> \g<text>', # fixed in rst_code/sphinx_code as a hack 'footnote': rst_footnotes, 'non-breaking-space': ' |nbsp| ', } ENVIRS['rst'] = { 'quote': rst_quote, 'warning': rst_warning, 'question': rst_question, 'notice': rst_notice, 'summary': rst_summary, 'block': rst_block, 'box': rst_box, } CODE['rst'] = rst_code # function for typesetting code LIST['rst'] = { 'itemize': {'begin': '', 'item': '*', 'end': '\n'}, # lists must end with a blank line - we insert one extra, 'enumerate': {'begin': '', 'item': '%d.', 'end': '\n'}, 'description': {'begin': '', 'item': '%s', 'end': '\n'}, 'separator': '\n', } from common import DEFAULT_ARGLIST ARGLIST['rst'] = DEFAULT_ARGLIST FIGURE_EXT['rst'] = ('.png', '.gif', '.jpg', '.jpeg', '.pdf', '.eps', '.ps') CROSS_REFS['rst'] = rst_ref_and_label INDEX_BIB['rst'] = rst_index_bib TABLE['rst'] = rst_table EXERCISE['rst'] = plain_exercise TOC['rst'] = lambda s: '.. contents:: Table of Contents\n :depth: 2' QUIZ['rst'] = rst_quiz INTRO['rst'] = """\ .. Automatically generated reStructuredText file from Doconce source (https://github.com/hplgit/doconce/) """ # http://stackoverflow.com/questions/11830242/non-breaking-space from common import INLINE_TAGS if re.search(INLINE_TAGS['non-breaking-space'], filestr): nbsp = """ .. |nbsp| unicode:: 0xA0 :trim: """ if 'TITLE:' not in filestr: print '*** error: non-breaking space character ~ is used,' print ' but this will give an error when the document does' print ' not have a title.' _abort() else: INTRO['rst'] += nbsp