Python pygments.formatters.html.HtmlFormatter() Examples

The following are 18 code examples of pygments.formatters.html.HtmlFormatter(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pygments.formatters.html , or try the search function .
Example #1
Source File: snippets.py    From diff_cover with Apache License 2.0 6 votes vote down vote up
def html(self):
        """
        Return an HTML representation of the snippet.
        """
        formatter = HtmlFormatter(
            cssclass=self.DIV_CSS_CLASS,
            linenos=True,
            linenostart=self._start_line,
            hl_lines=self._shift_lines(
                self._violation_lines,
                self._start_line
            ),
            lineanchors=self._src_filename
        )

        return pygments.format(self.src_tokens(), formatter) 
Example #2
Source File: mistune_markdown.py    From Django-blog with MIT License 6 votes vote down vote up
def block_code(self, code, lang=None):
        """Rendering block level code. ``pre > code``.

        :param code: text content of the code block.
        :param lang: language of the given code.
        """
        code = code.rstrip('\n')  # 去掉尾部的换行符
        # 如果没有lang, 就返回代码块
        if not lang:
            code = mistune.escape(code)
            return '<pre><code>%s\n</code></pre>\n' % code

        # 给代码加上高亮  例如: lang='python'的话
        # ```python
        #   print('666')
        # ```
        try:
            lexer = get_lexer_by_name(lang, stripall=True)
        except ClassNotFound:
            # 如果lang是不合法, 没有匹配到, 就设置为python
            lexer = get_lexer_by_name('python', stripall=True)
        formatter = html.HtmlFormatter()  # linenos=True
        return highlight(code, lexer, formatter) 
Example #3
Source File: sourcewindow.py    From MARA_Framework with GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, parent, lexer=None):
        super(MyHighlighter, self).__init__(parent)

        self._document = self.document()
        self._formatter = HtmlFormatter(nowrap=True)
        self._lexer = lexer
        self.set_style('paraiso-dark') 
Example #4
Source File: eoexecutor_visualization.py    From eo-learn with MIT License 5 votes vote down vote up
def make_report(self):
        """ Makes a html report and saves it into the same folder where logs are stored.
        """
        if self.eoexecutor.execution_stats is None:
            raise RuntimeError('Cannot produce a report without running the executor first, check EOExecutor.run '
                               'method')

        if os.environ.get('DISPLAY', '') == '':
            plt.switch_backend('Agg')

        try:
            dependency_graph = self._create_dependency_graph()
        except graphviz.backend.ExecutableNotFound as ex:
            dependency_graph = None
            warnings.warn("{}.\nPlease install the system package 'graphviz' (in addition "
                          "to the python package) to have the dependency graph in the final report!".format(ex),
                          Warning, stacklevel=2)

        formatter = HtmlFormatter(linenos=True)

        template = self._get_template()

        html = template.render(dependency_graph=dependency_graph,
                               general_stats=self.eoexecutor.general_stats,
                               task_descriptions=self._get_task_descriptions(),
                               task_sources=self._render_task_sources(formatter),
                               execution_stats=self._render_execution_errors(formatter),
                               execution_logs=self.eoexecutor.execution_logs,
                               execution_names=self.eoexecutor.execution_names,
                               code_css=formatter.get_style_defs())

        if not os.path.isdir(self.eoexecutor.report_folder):
            os.mkdir(self.eoexecutor.report_folder)

        with open(self.eoexecutor.get_report_filename(), 'w') as fout:
            fout.write(html) 
Example #5
Source File: language.py    From eoj3 with MIT License 5 votes vote down vote up
def transform_code_to_html(code, lang):
  if not lang:
    lang = "text"
  return highlight(code, get_lexer_by_name(dict(LANG_REGULAR_NAME).get(lang, lang)), HtmlFormatter()) 
Example #6
Source File: pygments_highlighter.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, parent, lexer=None):
        super(PygmentsHighlighter, self).__init__(parent)

        self._document = self.document()
        self._formatter = HtmlFormatter(nowrap=True)
        self.set_style('default')
        if lexer is not None:
            self._lexer = lexer
        else:
            if PY3:
                self._lexer = Python3Lexer()
            else:
                self._lexer = PythonLexer() 
Example #7
Source File: models.py    From django-websocket-request-example with MIT License 5 votes vote down vote up
def save(self, *args, **kwargs):
        """
        Use the `pygments` library to create a highlighted HTML
        representation of the code snippet.
        """
        lexer = get_lexer_by_name(self.language)
        linenos = self.linenos and 'table' or False
        options = self.title and {'title': self.title} or {}
        formatter = HtmlFormatter(style=self.style, linenos=linenos,
                                  full=True, **options)
        self.highlighted = highlight(self.code, lexer, formatter)
        super(Snippet, self).save(*args, **kwargs) 
