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


Python formatters.HtmlFormatter方法代码示例

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


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

示例1: block_code

# 需要导入模块: from pygments import formatters [as 别名]
# 或者: from pygments.formatters import HtmlFormatter [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

示例2: show_asm

# 需要导入模块: from pygments import formatters [as 别名]
# 或者: from pygments.formatters import HtmlFormatter [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

示例3: show_pseudo

# 需要导入模块: from pygments import formatters [as 别名]
# 或者: from pygments.formatters import HtmlFormatter [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

示例4: code

# 需要导入模块: from pygments import formatters [as 别名]
# 或者: from pygments.formatters import HtmlFormatter [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

示例5: _render_asm

# 需要导入模块: from pygments import formatters [as 别名]
# 或者: from pygments.formatters import HtmlFormatter [as 别名]
def _render_asm(self, instr, mnemonic_width, options, fill_char=""):
        formatter = HtmlFormatter()
        formatter.noclasses = True
        formatter.nowrap = True

        oprnds_str = ", ".join([oprnd.to_string(**options) for oprnd in instr.operands])

        asm_str = instr.prefix + " " if instr.prefix else ""
        asm_str += instr.mnemonic + fill_char * (mnemonic_width - len(instr.mnemonic))
        asm_str += " " + oprnds_str if oprnds_str else ""

        # TODO Highlight for ARM too.
        asm_str = highlight(asm_str, NasmLexer(), formatter)
        asm_str = asm_str.replace("span", "font")
        asm_str = asm_str.replace('style="color: ', 'color="')
        asm_str = asm_str.replace('style="border: 1px solid ', 'color="')

        return self.asm_tpl.format(address=instr.address, size=instr.size, assembly=asm_str) 
开发者ID:programa-stic,项目名称:barf-project,代码行数:20,代码来源:controlflowgraph.py

示例6: block_code

# 需要导入模块: from pygments import formatters [as 别名]
# 或者: from pygments.formatters import HtmlFormatter [as 别名]
def block_code(text, lang, inlinestyles=False, linenos=False):
    if not lang:
        text = text.strip()
        return u'<pre><code>%s</code></pre>\n' % mistune.escape(text)

    try:
        lexer = get_lexer_by_name(lang, stripall=True)
        formatter = HtmlFormatter(
            noclasses=inlinestyles, linenos=linenos
        )
        code = highlight(text, lexer, formatter)
        if linenos:
            return '<div class="highlight-wrapper">%s</div>\n' % code
        return code
    except:
        return '<pre class="%s"><code>%s</code></pre>\n' % (
            lang, mistune.escape(text)
        ) 
开发者ID:lepture,项目名称:mistune-contrib,代码行数:20,代码来源:highlight.py

示例7: view_source

# 需要导入模块: from pygments import formatters [as 别名]
# 或者: from pygments.formatters import HtmlFormatter [as 别名]
def view_source(context, web_view, filename):
    from base64 import b64encode
    from os.path import join
    from pygments import highlight
    from pygments.formatters import HtmlFormatter
    from pygments.lexers import get_lexer_for_filename

    from java.io import BufferedReader, InputStreamReader

    stream = context.getAssets().open(join(ASSET_SOURCE_DIR, filename))
    reader = BufferedReader(InputStreamReader(stream))
    text = "\n".join(iter(reader.readLine, None))

    formatter = HtmlFormatter()
    body = highlight(text, get_lexer_for_filename(filename), formatter)
    html = ("<html><head><style>{}\n{}</style></head><body>{}</body></html>"
            .format(formatter.get_style_defs(), EXTRA_CSS, body)).encode()
    web_view.loadData(b64encode(html).decode(), "text/html", "base64") 
开发者ID:chaquo,项目名称:chaquopy,代码行数:20,代码来源:ui_demo.py

示例8: get_experiment

