Example #1
0
def html_visit_lily(self, node):

    lily_source = INLINE_BEGIN.format(
        self.builder.config.lilypond_fontsize[0], )
    lily_source += node['lily_source'] + INLINE_END
    # lily_source += '#"' + node['lily_source'] + '"' + INLINE_END

    try:
        filename = render_lily(self, lily_source)
    except LilyExtError as exception:
        sytem_message = nodes.system_message(str(exception),
                                             type='WARNING',
                                             level=2,
                                             backrefs=[],
                                             source=node['lily_source'])
        sytem_message.walkabout(self)
        self.builder.warn('display lilypond {}: {}'.format(
            node['lily_source'], exception))
        raise nodes.SkipNode

    lily_source = self.encode(node['lily_source']).strip()
    if filename is None:
        # something failed -- use text-only as a bad substitute
        self.body.append('<span class="lily">{}</span>'.format(lily_source))
    else:
        template = '<img class="lily" src="{}" alt="{}" align="absbottom"/>'
        self.body.append(template.format(filename, lily_source))

    raise nodes.SkipNode
Example #2
0
def html_visit_displaylily(self, node):

    if node['nowrap']:
        lily_source = node['lily_source']
    else:
        lily_source = DIRECTIVE_BEGIN.format(
            self.builder.config.lilypond_fontsize[1], )
        lily_source += node['lily_source'] + DIRECTIVE_END

    try:
        filename = render_lily(self, lily_source)
    except LilyExtError as exception:
        sytem_message = nodes.system_message(str(exception),
                                             type='WARNING',
                                             level=2,
                                             backrefs=[],
                                             source=node['lily_source'])
        sytem_message.walkabout(self)
        self.builder.warn('inline lilypond {}: {}'.format(
            node['lily_source'], exception))
        raise nodes.SkipNode

    self.body.append(self.starttag(node, 'div', CLASS='lily'))
    self.body.append('<p>')
    lily_source = self.encode(node['lily_source']).strip()
    if filename is None:
        # something failed -- use text-only as a bad substitute
        self.body.append('<span class="lily">{}</span>'.format(lily_source))
    else:
        self.body.append('<img src="{}" alt="{}" />\n</div>'.format(
            filename, lily_source))
    self.body.append('</p>')

    raise nodes.SkipNode
Example #3
0
    def system_message(self, level, message, *children, **kwargs):
        """
        Return a system_message object.

        Raise an exception or generate a warning if appropriate.
        """
        attributes = kwargs.copy()
        category = kwargs.get("category", "")
        if kwargs.has_key("category"):
            del attributes["category"]
        if kwargs.has_key("base_node"):
            source, line = get_source_line(kwargs["base_node"])
            del attributes["base_node"]
            if source is not None:
                attributes.setdefault("source", source)
            if line is not None:
                attributes.setdefault("line", line)
        attributes.setdefault("source", self.source)
        msg = nodes.system_message(message, level=level, type=self.levels[level], *children, **attributes)
        debug, report_level, halt_level, stream = self[category].astuple()
        if level >= report_level or debug and level == 0:
            msgtext = msg.astext().encode(self.encoding, self.error_handler)
            if category:
                print >> stream, msgtext, "[%s]" % category
            else:
                print >> stream, msgtext
        if level >= halt_level:
            raise SystemMessage(msg)
        if level > 0 or debug:
            self.notify_observers(msg)
        self.max_level = max(level, self.max_level)
        return msg
Example #4
0
    def process_doctree(self, doctree, docname):
        for graph_node in doctree.traverse(traceable_graph):
            # Determine graph's starting traceables.
            start_tags = graph_node["traceables-tags"]
            start_traceables = self.get_start_traceables(start_tags,
                                                         graph_node)
            if not start_traceables:
                message = ("Traceables: no valid tags for graph,"
                           " so skipping graph")
                self.env.warn_node(message, graph_node)
                msg = nodes.system_message(message=message,
                                           level=2, type="ERROR",
                                           source=graph_node["source"],
                                           line=graph_node["line"])
                graph_node.replace_self(msg)
                continue

            # Determine relationships to include in graph.
            input = graph_node.get("traceables-relationships")
            relationship_length_pairs = self.parse_relationships(input)

            # Construct input for graph.
            graph_input = self.construct_graph_input(start_traceables,
                                                     relationship_length_pairs)

            # Generate diagram input and create output node.
            graphviz_node = graphviz.graphviz()
            graphviz_node["code"] = self.generate_dot(graph_input)
            graphviz_node["options"] = {}
            caption = graph_node.get("traceables-caption", "Traceables graph")
            graphviz_node["alt"] = caption
            graph_node.replace_self(graphviz_node)
    def system_message(self, level, message, *children, **kwargs):
        """
        Return a system_message object.

        Raise an exception or generate a warning if appropriate.
        """
        attributes = kwargs.copy()
        if kwargs.has_key('base_node'):
            source, line = get_source_line(kwargs['base_node'])
            del attributes['base_node']
            if source is not None:
                attributes.setdefault('source', source)
            if line is not None:
                attributes.setdefault('line', line)
        attributes.setdefault('source', self.source)
        msg = nodes.system_message(message,
                                   level=level,
                                   type=self.levels[level],
                                   *children,
                                   **attributes)
        if self.stream and (level >= self.report_level
                            or self.debug_flag and level == 0):
            msgtext = msg.astext().encode(self.encoding, self.error_handler)
            print >> self.stream, msgtext
        if level >= self.halt_level:
            raise SystemMessage(msg, level)
        if level > 0 or self.debug_flag:
            self.notify_observers(msg)
        self.max_level = max(level, self.max_level)
        return msg
