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


Python formatters.get_formatter_for_filename函数代码示例

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


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

示例1: hl

def hl(code,pl,font=None):
    lexer = get_lexer_by_name(pl)
    formatter = get_formatter_for_filename('.html',linenos=True)
    result = highlight(code,lexer,formatter)
    if font:
        result = '<span style="font-size:'+str(font)+'px;">'+result+'</span>'
    css = get_formatter_for_filename('.html',style='emacs').get_style_defs('.highlight')
    print css
    return result
开发者ID:Anivarth,项目名称:grain-code-beautifier,代码行数:9,代码来源:app.py

示例2: process_dict

    def process_dict(self, input_dict):
        ext = self.artifact.prior.ext

        if input_dict.has_key('1') and not input_dict['1'] and ext in [".css", ".sty"]:
            # Special case if we get a virtual empty file, generate style file
            self.artifact.final = True
            self.artifact.ext = ext
            output_dict = OrderedDict()
            if ext == '.css':
                output_dict['1'] = self.generate_css(self.arg_value('style', 'default'))
            elif ext == '.sty':
                output_dict['1'] = self.generate_sty(self.arg_value('style', 'default'))
            else:
                raise dexy.commands.UserFeedback("pyg filter doesn't know how to generate a stylesheet for %s extension" % ext)
            return output_dict
        else:
            args = self.args().copy()
            lexer = self.create_lexer_instance(args)

            formatter_args = {'lineanchors' : self.artifact.web_safe_document_key() }

            # Python 2.6 hates unicode keys
            for k, v in args.iteritems():
                formatter_args[str(k)] = v

            formatter = get_formatter_for_filename(self.artifact.name, **formatter_args)

            if self.artifact.ext in self.IMAGE_OUTPUT_EXTENSIONS:
                with open(self.artifact.output_data.data_file(), 'wb') as f:
                    f.write(highlight(self.artifact.input_data.join(), lexer, formatter))
            else:
                output_dict = OrderedDict()
                for k, v in input_dict.items():
                    output_dict[k] = highlight(v.decode("utf-8"), lexer, formatter)
                return output_dict
开发者ID:tomspur,项目名称:dexy,代码行数:35,代码来源:pygments_filters.py

示例3: get_formatter_for_filename

def get_formatter_for_filename(fn, **options):
    """Gets a formatter instance from a filename (usually via the filename
    extension). This mimics the behavior of
    ``pygments.formatters.get_formatter_for_filename()``.
    """
    if CACHE is None:
        load_or_build()
    exts = CACHE["formatters"]["exts"]
    fname = os.path.basename(fn)
    key = fname if fname in exts else os.path.splitext(fname)[1]
    if key in exts:
        modname, clsname = exts[key]
        mod = importlib.import_module(modname)
        cls = getattr(mod, clsname)
        formatter = cls(**options)
    else:
        # couldn't find formatter in cache, fallback to the hard way
        import inspect
        from pygments.formatters import get_formatter_for_filename

        formatter = get_formatter_for_filename(fn, **options)
        # add this filename to the cache for future use
        cls = type(formatter)
        mod = inspect.getmodule(cls)
        exts[fname] = (mod.__name__, cls.__name__)
        write_cache(cache_filename())
    return formatter
开发者ID:donnemartin,项目名称:gitsome,代码行数:27,代码来源:pygments_cache.py

示例4: process_text_to_dict

    def process_text_to_dict(self, input_text):
        composer = Composer()
        builder = idiopidae.parser.parse('Document', input_text + "\n\0")

        ext = self.artifact.input_ext
        name = "input_text%s" % ext
        # List any file extensions which don't map neatly to lexers.
        if ext == '.pycon':
            lexer = PythonConsoleLexer()
        elif ext == '.rbcon':
            lexer = RubyConsoleLexer()
        elif ext in ('.json', '.dexy'):
            lexer = JavascriptLexer()
        else:
            lexer = get_lexer_for_filename(name)
        formatter = get_formatter_for_filename(self.artifact.filename(),
                                               lineanchors='l')
        output_dict = OrderedDict()

        for i, s in enumerate(builder.sections):
            lines = builder.statements[i]['lines']
            formatted_lines = composer.format(lines, lexer, formatter) 
            output_dict[s] = formatted_lines

        return output_dict
开发者ID:cassj,项目名称:dexy,代码行数:25,代码来源:idio_handler.py

示例5: create_formatter_instance

    def create_formatter_instance(self, args):
        formatter_args = {'lineanchors' : self.artifact.web_safe_document_key() }

        # Python 2.6 doesn't like unicode keys as kwargs
        for k, v in args.iteritems():
            formatter_args[str(k)] = v

        return get_formatter_for_filename(self.artifact.filename(), **formatter_args)
