當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。