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


Python HtmlFormatter.get_style_defs方法代码示例

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


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

示例1: test_get_style_defs

# 需要导入模块: from pygments.formatters import HtmlFormatter [as 别名]
# 或者: from pygments.formatters.HtmlFormatter import get_style_defs [as 别名]
    def test_get_style_defs(self):
        fmt = HtmlFormatter()
        sd = fmt.get_style_defs()
        self.assert_(sd.startswith('.'))

        fmt = HtmlFormatter(cssclass='foo')
        sd = fmt.get_style_defs()
        self.assert_(sd.startswith('.foo'))
        sd = fmt.get_style_defs('.bar')
        self.assert_(sd.startswith('.bar'))
        sd = fmt.get_style_defs(['.bar', '.baz'])
        fl = sd.splitlines()[0]
        self.assert_('.bar' in fl and '.baz' in fl)
开发者ID:erickt,项目名称:pygments,代码行数:15,代码来源:test_html_formatter.py

示例2: post

# 需要导入模块: from pygments.formatters import HtmlFormatter [as 别名]
# 或者: from pygments.formatters.HtmlFormatter import get_style_defs [as 别名]
    def post(self):
        #get language 
        lang = self.request.get('lang')
        #get code
        code = self.request.get('code')

        #format code
        lexer = get_lexer_by_name(lang, stripall=True)
        formatter = HtmlFormatter()
        formatter.get_style_defs('.syntax')
        
        response = {"html": highlight(code, lexer, formatter)}
        
        #render json response
        self.response.out.write(json.dumps(response))
开发者ID:davidhampgonsalves,项目名称:pygmenter,代码行数:17,代码来源:pygmentize.py

示例3: process_exception

# 需要导入模块: from pygments.formatters import HtmlFormatter [as 别名]
# 或者: from pygments.formatters.HtmlFormatter import get_style_defs [as 别名]
    def process_exception(self, request, e):
        if isinstance(e, Http404):
            return self.process_404(request)

        import traceback
        tb = '\n'.join(traceback.format_exception(*sys.exc_info()))

        if HAS_PYGMENTS:
            formatter = HtmlFormatter(style='borland')
            html_tb = highlight(tb, PythonTracebackLexer(), formatter)
        else:
            html_tb = '<pre><code>%s</pre></code>' % (tb)

        context = {
            'title': str(e),
            'traceback': html_tb,
            'request': repr(request).replace('>', '&gt;').replace('<', '&lt;'),
            'version': VERSION,
            'python_version': '{}.{}.{}-{}-{}'.format(*sys.version_info),
            'css': ERROR_CSS,
        }

        if HAS_PYGMENTS:
            context['css'] += formatter.get_style_defs('.highlight')

        return Response(ERROR_TEMPLATE.format(**context), status=500)
开发者ID:rivrproject,项目名称:rivr,代码行数:28,代码来源:debug.py

示例4: _regen_header

# 需要导入模块: from pygments.formatters import HtmlFormatter [as 别名]
# 或者: from pygments.formatters.HtmlFormatter import get_style_defs [as 别名]
    def _regen_header(self):
        """ 
        Fills self.header with lines of CSS extracted from IPython 
        and Pygments.
        """
        from pygments.formatters import HtmlFormatter
        
        #Clear existing header.
        header = []
        
        #Construct path to IPy CSS
        sheet_filename = os.path.join(path.get_ipython_package_dir(), 
            'html', 'static', 'style', 'style.min.css')
        
        #Load style CSS file.
        with io.open(sheet_filename, encoding='utf-8') as file:
            file_text = file.read()
            header.append(file_text)

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

        #Set header        
        self.header = header
开发者ID:NitikaAgarwal,项目名称:ipython,代码行数:28,代码来源:csshtmlheader.py

示例5: syntax

# 需要导入模块: from pygments.formatters import HtmlFormatter [as 别名]
# 或者: from pygments.formatters.HtmlFormatter import get_style_defs [as 别名]
def syntax(dic, text):
	"""
	highlight code using pygments
	
	USAGE:
	[rk:syntax lang="LANG_NAME"]CODE[/rk:syntax]
	"""
	pygments_formatter = HtmlFormatter()
	langs = {}
	for i in dic:
		try:
			lexer = get_lexer_by_name(i['attributes']['lang'])
		except ValueError:
			lexer = get_lexer_by_name('text')
		if i['attributes']['lang'] == 'php' and i['code'].find('<?php') < 1:
			i['code'] = '<?php\n\r%s' % i['code']
		parsed = highlight(i['code'], lexer, pygments_formatter)
		text = text.replace(i['tag'],  '<div class="box" style="overflow:hidden;font-size:11px;">%s</div>' % parsed)
		langs['<style>%s</style>' % pygments_formatter.get_style_defs()] = True
	
	styles = ''
	for style in langs.keys():
		styles = styles + style
	text = text + styles
	return text
开发者ID:athityakumar,项目名称:kgp-django-website,代码行数:27,代码来源:tags.py

示例6: pcat

