def prepare(doc): date = doc.get_metadata('date') if date == 'today': doc.metadata['date'] = datetime.date.today().isoformat() doc.metadata['pagetitle'] = pf.convert_text( pf.Plain(*doc.metadata['title'].content), input_format='panflute', output_format='markdown') datadir = doc.get_metadata('datadir') with open(os.path.join(datadir, 'annex-f'), 'r') as f: stable_names.update(line.split() for line in f) def highlighting(output_format): return pf.convert_text( '`_`{.default}', output_format=output_format, extra_args=[ '--highlight-style', os.path.join(datadir, 'syntax', 'wg21.theme'), '--template', os.path.join(datadir, 'template', 'highlighting') ]) doc.metadata['highlighting-macros'] = pf.MetaBlocks( pf.RawBlock(highlighting('latex'), 'latex')) doc.metadata['highlighting-css'] = pf.MetaBlocks( pf.RawBlock(highlighting('html'), 'html'))
def prepare(doc): datadir = doc.get_metadata('datadir') kate = pf.run_pandoc(args=['--print-highlight-style', 'kate']) json_styles = json.loads(kate) json_styles['background-color'] = '#' + doc.get_metadata('shadecolor') text_styles = json_styles['text-styles'] text_styles['BuiltIn'] = text_styles['Normal'] text_styles['Comment']['italic'] = True text_styles['ControlFlow'] = text_styles['DataType'] text_styles['Keyword'] = text_styles['DataType'] text_styles['Variable']['text-color'] = '#' + doc.get_metadata('addcolor') text_styles['String']['text-color'] = '#' + doc.get_metadata('rmcolor') with tempfile.NamedTemporaryFile('w', suffix='.theme') as f: json.dump(json_styles, f) f.flush() def highlighting(output_format): return pf.convert_text('`_`{.cpp}', output_format=output_format, extra_args=[ '--highlight-style', f.name, '--template', os.path.join(datadir, 'template', 'highlighting') ]) doc.metadata['highlighting-macros'] = pf.MetaBlocks( pf.RawBlock(highlighting('latex'), 'latex')) doc.metadata['highlighting-css'] = pf.MetaBlocks( pf.RawBlock(highlighting('html'), 'html'))
def indexhtml(doc): """Generate HTML index for title page""" keys = sorted(doc.toc.keys(), key=placekey) def depth(key): return key.count(".") HTML = fr"""<ul>""" for k in keys: e = doc.toc[k] title = e["title"] file = os.path.splitext(e["filename"])[0] base = doc.get_metadata("binarybaseurl", "") if depth(k) > 0: continue entry = dedent(fr""" <li><a href="{file+'.html'}"><b>Chapter {k}:</b> {title}</a> <small>(<a href="{base+'/'+file+'.pdf'}"><i class="fas fa-file-pdf"></i>PDF: best formatting</a> , <a href="{base+'/'+file+'.docx'}"><i class="fas fa-file-word"></i>Word: buggy</a>)</small> </li> """) HTML += entry HTML += r"""</ul>""" doc.metadata["indexcontents"] = pf.MetaBlocks( pf.RawBlock(HTML, format="html"))
def _finalize(doc): """_finalize :param doc: """ swap_string = "\n".join( " {short!r}: {identifier!r}\n {long!r}: {identifier!r}".format( identifier="+{}_".format(identifier), short=short_, long=long_) for identifier, (short_, long_, __) in doc.abbr["definitions"].items()) logger.debug( "Add abbreviations to vale substitutions:\n{}\n".format(swap_string)) appendix = doc.abbr["appendix"] if appendix: heading = pf.Header(pf.Str("Abbreviations"), identifier="abbreviations", classes=["unnumbered"]) doc.content.append(heading) appendix.sort(key=lambda x: x[0]) appendix = map(lambda x: x[1], appendix) doc.content.append(pf.DefinitionList(*appendix)) if "preamble" in doc.metadata: existing_preamble = doc.metadata["preamble"].content else: existing_preamble = [] doc.metadata["preamble"] = pf.MetaBlocks( *existing_preamble, *[value for key, value in doc.abbr["latex_preamble"].items()], )
def builtin2meta(val): if isinstance(val, bool): return pf.MetaBool(val) elif isinstance(val, (float, int)): return pf.MetaString(str(val)) elif isinstance(val, string_types): return pf.MetaString(val) elif isinstance(val, list): return pf.MetaList(*[builtin2meta(x) for x in val]) elif isinstance(val, dict): return pf.MetaMap(*[(k, builtin2meta(v)) for k, v in val.items()]) elif isinstance(val, pf.Block): return pf.MetaBlocks(val) elif isinstance(val, pf.Inline): return pf.MetaInlines(val) elif isinstance( val, ( pf.MetaBool, pf.MetaString, pf.MetaValue, pf.MetaList, pf.MetaMap, pf.MetaBlocks, pf.MetaInlines, ), ): return val raise TypeError("unknown type: {} (type: {})".format(val, type(val)))
def repair_toc_title(elem, doc): if doc.format == "odt" and isinstance(elem, pf.MetaMap): for key, value in elem.content.items(): string = pf.stringify(value).strip() if key == "toc-title": raw = pf.RawBlock(string, format="opendocument") elem[key] = pf.MetaBlocks(raw)
def pdflink(doc): """Link to the PDF version of the document""" pdfbase = doc.get_metadata("binarybaseurl", "") file = pdfbase + "/" + doc.get_metadata("filename", "nofile") + ".pdf" HTML = ( "\n" + fr"""<div><p style="color:#871640;">★ See also the <a id="pdflink" href='{file}'><b>PDF version of this chapter</b></a> (better formatting/references) ★</p></div>""" + "\n") doc.metadata["pdffile"] = pf.MetaString(file) doc.metadata["pdflink"] = pf.MetaBlocks(pf.RawBlock(HTML, format="html"))
def code_filter(elem, doc): global abstract global in_abstract if isinstance(elem, pf.Header): in_abstract = False if elem.identifier == "abstract": nodes = elem.parent.content within = False for n in iter(nodes): if isinstance(n, pf.Header) and n.identifier == "abstract": within = True continue if isinstance(n, pf.Header) and n.identifier == "endabstract": break if within: abstract.content.append(pf.MetaBlocks(copy.deepcopy(n))) in_abstract = True return [] if elem.identifier == "endabstract": doc.metadata['abstract'] = abstract return [] if in_abstract: return []
def writetoc(doc, TOC): """Write to the table of content""" logstring("\nWriting TOC:\n" + TOC, doc) doc.metadata["toc"] = pf.MetaBlocks(pf.RawBlock(TOC, format="html"))
def writetoc(doc, TOC): logstring("\nWriting TOC:\n" + TOC, doc) doc.metadata["toc"] = pf.MetaBlocks(pf.RawBlock(TOC, format="html"))
def prepare(doc): date = doc.get_metadata('date') if date == 'today': doc.metadata['date'] = datetime.date.today().isoformat() datadir = doc.get_metadata('datadir') def highlighting(output_format): return pf.convert_text( '`_`{.default}', output_format=output_format, extra_args=[ '--highlight-style', os.path.join(datadir, 'syntax', 'wg21.theme'), '--template', os.path.join(datadir, 'template', 'highlighting') ]) doc.metadata['highlighting-macros'] = pf.MetaBlocks( pf.RawBlock(highlighting('latex'), 'latex')) doc.metadata['highlighting-css'] = pf.MetaBlocks( pf.RawBlock(highlighting('html'), 'html')) def intersperse(lst, item): result = [item] * (len(lst) * 2 - 1) result[0::2] = lst return result def codeblock(elem, doc): if not isinstance(elem, pf.CodeBlock): return None if not elem.classes: elem.classes.append('default') codeblocks.append(elem) codeblocks = [] doc.walk(codeblock) texts = pf.convert_text( intersperse(codeblocks, pf.Plain(pf.RawInline('---', doc.format))), input_format='panflute', output_format=doc.format, extra_args=[ '--syntax-definition', os.path.join(datadir, 'syntax', 'isocpp.xml') ]).split('\n---\n') assert(len(codeblocks) == len(texts)) def convert(elem, text): if not any(cls in elem.classes for cls in ['cpp', 'default', 'diff']): return elem def repl(match_obj): match = match_obj.group(1) if not match: # @@ return match_obj.group(0) if match.isspace(): # @ @ return match result = convert.cache.get(match) if result is not None: return result if doc.format == 'latex': # Undo `escapeLaTeX` from https://github.com/jgm/skylighting match = match.replace('\\textbackslash{}', '\\') \ .replace('\\{', '{') \ .replace('\\}', '}') result = pf.convert_text( pf.Plain(*pf.convert_text(match)[0].content).walk(divspan, doc), input_format='panflute', output_format=doc.format) convert.cache[match] = result return result result = pf.RawBlock(embedded.sub(repl, text), doc.format) if 'diff' not in elem.classes: return result # For HTML, this is handled via CSS in `data/template/wg21.html`. command = '\\renewcommand{{\\{}}}[1]{{\\textcolor[HTML]{{{}}}{{#1}}}}' return pf.Div( pf.RawBlock('{', 'latex'), pf.RawBlock(command.format('NormalTok', doc.get_metadata('uccolor')), 'latex'), pf.RawBlock(command.format('VariableTok', doc.get_metadata('addcolor')), 'latex'), pf.RawBlock(command.format('StringTok', doc.get_metadata('rmcolor')), 'latex'), result, pf.RawBlock('}', 'latex')) convert.cache = {} prepare.converted = [convert(elem, text) for elem, text in zip(codeblocks, texts)]