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

Python styles.get_style_by_name函数代码示例

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

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



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

示例1: _make_style_from_name

    def _make_style_from_name(self, name):
        """
        Small wrapper that make an IPython compatible style from a style name

        We need that to add style for prompt ... etc. 
        """
        style_cls = get_style_by_name(name)
        style_overrides = {
            Token.Prompt: "#009900",
            Token.PromptNum: "#00ff00 bold",
            Token.OutPrompt: "#990000",
            Token.OutPromptNum: "#ff0000 bold",
        }
        if name == "default":
            style_cls = get_style_by_name("default")
            # The default theme needs to be visible on both a dark background
            # and a light background, because we can't tell what the terminal
            # looks like. These tweaks to the default theme help with that.
            style_overrides.update(
                {
                    Token.Number: "#007700",
                    Token.Operator: "noinherit",
                    Token.String: "#BB6622",
                    Token.Name.Function: "#2080D0",
                    Token.Name.Class: "bold #2080D0",
                    Token.Name.Namespace: "bold #2080D0",
                }
            )
        style_overrides.update(self.highlighting_style_overrides)
        style = PygmentsStyle.from_defaults(pygments_style_cls=style_cls, style_dict=style_overrides)

        return style
开发者ID:Rahul-Sindhu,项目名称:ipython,代码行数:32,代码来源:ptshell.py


示例2: render_GET

    def render_GET(self, request):
        try:
            style = get_style_by_name(self.style_name)
        except ClassNotFound:
            style = get_style_by_name('default')
            self.style_name = 'default'

        prev_url = None
        if self.days_back:
            prev_url = self.url_for(request, self.days_back - 1)
        next_url = self.url_for(request, (self.days_back or 0) + 1)
        formatter = LogFormatter(style=style)

        if self.days_back:
            log_date = date.today() - timedelta(self.days_back)
            suffix = log_date.strftime('.%Y_%m_%d').replace('_0', '_')
            self.logfilename += suffix
        try:
            with codecs.open(self.logfilename, 'r', 'utf-8') as logfile:
                html = self.render_log(logfile.read(), formatter,
                                       prev_url, next_url)
        except IOError:
            request.setResponseCode(404)
            return '<html><body>Go away.</body></html>'
        request.setHeader('Content-Type', 'text/html;charset=utf-8')
        return html.encode('utf-8')
开发者ID:Trundle,项目名称:kitbot,代码行数:26,代码来源:bot.py


示例3: _make_style_from_name

    def _make_style_from_name(self, name):
        """
        Small wrapper that make an IPython compatible style from a style name

        We need that to add style for prompt ... etc. 
        """
        style_cls = get_style_by_name(name)
        style_overrides = {
            Token.Prompt: style_cls.styles.get( Token.Keyword, '#009900'),
            Token.PromptNum: style_cls.styles.get( Token.Literal.Number, '#00ff00 bold')
        }
        if name is 'default':
            style_cls = get_style_by_name('default')
            # The default theme needs to be visible on both a dark background
            # and a light background, because we can't tell what the terminal
            # looks like. These tweaks to the default theme help with that.
            style_overrides.update({
                Token.Number: '#007700',
                Token.Operator: 'noinherit',
                Token.String: '#BB6622',
                Token.Name.Function: '#2080D0',
                Token.Name.Class: 'bold #2080D0',
                Token.Name.Namespace: 'bold #2080D0',
            })
        style_overrides.update(self.highlighting_style_overrides)
        style = PygmentsStyle.from_defaults(pygments_style_cls=style_cls,
                                            style_dict=style_overrides)

        return style
开发者ID:Katkamaculikova123,项目名称:ipython,代码行数:29,代码来源:ptshell.py


示例4: render

 def render(self, context):
     if not is_qouted(self.style):
         self.style = template.Variable(self.style).resolve(context)
     else: self.style = self.style[1:-1]
     if self.linenos:
         formatter = HtmlFormatter(style = get_style_by_name(self.style), linenos = self.linenos)
     else: formatter = HtmlFormatter(style = get_style_by_name(self.style))
     return mark_safe(formatter.get_style_defs('.highlight'))
开发者ID:BastinRobin,项目名称:a.out,代码行数:8,代码来源:syntax.py


