当前位置: 首页>>代码示例>>Python>>正文


Python pygments.highlight方法代码示例

本文整理汇总了Python中pygments.highlight方法的典型用法代码示例。如果您正苦于以下问题:Python pygments.highlight方法的具体用法?Python pygments.highlight怎么用?Python pygments.highlight使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pygments的用法示例。


在下文中一共展示了pygments.highlight方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: androaxml_main

# 需要导入模块: import pygments [as 别名]
# 或者: from pygments import highlight [as 别名]
def androaxml_main(inp, outp=None, resource=None):
    ret_type = androconf.is_android(inp)
    if ret_type == "APK":
        a = apk.APK(inp)
        if resource:
            if resource not in a.files:
                print("The APK does not contain a file called '{}'".format(resource), file=sys.stderr)
                sys.exit(1)

            axml = AXMLPrinter(a.get_file(resource)).get_xml_obj()
        else:
            axml = a.get_android_manifest_xml()
    elif ".xml" in inp:
        axml = AXMLPrinter(read(inp)).get_xml_obj()
    else:
        print("Unknown file type")
        sys.exit(1)

    buff = etree.tostring(axml, pretty_print=True, encoding="utf-8")
    if outp:
        with open(outp, "wb") as fd:
            fd.write(buff)
    else:
        sys.stdout.write(highlight(buff.decode("UTF-8"), get_lexer_by_name("xml"), TerminalFormatter())) 
开发者ID:amimo,项目名称:dcc,代码行数:26,代码来源:main.py

示例2: get_source_method

# 需要导入模块: import pygments [as 别名]
# 或者: from pygments import highlight [as 别名]
def get_source_method(self, m):
        """
        Return the Java source of a single method

        :param m: `EncodedMethod` Object
        :return:
        """
        class_name = m.get_class_name()
        method_name = m.get_name()

        if class_name not in self.classes:
            return ""

        lexer = get_lexer_by_name("java", stripall=True)
        lexer.add_filter(MethodFilter(method_name=method_name))
        formatter = TerminalFormatter()
        result = highlight(self.classes[class_name], lexer, formatter)
        return result 
开发者ID:amimo,项目名称:dcc,代码行数:20,代码来源:decompiler.py

示例3: _show_source_pygments

# 需要导入模块: import pygments [as 别名]
# 或者: from pygments import highlight [as 别名]
def _show_source_pygments(self) -> None:

        def show_source_cb(source: str) -> None:
            """Show source as soon as it's ready."""
            # WORKAROUND for https://github.com/PyCQA/pylint/issues/491
            # pylint: disable=no-member
            lexer = pygments.lexers.HtmlLexer()
            formatter = pygments.formatters.HtmlFormatter(
                full=True, linenos='table')
            # pylint: enable=no-member
            highlighted = pygments.highlight(source, lexer, formatter)

            tb = objreg.get('tabbed-browser', scope='window',
                            window=self._tab.win_id)
            new_tab = tb.tabopen(background=False, related=True)
            new_tab.set_html(highlighted, self._tab.url())
            new_tab.data.viewing_source = True

        self._tab.dump_async(show_source_cb) 
开发者ID:qutebrowser,项目名称:qutebrowser,代码行数:21,代码来源:browsertab.py

示例4: block_code

# 需要导入模块: import pygments [as 别名]
# 或者: from pygments import highlight [as 别名]
def block_code(uuid, text, lang, inlinestyles=False, linenos=False):
    """Renders a code block"""
    if is_plant_uml(text, lang):
        fName = Settings().plantUMLCache.getResource(text, uuid)
        if fName is None:
            return '<br/><img src="cdm-image:na50.png"><br/>\n'
        return '<br/><img src="plantuml:' + fName + '"><br/>\n'

    lexer = get_lexer(text, lang)
    if lexer:
        try:
            formatter = HtmlFormatter(noclasses=inlinestyles, linenos=linenos)
            code = highlight(text, lexer, formatter)
            return ''.join([PRE_WRAP_START, '<pre>',
                            code.replace('125%', '100%'), '</pre>',
                            PRE_WRAP_END, '\n'])
        except:
            pass

    return ''.join([PRE_WRAP_START, '<pre>', mistune.escape(text),
                    '</pre>', PRE_WRAP_END, '\n']) 
开发者ID:SergeySatskiy,项目名称:codimension,代码行数:23,代码来源:md.py

示例5: field_to_html

# 需要导入模块: import pygments [as 别名]
# 或者: from pygments import highlight [as 别名]
def field_to_html(field):
    """Need to extract the math in brackets so that it doesn't get markdowned.
    If math is separated with dollar sign it is converted to brackets."""
    if CONFIG['dollar']:
        for (sep, (op, cl)) in [("$$", (r"\\[", r"\\]")), ("$", (r"\\(", r"\\)"))]:
            escaped_sep = sep.replace(r"$", r"\$")
            # ignore escaped dollar signs when splitting the field    
            field = re.split(r"(?<!\\){}".format(escaped_sep), field) 
            # add op(en) and cl(osing) brackets to every second element of the list
            field[1::2] = [op + e + cl for e in field[1::2]] 
            field = "".join(field)
    else:
        for bracket in ["(", ")", "[", "]"]:
            field = field.replace(r"\{}".format(bracket), r"\\{}".format(bracket))
            # backslashes, man.
    
    if CONFIG['highlight']:
        return highlight_markdown(field)


    return misaka.html(field, extensions=("fenced-code", "math")) 
