• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python html.HtmlFormatter类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: _highlight_lines

    def _highlight_lines(self, tokensource):
        """
        Highlighted the lines specified in the `hl_lines` option by
        post-processing the token stream coming from `_format_lines`.
        """
        if not isinstance(self.hl_lines, dict):
            HtmlFormatter._highlight_lines(tokensource)
        else:
            hl_lines = {}
            for css, lines in self.hl_lines.items():
                hl_lines.update(dict([(line, css) for line in lines]))

            hls = hl_lines.keys()
            for i, (t, value) in enumerate(tokensource):
                if t != 1:
                    yield t, value
                if i + 1 in hls: # i + 1 because Python indexes start at 0
                    css = hl_lines[i + 1]
                    if css:
                        yield 1, '<span class="%s">%s</span>' % (css, value)
                    elif self.noclasses:
                        style = ''
                        if self.style.highlight_color is not None:
                            style = (' style="background-color: %s"' %
                                     (self.style.highlight_color,))
                        yield 1, '<span%s>%s</span>' % (style, value)
                    else:
                        yield 1, '<span class="hll">%s</span>' % value
                else:
                    yield 1, value
开发者ID:adamhaney,项目名称:djangodevtools,代码行数:30,代码来源:cover.py


示例2: process_request

    def process_request(self, req):
        style = req.args['style']
        try:
            style_cls = get_style_by_name(style)
        except ValueError as e:
            raise HTTPNotFound(e)

        parts = style_cls.__module__.split('.')
        filename = resource_filename('.'.join(parts[:-1]), parts[-1] + '.py')
        mtime = datetime.fromtimestamp(os.path.getmtime(filename), localtz)
        last_modified = http_date(mtime)
        if last_modified == req.get_header('If-Modified-Since'):
            req.send_response(304)
            req.end_headers()
            return

        formatter = HtmlFormatter(style=style_cls)
        content = u'\n\n'.join([
            formatter.get_style_defs('div.code pre'),
            formatter.get_style_defs('table.code td')
        ]).encode('utf-8')

        req.send_response(200)
        req.send_header('Content-Type', 'text/css; charset=utf-8')
        req.send_header('Last-Modified', last_modified)
        req.send_header('Content-Length', len(content))
        req.write(content)
开发者ID:pkdevbox,项目名称:trac,代码行数:27,代码来源:pygments.py


示例3: prev_view_code

 def prev_view_code(self, code, laugange):
     htmlFormatter = HtmlFormatter()
     lexer = CppLexer()
     if laugange == "Cpp":
         lexer = CppLexer()
     elif laugange == "CSharp":
         lexer = CSharpLexer()
     codeDiv = highlight(code, lexer, htmlFormatter)
     codeCss = htmlFormatter.get_style_defs(".highlight")
     #
     html = """
     <html>
         <head>
             <style type="text/css">
             %s
             </style>
         </head>
         <body>
         %s
         </body>
     </html>
     """ % (codeCss, codeDiv)
     self.webView.setHtml(html)
     self.setStyleSheet(codeCss)
     # 输出文件测试验证
     # ff = open('test.html', 'w')
     # ff.write(html)
     # ff.close()
     pass
开发者ID:tylerzhu,项目名称:ExcelConvert,代码行数:29,代码来源:preViewClass.py


示例4: render_code

    def render_code(self):
        formatter = HtmlFormatter(style='default', nowrap=True, classprefix='code%s-' % self.pk)
        html = highlight(self.code, get_lexer_by_name(self.syntax), formatter)
        css = formatter.get_style_defs()

        # Included in a DIV, so the next item will be displayed below.
        return _('<div class="code"><style type="text/css">%(css)s</style>\n<pre>%(html)s</pre></div>\n') % {'css':css, 'html':html}
开发者ID:mrJayson,项目名称:lmsunsw,代码行数:7,代码来源:models.py


示例5: _bbcodeAsHtml

 def _bbcodeAsHtml(self):
     style = get_style_by_name('igor')
     formatter = HtmlFormatter(style=style)
     lexer = get_lexer_by_name("bbcode", stripall=True)
     css = formatter.get_style_defs()
     txt = highlight(self._bbcode, lexer, HtmlFormatter())
     return "<style>%s</style>\n%s" % (css, txt)