示例5: set_style

    def set_style(self, extensions, settings):
        """
        Search the extensions for the style to be used and return it.

        If it is not explicitly set, go ahead and insert the default
        style (github).
        """

        style = 'default'

        if not PYGMENTS_AVAILABLE:  # pragma: no cover
            settings["settings"]["use_pygments_css"] = False

        global_use_pygments_css = settings["settings"]["use_pygments_css"]
        use_pygments_css = False
        # Search for highlight extensions to see what whether pygments css is required.
        for hilite_ext in ('markdown.extensions.codehilite', 'pymdownx.inlinehilite'):
            if hilite_ext not in extensions:
                continue
            config = extensions[hilite_ext]
            if config is None:
                config = {}

            use_pygments_css = use_pygments_css or (
                not config.get('noclasses', False) and
                config.get('use_pygments', True) and
                config.get('use_codehilite_settings', True) and
                PYGMENTS_AVAILABLE and
                global_use_pygments_css
            )

        if global_use_pygments_css and not use_pygments_css:
            settings["settings"]["use_pygments_css"] = False
        else:
            settings["settings"]["use_pygments_css"] = use_pygments_css

        if use_pygments_css:
            # Ensure a working style is set
            style = settings["settings"]['pygments_style']
            try:
                # Check if the desired style exists internally
                get_style_by_name(style)
            except Exception:
                logger.Log.error("Cannot find style: %s! Falling back to 'default' style." % style)
                style = "default"

        settings["settings"]["pygments_style"] = style

        settings["page"]["pygments_style"] = self.load_highlight(
            style,
            settings["settings"]["use_pygments_css"],
            settings["settings"]['pygments_class']
        )
开发者ID:filltr,项目名称:PyMdown,代码行数:53,代码来源:__init__.py


示例6: _make_style_from_name_or_cls

    def _make_style_from_name_or_cls(self, name_or_cls):
        """
        Small wrapper that make an IPython compatible style from a style name

        We need that to add style for prompt ... etc.
        """
        style_overrides = {}
        if name_or_cls == 'legacy':
            legacy = self.colors.lower()
            if legacy == 'linux':
                style_cls = get_style_by_name('monokai')
                style_overrides = _style_overrides_linux
            elif legacy == 'lightbg':
                style_overrides = _style_overrides_light_bg
                style_cls = get_style_by_name('pastie')
            elif legacy == 'neutral':
                # The default theme needs to be visible on both a dark background
                # and a light background, because we can't tell what the terminal
                # looks like. These tweaks to the default theme help with that.
                style_cls = get_style_by_name('default')
                style_overrides.update({
                    Token.Number: '#007700',
                    Token.Operator: 'noinherit',
                    Token.String: '#BB6622',
                    Token.Name.Function: '#2080D0',
                    Token.Name.Class: 'bold #2080D0',
                    Token.Name.Namespace: 'bold #2080D0',
                    Token.Prompt: '#009900',
                    Token.PromptNum: '#00ff00 bold',
                    Token.OutPrompt: '#990000',
                    Token.OutPromptNum: '#ff0000 bold',
                })
            elif legacy =='nocolor':
                style_cls=_NoStyle
                style_overrides = {}
            else :
                raise ValueError('Got unknown colors: ', legacy)
        else :
            if isinstance(name_or_cls, string_types):
                style_cls = get_style_by_name(name_or_cls)
            else:
                style_cls = name_or_cls
            style_overrides = {
                Token.Prompt: '#009900',
                Token.PromptNum: '#00ff00 bold',
                Token.OutPrompt: '#990000',
                Token.OutPromptNum: '#ff0000 bold',
            }
        style_overrides.update(self.highlighting_style_overrides)
        style = PygmentsStyle.from_defaults(pygments_style_cls=style_cls,
                                            style_dict=style_overrides)

        return style
开发者ID:briandrawert,项目名称:ipython,代码行数:53,代码来源:interactiveshell.py


示例7: init_syntax_highlighting

    def init_syntax_highlighting(self, pygments_style):
        self.past_lines = []

        if pygments_style:
            if isstr(pygments_style):
                self.pygments_style = get_style_by_name(pygments_style)
            else:
                self.pygments_style = pygments_style
        else:
            self.pygments_style = get_style_by_name('default')

        self.lexer = PythonLexer()
        self.formatter = Terminal256Formatter(style=self.pygments_style)
开发者ID:zain,项目名称:pyr,代码行数:13,代码来源:console.py


