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


Python formatters.HtmlFormatter类代码示例

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


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

示例1: pretty_print

def pretty_print(paste, style_choice, linenos = "inline", full = False):	
    """Use Pygments library to highlight a TextField       

    returns str1, str2
        where str1 is the formatted text, and str2 is the css style block
        
    Syntax:
        code_str, style_str = pretty_print(code_str)
        
    Ex:
        Views:
        pretty_text_output, style_output = pretty_print(source_code)
        
        Template:
        <style> {{style_output|safe}} </style>
        {{pretty_text_output|safe}}
    """
    if paste.language: lexer = get_lexer_by_name(paste.language, stripall=True)        
    if not paste.language: lexer = guess_lexer(paste.code_paste, stripall=True)		
    
    if not style_choice.highlight: style_choice.highlight = DEFAULT_STYLE
        
    formatter = HtmlFormatter(linenos = linenos, full = full, cssclass = "source", style = style_choice.highlight)
    result = highlight(paste.code_paste, lexer, formatter)		
    css_style = formatter.get_style_defs()		
    
    return result, css_style
开发者ID:calebsmith,项目名称:PyPastebin,代码行数:27,代码来源:pretty.py

示例2: index

def index(request, *args, **kwargs):
    # the *args, **kwargs is because this view is used in urls.py
    # as a catch-all for the sake of pushstate
    context = {}
    html_formatter = HtmlFormatter(linenos=True)
    context['pygments_css'] = html_formatter.get_style_defs('.highlight')
    return render(request, 'analyzer/index.html', context)
开发者ID:peterbe,项目名称:webalyzer,代码行数:7,代码来源:views.py

示例3: main

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('source', default='-', nargs='?', type=str)
    parser.add_argument('--style', default='colorful', type=str)
    parser.add_argument('--format', default='html', type=str)
    parser.add_argument('--css', action="store_true", help='Router service config')
    parser.add_argument('--preprocess', action="store_true", help='Preprocess a markdown file from stdin')

    args = parser.parse_args()

    if args.css:
        htmlformat = HtmlFormatter(style=args.style)
        sys.stdout.write(htmlformat.get_style_defs('.highlight'))
        sys.exit(0)

    if args.preprocess:
        source = sys.stdin.read()
        processed = preprocess_source(source, args.style, args.format)
        sys.stdout.write(processed)
        return

    if args.source == '-' or not args.source:
        source = sys.stdin.read()
    else:
        source = open(args.source).read()

    stdout = exec_block(source, style=args.style, formatter=args.format)
    sys.stdout.write(stdout)
开发者ID:sdiehl,项目名称:tipy,代码行数:28,代码来源:pyshell.py

示例4: style_info

def style_info(request, response, function_info):
    """
    Listet alle Stylesheet-Namen auf und zwigt die jeweiligen Styles an.
    """
    style_list = list(get_all_styles())

    selected_style = None
    if function_info!=None:
        selected_style = function_info[0]
        if not selected_style in style_list:
            self.page_msg.red("Name Error!")
            selected_style = None

    context = {
        "styles": style_list,
        "selected_style": selected_style,
        "menu_link": request.URLs.actionLink("menu"),
    }
    request.templates.write("pygments_css", context, debug=False)

    if selected_style == None:
        # Es wurde kein Style ausgewählt
        return

    # CSS zum Style anzeigen
    stylesheet = HtmlFormatter(style=selected_style)
    stylesheet = stylesheet.get_style_defs('.pygments_code')

    request.render.highlight(
        ".css", stylesheet, pygments_style=selected_style
    )
开发者ID:Aaron1011,项目名称:python-code-snippets,代码行数:31,代码来源:pygments_info.py

示例5: setError

    def setError(self, err_type=None, err_value=None, err_traceback=None):
        """Translates the given error object into an HTML string and places it
        in the message panel

        :param error: an error object (typically an exception object)
        :type error: object"""

        msgbox = self._msgbox
        error = "".join(traceback.format_exception_only(err_type, err_value))
        msgbox.setText(error)
        msg = "<html><body><pre>%s</pre></body></html>" % error
        msgbox.setDetailedHtml(msg)

        html_orig = '<html><head><style type="text/css">{style}</style>' "</head><body>"
        exc_info = "".join(traceback.format_exception(err_type, err_value, err_traceback))
        style = ""
        if pygments is not None:
            formatter = HtmlFormatter()
            style = formatter.get_style_defs()
        html = html_orig.format(style=style)
        if pygments is None:
            html += "<pre>%s</pre>" % exc_info
        else:
            formatter = HtmlFormatter()
            html += highlight(exc_info, PythonTracebackLexer(), formatter)
        html += "</body></html>"
        msgbox.setOriginHtml(html)
开发者ID:cpascual,项目名称:taurus,代码行数:27,代码来源:taurusmessagepanel.py

示例6: test_filename

 def test_filename(self):
     optdict = dict(filename="test.py")
     outfile = StringIO()
     fmt = HtmlFormatter(**optdict)
     fmt.format(tokensource, outfile)
     html = outfile.getvalue()
     self.assertTrue(re.search("<span class=\"filename\">test.py</span><pre>", html))
