pygments.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. """
  2. Adaptor for building prompt_toolkit styles, starting from a Pygments style.
  3. Usage::
  4. from pygments.styles.tango import TangoStyle
  5. style = style_from_pygments_cls(pygments_style_cls=TangoStyle)
  6. """
  7. from __future__ import annotations
  8. from typing import TYPE_CHECKING
  9. from .style import Style
  10. if TYPE_CHECKING:
  11. from pygments.style import Style as PygmentsStyle
  12. from pygments.token import Token
  13. __all__ = [
  14. "style_from_pygments_cls",
  15. "style_from_pygments_dict",
  16. "pygments_token_to_classname",
  17. ]
  18. def style_from_pygments_cls(pygments_style_cls: type[PygmentsStyle]) -> Style:
  19. """
  20. Shortcut to create a :class:`.Style` instance from a Pygments style class
  21. and a style dictionary.
  22. Example::
  23. from prompt_toolkit.styles.from_pygments import style_from_pygments_cls
  24. from pygments.styles import get_style_by_name
  25. style = style_from_pygments_cls(get_style_by_name('monokai'))
  26. :param pygments_style_cls: Pygments style class to start from.
  27. """
  28. # Import inline.
  29. from pygments.style import Style as PygmentsStyle
  30. assert issubclass(pygments_style_cls, PygmentsStyle)
  31. return style_from_pygments_dict(pygments_style_cls.styles)
  32. def style_from_pygments_dict(pygments_dict: dict[Token, str]) -> Style:
  33. """
  34. Create a :class:`.Style` instance from a Pygments style dictionary.
  35. (One that maps Token objects to style strings.)
  36. """
  37. pygments_style = []
  38. for token, style in pygments_dict.items():
  39. pygments_style.append((pygments_token_to_classname(token), style))
  40. return Style(pygments_style)
  41. def pygments_token_to_classname(token: Token) -> str:
  42. """
  43. Turn e.g. `Token.Name.Exception` into `'pygments.name.exception'`.
  44. (Our Pygments lexer will also turn the tokens that pygments produces in a
  45. prompt_toolkit list of fragments that match these styling rules.)
  46. """
  47. parts = ("pygments",) + token
  48. return ".".join(parts).lower()