开发者ID:benwr,项目名称:ankdown,代码行数:23,代码来源:ankdown.py

示例6: main

# 需要导入模块: import pygments [as 别名]
# 或者: from pygments import highlight [as 别名]
def main():
    """Run the thing."""
    apply_arguments(docopt(__doc__, version=VERSION))
    # print(yaml.dump(CONFIG))
    initial_dir = os.getcwd()
    recur_dir = os.path.abspath(os.path.expanduser(CONFIG['recur_dir']))
    pkg_arg = os.path.abspath(os.path.expanduser(CONFIG['pkg_arg']))

    if CONFIG['highlight']:
        apply_highlight_css()

    with tempfile.TemporaryDirectory() as tmpdirname:
        os.chdir(tmpdirname) # genanki is very opinionated about where we are.

        card_iterator = cards_from_dir(recur_dir)
        cards_to_apkg(card_iterator, pkg_arg)

        os.chdir(initial_dir) 
开发者ID:benwr,项目名称:ankdown,代码行数:20,代码来源:ankdown.py

示例7: _get_source_highlight_function

# 需要导入模块: import pygments [as 别名]
# 或者: from pygments import highlight [as 别名]
def _get_source_highlight_function(self):
        try:
            import pygments
            import pygments.lexers
        except ImportError:
            return False

        try:
            pygments_formatter = self._get_pygments_formatter()
        except Exception as exc:
            self.message("pdb++: could not setup Pygments, disabling: {}".format(
                exc
            ))
            return False

        lexer = pygments.lexers.PythonLexer(stripnl=False)

        def syntax_highlight(src):
            return pygments.highlight(src, lexer, pygments_formatter)

        return syntax_highlight 
开发者ID:pdbpp,项目名称:pdbpp,代码行数:23,代码来源:pdbpp.py

示例8: _patch_linecache_for_source_highlight

# 需要导入模块: import pygments [as 别名]
# 或者: from pygments import highlight [as 别名]
def _patch_linecache_for_source_highlight(self):
        orig = pdb.linecache.getlines

        def wrapped_getlines(filename, globals):
            """Wrap linecache.getlines to highlight source (for do_list)."""
            old_cache = pdb.linecache.cache.pop(filename, None)
            try:
                lines = orig(filename, globals)
            finally:
                if old_cache:
                    pdb.linecache.cache[filename] = old_cache
            source = self.format_source("".join(lines))

            if sys.version_info < (3,):
                source = self.try_to_encode(source)

            return source.splitlines(True)

        pdb.linecache.getlines = wrapped_getlines

        try:
            yield
        finally:
            pdb.linecache.getlines = orig 
开发者ID:pdbpp,项目名称:pdbpp,代码行数:26,代码来源:pdbpp.py

示例9: do_list

# 需要导入模块: import pygments [as 别名]
# 或者: from pygments import highlight [as 别名]
def do_list(self, arg):
        """Enhance original do_list with highlighting."""
        if not (self.config.use_pygments is not False or self.config.highlight):
            return super(Pdb, self).do_list(arg)

        with self._patch_linecache_for_source_highlight():

            oldstdout = self.stdout
            self.stdout = StringIO()
            ret = super(Pdb, self).do_list(arg)
            orig_pdb_lines = self.stdout.getvalue().splitlines()
            self.stdout = oldstdout

        for line in self._format_color_prefixes(orig_pdb_lines):
            print(line, file=self.stdout)
        return ret 
开发者ID:pdbpp,项目名称:pdbpp,代码行数:18,代码来源:pdbpp.py

示例10: _color_with_pygments

# 需要导入模块: import pygments [as 别名]
# 或者: from pygments import highlight [as 别名]
def _color_with_pygments(self, codeblock, lexer, **formatter_opts):
        import pygments
        import pygments.formatters

        class HtmlCodeFormatter(pygments.formatters.HtmlFormatter):
            def _wrap_code(self, inner):
                """A function for use in a Pygments Formatter which
                wraps in <code> tags.
                """
                yield 0, "<code>"
                for tup in inner:
                    yield tup
                yield 0, "</code>"

            def wrap(self, source, outfile):
                """Return the source with a code, pre, and div."""
                return self._wrap_div(self._wrap_pre(self._wrap_code(source)))

        formatter_opts.setdefault("cssclass", "codehilite")
        formatter = HtmlCodeFormatter(**formatter_opts)
        return pygments.highlight(codeblock, lexer, formatter) 
开发者ID:b1ueb1ues,项目名称:dl,代码行数:23,代码来源:markdown2.py

示例11: show_asm