开发者ID:sol,项目名称:pygments,代码行数:7,代码来源:test_html_formatter.py

示例7: test_valid_output

    def test_valid_output(self):
        # test all available wrappers
        fmt = HtmlFormatter(full=True, linenos=True, noclasses=True,
                            outencoding='utf-8')

        handle, pathname = tempfile.mkstemp('.html')
        tfile = os.fdopen(handle, 'w+b')
        fmt.format(tokensource, tfile)
        tfile.close()
        catname = os.path.join(TESTDIR, 'dtds', 'HTML4.soc')
        try:
            try:
                import subprocess
                ret = subprocess.Popen(['nsgmls', '-s', '-c', catname, pathname],
                                       stdout=subprocess.PIPE).wait()
            except ImportError:
                # Python 2.3 - no subprocess module
                ret = os.popen('nsgmls -s -c "%s" "%s"' % (catname, pathname)).close()
                if ret == 32512: raise OSError  # not found
        except OSError:
            # nsgmls not available
            pass
        else:
            self.failIf(ret, 'nsgmls run reported errors')

        os.unlink(pathname)
开发者ID:erickt,项目名称:pygments,代码行数:26,代码来源:test_html_formatter.py

示例8: _generate_header

    def _generate_header(self, resources):
        """ 
        Fills self.header with lines of CSS extracted from IPython 
        and Pygments.
        """
        from pygments.formatters import HtmlFormatter
        header = []
        
        # Construct path to Jupyter CSS
        sheet_filename = os.path.join(
            os.path.dirname(nbconvert.resources.__file__),
            'style.min.css',
        )
        
        # Load style CSS file.
        with io.open(sheet_filename, encoding='utf-8') as f:
            header.append(f.read())

        # Add pygments CSS
        formatter = HtmlFormatter(style=self.style)
        pygments_css = formatter.get_style_defs(self.highlight_class)
        header.append(pygments_css)

        # Load the user's custom CSS and IPython's default custom CSS.  If they
        # differ, assume the user has made modifications to his/her custom CSS
        # and that we should inline it in the nbconvert output.
        config_dir = resources['config_dir']
        custom_css_filename = os.path.join(config_dir, 'custom', 'custom.css')
        if os.path.isfile(custom_css_filename):
            if DEFAULT_STATIC_FILES_PATH and self._default_css_hash is None:
                self._default_css_hash = self._hash(os.path.join(DEFAULT_STATIC_FILES_PATH, 'custom', 'custom.css'))
            if self._hash(custom_css_filename) != self._default_css_hash:
                with io.open(custom_css_filename, encoding='utf-8') as f:
                    header.append(f.read())
        return header
开发者ID:jupyter,项目名称:nbconvert,代码行数:35,代码来源:csshtmlheader.py

示例9: view_message

def view_message(request, app_slug, message_id):
    message = get_object_or_404(
        remotelog.LogMessage, 
        pk=message_id,
        application__slug=app_slug,
    )
    
    exc_text = message.exc_text
    pygments_css = None
    if exc_text:
        try:
            from pygments import highlight
            from pygments.lexers import PythonTracebackLexer
            from pygments.formatters import HtmlFormatter
            formatter = HtmlFormatter()
            exc_text = highlight(exc_text, PythonTracebackLexer(), formatter)
            pygments_css = formatter.get_style_defs('.highlight')
        except ImportError:
            pass
    
    opts = remotelog.LogMessage._meta
    context = {
        'message': message,
        'exc_text': exc_text,
        'pygments_css': pygments_css,
        
        # admin stuff
        'has_change_permission': True,
        'add': True,
        'change': True,
        'opts': opts,
        'app_label': opts.app_label,
    }
    return render_to_response('remotelog/view_message.html', context)
开发者ID:gtt116,项目名称:novalog,代码行数:34,代码来源:views.py

示例10: PygmentsHighlighter

class PygmentsHighlighter(object):
    """ highlight python code with a QSyntaxHighlighter,
        callable class (e.g. function with a state) to """

    def __init__(self):
        """ constructor """
        self._lexer = PythonLexer()
        self._formatter = HtmlFormatter()
        self._document = QtGui.QTextDocument()
        self._document.setDefaultStyleSheet(self._formatter.get_style_defs())
        self._format_cache = dict()

    def __call__(self, code):
        """ makes this class callable, actually do the highlightning """
        index = 0
        for token, text in self._lexer.get_tokens(code):
            length = len(text)
            char_format = self._get_format(token)
            pygmentsHighlighter._setFormat(index, length, char_format)
            index += length

    def _get_format(self, token):
        """ get the QTextCharFormat for a token """
        if token in self._format_cache:
            return self._format_cache[token]

        # get format from document
        code, html = next(self._formatter._format_lines([(token, u"dummy")]))
        self._document.setHtml(html)
        char_format = QtGui.QTextCursor(self._document).charFormat()

        # cache result
        self._format_cache[token] = char_format

        return char_format
