__init__.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. """
  2. pygments.styles
  3. ~~~~~~~~~~~~~~~
  4. Contains built-in styles.
  5. :copyright: Copyright 2006-2024 by the Pygments team, see AUTHORS.
  6. :license: BSD, see LICENSE for details.
  7. """
  8. from pygments.plugin import find_plugin_styles
  9. from pygments.util import ClassNotFound
  10. from pygments.styles._mapping import STYLES
  11. #: A dictionary of built-in styles, mapping style names to
  12. #: ``'submodule::classname'`` strings.
  13. #: This list is deprecated. Use `pygments.styles.STYLES` instead
  14. STYLE_MAP = {v[1]: v[0].split('.')[-1] + '::' + k for k, v in STYLES.items()}
  15. #: Internal reverse mapping to make `get_style_by_name` more efficient
  16. _STYLE_NAME_TO_MODULE_MAP = {v[1]: (v[0], k) for k, v in STYLES.items()}
  17. def get_style_by_name(name):
  18. """
  19. Return a style class by its short name. The names of the builtin styles
  20. are listed in :data:`pygments.styles.STYLE_MAP`.
  21. Will raise :exc:`pygments.util.ClassNotFound` if no style of that name is
  22. found.
  23. """
  24. if name in _STYLE_NAME_TO_MODULE_MAP:
  25. mod, cls = _STYLE_NAME_TO_MODULE_MAP[name]
  26. builtin = "yes"
  27. else:
  28. for found_name, style in find_plugin_styles():
  29. if name == found_name:
  30. return style
  31. # perhaps it got dropped into our styles package
  32. builtin = ""
  33. mod = 'pygments.styles.' + name
  34. cls = name.title() + "Style"
  35. try:
  36. mod = __import__(mod, None, None, [cls])
  37. except ImportError:
  38. raise ClassNotFound(f"Could not find style module {mod!r}" +
  39. (builtin and ", though it should be builtin")
  40. + ".")
  41. try:
  42. return getattr(mod, cls)
  43. except AttributeError:
  44. raise ClassNotFound(f"Could not find style class {cls!r} in style module.")
  45. def get_all_styles():
  46. """Return a generator for all styles by name, both builtin and plugin."""
  47. for v in STYLES.values():
  48. yield v[1]
  49. for name, _ in find_plugin_styles():
  50. yield name