# 需要导入模块: from pygments import formatters [as 别名]
# 或者: from pygments.formatters import HtmlFormatter [as 别名]
def get_experiment(path):
    logdir = APP.config['logdir']
    complete_path = os.path.join(logdir, path)
    if os.path.isfile(complete_path):
        file_content = get_file(complete_path)
        if path.endswith(".log"):
            result = ansiconv.to_html(html.escape(file_content))
        elif path.endswith(".ini"):
            lexer = IniLexer()
            formatter = HtmlFormatter(linenos=True)
            result = highlight(file_content, lexer, formatter)
        else:
            result = "Unknown file type: '{}'.".format(complete_path)
    else:
        result = "File '{}' does not exist.".format(complete_path)
    return Response(result, mimetype='text/html', status=200) 
开发者ID:ufal,项目名称:neuralmonkey,代码行数:18,代码来源:logbook.py

示例9: format_data

# 需要导入模块: from pygments import formatters [as 别名]
# 或者: from pygments.formatters import HtmlFormatter [as 别名]
def format_data(data):
    formatter = HtmlFormatter(cssclass="codehilite")

    if data is None:
        return data

    if isinstance(data, bool) or isinstance(data, int) or isinstance(data, float):
        return highlight(str(data), TextLexer(), formatter)
    elif isinstance(data, str):
        try:
            data = json.dumps(json.loads(data), indent=4, sort_keys=True)
            lexer = JsonLexer()
        except (ValueError, TypeError):
            lexer = TextLexer()
    elif isinstance(data, dict) or isinstance(data, list):
        data = json.dumps(data, indent=4, sort_keys=True)
        lexer = JsonLexer()
    else:
        lexer = TextLexer()

    lexer.stripall = True
    return highlight(data, lexer, formatter) 
开发者ID:ansible-community,项目名称:ara,代码行数:24,代码来源:pygments_highlights.py

示例10: table_definition

# 需要导入模块: from pygments import formatters [as 别名]
# 或者: from pygments.formatters import HtmlFormatter [as 别名]
def table_definition(table_name):
    """
    Get the source of a table function.

    If a table is registered DataFrame and not a function then all that is
    returned is {'type': 'dataframe'}.

    If the table is a registered function then the JSON returned has keys
    "type", "filename", "lineno", "text", and "html". "text" is the raw
    text of the function, "html" has been marked up by Pygments.

    """
    if orca.table_type(table_name) == 'dataframe':
        return jsonify(type='dataframe')

    filename, lineno, source = \
        orca.get_raw_table(table_name).func_source_data()

    html = highlight(source, PythonLexer(), HtmlFormatter())

    return jsonify(
        type='function', filename=filename, lineno=lineno, text=source,
        html=html) 
开发者ID:UDST,项目名称:orca,代码行数:25,代码来源:server.py

示例11: column_definition

# 需要导入模块: from pygments import formatters [as 别名]
# 或者: from pygments.formatters import HtmlFormatter [as 别名]
def column_definition(table_name, col_name):
    """
    Get the source of a column function.

    If a column is a registered Series and not a function then all that is
    returned is {'type': 'series'}.

    If the column is a registered function then the JSON returned has keys
    "type", "filename", "lineno", "text", and "html". "text" is the raw
    text of the function, "html" has been marked up by Pygments.

    """
    col_type = orca.get_table(table_name).column_type(col_name)

    if col_type != 'function':
        return jsonify(type=col_type)

    filename, lineno, source = \
        orca.get_raw_column(table_name, col_name).func_source_data()

    html = highlight(source, PythonLexer(), HtmlFormatter())

    return jsonify(
        type='function', filename=filename, lineno=lineno, text=source,
        html=html) 
开发者ID:UDST,项目名称:orca,代码行数:27,代码来源:server.py

示例12: injectable_definition