Example #6
0
def html_visit_dag(self, node):
    libs = self.builder.config.dag_tikzlibraries
    if node.get('libs'):
        libs += ',' + node.get('libs')
    libs = libs.replace(' ', '').replace('\t', '').strip(', ')
    fname = None
    dag = dagmatic.parse(node.get('dag', '')).tikz_string()
    caption = node.get('caption')
    bugfixed = node.get('bugfixed', False)

    try:
        fname = render_dag(self, dag, libs)
    except DagExtError, exc:
        info = str(exc)[str(exc).find('!'):-1]
        sm = nodes.system_message(info,
                                  type='WARNING',
                                  level=2,
                                  backrefs=[],
                                  source=dag)
        sm.walkabout(self)
        self.builder.warn('could not compile latex:\n'
                          '-----\n'
                          '%s\n'
                          '-----\n'
                          'Error message: %s' % (dag, str(exc)))
        raise nodes.SkipNode
    def process_doctree(self, doctree, docname):
        for graph_node in doctree.traverse(traceable_graph):
            # Determine graph's starting traceables.
            start_tags = graph_node["traceables-tags"]
            start_traceables = self.get_start_traceables(
                start_tags, graph_node)
            if not start_traceables:
                message = ("Traceables: no valid tags for graph,"
                           " so skipping graph")
                self.node_warning(self.env, message, graph_node)
                msg = nodes.system_message(message=message,
                                           level=2,
                                           type="ERROR",
                                           source=graph_node["source"],
                                           line=graph_node["line"])
                graph_node.replace_self(msg)
                continue

            # Determine relationships to include in graph.
            input = graph_node.get("traceables-relationships")
            relationship_length_pairs = self.parse_relationships(input)

            # Construct input for graph.
            graph_input = self.construct_graph_input(
                start_traceables, relationship_length_pairs)

            # Generate diagram input and create output node.
            graphviz_node = graphviz.graphviz()
            graphviz_node["code"] = self.generate_dot(graph_input)
            graphviz_node["options"] = {}
            caption = graph_node.get("traceables-caption", "Traceables graph")
            graphviz_node["alt"] = caption
            graph_node.replace_self(graphviz_node)
Example #8
0
    def system_message(self, level, message, *children, **kwargs):
        """
        Return a system_message object.

        Raise an exception or generate a warning if appropriate.
        """
        attributes = kwargs.copy()
        if "base_node" in kwargs:
            source, line = get_source_line(kwargs["base_node"])
            del attributes["base_node"]
            if source is not None:
                attributes.setdefault("source", source)
            if line is not None:
                attributes.setdefault("line", line)
        attributes.setdefault("source", self.source)
        msg = nodes.system_message(message, level=level, type=self.levels[level], *children, **attributes)
        if self.stream and (level >= self.report_level or self.debug_flag and level == self.DEBUG_LEVEL):
            msgtext = msg.astext().encode(self.encoding, self.error_handler)
            self.stream.write(msgtext)
            self.stream.write(b("\n"))
        if level >= self.halt_level:
            raise SystemMessage(msg, level)
        if level > self.DEBUG_LEVEL or self.debug_flag:
            self.notify_observers(msg)
        self.max_level = max(level, self.max_level)
        return msg
Example #9
0
    def system_message(self, level, message, *children, **kwargs):
        """
        Return a system_message object.

        Raise an exception or generate a warning if appropriate.
        """
        attributes = kwargs.copy()
        if kwargs.has_key('base_node'):
            source, line = get_source_line(kwargs['base_node'])
            del attributes['base_node']
            if source is not None:
                attributes.setdefault('source', source)
            if line is not None:
                attributes.setdefault('line', line)
        attributes.setdefault('source', self.source)
        msg = nodes.system_message(message, level=level,
                                   type=self.levels[level],
                                   *children, **attributes)
        if self.stream and (level >= self.report_level
                            or self.debug_flag and level == 0):
            msgtext = msg.astext().encode(self.encoding, self.error_handler)
            print >>self.stream, msgtext
        if level >= self.halt_level:
            raise SystemMessage(msg, level)
        if level > 0 or self.debug_flag:
            self.notify_observers(msg)
        self.max_level = max(level, self.max_level)
        return msg
def mock_renderer():
    def _run_directive(name: str, first_line: str, content: str,
                       position: int):
        node = nodes.Element(name=name, first=first_line, position=position)
        node += nodes.Text(content)
        return [node]

    return Mock(
        config={"myst_extensions": ["html_image", "html_admonition"]},
        document={"source": "source"},
        reporter=Mock(
            warning=Mock(return_value=nodes.system_message("warning")),
            error=Mock(return_value=nodes.system_message("error")),
        ),
        run_directive=_run_directive,
    )
Example #11
0
def html_visit_tikzfigure(self, node):
    latex = node['latex']
    opts = node['tikzopts']
    libs = node['tikzlibs']
    try:
        imagedir = self.builder.imgpath
        fname, relfn = RenderTikzFigureImage(latex, opts, libs,
                                             self.builder).render()
        #print("Rendered image:", fname, relfn)
    except TikzFigureExtError as exc:
        msg = unicode(str(exc), 'utf-8', 'replace')
        sm = nodes.system_message(msg,
                                  type='WARNING',
                                  level=2,
                                  backrefs=[],
                                  source=node['latex'])
        raise nodes.SkipNode
        sm.walkabout(self)
        self.builder.warn('display latex %r: ' % node['latex'] + str(exc))
        raise nodes.SkipNode
    if fname is None:
        # something failed -- use text-only as a bad substitute
        self.body.append('<span class="tikzfigure">%s</span>' %
                         self.encode(node['latex']).strip())
    else:
        c = ('<img src="%s" %s' % (fname, node['style']))
        self.body.append(c + '/>')
    raise nodes.SkipNode
Example #12
0
def html_visit_tikz(self,node):
    # print "\n***********************************"
    # print "You have entered the following argument"
    # print "***********************************"
    # print node['caption']
    # print "***********************************"
    # print "You have entered the following tikzlibraries"
    # print "***********************************"
    # print node['libs']
    # print "\n***********************************"
    # print "You have entered the following tikz-code"
    # print "***********************************"
    # print node['tikz']
    # print "***********************************"

    libs = self.builder.config.tikz_tikzlibraries + ',' + node['libs']
    libs = libs.replace(' ', '').replace('\t', '').strip(', ')

    try:
        fname = render_tikz(self, node['fname'], node['tikz'], libs)
    except TikzExtError, exc:
        info = str(exc)[str(exc).find('!'):-1]
        sm = nodes.system_message(info, type='WARNING', level=2,
                                  backrefs=[], source=node['tikz'])
        sm.walkabout(self)
        self.builder.warn('display latex %r: \n' % node['tikz'] + str(exc))
        raise nodes.SkipNode