# 需要导入模块: from pygments.formatters import HtmlFormatter [as 别名]
# 或者: from pygments.formatters.HtmlFormatter import get_style_defs [as 别名]
def pcat(filename, target='ipython'):

    code = read_file_or_url(filename)

    HTML_TEMPLATE = """<style>
    {}
    </style>
    {}
    """

    from pygments.lexers import get_lexer_for_filename
    lexer = get_lexer_for_filename(filename, stripall=True)

    from pygments.formatters import HtmlFormatter, TerminalFormatter
    from pygments import highlight

    try:
        assert(target=='ipython')
        from IPython.display import HTML, display
        from pygments.formatters import HtmlFormatter
        formatter = HtmlFormatter(linenos=True, cssclass="source")
        html_code = highlight(code, lexer, formatter)
        css = formatter.get_style_defs()
        html = HTML_TEMPLATE.format(css, html_code)
        htmlres = HTML(html)

        return htmlres

    except Exception as e:
        print(e)
        pass

    formatter = TerminalFormatter()
    output = highlight(code,lexer,formatter)
    print(output)
开发者ID:EconForge,项目名称:dolo,代码行数:37,代码来源:display.py

示例7: view_message

# 需要导入模块: from pygments.formatters import HtmlFormatter [as 别名]
# 或者: from pygments.formatters.HtmlFormatter import get_style_defs [as 别名]
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,代码行数:36,代码来源:views.py

示例8: _generate_header

# 需要导入模块: from pygments.formatters import HtmlFormatter [as 别名]
# 或者: from pygments.formatters.HtmlFormatter import get_style_defs [as 别名]
    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,代码行数:37,代码来源:csshtmlheader.py

示例9: PygmentsHighlighter

# 需要导入模块: from pygments.formatters import HtmlFormatter [as 别名]
# 或者: from pygments.formatters.HtmlFormatter import get_style_defs [as 别名]
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,代码行数:37,代码来源:PygmentsHighlighter.py

示例10: html_output

# 需要导入模块: from pygments.formatters import HtmlFormatter [as 别名]
# 或者: from pygments.formatters.HtmlFormatter import get_style_defs [as 别名]
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,代码行数:33,代码来源:prettyprint.py

示例11: html_output

# 需要导入模块: from pygments.formatters import HtmlFormatter [as 别名]
# 或者: from pygments.formatters.HtmlFormatter import get_style_defs [as 别名]
 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,代码行数:27,代码来源:codedupdetect.py

示例12: pretty_print

# 需要导入模块: from pygments.formatters import HtmlFormatter [as 别名]
# 或者: from pygments.formatters.HtmlFormatter import get_style_defs [as 别名]
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,代码行数:29,代码来源:pretty.py

示例13: _regen_header

# 需要导入模块: from pygments.formatters import HtmlFormatter [as 别名]
# 或者: from pygments.formatters.HtmlFormatter import get_style_defs [as 别名]
    def _regen_header(self):
        """ 
        Fills self.header with lines of CSS extracted from IPython 
        and Pygments.
        """
        
        #Clear existing header.
        header = []
        
        #Construct path to IPy CSS
        from IPython.html import DEFAULT_STATIC_FILES_PATH
        sheet_filename = os.path.join(DEFAULT_STATIC_FILES_PATH,
            'style', 'style.min.css')
        
        #Load style CSS file.
        with io.open(sheet_filename, encoding='utf-8') as file:
            file_text = file.read()
            header.append(file_text)

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

        #Set header        
        self.header = header
开发者ID:ArslanRafique,项目名称:dist-packages,代码行数:28,代码来源:csshtmlheader.py

示例14: _regen_header

# 需要导入模块: from pygments.formatters import HtmlFormatter [as 别名]
# 或者: from pygments.formatters.HtmlFormatter import get_style_defs [as 别名]
    def _regen_header(self):
        """ 
        Fills self.header with lines of CSS extracted from IPython 
        and Pygments.
        """

        # Clear existing header.
        header = []

        # Construct path to IPy CSS
        sheet_filename = os.path.join(path.get_ipython_package_dir(), "html", "static", "style", "style.min.css")

        # Load style CSS file.
        try:
            with io.open(sheet_filename, encoding="utf-8") as file:
                file_text = file.read()
                header.append(file_text)
        except IOError:

            # New version of IPython with style.min.css, pass
            pass

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

        # Set header
        self.header = header
开发者ID:praveer13,项目名称:ipython,代码行数:31,代码来源:csshtmlheader.py

示例15: get_pygments_css

# 需要导入模块: from pygments.formatters import HtmlFormatter [as 别名]
# 或者: from pygments.formatters.HtmlFormatter import get_style_defs [as 别名]
def get_pygments_css(request):
    formatter = HtmlFormatter(linenos=True, outencoding='utf-8')
    return HttpResponse(
        content=formatter.get_style_defs(arg=''),
        mimetype='text/css',
        content_type='text/css; charset=' + settings.DEFAULT_CHARSET,
        )
开发者ID:NORDUnet,项目名称:peer,代码行数:9,代码来源:revisions.py


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