# 需要导入模块: import pygments [as 别名]
# 或者: from pygments import highlight [as 别名]
def show_asm(self, item, primary):
    cur = self.db_cursor()
    if primary:
      db = "main"
    else:
      db = "diff"
    ea = str(int(item[1], 16))
    sql = "select prototype, assembly, name from %s.functions where address = ?"
    sql = sql % db
    cur.execute(sql, (ea, ))
    row = cur.fetchone()
    if row is None:
      Warning("Sorry, there is no assembly available for the selected function.")
    else:
      fmt = HtmlFormatter()
      fmt.noclasses = True
      fmt.linenos = True
      asm = self.prettify_asm(row["assembly"])
      final_asm = "; %s\n%s proc near\n%s\n%s endp\n"
      final_asm = final_asm % (row["prototype"], row["name"], asm, row["name"])
      src = highlight(final_asm, NasmLexer(), fmt)
      title = "Assembly for %s" % row["name"]
      cdiffer = CHtmlViewer()
      cdiffer.Show(src, title)
    cur.close() 
开发者ID:joxeankoret,项目名称:maltindex,代码行数:27,代码来源:diaphora_ida.py

示例12: show_pseudo

# 需要导入模块: import pygments [as 别名]
# 或者: from pygments import highlight [as 别名]
def show_pseudo(self, item, primary):
    cur = self.db_cursor()
    if primary:
      db = "main"
    else:
      db = "diff"
    ea = str(int(item[1], 16))
    sql = "select prototype, pseudocode, name from %s.functions where address = ?"
    sql = sql % db
    cur.execute(sql, (str(ea), ))
    row = cur.fetchone()
    if row is None or row["prototype"] is None or row["pseudocode"] is None:
      Warning("Sorry, there is no pseudo-code available for the selected function.")
    else:
      fmt = HtmlFormatter()
      fmt.noclasses = True
      fmt.linenos = True
      func = "%s\n%s" % (row["prototype"], row["pseudocode"])
      src = highlight(func, CppLexer(), fmt)
      title = "Pseudo-code for %s" % row["name"]
      cdiffer = CHtmlViewer()
      cdiffer.Show(src, title)
    cur.close() 
开发者ID:joxeankoret,项目名称:maltindex,代码行数:25,代码来源:diaphora_ida.py

示例13: _pygment_highlight

# 需要导入模块: import pygments [as 别名]
# 或者: from pygments import highlight [as 别名]
def _pygment_highlight(source, output_formatter, language='ipython'):
    """
    Return a syntax-highlighted version of the input source
    
    Parameters
    ----------
    source : str
        Source code to highlight the syntax of.
    output_formatter : Pygments formatter
    language : str
        Language to highlight the syntax of.
    """
    
    if language == 'ipython':
        lexer = IPythonLexer()
    else:
        lexer = get_lexer_by_name(language, stripall=True)

    return pygements_highlight(source, lexer, output_formatter) 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:21,代码来源:highlight.py

示例14: _color_with_pygments

# 需要导入模块: import pygments [as 别名]
# 或者: from pygments import highlight [as 别名]
def _color_with_pygments(self, codeblock, lexer, **formatter_opts):
        import pygments
        import pygments.formatters

        class HtmlCodeFormatter(pygments.formatters.HtmlFormatter):

            def _wrap_code(self, inner):
                """A function for use in a Pygments Formatter which
                wraps in <code> tags.
                """
                yield 0, "<code>"
                for tup in inner:
                    yield tup
                yield 0, "</code>"

            def wrap(self, source, outfile):
                """Return the source with a code, pre, and div."""
                return self._wrap_div(self._wrap_pre(self._wrap_code(source)))

        formatter_opts.setdefault("cssclass", "codehilite")
        formatter = HtmlCodeFormatter(**formatter_opts)
        return pygments.highlight(codeblock, lexer, formatter) 
开发者ID:tzshlyt,项目名称:python-webapp-blog,代码行数:24,代码来源:markdown2.py

示例15: code

# 需要导入模块: import pygments [as 别名]
# 或者: from pygments import highlight [as 别名]
def code(self, session=None):
        all_errors = ""

        try:
            dag_id = request.args.get('dag_id')
            dag_orm = DagModel.get_dagmodel(dag_id, session=session)
            code = DagCode.get_code_by_fileloc(dag_orm.fileloc)
            html_code = Markup(highlight(
                code, lexers.PythonLexer(), HtmlFormatter(linenos=True)))

        except Exception as e:
            all_errors += (
                "Exception encountered during " +
                "dag_id retrieval/dag retrieval fallback/code highlighting:\n\n{}\n".format(e)
            )
            html_code = Markup('<p>Failed to load file.</p><p>Details: {}</p>').format(
                escape(all_errors))

        return self.render_template(
            'airflow/dag_code.html', html_code=html_code, dag=dag_orm, title=dag_id,
            root=request.args.get('root'),
            demo_mode=conf.getboolean('webserver', 'demo_mode'),
            wrapped=conf.getboolean('webserver', 'default_wrap')) 
开发者ID:apache,项目名称:airflow,代码行数:25,代码来源:views.py


注:本文中的pygments.highlight方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。