base.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. """
  2. Base classes for prompt_toolkit lexers.
  3. """
  4. from __future__ import annotations
  5. from abc import ABCMeta, abstractmethod
  6. from typing import Callable, Hashable
  7. from prompt_toolkit.document import Document
  8. from prompt_toolkit.formatted_text.base import StyleAndTextTuples
  9. __all__ = [
  10. "Lexer",
  11. "SimpleLexer",
  12. "DynamicLexer",
  13. ]
  14. class Lexer(metaclass=ABCMeta):
  15. """
  16. Base class for all lexers.
  17. """
  18. @abstractmethod
  19. def lex_document(self, document: Document) -> Callable[[int], StyleAndTextTuples]:
  20. """
  21. Takes a :class:`~prompt_toolkit.document.Document` and returns a
  22. callable that takes a line number and returns a list of
  23. ``(style_str, text)`` tuples for that line.
  24. XXX: Note that in the past, this was supposed to return a list
  25. of ``(Token, text)`` tuples, just like a Pygments lexer.
  26. """
  27. def invalidation_hash(self) -> Hashable:
  28. """
  29. When this changes, `lex_document` could give a different output.
  30. (Only used for `DynamicLexer`.)
  31. """
  32. return id(self)
  33. class SimpleLexer(Lexer):
  34. """
  35. Lexer that doesn't do any tokenizing and returns the whole input as one
  36. token.
  37. :param style: The style string for this lexer.
  38. """
  39. def __init__(self, style: str = "") -> None:
  40. self.style = style
  41. def lex_document(self, document: Document) -> Callable[[int], StyleAndTextTuples]:
  42. lines = document.lines
  43. def get_line(lineno: int) -> StyleAndTextTuples:
  44. "Return the tokens for the given line."
  45. try:
  46. return [(self.style, lines[lineno])]
  47. except IndexError:
  48. return []
  49. return get_line
  50. class DynamicLexer(Lexer):
  51. """
  52. Lexer class that can dynamically returns any Lexer.
  53. :param get_lexer: Callable that returns a :class:`.Lexer` instance.
  54. """
  55. def __init__(self, get_lexer: Callable[[], Lexer | None]) -> None:
  56. self.get_lexer = get_lexer
  57. self._dummy = SimpleLexer()
  58. def lex_document(self, document: Document) -> Callable[[int], StyleAndTextTuples]:
  59. lexer = self.get_lexer() or self._dummy
  60. return lexer.lex_document(document)
  61. def invalidation_hash(self) -> Hashable:
  62. lexer = self.get_lexer() or self._dummy
  63. return id(lexer)