Example #8
Source File: util.py    From blog-a with MIT License 5 votes vote down vote up
def blockcode(self, text, lang):
        if not lang:
            return '\n<pre><code>{}</code></pre>\n'.format(houdini.escape_html(text.strip()))

        lexer = get_lexer_by_name(lang)
        formatter = HtmlFormatter()
        return highlight(text, lexer, formatter) 
Example #9
Source File: pygments_highlighter.py    From qtconsole with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, parent, lexer=None):
        super(PygmentsHighlighter, self).__init__(parent)

        self._document = self.document()
        self._formatter = HtmlFormatter(nowrap=True)
        self.set_style('default')
        if lexer is not None:
            self._lexer = lexer
        else:
            if PY3:
                self._lexer = Python3Lexer()
            else:
                self._lexer = PythonLexer() 
Example #10
Source File: renderer.py    From maildown with MIT License 5 votes vote down vote up
def block_code(code, lang=None):
        if not lang:
            return "\n<pre><code>%s</code></pre>\n" % mistune.escape(code)
        lexer = lexers.get_lexer_by_name(lang, stripall=True)
        formatter = html.HtmlFormatter()
        return pygments.highlight(code, lexer, formatter) 
Example #11
Source File: pygments_sh.py    From Turing with MIT License 5 votes vote down vote up
def __init__(self, document, lexer=None, color_scheme=None):
        super(PygmentsSH, self).__init__(document, color_scheme=color_scheme)
        self._pygments_style = self.color_scheme.name
        self._style = None
        self._formatter = HtmlFormatter(nowrap=True)
        self._lexer = lexer if lexer else PythonLexer()

        self._brushes = {}
        self._formats = {}
        self._init_style()
        self._prev_block = None 
Example #12
Source File: sourcewindow.py    From dcc with Apache License 2.0 5 votes vote down vote up
def __init__(self, parent, lexer=None):
        super(MyHighlighter, self).__init__(parent)

        self._document = self.document()
        self._formatter = HtmlFormatter(nowrap=True)
        self._lexer = lexer
        self.set_style('paraiso-dark') 
Example #13
Source File: html.py    From mailur with GNU General Public License v3.0 5 votes vote down vote up
def block_code(self, code, lang):
        if not lang:
            return '\n<pre><code>%s</code></pre>\n' % \
                mistune.escape(code)
        lexer = get_lexer_by_name(lang, stripall=True)
        formatter = html.HtmlFormatter(noclasses=True)
        return highlight(code, lexer, formatter) 
Example #14
Source File: console.py    From node-launcher with MIT License 5 votes vote down vote up
def handle_cli_output(self, cli_process: QProcess):
        output: QByteArray = cli_process.readAllStandardOutput()
        message = output.data().decode('utf-8').strip()

        if message.startswith('{') or message.startswith('['):
            formatter = HtmlFormatter()
            formatter.noclasses = True
            formatter.linenos = False
            formatter.nobackground = True
            message = highlight(message, JsonLexer(), formatter)
            self.output_area.insertHtml(message)
        else:
            self.output_area.append(message) 
Example #15
Source File: pygments_highlighter.py    From pySINDy with MIT License 5 votes vote down vote up
def __init__(self, parent, lexer=None):
        super(PygmentsHighlighter, self).__init__(parent)

        self._document = self.document()
        self._formatter = HtmlFormatter(nowrap=True)
        self.set_style('default')
        if lexer is not None:
            self._lexer = lexer
        else:
            if PY3:
                self._lexer = Python3Lexer()
            else:
                self._lexer = PythonLexer() 
Example #16
Source File: snippets.py    From diff_cover with Apache License 2.0 5 votes vote down vote up
def style_defs(cls):
        """
        Return the CSS style definitions required
        by the formatted snippet.
        """
        formatter = HtmlFormatter()
        formatter.style.highlight_color = cls.VIOLATION_COLOR
        return formatter.get_style_defs() 
Example #17
Source File: pygments_highlighter.py    From Computable with MIT License 5 votes vote down vote up
def __init__(self, parent, lexer=None):
        super(PygmentsHighlighter, self).__init__(parent)

        self._document = self.document()
        self._formatter = HtmlFormatter(nowrap=True)
        self._lexer = lexer if lexer else PythonLexer()
        self.set_style('default') 
Example #18
Source File: codehilite.py    From marko with MIT License 5 votes vote down vote up
def render_fenced_code(self, element):
        code = element.children[0].children
        options = CodeHiliteRendererMixin.options.copy()
        options.update(_parse_extras(getattr(element, "extra", None)))
        if element.lang:
            try:
                lexer = get_lexer_by_name(element.lang, stripall=True)
            except ClassNotFound:
                lexer = guess_lexer(code)
        else:
            lexer = guess_lexer(code)
        formatter = html.HtmlFormatter(**options)
        return highlight(code, lexer, formatter)