def render_amsmath(self, token): # environment = token.meta["environment"] content = token.content if token.meta["numbered"] != "*": # TODO how to parse and reference labels within environment? # for now we give create a unique hash, so the equation will be numbered # but there will be no reference clashes label = self._random_label() node = nodes.math_block( content, content, nowrap=True, number=None, classes=["amsmath"], label=label, ) target = self.add_math_target(node) self.add_line_and_source_path(target, token) self.current_node.append(target) else: node = nodes.math_block(content, content, nowrap=True, number=None, classes=["amsmath"]) self.add_line_and_source_path(node, token) self.current_node.append(node)
def create_math_block(latex): if use_sphinx: node = math_block() node['nowrap'] = False node['label'] = None node['latex'] = latex else: node = math_block(text=latex) return node
def make_math_node(latex, docname, nowrap): node = nodes.math_block(latex, latex) node['label'] = None # Otherwise equations are numbered node['nowrap'] = nowrap node['docname'] = docname node['number'] = None return node
def run(self) -> List[nodes.Node]: """Run the directive.""" key = self.arguments[0] try: result = retrieve_glue_data(self.document, key) except RetrievalError as exc: return [glue_warning(str(exc), self.document, self.line)] if "text/latex" not in result.data: return [ glue_warning( f"No text/latex found in {key!r} data", self.document, self.lineno, ) ] latex = strip_latex_delimiters(str(result.data["text/latex"])) label = self.options.get("label", self.options.get("name")) node = nodes.math_block( latex, latex, nowrap="nowrap" in self.options, label=label, number=None, classes=["pasted-math"] + (self.options.get("class") or []), ) self.add_name(node) self.set_source_info(node) if is_sphinx(self.document): return self.add_target(node) return [node]
def visit_Text(self, node): parent = node.parent while parent: if isinstance(parent, node_blacklist): if DEBUG and any(i == 'math' for i, _ in split_dollars(str(node).replace('\x00', '\\'))): print("sphinx-math-dollar: Skipping", node, "(node_blacklist = %s)" % (node_blacklist,), file=sys.stderr) return parent = parent.parent # See https://github.com/sympy/sphinx-math-dollar/issues/22 data = split_dollars(str(node).replace('\x00', '\\')) nodes = [] has_math = False for typ, text in data: if typ == "math": has_math = True nodes.append(math(text, Text(text))) elif typ == "text": nodes.append(Text(text)) elif typ == "display math": has_math = True new_node = math_block(text, Text(text)) new_node.attributes.setdefault('nowrap', False) new_node.attributes.setdefault('number', None) nodes.append(new_node) else: raise ValueError("Unrecognized type from split_dollars %r" % typ) if has_math: node.parent.replace(node, nodes)
def run(self): set_classes(self.options) self.assert_has_content() latex_code = '\n'.join(self.content) node = nodes.math_block(self.block_text, latex_code, **self.options) node.line = self.content_offset + 1 return [node]
def render_math(self, token): if token.content.startswith("$$"): content = token.content[2:-2] node = nodes.math_block(content, content, nowrap=False, number=None) else: content = token.content[1:-1] node = nodes.math(content, content) self.add_line_and_source_path(node, token) self.current_node.append(node)
def render_math_inline(self, token: SyntaxTreeNode) -> None: content = token.content if token.markup == "$$": # available when dmath_double_inline is True node = nodes.math_block(content, content, nowrap=False, number=None) else: node = nodes.math(content, content) self.add_line_and_source_path(node, token) self.current_node.append(node)
def render_text_latex(self, output: NotebookNode, index: int): text = output["data"]["text/latex"] return [ nodes.math_block( text=strip_latex_delimiters(text), nowrap=False, number=None, classes=["output", "text_latex"], ) ]
def render_text_latex(self, data: MimeData) -> list[nodes.Element]: """Render a notebook text/latex mime data output.""" # TODO should we always assume this is math? return [ nodes.math_block( text=strip_latex_delimiters(data.string), nowrap=False, number=None, classes=["output", "text_latex"], ) ]
def render_text_latex(self, output: NotebookNode, index: int): text = output["data"]["text/latex"] self.env.get_domain("math").data["has_equations"][self.env.docname] = True return [ nodes.math_block( text=strip_latex_delimiters(text), nowrap=False, number=None, classes=["output", "text_latex"], ) ]
def render_math_block_eqno(self, token: Token): """Render math with referencable labels, e.g. ``$a=1$ (label)``.""" label = token.info content = token.content node = nodes.math_block( content, content, nowrap=False, number=None, label=label ) target = self.add_math_target(node) self.add_line_and_source_path(target, token) self.current_node.append(target) self.add_line_and_source_path(node, token) self.current_node.append(node)
def run(self): # type: () -> List[nodes.Node] latex = '\n'.join(self.content) if self.arguments and self.arguments[0]: latex = self.arguments[0] + '\n\n' + latex node = nodes.math_block(latex, latex, docname=self.state.document.settings.env.docname, number=self.options.get('name'), label=self.options.get('label'), nowrap='nowrap' in self.options) ret = [node] set_source_info(self, node) self.add_target(ret) return ret
def run(self): set_classes(self.options) self.assert_has_content() # join lines, separate blocks content = '\n'.join(self.content).split('\n\n') _nodes = [] for block in content: if not block: continue node = nodes.math_block(self.block_text, block, **self.options) node.line = self.content_offset + 1 self.add_name(node) _nodes.append(node) return _nodes
def apply(self, **kwargs): # type: (Any) -> None for math_node in self.document.traverse(nodes.math): # case: old styled ``math`` node generated by old extensions if len(math_node) == 0: warnings.warn( "math node for Sphinx was replaced by docutils'. " "Please use ``docutils.nodes.math`` instead.", RemovedInSphinx30Warning) equation = math_node['latex'] math_node += nodes.Text(equation, equation) translator = self.app.builder.get_translator_class() if hasattr(translator, 'visit_displaymath') and translator != XMLTranslator: # case: old translators which does not support ``math_block`` node warnings.warn( "Translator for %s does not support math_block node'. " "Please update your extension." % translator, RemovedInSphinx30Warning) for old_math_block_node in self.document.traverse(math_block): alt = displaymath(latex=old_math_block_node.astext(), number=old_math_block_node.get('number'), label=old_math_block_node.get('label'), nowrap=old_math_block_node.get('nowrap'), docname=old_math_block_node.get('docname')) old_math_block_node.replace_self(alt) elif getattr(self.app.builder, 'math_renderer_name', None) == 'unknown': # case: math extension provides old styled math renderer for math_block_node in self.document.traverse(nodes.math_block): math_block_node['latex'] = math_block_node.astext() # case: old styled ``displaymath`` node generated by old extensions for math_block_node in self.document.traverse(math_block): if len(math_block_node) == 0: warnings.warn( "math node for Sphinx was replaced by docutils'. " "Please use ``docutils.nodes.math_block`` instead.", RemovedInSphinx30Warning) if isinstance(math_block_node, displaymath): newnode = nodes.math_block('', math_block_node['latex'], **math_block_node.attributes) math_block_node.replace_self(newnode) else: latex = math_block_node['latex'] math_block_node += nodes.Text(latex, latex)
def run(self) -> List[Node]: latex = '\n'.join(self.content) if self.arguments and self.arguments[0]: latex = self.arguments[0] + '\n\n' + latex label = self.options.get('label', self.options.get('name')) node = nodes.math_block(latex, latex, classes=self.options.get('class', []), docname=self.env.docname, number=None, label=label, nowrap='nowrap' in self.options) self.add_name(node) self.set_source_info(node) ret = [node] # type: List[Node] self.add_target(ret) return ret
def run(self): # type: () -> List[nodes.Node] latex = '\n'.join(self.content) if self.arguments and self.arguments[0]: latex = self.arguments[0] + '\n\n' + latex label = self.options.get('label', self.options.get('name')) node = nodes.math_block(latex, latex, docname=self.env.docname, number=None, label=label, nowrap='nowrap' in self.options) self.add_name(node) set_source_info(self, node) ret = [node] # type: List[nodes.Node] self.add_target(ret) return ret
def run(self): set_classes(self.options) self.assert_has_content() # join lines, separate blocks content = '\n'.join(self.content).split('\n\n') nodes = [] for block in content: nodes.append(Text("Input: ")) nodes.append(literal(block, Text(block))) formula = eval(block, pygrim.__dict__) latex = formula.latex() latex = "$$" + latex + "$$" node = math_block(latex, Text(latex), **self.options) node.attributes['nowrap'] = True nodes.append(node) return nodes '''
def visit_script(self, node): if node.attrib.get("type", "").split(";")[0] == "math/tex": node.attrib.pop("type") parent = self.parse_stack_r[-1] if parent.tag == "span": return nodes.math() elif parent.tag == "div": # sphinx mathjax crashes without these attributes present math = nodes.math_block() math["nowrap"] = None math["number"] = None return math else: self.document.reporter.warning( "math/tex script with unknown parent: %s" % parent.tag) else: return IGNORE_ALL_CHILDREN
def create_node(self, output: dict, document, env): """Create the output node, give the cell output.""" mimebundle = output["data"] if "text/latex" in mimebundle: text = mimebundle["text/latex"].strip("$") node = nodes.math_block( text, text, classes=["pasted-math"], docname=env.docname, number=self["math_number"], nowrap=self["math_nowrap"], label=self["math_label"], ) node.line, node.source = self.line, self.source if "math_class" in self and self["math_class"]: node["classes"].append(self["math_class"]) return node return None
def run(self): #set_classes(self.options) r = urdf.Robot.from_xml_file(self.options['file']) _nodes = [] for link in r.links: if not link.inertial or link.inertial.mass <= 0.01: # skip romeo eyes because inertia is 0 #print("skipping " + link.name) # TODO: make an option continue # what follows is much inspired from RSTState.new_subsection method # from docutils/parsers/rst/states.py section_node = nodes.section() title = link.name lineno = 0 messages = [] textnodes, title_messages = self.state.inline_text(title, lineno) titlenode = nodes.title(title, '', *textnodes) name = normalize_name(titlenode.astext()) section_node['names'].append(name) section_node['ids'].append(name) #todo section_node += titlenode section_node += messages section_node += title_messages #self.document.note_implicit_target(section_node, section_node) #self.state.section(link.name, "", "+", lineno, messages) #assert(link.inertial.origin.rotation[0] == 0) inertia_node = math_block(text=rotational_inertia.format( link.inertial.inertia)) inertia_node['nowrap'] = False inertia_node['label'] = None inertia_node['latex'] = rotational_inertia.format( link.inertial.inertia) _nodes += [section_node, nodes.Text("hihi"), create_math_block(mass.format( link.inertial.mass)), create_math_block(com.format( link.inertial.origin.position)), create_math_block(rotational_inertia.format( link.inertial.inertia))] return _nodes
def apply(self, **kwargs): # type: (Any) -> None for math_node in self.document.traverse(nodes.math): # case: old styled ``math`` node generated by old extensions if len(math_node) == 0: warnings.warn("math node for Sphinx was replaced by docutils'. " "Please use ``docutils.nodes.math`` instead.", RemovedInSphinx30Warning) equation = math_node['latex'] math_node += nodes.Text(equation, equation) translator = self.app.builder.get_translator_class() if hasattr(translator, 'visit_displaymath') and translator != XMLTranslator: # case: old translators which does not support ``math_block`` node warnings.warn("Translator for %s does not support math_block node'. " "Please update your extension." % translator, RemovedInSphinx30Warning) for old_math_block_node in self.document.traverse(math_block): alt = displaymath(latex=old_math_block_node.astext(), number=old_math_block_node.get('number'), label=old_math_block_node.get('label'), nowrap=old_math_block_node.get('nowrap'), docname=old_math_block_node.get('docname')) old_math_block_node.replace_self(alt) elif getattr(self.app.builder, 'math_renderer_name', None) == 'unknown': # case: math extension provides old styled math renderer for math_block_node in self.document.traverse(nodes.math_block): math_block_node['latex'] = math_block_node.astext() # case: old styled ``displaymath`` node generated by old extensions for math_block_node in self.document.traverse(math_block): if len(math_block_node) == 0: warnings.warn("math node for Sphinx was replaced by docutils'. " "Please use ``docutils.nodes.math_block`` instead.", RemovedInSphinx30Warning) if isinstance(math_block_node, displaymath): newnode = nodes.math_block('', math_block_node['latex'], **math_block_node.attributes) math_block_node.replace_self(newnode) else: latex = math_block_node['latex'] math_block_node += nodes.Text(latex, latex)
def render_math_block(self, token): content = token.content node = nodes.math_block(content, content, nowrap=False, number=None) self.add_line_and_source_path(node, token) self.current_node.append(node)
def cell_output_to_nodes(outputs, data_priority, write_stderr, dir, thebe_config): """Convert a jupyter cell with outputs and filenames to doctree nodes. Parameters ---------- outputs : a list of outputs from a Jupyter cell data_priority : list of mime types Which media types to prioritize. write_stderr : bool If True include stderr in cell output dir : string Sphinx "absolute path" to the output folder, so it is a relative path to the source folder prefixed with ``/``. thebe_config: dict Thebelab configuration object or None Returns ------- to_add : list of docutils nodes Each output, converted into a docutils node. """ to_add = [] for output in outputs: output_type = output["output_type"] if output_type == "stream": if output["name"] == "stderr": if not write_stderr: continue else: # Output a container with an unhighlighted literal block for # `stderr` messages. # # Adds a "stderr" class that can be customized by the user for both # the container and the literal_block. # # Not setting "rawsource" disables Pygment hightlighting, which # would otherwise add a <div class="highlight">. container = docutils.nodes.container(classes=["stderr"]) container.append( docutils.nodes.literal_block( text=output["text"], rawsource="", # disables Pygment highlighting language="none", classes=["stderr"], )) to_add.append(container) else: to_add.append( docutils.nodes.literal_block( text=output["text"], rawsource=output["text"], language="none", classes=["output", "stream"], )) elif output_type == "error": traceback = "\n".join(output["traceback"]) text = nbconvert.filters.strip_ansi(traceback) to_add.append( docutils.nodes.literal_block( text=text, rawsource=text, language="ipythontb", classes=["output", "traceback"], )) elif output_type in ("display_data", "execute_result"): try: # First mime_type by priority that occurs in output. mime_type = next(x for x in data_priority if x in output["data"]) except StopIteration: continue data = output["data"][mime_type] if mime_type.startswith("image"): # Sphinx treats absolute paths as being rooted at the source # directory, so make a relative path, which Sphinx treats # as being relative to the current working directory. filename = os.path.basename( output.metadata["filenames"][mime_type]) # checks if file dir path is inside a subdir of dir filedir = os.path.dirname( output.metadata["filenames"][mime_type]) subpaths = filedir.split(dir) if subpaths and len(subpaths) > 1: subpath = subpaths[1] dir += subpath uri = os.path.join(dir, filename) to_add.append(docutils.nodes.image(uri=uri)) elif mime_type == "text/html": to_add.append( docutils.nodes.raw(text=data, format="html", classes=["output", "text_html"])) elif mime_type == "text/latex": to_add.append( math_block( text=strip_latex_delimiters(data), nowrap=False, number=None, classes=["output", "text_latex"], )) elif mime_type == "text/plain": to_add.append( docutils.nodes.literal_block( text=data, rawsource=data, language="none", classes=["output", "text_plain"], )) elif mime_type == "application/javascript": to_add.append( docutils.nodes.raw( text='<script type="{mime_type}">{data}</script>'. format(mime_type=mime_type, data=data), format="html", )) elif mime_type == WIDGET_VIEW_MIMETYPE: to_add.append(JupyterWidgetViewNode(view_spec=data)) return to_add
def run(self): text = 'E = mc^2' return [nodes.math_block(text, text)]
def cell_output_to_nodes(cell, data_priority, write_stderr, dir, thebe_config): """Convert a jupyter cell with outputs and filenames to doctree nodes. Parameters ---------- cell : jupyter cell data_priority : list of mime types Which media types to prioritize. write_stderr : bool If True include stderr in cell output dir : string Sphinx "absolute path" to the output folder, so it is a relative path to the source folder prefixed with ``/``. thebe_config: dict Thebelab configuration object or None """ to_add = [] for index, output in enumerate(cell.get('outputs', [])): output_type = output['output_type'] if ( output_type == 'stream' ): if output["name"] == "stderr": if not write_stderr: continue else: # Output a container with an unhighlighted literal block for # `stderr` messages. # # Adds a "stderr" class that can be customized by the user for both # the container and the literal_block. # # Not setting "rawsource" disables Pygment hightlighting, which # would otherwise add a <div class="highlight">. container = docutils.nodes.container(classes=["stderr"]) container.append(docutils.nodes.literal_block( text=output['text'], rawsource='', # disables Pygment highlighting language='none', classes=["stderr"] )) to_add.append(container) else: to_add.append(docutils.nodes.literal_block( text=output['text'], rawsource=output['text'], language='none', classes=["output", "stream"] )) elif ( output_type == 'error' ): traceback = '\n'.join(output['traceback']) text = nbconvert.filters.strip_ansi(traceback) to_add.append(docutils.nodes.literal_block( text=text, rawsource=text, language='ipythontb', classes =["output", "traceback"] )) elif ( output_type in ('display_data', 'execute_result') ): try: # First mime_type by priority that occurs in output. mime_type = next( x for x in data_priority if x in output['data'] ) except StopIteration: continue data = output['data'][mime_type] if mime_type.startswith('image'): # Sphinx treats absolute paths as being rooted at the source # directory, so make a relative path, which Sphinx treats # as being relative to the current working directory. filename = os.path.basename( output.metadata['filenames'][mime_type] ) uri = os.path.join(dir, filename) to_add.append(docutils.nodes.image(uri=uri)) elif mime_type == 'text/html': to_add.append(docutils.nodes.raw( text=data, format='html', classes=["output", "text_html"] )) elif mime_type == 'text/latex': to_add.append(math_block( text=strip_latex_delimiters(data), nowrap=False, number=None, classes=["output", "text_latex"] )) elif mime_type == 'text/plain': to_add.append(docutils.nodes.literal_block( text=data, rawsource=data, language='none', classes=["output", "text_plain"] )) elif mime_type == 'application/javascript': to_add.append(docutils.nodes.raw( text='<script type="{mime_type}">{data}</script>' .format(mime_type=mime_type, data=data), format='html', )) elif mime_type == WIDGET_VIEW_MIMETYPE: to_add.append(JupyterWidgetViewNode(view_spec=data)) return to_add