def _add_latex(elem, latex): if bool(latex): # Is it a Span or a Code? if isinstance(elem, (Span, Code)): return [elem, RawInline(latex, "tex")] # It is a CodeBlock: create a minipage to ensure the # _tip to be on the same page as the codeblock if isinstance(elem, CodeBlock): return [ RawBlock("\\begin{minipage}{\\textwidth}" + latex, "tex"), elem, RawBlock("\\end{minipage}", "tex"), ] # It is a Div: try to insert an inline raw before the first inline element inserted = [False] def insert(element, _): if ( not inserted[0] and isinstance(element, Inline) and not isinstance(element.parent, Inline) ): inserted[0] = True return [RawInline(latex, "tex"), element] return None elem.walk(insert) if not inserted[0]: return [RawBlock("\\needspace{5em}", "tex"), RawBlock(latex, "tex"), elem] return [RawBlock("\\needspace{5em}", "tex"), elem] return None
def add_latex(elem, latex): # Is it a Span? if isinstance(elem, Span): elem.content.insert(0, RawInline(latex, 'tex')) # Is it a Div? elif isinstance(elem, Div): elem.content.insert(0, RawBlock('{' + latex, 'tex')) elem.content.append(RawBlock('}', 'tex'))
def add_latex(elem, environment): """ Add LaTeX code to the element. Arguments --------- elem: The current element environment: The environment to add Returns ------- The modified element """ def note(element, doc): if (isinstance(element, Note) and doc.format == "beamer" and not environment["localfootnotes"]): return RawInline( "".join([ "\\footnote<.->[frame]{", convert_text( element.content, input_format="panflute", output_format="latex", ), "}", ]), "tex", ) images = [] def extract_images(element, _doc): # Extract image which is alone with a title if (isinstance(element, Para) and len(element.content) == 1 and isinstance(element.content[0], Image) and bool(element.content[0].content)): images.append(element) return [] # The images need to be placed after the framed environment return [ RawBlock("\\begin{" + environment["env"] + "}", "tex"), elem.walk(extract_images).walk(note), RawBlock("\\end{" + environment["env"] + "}", "tex"), ] + images
def theorems(e, doc): if type(e) == Div and 'theorem' in e.classes: doc.theoremcount += 1 if doc.format == 'latex': label = '\\label{' + e.identifier + '}' if e.identifier else '' left = RawBlock('\\begin{theorem}' + label, format='latex') right = RawBlock('\\end{theorem}', format='latex') elif doc.format in ('html', 'html5'): label = '<dt>Theorem {}</dt>\n<dd>'.format(doc.theoremcount) left = RawBlock(label, format='html') right = RawBlock('</dd>\n</dl>', format='html') else: return e.content = [left] + list(e.content) + [right] return e
def bootstrap_fold_code(elem: Element, doc: Doc) -> Optional[Element]: if isinstance(elem, CodeBlock): name = get_name(elem) if "bootstrap-fold" in elem.classes and name is not None: fixed_name = fix_name(name) button_attrs = { "class": "btn btn-outline-primary btn-sm fold-toggle", "type": "button", "data-toggle": "collapse", "data-target": "#" + fixed_name + "-container", "aria-controls": fixed_name + "-container" } attr_str = " ".join(f"{k}=\"{v}\"" for k, v in button_attrs.items()) button = RawBlock( f"<button {attr_str}><<{name}>>=</button>") elem.classes.append("overflow-auto") elem.attributes["style"] = "max-height: 50vh" return Div(button, Div(elem, classes=["collapse"], identifier=fixed_name + "-container"), classes=["fold-block"]) else: if "annotated" in elem.attributes: return None return annotate.action(elem, doc) return None
def newpage(elem, doc): """ Replace HorizontalRule by a \\cleardoublepage. """ # Is it in the right format and is it an HorizontalRule? if doc.format == "latex" and isinstance(elem, HorizontalRule): return RawBlock("\\cleardoublepage", "tex") return None
def add_latex(elem, color, bgcolor): # Is it a Span? if isinstance(elem, Span): if bgcolor: elem.content.insert(0, RawInline(bgcolor + '\\hl{', 'tex')) elem.content.append(RawInline('}', 'tex')) elem.content.insert(0, RawInline(color, 'tex')) # Is it a Div? elif isinstance(elem, Div): if bgcolor: elem.content.insert( 0, RawBlock('{' + color + bgcolor + '\\hl{', 'tex')) elem.content.append(RawBlock('}', 'tex')) else: elem.content.insert(0, RawBlock('{' + color, 'tex')) elem.content.append(RawBlock('}', 'tex'))
def generate_latex_header(elem, stringified): """ Generate a LaTeX header """ levels = ['section', 'subsection', 'subsubsection', 'paragraph'] return RawBlock('\\%s[%s]{%s}\n' % (levels[elem.level - 1], stringified, stringify(elem)), format='tex')
def finalize(doc): global sectionlist inc = 0 for (pos, name) in sectionlist: debug("adding : " + name + " at $pos") doc.content.insert( pos + inc, RawBlock("\n\\section*{" + name + "}\n", format="latex")) inc = inc + 1 debug('Ending "sections.py" ...')
def code_block(elem, _doc): if isinstance(elem, CodeBlock): languages = elem.classes syntax = 'class="{}"'.format(languages[0] if languages else "text") body = "\n".join([ "<pre><code {}>".format(syntax), elem.text, "</code></pre>\n", ]) return RawBlock(body)
def splitblockold(e, doc): # print(doc.format) if doc.format == "latex" or doc.format == "beamer": if isinstance(e, Header): # debug(e) if e.level == 3 or e.level == 5: if "twocolumnsbegin" in e.classes: return doColumnsBegin('0.485') elif "twocolumnsep" in e.classes: return doColumnsSeperator('0.485') elif "twocolumnsend" in e.classes: return doColumnsEnd() elif "threecolumnsbegin" in e.classes: return doColumnsBegin('0.33') elif "threecolumnsep" in e.classes: return doColumnsSeperator('0.33') elif "threecolumnsend" in e.classes: return doColumnsEnd() elif "twocolumnsbigleftbegin" in e.classes: return doColumnsBegin('0.66') elif "twocolumnsbigleftsep" in e.classes: return doColumnsSeperator('0.33') elif "twocolumnsbigleftend" in e.classes: return doColumnsEnd() elif "fourquadone" in e.classes: return RawBlock("\\FourQuad{%\n", format="latex") elif "fourquadtwo" in e.classes: return RawBlock("\n}{%\n", format="latex") elif "fourquadthree" in e.classes: return RawBlock("\n}{%\n", format="latex") elif "fourquadfour" in e.classes: return RawBlock("\n}{%\n", format="latex") elif "fourquadend" in e.classes: return RawBlock("\n}% END QuadFour\n", format="latex") else: return else: return else: return
def add_latex(elem, latex): """ Add LaTeX code to elem. """ # Is it a Span? if isinstance(elem, Span): elem.content.insert(0, RawInline(latex, "tex")) # Is it a Div? elif isinstance(elem, Div): elem.content.insert(0, RawBlock("{" + latex, "tex")) elem.content.append(RawBlock("}", "tex")) # Is it a Code? elif isinstance(elem, Code): return [RawInline("{" + latex, "tex"), elem, RawInline("}", "tex")] # Is it a CodeBlock? elif isinstance(elem, CodeBlock): return [RawBlock("{" + latex, "tex"), elem, RawBlock("}", "tex")] return None
def margin(elem, doc): # Is it in the right format and is it a Div or CodeBlock? if doc.format in ["latex", "beamer"] and elem.tag in ["Div", "CodeBlock"]: left = None right = None # Get the classes classes = set(elem.classes) # Loop on all fontsize definition for definition in doc.defined: # Are the classes correct? if classes >= definition["classes"]: left = definition["left"] right = definition["right"] break # Is there a latex-margin-left attribute? if "latex-left-margin" in elem.attributes: left = get_correct_margin(elem.attributes["latex-left-margin"]) # Is there a latex-margin-right attribute? if "latex-right-margin" in elem.attributes: right = get_correct_margin(elem.attributes["latex-right-margin"]) if left is not None or right is not None: if left is None: left = "0pt" if right is None: right = "0pt" return [ RawBlock( "\\begin{pandocchangemargin}{" + left + "}{" + right + "}", "tex" ), # noqa: E501 elem, RawBlock("\\end{pandocchangemargin}", "tex"), ]
def moreblocks(e, doc): # print(doc.format) if doc.format == "latex" or doc.format == "beamer": if isinstance(e, Header): # debug(e) if e.level == 4: tag = "" if e.identifier: label = '\\label{' + removeUmlaute(e.identifier) + '}' else: label = '' tag = '' for key in blockmap: if key in e.classes: tag = blockmap[key] if tag == '': if 'endblock' in e.classes: return Plain() # RawBlock('\\relax', format='latex')? else: return left = RawInline('\\begin{' + tag + '}[', format='latex') right = RawInline(']' + label + '\n', format='latex') n = Plain() n.content = [left] + list(e.content) + [right] i = 1 length = len(doc.content) # debug(doc.content[e.index+i]) while not (isinstance(doc.content[e.index + i], Header)): i += 1 if (e.index + i) >= length: break ret = RawBlock(endTag(tag), format='latex') if (e.index + i) >= length: # We need to add it at the end of the list! doc.content.append(ret) else: doc.content.insert(e.index + i, ret) return n else: return else: return else: return
def latex(elem, environment, title): """ Generate the LaTeX code Arguments --------- elem: The current element environment: The environment to add title: The environment title Returns ------- A list of pandoc elements. """ return [ RawBlock("\\begin{%s}%s" % (environment, title), "tex"), elem, RawBlock("\\end{%s}" % environment, "tex"), ]
def generate(self): credentials = self.get_credentials() http = credentials.authorize(httplib2.Http()) data = None if self.config['type'] == 'spreadsheets': template = LATEX_JINJA_ENV.get_template('./gdrive-table.tex') discoveryUrl = 'https://sheets.googleapis.com/$discovery/rest?version=v4' service = discovery.build('sheets', 'v4', http=http, discoveryServiceUrl=discoveryUrl) result = service.spreadsheets().values().get( spreadsheetId=self.config['doc_id'], range=self.config['range']).execute() data = result.get('values', []) output_latex = template.render(data=data, **self.config) return RawBlock(text=output_latex, format="latex") if self.config['type'] == 'drawings': service = discovery.build('drive', 'v3', http=http) results = service.files().get( fileId=self.config['doc_id'], fields='modifiedTime,name').execute() request = service.files().export_media( fileId=self.config['doc_id'], mimeType='application/pdf') file_name = 'gdrive-data/' + self.config['doc_id'] + '.pdf' print(request, file=sys.stderr) with open(file_name, 'wb') as fh: downloader = MediaIoBaseDownload(fh, request) done = False while done is False: status, done = downloader.next_chunk() print(status, done, file=sys.stderr) print("Download %d%%." % int(status.progress() * 100), file=sys.stderr) return Para( Image(Str(''), url=file_name, title=self.config.get('title', ''), attributes={'width': '100%'})) return data
def smf(elem, doc): if type(elem) == Para: content = stringify(elem) # TODO: This shouldn't rewrite every paragraph (blockquotes, for example) so we need to dig into the elem attributes more. # Fix smart quotes, etc. content = content.replace("’", "\'") # Elipsis content = content.replace("…", "...") # Fix em-dash content = content.replace("–", "\emdash ") content = content.replace("—", "\emdash ") # {\pard \ql \f0 \sa180 \li720 \fi0 content = '{\pard \ql \\f0 \sa180 \li0 \\fi720 \sl480 \slmult1 ' + content + ' \\par}\n' return (RawBlock(content, 'rtf'))
def action(elem, doc): if isinstance(elem, CodeBlock) and "inject" in elem.attributes: name = elem.identifier label = Emph(Str(f"«{name}»=")) itemNav = Link(Str(f"{name} output"), url=f"#{name}", classes=["nav-item", "nav-link", "active"], identifier="nav-source-tab", attributes={ "data-toggle": "tab", "aria-controls": f"{name}", "aria-selected": "true" }) sourceNav = Link(label, url="#nav-source", classes=["nav-item", "nav-link"], identifier="nav-source-tab", attributes={ "data-toggle": "tab", "aria-controls": "nav-source", "aria-selected": "false" }) nav = Div(Plain(itemNav, sourceNav), classes=["nav", "nav-tabs"], identifier=f"{name}-nav") elem.identifier = f"{name}-source" elem.attributes["annotated"] = "true" targetPane = Div(classes=["tab-pane", "fade", "show", "active"], identifier=name) sourcePane = Div(elem, classes=["tab-pane", "fade"], identifier="nav-source") content = Div(targetPane, sourcePane, classes=["tab-content"], identifier=f"{name}-content") expanded_source = tangle.get_code(doc.code_map, name) script = RawBlock(f"<script>\n{expanded_source}\n</script>") return Div(nav, content, script, classes=["entangled-inject"])
def latexblock(code): """LaTeX block""" return RawBlock(code, format='latex')
def horizontal_rule(elem, _doc): if isinstance(elem, HorizontalRule): return RawBlock("---\n")
def action(elem, doc): if type(elem) == CodeBlock and "pseudo" in elem.classes: text = elem.text text = process_code(text) return RawBlock(text, format='latex')
def htmlblock(code): """Html block""" return RawBlock(code, format='html')
def to_raw(txt): return Div(RawBlock('<pre class="ansi2html-content">' + conv.convert(txt, full=False) + '</pre>', format="html"), classes=["programOutput"])
def doColumnsEnd(): return RawBlock('\t\\end{column}\n\\end{columns}\n', format='latex')
def doColumnsSeperator(size): ret = ('\t\\end{column}\n' '\t\\begin{column}[t]{'+size+'\\textwidth}') return RawBlock(ret, format='latex')
def doColumnsBegin(size): ret = ('\\vspace*{-1em}' '\\begin{columns}[T]\n' '\t\\begin{column}[t]{'+size+'\\textwidth}') return RawBlock(ret, format='latex')
def finalize(doc): """ Finalize document. Arguments --------- doc: pandoc document """ # Loop on all listings definition if doc.format == "latex": # Add header-includes if necessary if "header-includes" not in doc.metadata: doc.metadata["header-includes"] = MetaList() # Convert header-includes to MetaList if necessary elif not isinstance(doc.metadata["header-includes"], MetaList): doc.metadata["header-includes"] = MetaList( doc.metadata["header-includes"]) doc.metadata["header-includes"].append( MetaInlines(RawInline(r"\usepackage{tocloft}", "tex"))) i = 0 listof = [] for category, definition in doc.defined.items(): if definition["listing-title"] is not None: if doc.format == "latex": latex_category = re.sub("[^a-z]+", "", category) latex = (r"\newlistof{%s}{%s}{%s}" r"\renewcommand{\cft%stitlefont}{\cfttoctitlefont}" % ( latex_category, latex_category, convert_text( Plain(*definition["listing-title"]), input_format="panflute", output_format="latex", ), latex_category, )) doc.metadata["header-includes"].append( MetaInlines(RawInline(latex, "tex"))) listof.append(r"\listof%s" % latex_category) else: classes = ["pandoc-numbering-listing"] + definition["classes"] if definition["listing-unnumbered"]: classes.append("unnumbered") if definition["listing-unlisted"]: classes.append("unlisted") if definition["listing-identifier"] is False: header = Header(*definition["listing-title"], level=1, classes=classes) elif definition["listing-identifier"] is True: header = Header(*definition["listing-title"], level=1, classes=classes) header = convert_text( convert_text(header, input_format="panflute", output_format="markdown"), output_format="panflute", )[0] else: header = Header( *definition["listing-title"], level=1, classes=classes, identifier=definition["listing-identifier"]) doc.content.insert(i, header) i = i + 1 table = table_other(doc, category, definition) if table: doc.content.insert(i, table) i = i + 1 if doc.format == "latex": header = ( r"\ifdef{\mainmatter}" r"{\let\oldmainmatter\mainmatter\renewcommand{\mainmatter}[0]{%s\oldmainmatter}}" r"{}") doc.metadata["header-includes"].append( MetaInlines(RawInline(header % "\n".join(listof), "tex"))) latex = r"\ifdef{\mainmatter}{}{%s}" doc.content.insert(0, RawBlock(latex % "\n".join(listof), "tex"))