Example #13
0
def html_visit_displaymath(self, node):
    if node['nowrap']:
        latex = node['latex']
    else:
        latex = wrap_displaymath(node['latex'], None)
    try:
        fname, depth = render_math(self, latex)
    except MathExtError as exc:
        sm = nodes.system_message(str(exc), type='WARNING', level=2,
                                  backrefs=[], source=node['latex'])
        sm.walkabout(self)
        self.builder.warn('inline latex %r: ' % node['latex'] + str(exc))
        raise nodes.SkipNode
    self.body.append(self.starttag(node, 'div', CLASS='math'))
    self.body.append('<p>')
    if node['number']:
        self.body.append('<span class="eqno">(%s)</span>' % node['number'])
    if fname is None:
        # something failed -- use text-only as a bad substitute
        self.body.append('<span class="math">%s</span></p>\n</div>' %
                         self.encode(node['latex']).strip())
    else:
        self.body.append(('<img src="%s"' % fname) + get_tooltip(self, node)
                         + '/></p>\n</div>')
    raise nodes.SkipNode
Example #14
0
def html_visit_tikz(self,node):
    libs = self.builder.config.tikz_tikzlibraries + ',' + node['libs']
    libs = libs.replace(' ', '').replace('\t', '').strip(', ')

    try:
        fname = render_tikz(self,node['tikz'],libs,node['stringsubst'])
    except TikzExtError as exc:
        info = str(exc)[str(exc).find('!'):-1]
        sm = nodes.system_message(info, type='WARNING', level=2,
                                  backrefs=[], source=node['tikz'])
        sm.walkabout(self)
        self.builder.warn('display latex %r: \n' % node['tikz'] + str(exc))
        raise nodes.SkipNode
    if fname is None:
        # something failed -- use text-only as a bad substitute
        self.body.append('<span class="math">%s</span>' %
                         self.encode(node['tikz']).strip())
    else:
        self.body.append(self.starttag(node, 'div', CLASS='figure'))
        self.body.append('<p>')
        self.body.append('<img src="%s" alt="%s" /></p>\n' %
                         (fname, self.encode(node['tikz']).strip()))
        if node['caption']:
            self.body.append('<p class="caption">%s</p>' %
                             self.encode(node['caption']).strip())
        self.body.append('</div>')
        raise nodes.SkipNode
Example #15
0
def html_visit_tikz(self,node):
    libs = self.builder.config.tikz_tikzlibraries + ',' + node['libs']
    libs = libs.replace(' ', '').replace('\t', '').strip(', ')

    try:
        fname = render_tikz(self,node['tikz'],libs,node['stringsubst'])
    except TikzExtError as exc:
        info = str(exc)[str(exc).find('!'):-1]
        sm = nodes.system_message(info, type='WARNING', level=2,
                                  backrefs=[], source=node['tikz'])
        sm.walkabout(self)
        self.builder.warn('display latex %r: \n' % node['tikz'] + str(exc))
        raise nodes.SkipNode
    if fname is None:
        # something failed -- use text-only as a bad substitute
        self.body.append('<span class="math">%s</span>' %
                         self.encode(node['tikz']).strip())
    else:
        self.body.append(self.starttag(node, 'div', CLASS='figure'))
        self.body.append('<p>')
        self.body.append('<img src="%s" alt="%s" /></p>\n' %
                         (fname, self.encode(node['tikz']).strip()))
        if node['caption']:
            self.body.append('<p class="caption">%s</p>' %
                             self.encode(node['caption']).strip())
        self.body.append('</div>')
        raise nodes.SkipNode
Example #16
0
def html_visit_displaymath(self: HTMLTranslator,
                           node: nodes.math_block) -> None:
    if node['nowrap']:
        latex = node.astext()
    else:
        latex = wrap_displaymath(node.astext(), None, False)
    try:
        fname, depth = render_math(self, latex)
    except MathExtError as exc:
        msg = str(exc)
        sm = nodes.system_message(msg,
                                  type='WARNING',
                                  level=2,
                                  backrefs=[],
                                  source=node.astext())
        sm.walkabout(self)
        logger.warning(__('inline latex %r: %s'), node.astext(), msg)
        raise nodes.SkipNode from exc
    self.body.append(self.starttag(node, 'div', CLASS='math'))
    self.body.append('<p>')
    if node['number']:
        number = get_node_equation_number(self, node)
        self.body.append('<span class="eqno">(%s)' % number)
        self.add_permalink_ref(node, _('Permalink to this equation'))
        self.body.append('</span>')
    if fname is None:
        # something failed -- use text-only as a bad substitute
        self.body.append('<span class="math">%s</span></p>\n</div>' %
                         self.encode(node.astext()).strip())
    else:
        self.body.append(('<img src="%s"' % fname) + get_tooltip(self, node) +
                         '/></p>\n</div>')
    raise nodes.SkipNode
Example #17
0
 def system_message(self, level, message, *children, **kwargs):
     self.messages.append((level, message, children, kwargs))
     return nodes.system_message(message,
                                 level=level,
                                 type=self.levels[level],
                                 *children,
                                 **kwargs)
    def run(self):
        env = self.state.document.settings.env
        tag = self.arguments[0]
        messages = []

        # Verify the supplied attributes are valid.
        attributes = {}
        for name, value in self.options.items():
            if is_valid_traceable_attribute_name(name):
                attributes[name] = value
            else:
                message = ("Traceable attribute has invalid syntax: {0!r}"
                           .format(name))
                env.warn(env.docname, message, self.lineno)
                msg = nodes.system_message(message=message,
                                           level=2, type="ERROR",
                                           source=env.docname,
                                           line=self.lineno)
                messages.append(msg)

        # Determine traceable display format.
        format = attributes.pop("format", "admonition")

        target_node = self.create_target_node(env, tag, attributes)
        index_node = self.create_index_node(env, tag, attributes)

        traceable = Traceable(target_node)
        try:
            TraceablesStorage(env).add_traceable(traceable)
        except ValueError, e:
            env.warn_node(e.message, target_node)