示例8: _make_style_from_name

    def _make_style_from_name(self, name):
        """
        Small wrapper that make an IPython compatible style from a style name

        We need that to add style for prompt ... etc. 
        """
        style_overrides = {}
        if name == "legacy":
            legacy = self.colors.lower()
            if legacy == "linux":
                style_cls = get_style_by_name("monokai")
                style_overrides = _style_overrides_linux
            elif legacy == "lightbg":
                style_overrides = _style_overrides_light_bg
                style_cls = get_style_by_name("pastie")
            elif legacy == "neutral":
                # The default theme needs to be visible on both a dark background
                # and a light background, because we can't tell what the terminal
                # looks like. These tweaks to the default theme help with that.
                style_cls = get_style_by_name("default")
                style_overrides.update(
                    {
                        Token.Number: "#007700",
                        Token.Operator: "noinherit",
                        Token.String: "#BB6622",
                        Token.Name.Function: "#2080D0",
                        Token.Name.Class: "bold #2080D0",
                        Token.Name.Namespace: "bold #2080D0",
                        Token.Prompt: "#009900",
                        Token.PromptNum: "#00ff00 bold",
                        Token.OutPrompt: "#990000",
                        Token.OutPromptNum: "#ff0000 bold",
                    }
                )
            elif legacy == "nocolor":
                style_cls = _NoStyle
                style_overrides = {}
            else:
                raise ValueError("Got unknown colors: ", legacy)
        else:
            style_cls = get_style_by_name(name)
            style_overrides = {
                Token.Prompt: "#009900",
                Token.PromptNum: "#00ff00 bold",
                Token.OutPrompt: "#990000",
                Token.OutPromptNum: "#ff0000 bold",
            }
        style_overrides.update(self.highlighting_style_overrides)
        style = PygmentsStyle.from_defaults(pygments_style_cls=style_cls, style_dict=style_overrides)

        return style
开发者ID:michaelpacer,项目名称:ipython,代码行数:51,代码来源:interactiveshell.py


示例9: style_factory

def style_factory(name, cli_style):
    try:
        style = get_style_by_name(name)
    except ClassNotFound:
        style = get_style_by_name('native')

    class VStyle(Style):
        styles = {}

        styles.update(style.styles)
        styles.update(default_style_extensions)
        custom_styles = dict([(string_to_tokentype(x), y)
                                for x, y in cli_style.items()])
        styles.update(custom_styles)
    return PygmentsStyle(VStyle)
开发者ID:adnanyaqoobvirk,项目名称:vcli,代码行数:15,代码来源:vstyle.py


示例10: _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


示例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: create_tags

    def create_tags(self):
        tags={}

        bold_font = font.Font(self.text, self.text.cget("font"))
        bold_font.configure(weight=font.BOLD)

        italic_font = font.Font(self.text, self.text.cget("font"))
        italic_font.configure(slant=font.ITALIC)

        bold_italic_font = font.Font(self.text, self.text.cget("font"))
        bold_italic_font.configure(weight=font.BOLD, slant=font.ITALIC)

        style = get_style_by_name("default")
        for ttype, ndef in style:
            # print(ttype, ndef)
            tag_font = None
            if ndef["bold"] and ndef["italic"]:
                tag_font = bold_italic_font
            elif ndef["bold"]:
                tag_font = bold_font
            elif ndef["italic"]:
                tag_font = italic_font

            if ndef["color"]:
                foreground = "#%s" % ndef["color"]
            else:
                foreground = None

            tags[ttype]=str(ttype)
            self.text.tag_configure(tags[ttype], foreground=foreground, font=tag_font)
            # self.text.tag_configure(str(ttype), foreground=foreground, font=tag_font)

        return tags
开发者ID:ctodobom,项目名称:DragonPy,代码行数:33,代码来源:highlighting.py


示例13: 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


示例14: __init__

    def __init__(self, style='default'):

        """ The parameter *style* select the Pygments style.

        Pygments style attributes are:

        * bgcolor,
        * bold,
        * border,
        * color,
        * italic,
        * mono,
        * roman,
        * sans,
        * underline.

        """

        pygments_style = get_style_by_name(style)
        for token, style_attributes in pygments_style.list_styles():
            text_format = QtGui.QTextCharFormat()
            if style_attributes['bgcolor']:
                text_format.setBackground(to_brush(style_attributes['bgcolor']))
            if style_attributes['color']:
                text_format.setForeground(to_brush(style_attributes['color']))
            if style_attributes['bold']:
                text_format.setFontWeight(QtGui.QFont.Bold)
            if style_attributes['italic']:
                text_format.setFontItalic(True)
            self[token] = text_format
开发者ID:manasdas17,项目名称:git-gui,代码行数:30,代码来源:SyntaxHighlighterStyle.py


示例15: get_all_code_styles

def get_all_code_styles():
    """
    Return a mapping from style names to their classes.
    """
    result = dict((name, style_from_pygments_cls(get_style_by_name(name))) for name in get_all_styles())
    result['win32'] = Style.from_dict(win32_code_style)
    return result
开发者ID:jonathanslenders,项目名称:ptpython,代码行数:7,代码来源:style.py


