Coverage for /home/martinb/.local/share/virtualenvs/camcops/lib/python3.6/site-packages/pygments/formatters/__init__.py : 31%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1# -*- coding: utf-8 -*-
2"""
3 pygments.formatters
4 ~~~~~~~~~~~~~~~~~~~
6 Pygments formatters.
8 :copyright: Copyright 2006-2021 by the Pygments team, see AUTHORS.
9 :license: BSD, see LICENSE for details.
10"""
12import re
13import sys
14import types
15import fnmatch
16from os.path import basename
18from pygments.formatters._mapping import FORMATTERS
19from pygments.plugin import find_plugin_formatters
20from pygments.util import ClassNotFound
22__all__ = ['get_formatter_by_name', 'get_formatter_for_filename',
23 'get_all_formatters', 'load_formatter_from_file'] + list(FORMATTERS)
25_formatter_cache = {} # classes by name
26_pattern_cache = {}
29def _fn_matches(fn, glob):
30 """Return whether the supplied file name fn matches pattern filename."""
31 if glob not in _pattern_cache:
32 pattern = _pattern_cache[glob] = re.compile(fnmatch.translate(glob))
33 return pattern.match(fn)
34 return _pattern_cache[glob].match(fn)
37def _load_formatters(module_name):
38 """Load a formatter (and all others in the module too)."""
39 mod = __import__(module_name, None, None, ['__all__'])
40 for formatter_name in mod.__all__:
41 cls = getattr(mod, formatter_name)
42 _formatter_cache[cls.name] = cls
45def get_all_formatters():
46 """Return a generator for all formatter classes."""
47 # NB: this returns formatter classes, not info like get_all_lexers().
48 for info in FORMATTERS.values():
49 if info[1] not in _formatter_cache:
50 _load_formatters(info[0])
51 yield _formatter_cache[info[1]]
52 for _, formatter in find_plugin_formatters():
53 yield formatter
56def find_formatter_class(alias):
57 """Lookup a formatter by alias.
59 Returns None if not found.
60 """
61 for module_name, name, aliases, _, _ in FORMATTERS.values():
62 if alias in aliases:
63 if name not in _formatter_cache:
64 _load_formatters(module_name)
65 return _formatter_cache[name]
66 for _, cls in find_plugin_formatters():
67 if alias in cls.aliases:
68 return cls
71def get_formatter_by_name(_alias, **options):
72 """Lookup and instantiate a formatter by alias.
74 Raises ClassNotFound if not found.
75 """
76 cls = find_formatter_class(_alias)
77 if cls is None:
78 raise ClassNotFound("no formatter found for name %r" % _alias)
79 return cls(**options)
82def load_formatter_from_file(filename, formattername="CustomFormatter",
83 **options):
84 """Load a formatter from a file.
86 This method expects a file located relative to the current working
87 directory, which contains a class named CustomFormatter. By default,
88 it expects the Formatter to be named CustomFormatter; you can specify
89 your own class name as the second argument to this function.
91 Users should be very careful with the input, because this method
92 is equivalent to running eval on the input file.
94 Raises ClassNotFound if there are any problems importing the Formatter.
96 .. versionadded:: 2.2
97 """
98 try:
99 # This empty dict will contain the namespace for the exec'd file
100 custom_namespace = {}
101 with open(filename, 'rb') as f:
102 exec(f.read(), custom_namespace)
103 # Retrieve the class `formattername` from that namespace
104 if formattername not in custom_namespace:
105 raise ClassNotFound('no valid %s class found in %s' %
106 (formattername, filename))
107 formatter_class = custom_namespace[formattername]
108 # And finally instantiate it with the options
109 return formatter_class(**options)
110 except IOError as err:
111 raise ClassNotFound('cannot read %s: %s' % (filename, err))
112 except ClassNotFound:
113 raise
114 except Exception as err:
115 raise ClassNotFound('error when loading custom formatter: %s' % err)
118def get_formatter_for_filename(fn, **options):
119 """Lookup and instantiate a formatter by filename pattern.
121 Raises ClassNotFound if not found.
122 """
123 fn = basename(fn)
124 for modname, name, _, filenames, _ in FORMATTERS.values():
125 for filename in filenames:
126 if _fn_matches(fn, filename):
127 if name not in _formatter_cache:
128 _load_formatters(modname)
129 return _formatter_cache[name](**options)
130 for cls in find_plugin_formatters():
131 for filename in cls.filenames:
132 if _fn_matches(fn, filename):
133 return cls(**options)
134 raise ClassNotFound("no formatter found for file name %r" % fn)
137class _automodule(types.ModuleType):
138 """Automatically import formatters."""
140 def __getattr__(self, name):
141 info = FORMATTERS.get(name)
142 if info:
143 _load_formatters(info[0])
144 cls = _formatter_cache[info[1]]
145 setattr(self, name, cls)
146 return cls
147 raise AttributeError(name)
150oldmod = sys.modules[__name__]
151newmod = _automodule(__name__)
152newmod.__dict__.update(oldmod.__dict__)
153sys.modules[__name__] = newmod
154del newmod.newmod, newmod.oldmod, newmod.sys, newmod.types