Example #19
0
def html_visit_displaymath(self, node):
    # type: (nodes.NodeVisitor, displaymath) -> None
    if node['nowrap']:
        latex = node['latex']
    else:
        latex = wrap_displaymath(node['latex'], None,
                                 self.builder.config.math_number_all)
    try:
        fname, depth = render_math(self, latex)
    except MathExtError as exc:
        msg = text_type(exc)
        sm = nodes.system_message(msg, type='WARNING', level=2,
                                  backrefs=[], source=node['latex'])
        sm.walkabout(self)
        logger.warning('inline latex %r: %s', node['latex'], msg)
        raise nodes.SkipNode
    self.body.append(self.starttag(node, 'div', CLASS='math'))
    self.body.append('<p>')
    if node['number']:
        self.body.append('<span class="eqno">(%s)' % node['number'])
        self.add_permalink_ref(node, _('Permalink to this equation'))
        self.body.append('</span>')
    if fname is None:
        # something failed -- use text-only as a bad substitute
        self.body.append('<span class="math">%s</span></p>\n</div>' %
                         self.encode(node['latex']).strip())
    else:
        self.body.append(('<img src="%s"' % fname) + get_tooltip(self, node) +
                         '/></p>\n</div>')
    raise nodes.SkipNode
Example #20
0
def render_ditaa_html(self, node, code, options, prefix='ditaa',
                    imgcls=None, alt=None):
    try:
        fname, outfn = render_ditaa(self, code, options, prefix)
    except DitaaError as exc:
        info = str(exc)
        sm = nodes.system_message(info, type='WARNING', level=2,
                                  backrefs=[], source=node['code'])
        sm.walkabout(self)
        self.builder.warn(info)
        raise nodes.SkipNode

    inline = node.get('inline', False)
    if inline:
        wrapper = 'span'
    else:
        wrapper = 'p'

    self.body.append(self.starttag(node, wrapper, CLASS='ditaa'))
    if fname is None:
        self.body.append(self.encode(code))
    else:
        # nothing in image map (the lines are <map> and </map>)
        self.body.append('<img src="%s"/>\n' %
                         fname)

    self.body.append('</%s>\n' % wrapper)
    raise nodes.SkipNode
Example #21
0
def html_visit_displaymath(self, node):
    if node['nowrap']:
        latex = node['latex']
    else:
        latex = wrap_displaymath(node['latex'], None,
                                 self.builder.config.math_number_all)
    try:
        fname, depth = render_math(self, latex)
    except MathExtError as exc:
        sm = nodes.system_message(str(exc), type='WARNING', level=2,
                                  backrefs=[], source=node['latex'])
        sm.walkabout(self)
        self.builder.warn('inline latex %r: ' % node['latex'] + str(exc))
        raise nodes.SkipNode
    self.body.append(self.starttag(node, 'div', CLASS='math'))
    self.body.append('<p>')
    if node['number']:
        self.body.append('<span class="eqno">(%s)</span>' % node['number'])
    if fname is None:
        # something failed -- use text-only as a bad substitute
        self.body.append('<span class="math">%s</span></p>\n</div>' %
                         self.encode(node['latex']).strip())
    else:
        self.body.append(('<img src="%s"' % fname) + get_tooltip(self, node) +
                         '/></p>\n</div>')
    raise nodes.SkipNode
Example #22
0
def html_visit_displaymath(self, node):
    # type: (nodes.NodeVisitor, displaymath) -> None
    if node['nowrap']:
        latex = node['latex']
    else:
        latex = wrap_displaymath(node['latex'], None,
                                 self.builder.config.math_number_all)
    try:
        fname, depth = render_math(self, latex)
    except MathExtError as exc:
        msg = text_type(exc)
        sm = nodes.system_message(msg,
                                  type='WARNING',
                                  level=2,
                                  backrefs=[],
                                  source=node['latex'])
        sm.walkabout(self)
        logger.warning('inline latex %r: %s', node['latex'], msg)
        raise nodes.SkipNode
    self.body.append(self.starttag(node, 'div', CLASS='math'))
    self.body.append('<p>')
    if node['number']:
        number = get_node_equation_number(self, node)
        self.body.append('<span class="eqno">(%s)</span>' % number)
    if fname is None:
        # something failed -- use text-only as a bad substitute
        self.body.append('<span class="math">%s</span></p>\n</div>' %
                         self.encode(node['latex']).strip())
    else:
        self.body.append(('<img src="%s"' % fname) + get_tooltip(self, node) +
                         '/></p>\n</div>')
    raise nodes.SkipNode
Example #23
0
def html_visit_math(self, node):
    try:
        fname, depth = render_math(self, '$'+node['latex']+'$')
    except MathExtError, exc:
        sm = nodes.system_message(str(exc), type='WARNING', level=2,
                                  backrefs=[], source=node['latex'])
        sm.walkabout(self)
        self.builder.warn('display latex %r: ' % node['latex'] + str(exc))
        raise nodes.SkipNode
Example #24
0
def html_visit_rail(self, node):
    try:
        fname, depth = render_rail(self, '$'+node['latex']+'$')
    except RailExtError, exc:
        msg = unicode(str(exc), 'utf-8', 'replace')
        sm = nodes.system_message(msg, type='WARNING', level=2,
                                  backrefs=[], source=node['latex'])
        sm.walkabout(self)
        self.builder.warn('display latex %r: ' % node['latex'] + str(exc))
        raise nodes.SkipNode
Example #25
0
def html_visit_displayrail(self, node):
    latex = node['latex']
    try:
        fname, depth = render_rail(self, latex)
    except RailExtError, exc:
        sm = nodes.system_message(str(exc), type='WARNING', level=2,
                                  backrefs=[], source=node['latex'])
        sm.walkabout(self)
        self.builder.warn('inline latex %r: ' % node['latex'] + str(exc))
        raise nodes.SkipNode
Example #26
0
def html_visit_displayrail(self, node):
    latex = node['latex']
    try:
        fname, depth = render_rail(self, latex)
    except RailExtError, exc:
        sm = nodes.system_message(str(exc), type='WARNING', level=2,
                                  backrefs=[], source=node['latex'])
        sm.walkabout(self)
        self.builder.warn('inline latex %r: ' % node['latex'] + str(exc))
        raise nodes.SkipNode