开发者ID:mrflip,项目名称:dexy,代码行数:8,代码来源:pygments_filters.py

示例6: create_formatter_instance

    def create_formatter_instance(self):
        if self.setting('line-numbers') and not self.setting('linenos'):
            self.update_settings({'linenos' : self.setting('line-numbers')})

        formatter_args = self.constructor_args('formatter', {
            'lineanchors' : self.output_data.web_safe_document_key() })
        self.log_debug("creating pygments formatter with args %s" % (formatter_args))

        return get_formatter_for_filename(self.output_data.name, **formatter_args)
开发者ID:GWhized,项目名称:dexy,代码行数:9,代码来源:pyg.py

示例7: test_get_formatters

def test_get_formatters():
    # test that the formatters functions work
    x = formatters.get_formatter_by_name("html", opt="val")
    assert isinstance(x, formatters.HtmlFormatter)
    assert x.options["opt"] == "val"

    x = formatters.get_formatter_for_filename("a.html", opt="val")
    assert isinstance(x, formatters.HtmlFormatter)
    assert x.options["opt"] == "val"
开发者ID:spencerlyon2,项目名称:pygments,代码行数:9,代码来源:test_basic_api.py

示例8: test_get_formatters

    def test_get_formatters(self):
        a = self.assert_
        ae = self.assertEquals
        # test that the formatters functions work
        x = formatters.get_formatter_by_name("html", opt="val")
        a(isinstance(x, formatters.HtmlFormatter))
        ae(x.options["opt"], "val")

        x = formatters.get_formatter_for_filename("a.html", opt="val")
        a(isinstance(x, formatters.HtmlFormatter))
        ae(x.options["opt"], "val")
开发者ID:erickt,项目名称:pygments,代码行数:11,代码来源:test_basic_api.py

示例9: process_dict

    def process_dict(self, input_dict):
        ext = self.artifact.input_ext
        has_args = self.artifact.args.has_key('pygments')
        if has_args:
            args = self.artifact.args['pygments']
        else:
            args = {}

        if args.has_key('lexer'):
            lexer = get_lexer_by_name(args['lexer'])
            del args['lexer']
        else:
            if ext == '.pycon':
                lexer = PythonConsoleLexer()
            elif ext == '.rbcon':
                lexer = RubyConsoleLexer()
            elif ext in ('.json', '.dexy'):
                lexer = JavascriptLexer()
            elif ext == '.Rd':
                lexer = TexLexer() # does a passable job
            elif ext == '.svg':
                lexer = XmlLexer()
            else:
                fake_file_name = "input_text%s" % ext
                lexer = get_lexer_for_filename(fake_file_name)

        formatter_args = {'lineanchors' : self.artifact.web_safe_document_key() }
        # all args left are for the formatter...
        formatter_args.update(args)

        formatter = get_formatter_for_filename(self.artifact.filename(),
                **formatter_args)
        ### @end
        # TODO whitelist acceptable formatter args
        # TODO allow passing lexer args?

        if self.artifact.ext in self.IMAGE_OUTPUT_EXTENSIONS:
            self.artifact.binary_output = True
            # TODO set to final
            f = open(self.artifact.filepath(), 'w')
            f.write(highlight(self.artifact.input_text(), lexer, formatter))
            f.close()
        else:
            output_dict = OrderedDict()
            for k, v in input_dict.items():
                # TODO figure out where these characters are coming from and don't hard-code this.
                v = str(v.replace(" \x08", "").replace(chr(13), ""))
                try:
                    output_dict[k] = str(highlight(v, lexer, formatter))
                except UnicodeEncodeError as e:
                    self.artifact.log.warn("error processing section %s of file %s" % (k, self.artifact.key))
                    raise e
            return output_dict
开发者ID:pombredanne,项目名称:dexy,代码行数:53,代码来源:pygments_filters.py

