8
:copyright: 2006-2007 by Georg Brandl.
9
:license: BSD, see LICENSE for more details.
8
:copyright: Copyright 2006-2010 by the Pygments team, see AUTHORS.
9
:license: BSD, see LICENSE for details.
13
15
from os.path import basename
18
from sets import Set as set
20
17
from pygments.lexers._mapping import LEXERS
21
18
from pygments.plugin import find_plugin_lexers
22
from pygments.util import ClassNotFound
19
from pygments.util import ClassNotFound, bytes
25
22
__all__ = ['get_lexer_by_name', 'get_lexer_for_filename', 'find_lexer_class',
83
80
raise ClassNotFound('no lexer for alias %r found' % _alias)
86
def get_lexer_for_filename(_fn, **options):
88
Get a lexer for a filename.
83
def get_lexer_for_filename(_fn, code=None, **options):
85
Get a lexer for a filename. If multiple lexers match the filename
86
pattern, use ``analyze_text()`` to figure out which one is more
91
91
for modname, name, _, filenames, _ in LEXERS.itervalues():
92
92
for filename in filenames:
93
93
if fnmatch.fnmatch(fn, filename):
94
94
if name not in _lexer_cache:
95
95
_load_lexers(modname)
96
return _lexer_cache[name](**options)
96
matches.append(_lexer_cache[name])
97
97
for cls in find_plugin_lexers():
98
98
for filename in cls.filenames:
99
99
if fnmatch.fnmatch(fn, filename):
100
return cls(**options)
102
if sys.version_info > (3,) and isinstance(code, bytes):
103
# decode it, since all analyse_text functions expect unicode
104
code = code.decode('latin1')
107
# The class _always_ defines analyse_text because it's included in
108
# the Lexer class. The default implementation returns None which
109
# gets turned into 0.0. Run scripts/detect_missing_analyse_text.py
110
# to find lexers which need it overridden.
111
d = cls.analyse_text(code)
112
#print "Got %r from %r" % (d, cls)
116
matches.sort(key=get_rating)
118
#print "Possible lexers, after sort:", matches
119
return matches[-1](**options)
101
120
raise ClassNotFound('no lexer for filename %r found' % _fn)