Example #27
0
def html_visit_rail(self, node):
    try:
        fname, depth = render_rail(self, '$'+node['latex']+'$')
    except RailExtError, exc:
        msg = unicode(str(exc), 'utf-8', 'replace')
        sm = nodes.system_message(msg, type='WARNING', level=2,
                                  backrefs=[], source=node['latex'])
        sm.walkabout(self)
        self.builder.warn('display latex %r: ' % node['latex'] + str(exc))
        raise nodes.SkipNode
Example #28
0
def html_visit_math(self, node):
    try:
        fname, depth = render_math(self, '$'+node['latex']+'$')
    except MathExtError, exc:
        msg = unicode(exc)
        sm = nodes.system_message(msg, type='WARNING', level=2,
                                  backrefs=[], source=node['latex'])
        sm.walkabout(self)
        self.builder.warn('display latex %r: ' % node['latex'] + msg)
        raise nodes.SkipNode
    def run(self):
        env = self.state.document.settings.env
        tag = self.arguments[0]
        messages = []

        # Verify the supplied attributes are valid.
        attributes = {}
        for name, value in self.options.items():
            if is_valid_traceable_attribute_name(name):
                attributes[name] = value
            else:
                message = ("Traceable attribute has invalid syntax: {0!r}"
                           .format(name))
                self.document_warning(env, message, self.lineno)
                msg = nodes.system_message(message=message,
                                           level=2, type="ERROR",
                                           source=env.docname,
                                           line=self.lineno)
                messages.append(msg)

        # Determine traceable display format.
        format = attributes.pop("format", "admonition")

        target_node = self.create_target_node(env, tag, attributes)
        index_node = self.create_index_node(env, tag, attributes)

        traceable = Traceable(target_node)
        try:
            TraceablesStorage(env).add_traceable(traceable)
        except ValueError as e:
            self.node_warning(env, e, target_node)
            # TODO: Should use error handling similar to this:
            # Error = ExtensionError
            # except self.Error as error:
            #    message = str(error)
            #    self.node_warning(env, message, node)
            #    msg = nodes.system_message(message=message,
            #                               level=2, type="ERROR",
            #                               source=node.source,
            #                               line=node.line)
            #    node.replace_self(msg)

        # Construct placeholder node for traceable display.
        display_node = traceable_display()
        display_node["source"] = env.docname
        display_node["line"] = self.lineno
        display_node["traceables-tag"] = tag
        display_node["traceables-format"] = format
        display_node["traceables-options"] = {}

        # Insert remaining content into placeholder.
        self.state.nested_parse(self.content, self.content_offset,
                                display_node)

        return [target_node, index_node, display_node] + messages
 def process_doctree(self, doctree, docname):
     for node in doctree.traverse(self.process_node_type):
         try:
             self.process_node(node, doctree, docname)
         except self.Error, error:
             message = str(error)
             self.env.warn_node(message, node)
             msg = nodes.system_message(message=message,
                                        level=2, type="ERROR",
                                        source=node.source,
                                        line=node.line)
             node.replace_self(msg)
Example #31
0
def html_visit_tikzinline(self,node):
    libs = self.builder.config.tikz_tikzlibraries
    libs = libs.replace(' ', '').replace('\t', '').strip(', ')
    try:
        fname = render_tikz(self,node['tikz'],libs);
    except TikzExtError, exc:
        info = str(exc)[str(exc).find('!'):-1]
        sm = nodes.system_message(info, type='WARNING', level=2,
                                  backrefs=[], source=node['tikz'])
        sm.walkabout(self)
        self.builder.warn('display latex %r: \n' % node['tikz'] + str(exc))
        raise nodes.SkipNode
Example #32
0
def html_visit_lily(self, node):
    music = Inline_HEAD % self.builder.config.pnglily_fontsize[0]
    music += node['music'] + Inline_BACK
    #music += '#"' + node['music'] + '"' + Inline_BACK
    try:
        fname = render_lily(self, music)
    except LilyExtError, exc:
        sm = nodes.system_message(unicode(exc), type='WARNING', level=2,
                                  backrefs=[], source=node['music'])
        sm.walkabout(self)
        self.builder.warn('display lilypond %r: ' % node['music'] + unicode(exc))
        raise nodes.SkipNode
def html_visit_displaymath(self, node):
    if node['nowrap']:
        latex = node['latex']
    else:
        latex = wrap_displaymath(node['latex'], None)
    try:
        fname, depth = render_math(self, latex)
    except MathExtError, exc:
        sm = nodes.system_message(str(exc), type='WARNING', level=2,
                                  backrefs=[], source=node['latex'])
        sm.walkabout(self)
        self.builder.warn('inline latex %r: ' % node['latex'] + str(exc))
        raise nodes.SkipNode
Example #34
0
def html_visit_displaymath(self, node):
    if node['nowrap']:
        latex = node['latex']
    else:
        latex = wrap_displaymath(node['latex'], None)
    try:
        fname, depth = render_math(self, latex)
    except MathExtError, exc:
        sm = nodes.system_message(str(exc), type='WARNING', level=2,
                                  backrefs=[], source=node['latex'])
        sm.walkabout(self)
        self.builder.warn('inline latex %r: ' % node['latex'] + str(exc))
        raise nodes.SkipNode
Example #35
0
 def process_doctree(self, doctree, docname):
     for node in doctree.traverse(self.process_node_type):
         try:
             self.process_node(node, doctree, docname)
         except self.Error as error:
             message = str(error)
             self.node_warning(self.env, message, node)
             msg = nodes.system_message(message=message,
                                        level=2,
                                        type="ERROR",
                                        source=node.source,
                                        line=node.line)
             node.replace_self(msg)
Example #36
0
def html_visit_tikz(self, node):
    latex = node['latex']
    try:
        imagedir = self.builder.imgpath
        fname = RenderTikzImage(latex).render()
        print "Rendered imge:", fname
    except TikzExtError, exc:
        msg = unicode(str(exc), 'utf-8', 'replace')
        sm = nodes.system_message(msg, type='WARNING', level=2,
                backrefs=[], source=node['latex'])
        raise nodes.SkipNode
        sm.walkabout(self)
        self.builder.warn('display latex %r: ' % node['latex'] + str(exc))
        raise nodes.SkipNode