示例10: process_text_to_dict

    def process_text_to_dict(self, input_text):
        composer = Composer()
        builder = idiopidae.parser.parse('Document', input_text + "\n\0")

        ext = self.artifact.input_ext
        name = "input_text%s" % ext

        if self.artifact.args.has_key('pyg-lexer'):
            lexer = get_lexer_by_name(self.artifact.args['pyg-lexer'])
        elif ext == '.pycon':
            lexer = PythonConsoleLexer()
        elif ext == '.rbcon':
            lexer = RubyConsoleLexer()
        elif ext in ('.json', '.dexy'):
            lexer = JavascriptLexer()
        elif ext in ('.php'):
            # If we are using idio, then our code will be in sections so we
            # need to start inline with PHP. To avoid this, use pyg instead of
            # idio. (Eventually should be able to specify lexer + options in config.)
            lexer = PhpLexer(startinline=True)
        else:
            lexer = get_lexer_for_filename(name)

        if self.artifact.args.has_key('idio'):
            idio_args = self.artifact.args['idio']
        elif self.artifact.args.has_key('pygments'):
            idio_args = self.artifact.args['pygments']
        else:
            idio_args = {}

        formatter_args = {'lineanchors' : self.artifact.web_safe_document_key() }
        formatter_args.update(idio_args)

        formatter = get_formatter_for_filename(self.artifact.filename(),
            **formatter_args)

        output_dict = OrderedDict()
        lineno = 1

        for i, s in enumerate(builder.sections):
            lines = builder.statements[i]['lines']
            if len(lines) == 0:
                next
            if not re.match("^\d+$", s):
                # Manually named section, the sectioning comment takes up a
                # line, so account for this to keep line nos in sync.
                lineno += 1
            formatter.linenostart = lineno
            formatted_lines = composer.format(lines, lexer, formatter)
            output_dict[s] = formatted_lines
            lineno += len(lines)

        return output_dict
开发者ID:blindside,项目名称:dexy,代码行数:53,代码来源:idio_filters.py

示例11: process_dict

    def process_dict(self, input_dict):
        ext = self.artifact.input_ext
        has_args = self.artifact.args.has_key('pygments')
        if has_args:
            args = self.artifact.args['pygments']
        else:
            args = {}

        if args.has_key('lexer'):
            lexer = get_lexer_by_name(args['lexer'])
            del args['lexer']
        else:
            if ext == '.pycon':
                lexer = PythonConsoleLexer()
            elif ext == '.rbcon':
                lexer = RubyConsoleLexer()
            elif (ext in ('.json', '.dexy') or self.artifact.name.endswith(".dexy")) and (pygments.__version__ < '1.5'):
                lexer = JavascriptLexer()
            elif ext in ('.dexy') or self.artifact.name.endswith(".dexy"):
                # JSON lexer available in pygments 1.5
                lexer = pygments.lexers.web.JSONLexer()
            elif ext == '.Rd':
                lexer = TexLexer() # does a passable job
            elif ext == '.svg':
                lexer = XmlLexer()
            else:
                fake_file_name = "input_text%s" % ext
                lexer = get_lexer_for_filename(fake_file_name)

        formatter_args = {'lineanchors' : self.artifact.web_safe_document_key() }
        # all args left are for the formatter...
        formatter_args.update(args)

        formatter = get_formatter_for_filename(self.artifact.filename(),
                **formatter_args)
        ### @end
        # TODO whitelist acceptable formatter args
        # TODO allow passing lexer args?

        if self.artifact.ext in self.IMAGE_OUTPUT_EXTENSIONS:
            self.artifact.binary_output = True
            # TODO set to final
            with open(self.artifact.filepath(), 'wb') as f:
                f.write(highlight(self.artifact.input_text(), lexer, formatter))
        else:
            output_dict = OrderedDict()
            for k, v in input_dict.items():
                # TODO figure out where these characters are coming from and don't hard-code this.
                v = v.replace(" \x08", "").replace(chr(13), "")
                output_dict[k] = highlight(v, lexer, formatter)
            return output_dict
开发者ID:blindside,项目名称:dexy,代码行数:51,代码来源:pygments_filters.py

示例12: process

    def process(self):
        if self.artifact.ext in self.IMAGE_OUTPUT_EXTENSIONS:
            try:
                import PIL
            except ImportError:
                print "python imaging library is required by pygments to create image output"
                raise dexy.exceptions.InactiveFilter('pyg', self.artifact.key)

        input_dict = self.input().as_sectioned()
        ext = self.artifact.prior.ext

        if input_dict.has_key('1') and not input_dict['1'] and ext in [".css", ".sty"]:
            # Special case if we get a virtual empty file, generate style file
            self.artifact.final = True
            self.artifact.ext = ext
            output_dict = OrderedDict()
            if ext == '.css':
                output_dict['1'] = self.generate_css(self.arg_value('style', 'default'))
            elif ext == '.sty':
                output_dict['1'] = self.generate_sty(self.arg_value('style', 'default'))
            else:
                raise dexy.commands.UserFeedback("pyg filter doesn't know how to generate a stylesheet for %s extension" % ext)
            return output_dict
        else:
            args = self.args().copy()
            lexer = self.create_lexer_instance(args)

            formatter_args = {'lineanchors' : self.output().web_safe_document_key() }

            # Python 2.6 hates unicode keys
            for k, v in args.iteritems():
                formatter_args[str(k)] = v

            formatter = get_formatter_for_filename(self.output().name, **formatter_args)

            if self.artifact.ext in self.IMAGE_OUTPUT_EXTENSIONS:
                with open(self.output_filepath(), 'wb') as f:
                    f.write(highlight(self.input().data(), lexer, formatter))

            else:
                output_dict = OrderedDict()
                for k, v in input_dict.items():
                    output_dict[k] = highlight(v.decode("utf-8"), lexer, formatter)
                self.output().set_data(output_dict)