开发者ID:ADFD,项目名称:adfd,代码行数:7,代码来源:model.py


示例6: highlight_paste

def highlight_paste(paste, hl_lines):
    '''Use pygments to syntax highlight a paste, returns by the way the CSS'''
    lexer = get_lexer_by_name(paste.hl_alias)
    formatter = HtmlFormatter(linenos=True, cssclass='source', hl_lines=hl_lines)
    return (
        highlight(paste.content, lexer, formatter),
        formatter.get_style_defs('.source')
    )
开发者ID:GabrielC101,项目名称:PPaste,代码行数:8,代码来源:main.py


示例7: style_defs

 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()
开发者ID:Shoobx,项目名称:diff-cover,代码行数:8,代码来源:snippets.py


示例8: __init__

 def __init__(self, **options):
     HtmlFormatter.__init__(self, **options)
     self.hl_lines = {None: self.hl_lines}
     if isinstance(options.get('css_lines'), dict):
         for k, lines in options['css_lines'].items():
             self.hl_lines[k] = set()
             for lineno in lines:
                 try:
                     self.hl_lines[k].add(int(lineno))
                 except ValueError:
                     pass
开发者ID:adamhaney,项目名称:djangodevtools,代码行数:11,代码来源:cover.py


示例9: get

 def get(self, paste_id):
     try:
         aid = b64.num_decode(paste_id)
         paste = Paste.get_by_id(aid)
         content, lang = paste.content, paste.type
         formatter = HtmlFormatter()
         self.response.out.write(template.render("paste.html", {'css': formatter.get_style_defs('.highlight'),
                                                                'paste': highlight(content, get_lexer_by_name(lang), formatter)}))
     except Exception:
         self.response.set_status(404)
         self.response.out.write(template.render("404.html", {}))
开发者ID:itsbth,项目名称:My-First-Pastebin,代码行数:11,代码来源:pastebin.py


示例10: getOutput

    def getOutput(self):
        """
        Returns the output

        :rtype: str
        """
        if not self.formatted:
            lex = JavaLexer()
            formatter = HtmlFormatter(full=True)
            formatter.noclasses = True
            self._output = highlight(self._output, lex, formatter)
            self.formatted = True
        return self._output
开发者ID:DragonFire168,项目名称:MoodleGradeTool,代码行数:13,代码来源:sourceformatting.py


示例11: render_code

def render_code(instance, style_name='default'):
    # Some interesting options in the HtmlFormatter:
    # - nowrap       -> no wrap inside <pre>
    # - classprefix  -> prefix for the classnames
    # - noclasses    -> all inline styles.
    #
    # To get_style_defs(), you can pass a selector prefix.
    #
    style = styles.get_style_by_name(style_name)
    formatter = HtmlFormatter(linenos=instance.linenumbers, style=style, nowrap=True, classprefix='code%s-' % instance.pk)
    html = highlight(instance.code, get_lexer_by_name(instance.language), formatter)
    css = formatter.get_style_defs()

    # Included in a DIV, so the next item will be displayed below.
    return '<div class="code"><style type="text/css">' + css + '</style>\n<pre>' + html + '</pre></div>\n'
开发者ID:django-fluent,项目名称:django-fluent-contents,代码行数:15,代码来源:backend.py


示例12: __init__

    def __init__(self, parent, lexer=None):
        super(PygmentsHighlighter, self).__init__(parent)

        self._document = QtGui.QTextDocument()
        self._formatter = HtmlFormatter(nowrap=True)
        self._lexer = lexer if lexer else PythonLexer()
        self.set_style('default')
开发者ID:dhomeier,项目名称:ipython-py3k,代码行数:7,代码来源:pygments_highlighter.py


示例13: __init__

 def __init__(self, document, lexer=None):
     super(PygmentsSyntaxHighlighter, self).__init__(document)
     self._document = QtGui.QTextDocument()
     self._formatter = HtmlFormatter(nowrap=True)
     self._lexer = lexer if lexer else PythonLexer()
     self.__previousFilename = ""
     self.style = "default"