Example #37
0
def render_ditaa_latex(self, node, code, options, prefix='ditaa'):
    try:
        fname, outfn = render_ditaa(self, code, options, prefix)
    except DitaaError as exc:
        info = str(exc)
        sm = nodes.system_message(info, type='WARNING', level=2,
                                  backrefs=[], source=node['code'])
        sm.walkabout(self)
        self.builder.warn(info)
        raise nodes.SkipNode

    if fname is not None:
        self.body.append('\\par\\includegraphics{%s}\\par' % outfn)
    raise nodes.SkipNode
Example #38
0
def html_visit_tikzinline(self, node):
    libs = self.builder.config.tikz_tikzlibraries
    libs = libs.replace(' ', '').replace('\t', '').strip(', ')
    try:
        fname = render_tikz(self, node, libs)
    except TikzExtError as exc:
        info = str(exc)[str(exc).find('!'):].replace('\\n', '\n')
        sm = nodes.system_message(info, type='WARNING', level=2,
                                  backrefs=[], source=node['tikz'])
        sm.walkabout(self)
    else:
        self.body.append('<img src="%s" alt="%s"/>' %
                         (fname, self.encode(node['alt']).strip()))
    raise nodes.SkipNode
Example #39
0
    def system_message(self, level, message, *children, **kwargs):
        """
        Return a system_message object.

        Raise an exception or generate a warning if appropriate.
        """
        attributes = kwargs.copy()
        if 'base_node' in kwargs:
            source, line = get_source_line(kwargs['base_node'])
            del attributes['base_node']
            if source is not None:
                attributes.setdefault('source', source)
            if line is not None:
                attributes.setdefault('line', line)
                # assert source is not None, "node has line- but no source-argument"
        if not 'source' in attributes:  # 'line' is absolute line number
            try:  # look up (source, line-in-source)
                source, line = self.locator(attributes.get('line'))
                # print "locator lookup", kwargs.get('line'), "->", source, line
            except AttributeError:
                source, line = None, None
            if source is not None:
                attributes['source'] = source
            if line is not None:
                attributes['line'] = line
        # assert attributes['line'] is not None, (message, kwargs)
        # assert attributes['source'] is not None, (message, kwargs)
        attributes.setdefault('source', self.source)

        msg = nodes.system_message(message,
                                   level=level,
                                   type=self.levels[level],
                                   *children,
                                   **attributes)
        if self.stream and (level >= self.report_level
                            or self.debug_flag and level == self.DEBUG_LEVEL
                            or level >= self.halt_level):
            msgtext = msg.astext() + '\n'
            try:
                self.stream.write(msgtext)
            except UnicodeEncodeError:
                self.stream.write(
                    msgtext.encode(self.encoding, self.error_handler))
        if level >= self.halt_level:
            raise SystemMessage(msg, level)
        if level > self.DEBUG_LEVEL or self.debug_flag:
            self.notify_observers(msg)
        self.max_level = max(level, self.max_level)
        return msg
Example #40
0
def html_visit_displaylily(self, node):
    if node['nowrap']:
        music = node['music']
    else:
        music = Directive_HEAD % (self.builder.config.pnglily_fontsize[1],
                                  self.builder.config.pnglily_fontsize[1])
        music += node['music'] + Directive_BACK
    try:
        fname = render_lily(self, music)
    except LilyExtError, exc:
        sm = nodes.system_message(unicode(exc), type='WARNING', level=2,
                                  backrefs=[], source=node['music'])
        sm.walkabout(self)
        self.builder.warn('inline lilypond %r: ' % node['music'] + unicode(exc))
        raise nodes.SkipNode
Example #41
0
def html_visit_circuits(self, node):
    latex = node['latex']
    opts = node['tikzopts']
    libs = node['tikzlibs']
    try:
        imagedir = self.builder.imgpath
        fname, relfn = RenderCircuitsImage(latex, opts, libs, self.builder).render()
        #print "Rendered imge:", fname, relfn
    except CircuitsExtError, exc:
        msg = unicode(str(exc), 'utf-8', 'replace')
        sm = nodes.system_message(msg, type='WARNING', level=2,
                backrefs=[], source=node['latex'])
        raise nodes.SkipNode
        sm.walkabout(self)
        self.builder.warn('display latex %r: ' % node['latex'] + str(exc))
        raise nodes.SkipNode
Example #42
0
    def system_message(self, level, message, *children, **kwargs):
        """
        Return a system_message object.

        Raise an exception or generate a warning if appropriate.
        """
        attributes = kwargs.copy()
        if 'base_node' in kwargs:
            source, line = get_source_line(kwargs['base_node'])
            del attributes['base_node']
            if source is not None:
                attributes.setdefault('source', source)
            if line is not None:
                attributes.setdefault('line', line)
                # assert source is not None, "node has line- but no source-argument"
        if not 'source' in attributes: # 'line' is absolute line number
            try: # look up (source, line-in-source)
                source, line = self.locator(attributes.get('line'))
                # print "locator lookup", kwargs.get('line'), "->", source, line
            except AttributeError:
                source, line = None, None
            if source is not None:
                attributes['source'] = source
            if line is not None:
                attributes['line'] = line
        # assert attributes['line'] is not None, (message, kwargs)
        # assert attributes['source'] is not None, (message, kwargs)
        attributes.setdefault('source', self.source)

        msg = nodes.system_message(message, level=level,
                                   type=self.levels[level],
                                   *children, **attributes)
        if self.stream and (level >= self.report_level
                            or self.debug_flag and level == self.DEBUG_LEVEL
                            or level >= self.halt_level):
            msgtext = msg.astext() + '\n'
            try:
                self.stream.write(msgtext)
            except UnicodeEncodeError:
                self.stream.write(msgtext.encode(self.encoding,
                                                 self.error_handler))
        if level >= self.halt_level:
            raise SystemMessage(msg, level)
        if level > self.DEBUG_LEVEL or self.debug_flag:
            self.notify_observers(msg)
        self.max_level = max(level, self.max_level)
        return msg