开发者ID:adityaathalye,项目名称:dexy,代码行数:44,代码来源:pygments_filters.py

示例13: process_dict

 def process_dict(self, input_dict):
     ext = self.artifact.input_ext
     name = "input_text%s" % ext
     # List any file extensions which don't map neatly to lexers.
     if ext == '.pycon':
         lexer = PythonConsoleLexer()
     elif ext == '.rbcon':
         lexer = RubyConsoleLexer()
     elif ext in ('.json', '.dexy'):
         lexer = JavascriptLexer()
     elif ext == '.Rd':
         lexer = TextLexer()
     else:
         lexer = get_lexer_for_filename(name)
     formatter = get_formatter_for_filename(self.artifact.filename(),
                                            lineanchors='l')
     output_dict = OrderedDict()
     for k, v in input_dict.items():
         try:
             output_dict[k] = str(highlight(v, lexer, formatter))
         except UnicodeEncodeError as e:
             self.log.warn("error processing section %s of file %s" % (k, self.artifact.key))
             raise e
     return output_dict
开发者ID:cassj,项目名称:dexy,代码行数:24,代码来源:pyg_handler.py

示例14: get_formatter_by_name

    opts.pop('-F', None)

    # select formatter
    outfn = opts.pop('-o', None)
    fmter = opts.pop('-f', None)
    if fmter:
        try:
            fmter = get_formatter_by_name(fmter, **parsed_opts)
        except (OptionError, ClassNotFound), err:
            print >>sys.stderr, 'Error:', err
            return 1

    if outfn:
        if not fmter:
            try:
                fmter = get_formatter_for_filename(outfn, **parsed_opts)
            except (OptionError, ClassNotFound), err:
                print >>sys.stderr, 'Error:', err
                return 1
        try:
            outfile = file(outfn, 'wb')
        except Exception, err:
            print >>sys.stderr, 'Error: cannot open outfile:', err
            return 1
    else:
        if not fmter:
            fmter = TerminalFormatter(**parsed_opts)
        outfile = sys.stdout

    # select lexer
    lexer = opts.pop('-l', None)
开发者ID:achernet,项目名称:wxPython,代码行数:31,代码来源:cmdline.py

示例15: main


#.........这里部分代码省略.........
            print(err, file=sys.stderr)
            return 1

        arg = a_opt or ''
        try:
            print(fmter.get_style_defs(arg))
        except Exception as err:
            print('Error:', err, file=sys.stderr)
            return 1
        return 0

    # if no -S is given, -a is not allowed
    if a_opt is not None:
        print(usage, file=sys.stderr)
        return 2

    # parse -F options
    F_opts = _parse_filters(F_opts)
    opts.pop('-F', None)

    # select formatter
    outfn = opts.pop('-o', None)
    fmter = opts.pop('-f', None)
    if fmter:
        try:
            fmter = get_formatter_by_name(fmter, **parsed_opts)
        except (OptionError, ClassNotFound) as err:
            print('Error:', err, file=sys.stderr)
            return 1

    if outfn:
        if not fmter:
            try:
                fmter = get_formatter_for_filename(outfn, **parsed_opts)
            except (OptionError, ClassNotFound) as err:
                print('Error:', err, file=sys.stderr)
                return 1
        try:
            outfile = open(outfn, 'wb')
        except Exception as err:
            print('Error: cannot open outfile:', err, file=sys.stderr)
            return 1
    else:
        if not fmter:
            fmter = TerminalFormatter(**parsed_opts)
        outfile = sys.stdout

    # select lexer
    lexer = opts.pop('-l', None)
    if lexer:
        try:
            lexer = get_lexer_by_name(lexer, **parsed_opts)
        except (OptionError, ClassNotFound) as err:
            print('Error:', err, file=sys.stderr)
            return 1

    if args:
        if len(args) > 1:
            print(usage, file=sys.stderr)
            return 2

        infn = args[0]
        try:
            code = open(infn, 'rb').read()
        except Exception as err:
            print('Error: cannot read infile:', err, file=sys.stderr)
开发者ID:JosmanPS,项目名称:sublime-evernote,代码行数:67,代码来源:cmdline.py


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