plugin.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. """
  2. pygments.plugin
  3. ~~~~~~~~~~~~~~~
  4. Pygments plugin interface. By default, this tries to use
  5. ``importlib.metadata``, which is in the Python standard
  6. library since Python 3.8, or its ``importlib_metadata``
  7. backport for earlier versions of Python. It falls back on
  8. ``pkg_resources`` if not found. Finally, if ``pkg_resources``
  9. is not found either, no plugins are loaded at all.
  10. lexer plugins::
  11. [pygments.lexers]
  12. yourlexer = yourmodule:YourLexer
  13. formatter plugins::
  14. [pygments.formatters]
  15. yourformatter = yourformatter:YourFormatter
  16. /.ext = yourformatter:YourFormatter
  17. As you can see, you can define extensions for the formatter
  18. with a leading slash.
  19. syntax plugins::
  20. [pygments.styles]
  21. yourstyle = yourstyle:YourStyle
  22. filter plugin::
  23. [pygments.filter]
  24. yourfilter = yourfilter:YourFilter
  25. :copyright: Copyright 2006-2022 by the Pygments team, see AUTHORS.
  26. :license: BSD, see LICENSE for details.
  27. """
  28. LEXER_ENTRY_POINT = 'pygments.lexers'
  29. FORMATTER_ENTRY_POINT = 'pygments.formatters'
  30. STYLE_ENTRY_POINT = 'pygments.styles'
  31. FILTER_ENTRY_POINT = 'pygments.filters'
  32. def iter_entry_points(group_name):
  33. try:
  34. from importlib.metadata import entry_points
  35. except ImportError:
  36. try:
  37. from importlib_metadata import entry_points
  38. except ImportError:
  39. try:
  40. from pip._vendor.pkg_resources import iter_entry_points
  41. except (ImportError, OSError):
  42. return []
  43. else:
  44. return iter_entry_points(group_name)
  45. groups = entry_points()
  46. if hasattr(groups, 'select'):
  47. # New interface in Python 3.10 and newer versions of the
  48. # importlib_metadata backport.
  49. return groups.select(group=group_name)
  50. else:
  51. # Older interface, deprecated in Python 3.10 and recent
  52. # importlib_metadata, but we need it in Python 3.8 and 3.9.
  53. return groups.get(group_name, [])
  54. def find_plugin_lexers():
  55. for entrypoint in iter_entry_points(LEXER_ENTRY_POINT):
  56. yield entrypoint.load()
  57. def find_plugin_formatters():
  58. for entrypoint in iter_entry_points(FORMATTER_ENTRY_POINT):
  59. yield entrypoint.name, entrypoint.load()
  60. def find_plugin_styles():
  61. for entrypoint in iter_entry_points(STYLE_ENTRY_POINT):
  62. yield entrypoint.name, entrypoint.load()
  63. def find_plugin_filters():
  64. for entrypoint in iter_entry_points(FILTER_ENTRY_POINT):
  65. yield entrypoint.name, entrypoint.load()