Example #43
0
    def system_message(self, level, message, *children, **kwargs):
        """
        Return a system_message object.

        Raise an exception or generate a warning if appropriate.
        """
        # `message` can be a `string`, `unicode`, or `Exception` instance.
        if isinstance(message, Exception):
            message = SafeString(message)

        attributes = kwargs.copy()
        if 'base_node' in kwargs:
            source, line = get_source_line(kwargs['base_node'])
            del attributes['base_node']
            if source is not None:
                attributes.setdefault('source', source)
            if line is not None:
                attributes.setdefault('line', line)
                # assert source is not None, "node has line- but no source-argument"
        if not 'source' in attributes:  # 'line' is absolute line number
            try:  # look up (source, line-in-source)
                source, line = self.get_source_and_line(attributes.get('line'))
            except AttributeError:
                source, line = None, None
            if source is not None:
                attributes['source'] = source
            if line is not None:
                attributes['line'] = line
        # assert attributes['line'] is not None, (message, kwargs)
        # assert attributes['source'] is not None, (message, kwargs)
        attributes.setdefault('source', self.source)

        msg = nodes.system_message(message,
                                   level=level,
                                   type=self.levels[level],
                                   *children,
                                   **attributes)
        if self.stream and (level >= self.report_level
                            or self.debug_flag and level == self.DEBUG_LEVEL
                            or level >= self.halt_level):
            self.stream.write(msg.astext() + '\n')
        if level >= self.halt_level:
            raise SystemMessage(msg, level)
        if level > self.DEBUG_LEVEL or self.debug_flag:
            self.notify_observers(msg)
        self.max_level = max(level, self.max_level)
        return msg
Example #44
0
def system_message(vmsg, source, lineno):
    """
    :param ValidationErrorMessage vmsg: message object
    :param source: file path
    :param lineno: lineno
    :return: system_message node
    """
    msg = u'{etype}: {target} -> {suggestion}'.format(
        etype=vmsg.error_type,
        target=vmsg.target_text,
        suggestion=vmsg.suggestion_text,
    )
    return nodes.system_message(msg,
                                type='WARNING',
                                level=2,
                                source=source,
                                lineno=lineno)
Example #45
0
def html_visit_math(self, node):
    try:
        fname, depth = render_math(self, "$" + node["latex"] + "$")
    except MathExtError as exc:
        msg = text_type(exc)
        sm = nodes.system_message(msg, type="WARNING", level=2, backrefs=[], source=node["latex"])
        sm.walkabout(self)
        self.builder.warn("display latex %r: " % node["latex"] + msg)
        raise nodes.SkipNode
    if fname is None:
        # something failed -- use text-only as a bad substitute
        self.body.append('<span class="math">%s</span>' % self.encode(node["latex"]).strip())
    else:
        c = ('<img class="math" src="%s"' % fname) + get_tooltip(self, node)
        if depth is not None:
            c += ' style="vertical-align: %dpx"' % (-depth)
        self.body.append(c + "/>")
    raise nodes.SkipNode
Example #46
0
def html_visit_math(self, node):
    try:
        fname, depth = render_math(self, '$'+node['latex']+'$')
    except MathExtError as exc:
        msg = str(str(exc), 'utf-8', 'replace')
        sm = nodes.system_message(msg, type='WARNING', level=2,
                                  backrefs=[], source=node['latex'])
        sm.walkabout(self)
        self.builder.warn('display latex %r: ' % node['latex'] + str(exc))
        raise nodes.SkipNode
    if fname is None:
        # something failed -- use text-only as a bad substitute
        self.body.append('<span class="math">%s</span>' %
                         self.encode(node['latex']).strip())
    else:
        c  = ('<img class="math" src="%s"' % fname) + get_tooltip(self, node)
        if depth is not None:
            c += ' style="vertical-align: %dpx"' % (-depth)
        self.body.append(c + '/>')
    raise nodes.SkipNode
Example #47
0
def html_visit_tikz(self, node):
    libs = self.builder.config.tikz_tikzlibraries + ',' + node['libs']
    libs = libs.replace(' ', '').replace('\t', '').strip(', ')
    try:
        fname = render_tikz(self, node, libs, node['stringsubst'])
    except TikzExtError as exc:
        info = str(exc)[str(exc).find('!'):].replace('\\n', '\n')
        sm = nodes.system_message(info, type='WARNING', level=2,
                                  backrefs=[], source=node['tikz'])
        sm.walkabout(self)
    else:
        # If scaling option is set, add 'width' attribute
        scale = ''
        if node['xscale']:
            scale = 'width="%s%%"' % (node['xscale'])
        self.body.append(self.starttag(node, 'div', CLASS='figure',
                                       STYLE='text-align: %s' % self.encode(node['align']).strip()))
        self.body.append('<p>')
        self.body.append('<img %s src="%s" alt="%s" /></p>\n' %
                         (scale, fname, self.encode(node['alt']).strip()))
Example #48
0
def html_visit_math(self: HTMLTranslator, node: nodes.math) -> None:
    try:
        fname, depth = render_math(self, '$' + node.astext() + '$')
    except MathExtError as exc:
        msg = str(exc)
        sm = nodes.system_message(msg, type='WARNING', level=2,
                                  backrefs=[], source=node.astext())
        sm.walkabout(self)
        logger.warning(__('display latex %r: %s'), node.astext(), msg)
        raise nodes.SkipNode from exc
    if fname is None:
        # something failed -- use text-only as a bad substitute
        self.body.append('<span class="math">%s</span>' %
                         self.encode(node.astext()).strip())
    else:
        c = ('<img class="math" src="%s"' % fname) + get_tooltip(self, node)
        if depth is not None:
            c += ' style="vertical-align: %dpx"' % (-depth)
        self.body.append(c + '/>')
    raise nodes.SkipNode
