base.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. """
  2. The base classes for the styling.
  3. """
  4. from __future__ import unicode_literals
  5. from abc import ABCMeta, abstractmethod
  6. from collections import namedtuple
  7. from six import with_metaclass
  8. __all__ = (
  9. 'Attrs',
  10. 'DEFAULT_ATTRS',
  11. 'ANSI_COLOR_NAMES',
  12. 'Style',
  13. 'DynamicStyle',
  14. )
  15. #: Style attributes.
  16. Attrs = namedtuple('Attrs', 'color bgcolor bold underline italic blink reverse')
  17. """
  18. :param color: Hexadecimal string. E.g. '000000' or Ansi color name: e.g. 'ansiblue'
  19. :param bgcolor: Hexadecimal string. E.g. 'ffffff' or Ansi color name: e.g. 'ansired'
  20. :param bold: Boolean
  21. :param underline: Boolean
  22. :param italic: Boolean
  23. :param blink: Boolean
  24. :param reverse: Boolean
  25. """
  26. #: The default `Attrs`.
  27. DEFAULT_ATTRS = Attrs(color=None, bgcolor=None, bold=False, underline=False,
  28. italic=False, blink=False, reverse=False)
  29. #: ``Attrs.bgcolor/fgcolor`` can be in either 'ffffff' format, or can be any of
  30. #: the following in case we want to take colors from the 8/16 color palette.
  31. #: Usually, in that case, the terminal application allows to configure the RGB
  32. #: values for these names.
  33. ANSI_COLOR_NAMES = [
  34. 'ansiblack', 'ansiwhite', 'ansidefault',
  35. # Low intensity.
  36. 'ansired', 'ansigreen', 'ansiyellow', 'ansiblue', 'ansifuchsia', 'ansiturquoise', 'ansilightgray',
  37. # High intensity. (Not supported everywhere.)
  38. 'ansidarkgray', 'ansidarkred', 'ansidarkgreen', 'ansibrown', 'ansidarkblue',
  39. 'ansipurple', 'ansiteal',
  40. ]
  41. class Style(with_metaclass(ABCMeta, object)):
  42. """
  43. Abstract base class for prompt_toolkit styles.
  44. """
  45. @abstractmethod
  46. def get_attrs_for_token(self, token):
  47. """
  48. Return :class:`.Attrs` for the given token.
  49. """
  50. @abstractmethod
  51. def invalidation_hash(self):
  52. """
  53. Invalidation hash for the style. When this changes over time, the
  54. renderer knows that something in the style changed, and that everything
  55. has to be redrawn.
  56. """
  57. class DynamicStyle(Style):
  58. """
  59. Style class that can dynamically returns an other Style.
  60. :param get_style: Callable that returns a :class:`.Style` instance.
  61. """
  62. def __init__(self, get_style):
  63. self.get_style = get_style
  64. def get_attrs_for_token(self, token):
  65. style = self.get_style()
  66. assert isinstance(style, Style)
  67. return style.get_attrs_for_token(token)
  68. def invalidation_hash(self):
  69. return self.get_style().invalidation_hash()