开发者ID:knossos-project,项目名称:PythonQt,代码行数:35,代码来源:PygmentsHighlighter.py

示例11: blog_mod_render_items

 def blog_mod_render_items(self, blog, items):
     if self.markdown_highlight_style:
         from pygments.style import Style
         from pygments.styles import get_style_by_name
         from pygments.formatters import HtmlFormatter
         
         # User-defined custom style takes precedence
         try:
             with tmp_sys_path(self.config.get('command_dir', "")):
                 mod = import_module(self.markdown_highlight_style)
         except ImportError:
             mdstyle = None
         else:
             mdstyle = first_subclass(mod, Style)
         
         # Try for built-in style if no custom style
         if not mdstyle:
             mdstyle = get_style_by_name(self.markdown_highlight_style)
         
         # Generate CSS with selector for markdown codehilite extension
         css = HtmlFormatter(style=mdstyle).get_style_defs(arg=".codehilite")
         if not css.endswith(os.linesep):
             css = "{}{}".format(css, os.linesep)
         csspath = blog.metadata['highlight_stylesheet_url']
         if csspath.startswith('/'):
             csspath = csspath[1:]
         items.append((encode(css, blog.metadata['charset']), csspath))
     
     return items
开发者ID:pdonis,项目名称:simpleblog3,代码行数:29,代码来源:render_markdown.py

示例12: html_output

def html_output(filenames, outfile, width, style):
    if not outfile:
        outfile = "output.html"
    lines_wrapped = 0
    formatter = HtmlFormatter(linenos=False, cssclass="source", style=style)
    output = open(outfile, "w")
    output.write('<html><head><style type="text/css">')
    output.write(css_styles)
    output.write(formatter.get_style_defs())
    output.write("\n</style></head><body>")
    W = width
    for filename in filenames:
        output.write("<h1>" + filename + "</h1>\n")

        lexer = get_lexer_for_filename(filename)
        F = open(filename, "r")
        code = ""
        for line in F:
            while len(line) > W:
                lines_wrapped += 1
                code += line[:W] + "\n"
                line = line[W:]
            code += line[:W]

        result = highlight(code, lexer, formatter, output)
        F.close()

    output.write("</body></html>")
    if lines_wrapped > 0:
        print "(wrapped " + str(lines_wrapped) + " lines)"
    output.close()
开发者ID:pauek,项目名称:prettyprint,代码行数:31,代码来源:prettyprint.py

示例13: html_output

 def html_output(self,outfile_fn):
     def code(match):
         with open(match.srcfile(), 'rb') as src:
             for i in range(match.getStartLine()):
                 src.readline()
             return [src.readline() for i in range(match.getLineCount())]
     try:
         import chardet
         lexer = CppLexer(encoding='chardet')
     except:
         lexer = CppLexer(encoding='utf-8')
     formatter = HtmlFormatter(encoding='utf-8')
     with open(outfile_fn, 'wb') as out:
         out.write('<html><head><style type="text/css">%s</style></head><body>'%formatter.get_style_defs('.highlight'))
         id = 0
         copies = sorted(self.findcopies(),reverse=True,key=lambda x:x.matchedlines)
         out.write('<ul>%s</ul>'%'\n'.join(['<a href="#match_%i">Match %i</a>'%(i,i) for i in range(len(copies))]))
         for matches in copies:
             out.write('<h1 id="match_%i">MATCH %i</h1><ul>'%(id,id))
             out.write(' '.join(['<li>%s:%i-%i</li>'%(m.srcfile(), m.getStartLine(), m.getStartLine() + m.getLineCount()) for m in matches]))
             out.write('</ul><div class="highlight">')
             highlight(''.join(code([s for s in matches][0])), lexer, formatter, outfile=out)
             out.write('<a href="#">Up</a></div>')
             id += 1
         out.write('</body></html>')
开发者ID:renemilk,项目名称:tctoolkit,代码行数:25,代码来源:codedupdetect.py

示例14: test_lineanchors

 def test_lineanchors(self):
     optdict = dict(lineanchors="foo")
     outfile = StringIO()
     fmt = HtmlFormatter(**optdict)
     fmt.format(tokensource, outfile)
     html = outfile.getvalue()
     self.assertTrue(re.search("<pre><a name=\"foo-1\">", html))
开发者ID:hacksterio,项目名称:pygments.rb,代码行数:7,代码来源:test_html_formatter.py

示例15: test_lineanchors_with_startnum

 def test_lineanchors_with_startnum(self):
     optdict = dict(lineanchors="foo", linenostart=5)
     outfile = StringIO()
     fmt = HtmlFormatter(**optdict)
     fmt.format(tokensource, outfile)
     html = outfile.getvalue()
     self.assertTrue(re.search("<pre><span></span><a name=\"foo-5\">", html))
开发者ID:sol,项目名称:pygments,代码行数:7,代码来源:test_html_formatter.py


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