Example #49
0
def html_visit_tikzinline(self,node):
    libs = self.builder.config.tikz_tikzlibraries
    libs = libs.replace(' ', '').replace('\t', '').strip(', ')
    try:
        fname = render_tikz(self,node['tikz'],libs);
    except TikzExtError as exc:
        info = str(exc)[str(exc).find('!'):-1]
        sm = nodes.system_message(info, type='WARNING', level=2,
                                  backrefs=[], source=node['tikz'])
        sm.walkabout(self)
        self.builder.warn('display latex %r: \n' % node['tikz'] + str(exc))
        raise nodes.SkipNode
    if fname is None:
        # something failed -- use text-only as a bad substitute
        self.body.append('<span class="math">%s</span>' %
                         self.encode(node['tikz']).strip())
    else:
        self.body.append('<img class="math" src="%s" alt="%s"/>' %
                         (fname, self.encode(node['tikz']).strip()))
        raise nodes.SkipNode
Example #50
0
def html_visit_math(self, node):
    try:
        fname, depth = render_math(self, '$'+node['latex']+'$')
    except MathExtError as exc:
        msg = text_type(exc)
        sm = nodes.system_message(msg, type='WARNING', level=2,
                                  backrefs=[], source=node['latex'])
        sm.walkabout(self)
        self.builder.warn('display latex %r: ' % node['latex'] + msg)
        raise nodes.SkipNode
    if fname is None:
        # something failed -- use text-only as a bad substitute
        self.body.append('<span class="math">%s</span>' %
                         self.encode(node['latex']).strip())
    else:
        c = ('<img class="math" src="%s"' % fname) + get_tooltip(self, node)
        if depth is not None:
            c += ' style="vertical-align: %dpx"' % (-depth)
        self.body.append(c + '/>')
    raise nodes.SkipNode
    def get_formatter(self, node, name):
        default = self.get_default_formatter()
        if not name and default:
            return default

        valid_formatters = self.get_registered_formatters()
        formatter = valid_formatters.get(name)
        if formatter:
            return formatter
        else:
            message = ("Unknown formatter name: '{0}';"
                       " available formatters: {1}"
                       .format(name, ", ".join(valid_formatters.keys())))
            self.env.warn_node(message, node)
            new_nodes = [nodes.system_message(message=message,
                                              level=2, type="ERROR",
                                              source=node["source"],
                                              line=node["line"])]
            node.replace_self(new_nodes)
            return None
Example #52
0
def html_visit_math(self, node):
    # type: (nodes.NodeVisitor, nodes.math) -> None
    try:
        fname, depth = render_math(self, '$' + node.astext() + '$')
    except MathExtError as exc:
        msg = text_type(exc)
        sm = nodes.system_message(msg, type='WARNING', level=2,
                                  backrefs=[], source=node.astext())
        sm.walkabout(self)
        logger.warning(__('display latex %r: %s'), node.astext(), msg)
        raise nodes.SkipNode
    if fname is None:
        # something failed -- use text-only as a bad substitute
        self.body.append('<span class="math">%s</span>' %
                         self.encode(node.astext()).strip())
    else:
        c = ('<img class="math" src="%s"' % fname) + get_tooltip(self, node)
        if depth is not None:
            c += ' style="vertical-align: %dpx"' % (-depth)
        self.body.append(c + '/>')
    raise nodes.SkipNode
Example #53
0
def html_visit_displaymath(self, node):
    if node["nowrap"]:
        latex = node["latex"]
    else:
        latex = wrap_displaymath(node["latex"], None)
    try:
        fname, depth = render_math(self, latex)
    except MathExtError as exc:
        sm = nodes.system_message(str(exc), type="WARNING", level=2, backrefs=[], source=node["latex"])
        sm.walkabout(self)
        self.builder.warn("inline latex %r: " % node["latex"] + str(exc))
        raise nodes.SkipNode
    self.body.append(self.starttag(node, "div", CLASS="math"))
    self.body.append("<p>")
    if node["number"]:
        self.body.append('<span class="eqno">(%s)</span>' % node["number"])
    if fname is None:
        # something failed -- use text-only as a bad substitute
        self.body.append('<span class="math">%s</span></p>\n</div>' % self.encode(node["latex"]).strip())
    else:
        self.body.append(('<img src="%s"' % fname) + get_tooltip(self, node) + "/></p>\n</div>")
    raise nodes.SkipNode
Example #54
0
    def system_message(self, level, message, *children, **kwargs):
        """
        Return a system_message object.

        Raise an exception or generate a warning if appropriate.
        """
        attributes = kwargs.copy()
        # print "System Message: ", self.levels[level],
        # print " source", unicode(attributes.get("source")).encode('utf8'),
        # print " line", attributes.get("line")
        # print " spot", attributes.get("spot")
        if 'base_node' in kwargs:
            source, line = get_source_line(kwargs['base_node'])
            del attributes['base_node']
            # print " from base_node", source, line
            if source is not None:
                attributes.setdefault('source', source)
            if line is not None:
                attributes.setdefault('line', line)
        attributes.setdefault('source', self.source)
        msg = nodes.system_message(message, level=level,
                                   type=self.levels[level],
                                   *children, **attributes)
        if self.stream and (level >= self.report_level
                            or self.debug_flag and level == self.DEBUG_LEVEL
                            or level >= self.halt_level):
            msgtext = msg.astext() + '\n'
            try:
                self.stream.write(msgtext)
            except UnicodeEncodeError:
                self.stream.write(msgtext.encode(self.encoding,
                                                 self.error_handler))
        if level >= self.halt_level:
            raise SystemMessage(msg, level)
        if level > self.DEBUG_LEVEL or self.debug_flag:
            self.notify_observers(msg)
        self.max_level = max(level, self.max_level)
        return msg
Example #55
0
    def get_formatter(self, node, name):
        default = self.get_default_formatter()
        if not name and default:
            return default

        valid_formatters = self.get_registered_formatters()
        formatter = valid_formatters.get(name)
        if formatter:
            return formatter
        else:
            message = ("Unknown formatter name: '{0}';"
                       " available formatters: {1}".format(
                           name, ", ".join(valid_formatters.keys())))
            self.node_warning(self.env, message, node)
            new_nodes = [
                nodes.system_message(message=message,
                                     level=2,
                                     type="ERROR",
                                     source=node["source"],
                                     line=node["line"])
            ]
            node.replace_self(new_nodes)
            return None
Example #56
0
 def system_message(self, level, message, *children, **kwargs):
     self.messages.append((level, message, children, kwargs))
     return nodes.system_message(message, level=level,
                                 type=self.levels[level],
                                 *children, **kwargs)