# 需要导入模块: from pygments import formatters [as 别名]
# 或者: from pygments.formatters import HtmlFormatter [as 别名]
def injectable_definition(inj_name):
    """
    Get the source of an injectable function.

    If an injectable is a registered Python variable and not a function
    then all that is returned is {'type': 'variable'}.

    If the column is a registered function then the JSON returned has keys
    "type", "filename", "lineno", "text", and "html". "text" is the raw
    text of the function, "html" has been marked up by Pygments.

    """
    inj_type = orca.injectable_type(inj_name)

    if inj_type == 'variable':
        return jsonify(type='variable')
    else:
        filename, lineno, source = \
            orca.get_injectable_func_source_data(inj_name)
        html = highlight(source, PythonLexer(), HtmlFormatter())
        return jsonify(
            type='function', filename=filename, lineno=lineno, text=source,
            html=html) 
开发者ID:UDST,项目名称:orca,代码行数:25,代码来源:server.py

示例13: stacktraces

# 需要导入模块: from pygments import formatters [as 别名]
# 或者: from pygments.formatters import HtmlFormatter [as 别名]
def stacktraces():
    code = []
    for threadId, stack in sys._current_frames().items():
        code.append("\n# ThreadID: %s" % threadId)
        for filename, lineno, name, line in traceback.extract_stack(stack):
            code.append('File: "%s", line %d, in %s' % (filename, lineno, name))
            if line:
                code.append("  %s" % (line.strip()))
 
    return highlight("\n".join(code), PythonLexer(), HtmlFormatter(
      full=False,
      # style="native",
      noclasses=True,
    ))


# This part was made by nagylzs 
开发者ID:vanangamudi,项目名称:newspaper-crawler-scripts,代码行数:19,代码来源:stacktracer.py

示例14: test_formatter_encodings

# 需要导入模块: from pygments import formatters [as 别名]
# 或者: from pygments.formatters import HtmlFormatter [as 别名]
def test_formatter_encodings():
    from pygments.formatters import HtmlFormatter

    # unicode output
    fmt = HtmlFormatter()
    tokens = [(Text, u"ä")]
    out = format(tokens, fmt)
    assert type(out) is str
    assert u"ä" in out

    # encoding option
    fmt = HtmlFormatter(encoding="latin1")
    tokens = [(Text, u"ä")]
    assert u"ä".encode("latin1") in format(tokens, fmt)

    # encoding and outencoding option
    fmt = HtmlFormatter(encoding="latin1", outencoding="utf8")
    tokens = [(Text, u"ä")]
    assert u"ä".encode("utf8") in format(tokens, fmt) 
开发者ID:pygments,项目名称:pygments,代码行数:21,代码来源:test_basic_api.py

示例15: test_external_css

# 需要导入模块: from pygments import formatters [as 别名]
# 或者: from pygments.formatters import HtmlFormatter [as 别名]
def test_external_css():
    # test correct behavior
    # CSS should be in /tmp directory
    fmt1 = HtmlFormatter(full=True, cssfile='fmt1.css', outencoding='utf-8')
    # CSS should be in TESTDIR (TESTDIR is absolute)
    fmt2 = HtmlFormatter(full=True, cssfile=path.join(TESTDIR, 'fmt2.css'),
                         outencoding='utf-8')
    tfile = tempfile.NamedTemporaryFile(suffix='.html')
    fmt1.format(tokensource, tfile)
    try:
        fmt2.format(tokensource, tfile)
        assert path.isfile(path.join(TESTDIR, 'fmt2.css'))
    except IOError:
        # test directory not writable
        pass
    tfile.close()

    assert path.isfile(path.join(path.dirname(tfile.name), 'fmt1.css'))
    os.unlink(path.join(path.dirname(tfile.name), 'fmt1.css'))
    try:
        os.unlink(path.join(TESTDIR, 'fmt2.css'))
    except OSError:
        pass 
开发者ID:pygments,项目名称:pygments,代码行数:25,代码来源:test_html_formatter.py


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