开发者ID:mukolx,项目名称:pyqode.core,代码行数:7,代码来源:pygments_syntax_highlighter.py


示例14: __init__

    def __init__(self, parent, lexer=None):
        super(QPygmentsHighlighter, self).__init__(parent)

        self._document = QtGui.QTextDocument()
        self._formatter = HtmlFormatter(nowrap=True)
        self._lexer = lexer if lexer else PythonLexer()
        self.style = styles.getStyle("Default").pygmentsStyle
        self.enabled = True
开发者ID:hofoen,项目名称:pcef-core,代码行数:8,代码来源:sh.py


示例15: process_request

    def process_request(self, req):
        # settings panel
        if not 'style' in req.args:
            req._no_pygments_stylesheet = True
            styles = list(get_all_styles())
            styles.sort(lambda a, b: cmp(a.lower(), b.lower()))

            if req.method == 'POST':
                style = req.args.get('new_style')
                if style and style in styles:
                    req.session['pygments_style'] = style

            output = self._highlight('html', self.EXAMPLE, False)
            req.hdf['output'] = Markup(output)
            req.hdf['current'] = req.session.get('pygments_style',
                                                 self.default_style)
            req.hdf['styles'] = styles
            req.hdf['pygments_path'] = self.env.href.pygments()
            return 'pygments_settings.cs', None

        # provide stylesheet
        else:
            style = req.args['style']

            parts = style.__module__.split('.')
            filename = resource_filename('.'.join(parts[:-1]), parts[-1] + '.py')
            mtime = datetime.utcfromtimestamp(os.path.getmtime(filename))
            last_modified = http_date(time.mktime(mtime.timetuple()))
            if last_modified == req.get_header('If-Modified-Since'):
                req.send_response(304)
                req.end_headers()
                return

            formatter = HtmlFormatter(style=style)
            content = u'\n\n'.join([
                formatter.get_style_defs('div.code pre'),
                formatter.get_style_defs('table.code td')
            ]).encode('utf-8')

            req.send_response(200)
            req.send_header('Content-Type', 'text/css; charset=utf-8')
            req.send_header('Last-Modified', last_modified)
            req.send_header('Content-Length', len(content))
            req.write(content)
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:44,代码来源:__init__.py


示例16: export

def export():
    if not os.path.exists(PYGMENTS_PATH):
        os.makedirs(PYGMENTS_PATH)

    styles = list(get_all_styles())

    for style in styles:
        print("Generating CSS for %s" % style)

        opts = {"style": style}

        path = os.path.join(PYGMENTS_PATH, "%s.css" % style)
        formatter = HtmlFormatter(**opts)
        css_content = formatter.get_style_defs()
        # little fix because pelican doesn't append background color.
        css_content = css_content.replace(".hll", ".highlight")

        with open(path, "w") as f:
            f.write(css_content)
开发者ID:aroaminggeek,项目名称:Flex,代码行数:19,代码来源:generate.py


示例17: export

def export():
    if not os.path.exists(PYGMENTS_PATH):
        os.makedirs(PYGMENTS_PATH)

    styles = list(get_all_styles())

    for style in styles:
        print('Generating CSS for %s' % style)

        opts = {
            'style': style,
            'noclasses': False,
            'nobackground': False,
        }

        path = os.path.join(PYGMENTS_PATH, '%s.css' % style)
        formatter = HtmlFormatter(**opts)
        css_content = formatter.get_style_defs('.highlight')

        with open(path, 'w') as f:
            f.write(css_content)
开发者ID:nrjones8,项目名称:blog,代码行数:21,代码来源:generate.py


示例18: __init__

    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()
开发者ID:SylvainCorlay,项目名称:qtconsole,代码行数:13,代码来源:pygments_highlighter.py


示例19: prepare_style