示例16: _create_styles

    def _create_styles(self):
        from pygments.styles import get_style_by_name
        global _tokens_name

        self._style = get_style_by_name(session.config.get('hlstyle'))

        tkStyles = dict(self._style)
        for token in sorted(tkStyles):
            while True:
                if token == Token:
                    break
                parent = token.parent
                if not tkStyles[token]['color']:
                    tkStyles[token]['color'] = tkStyles[parent]['color']
                if not tkStyles[token]['bgcolor']:
                    tkStyles[token]['bgcolor'] = tkStyles[parent]['bgcolor']
                if tkStyles[token]['color'] and tkStyles[token]['bgcolor']:
                    break
                token = parent

        self._styles = {}
        for token,tStyle in tkStyles.items():
            token = _tokens_name.setdefault(token,"DP::SH::%s"%str(token))
            self._styles[token] = {}

            self._styles[token]['foreground'] = "#%s"%tStyle['color'] if tStyle['color'] else ""
            self._styles[token]['background'] = "#%s"%tStyle['bgcolor'] if tStyle['bgcolor'] else ""

            self._styles[token]['underline'] = tStyle['underline']
            self._styles[token]['font'] = self._fonts[(tStyle['bold'],tStyle['italic'])]

        self._styles.setdefault("DP::SH::Token.Error", {})['background'] = "red"
        self._styles.setdefault("DP::SH::Token.Generic.Error", {})['background'] = "red"
开发者ID:mgautierfr,项目名称:devparrot,代码行数:33,代码来源:textHighlight.py


示例17: format

    def format(self, tokensource, outfile):
        x = y = 0
        colors = {}

        for (ttype, d) in get_style_by_name('default'):
            if d["color"]:
                color = "#" + d["color"]
            elif d["italic"]:
                color = "#991212"
            elif d["bold"]:
                color = "#129912"
            else:
                color = "#cccccc"

            colors[ttype] = ImageColor.getrgb(color)

        for (ttype, value) in tokensource:
            for char in value:
                if not char.isspace() or (ttype in Token.Comment):
                    self.canvas.image.putpixel((x, y), colors[ttype])

                if char == '\t':
                    x += TAB_SIZE
                elif char == '\n':
                    x = 0
                    y += 1
                else:
                    x += 1
开发者ID:hortont424,项目名称:scripts,代码行数:28,代码来源:minihighlighter.py


示例18: set_style

 def set_style(self, style):
     """ Sets the style to the specified Pygments style.
     """
     if isinstance(style, str):
         style = styles.get_style_by_name(style)
     self._style = style
     self._clear_caches()
开发者ID:riccardomarotti,项目名称:misura.client,代码行数:7,代码来源:highlighter.py


示例19: cli

def cli(url, http_options):
    click.echo('Version: %s' % __version__)

    # Override less options
    os.environ['LESS'] = '-RXF'

    url = fix_incomplete_url(url)
    context = Context(url)
    load_context(context)

    # For prompt-toolkit
    history = InMemoryHistory()
    lexer = PygmentsLexer(HttpPromptLexer)
    completer = HttpPromptCompleter(context)
    style = style_from_pygments(get_style_by_name('monokai'))

    # Execute default http options.
    execute(' '.join(http_options), context)
    save_context(context)

    while True:
        try:
            text = prompt('%s> ' % context.url, completer=completer,
                          lexer=lexer, style=style, history=history)
        except EOFError:
            break  # Control-D pressed
        else:
            execute(text, context)
            save_context(context)
            if context.should_exit:
                break

    click.echo("Goodbye!")
开发者ID:dxq-git,项目名称:http-prompt,代码行数:33,代码来源:cli.py


示例20: cli

def cli(url):
    click.echo('Version: %s' % __version__)

    # Override less options
    os.environ['LESS'] = '-RXF'

    url = fix_incomplete_url(url)
    context = Context(url)

    # For prompt-toolkit
    history = InMemoryHistory()
    lexer = PygmentsLexer(HttpPromptLexer)
    completer = HttpPromptCompleter(context)
    style = style_from_pygments(get_style_by_name('monokai'))

    while True:
        try:
            text = prompt('%s> ' % context.url, completer=completer,
                          lexer=lexer, style=style, history=history)
        except EOFError:
            break  # Control-D pressed
        else:
            if text.strip() == 'exit':
                break
            else:
                execute(text, context)

    click.echo("Goodbye!")
开发者ID:Palayoub,项目名称:http-prompt,代码行数:28,代码来源:cli.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python token.STANDARD_TYPES类代码示例发布时间:2022-05-25
下一篇:
Python styles.get_all_styles函数代码示例发布时间: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