def prepare_style():
    """ read and process style/ directory """
    config = Config()
    # copy static files
    if not os.path.exists(os.path.join(config.outputdir, 'style')):
        os.makedirs(os.path.join(config.outputdir, 'style'))

    # copy supplementary files to ouput dir
    for filename in os.listdir(config.styledir):
        if os.path.splitext(filename)[1].lower() != '.css':
            shutil.copy(
                os.path.join(config.styledir, filename),
                os.path.join(config.outputdir, 'style')
            )

    # generate syntax highlight css and append all other CSS files
    allcss = HtmlFormatter().get_style_defs('.codehilite')
    for cssfile in glob.iglob(os.path.join(config.styledir, '*.css')):
        allcss = allcss + codecs.open(cssfile, 'r', 'utf-8').read()
    allcss = allcss.replace('{{styleurl}}', "{}style/".format(config.blogurl))

    # minimise css
    return cssmin(allcss, wrap=1000)
开发者ID:hnrd,项目名称:blogtopoid,代码行数:23,代码来源:blogtopoid.py


示例20: PygmentsHighlighter

class PygmentsHighlighter(QtGui.QSyntaxHighlighter):
    """ Syntax highlighter that uses Pygments for parsing. """

    #---------------------------------------------------------------------------
    # 'QSyntaxHighlighter' interface
    #---------------------------------------------------------------------------

    def __init__(self, parent, lexer=None):
        super(PygmentsHighlighter, self).__init__(parent)

        self._document = QtGui.QTextDocument()
        self._formatter = HtmlFormatter(nowrap=True)
        self._lexer = lexer if lexer else PythonLexer()
        self.set_style('default')

    def highlightBlock(self, string):
        """ Highlight a block of text.
        """
        prev_data = self.currentBlock().previous().userData()
        if prev_data is not None:
            self._lexer._saved_state_stack = prev_data.syntax_stack
        elif hasattr(self._lexer, '_saved_state_stack'):
            del self._lexer._saved_state_stack

        # Lex the text using Pygments
        index = 0
        for token, text in self._lexer.get_tokens(string):
            length = len(text)
            self.setFormat(index, length, self._get_format(token))
            index += length

        if hasattr(self._lexer, '_saved_state_stack'):
            data = PygmentsBlockUserData(
                syntax_stack=self._lexer._saved_state_stack)
            self.currentBlock().setUserData(data)
            # Clean up for the next go-round.
            del self._lexer._saved_state_stack

    #---------------------------------------------------------------------------
    # 'PygmentsHighlighter' interface
    #---------------------------------------------------------------------------

    def set_style(self, style):
        """ Sets the style to the specified Pygments style.
        """
        if isinstance(style, str):
            style = get_style_by_name(style)
        self._style = style
        self._clear_caches()

    def set_style_sheet(self, stylesheet):
        """ Sets a CSS stylesheet. The classes in the stylesheet should
        correspond to those generated by:

            pygmentize -S <style> -f html

        Note that 'set_style' and 'set_style_sheet' completely override each
        other, i.e. they cannot be used in conjunction.
        """
        self._document.setDefaultStyleSheet(stylesheet)
        self._style = None
        self._clear_caches()

    #---------------------------------------------------------------------------
    # Protected interface
    #---------------------------------------------------------------------------

    def _clear_caches(self):
        """ Clear caches for brushes and formats.
        """
        self._brushes = {}
        self._formats = {}

    def _get_format(self, token):
        """ Returns a QTextCharFormat for token or None.
        """
        if token in self._formats:
            return self._formats[token]

        if self._style is None:
            result = self._get_format_from_document(token, self._document)
        else:
            result = self._get_format_from_style(token, self._style)

        self._formats[token] = result
        return result

    def _get_format_from_document(self, token, document):
        """ Returns a QTextCharFormat for token by 
        """
        code, html = next(self._formatter._format_lines([(token, 'dummy')]))
        self._document.setHtml(html)
        return QtGui.QTextCursor(self._document).charFormat()

    def _get_format_from_style(self, token, style):
        """ Returns a QTextCharFormat for token by reading a Pygments style.
        """
        result = QtGui.QTextCharFormat()
        for key, value in list(style.style_for_token(token).items()):
            if value:
#.........这里部分代码省略.........
开发者ID:dhomeier,项目名称:ipython-py3k,代码行数:101,代码来源:pygments_highlighter.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python lexer.bygroups函数代码示例发布时间:2022-05-25
下一篇:
Python formatters.HtmlFormatter类代码示例发布时间:2022-05-25
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap