Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/prompt_toolkit/styles/pygments.py: 42%

19 statements  

« prev     ^ index     » next       coverage.py v7.4.4, created at 2024-04-20 06:09 +0000

1""" 

2Adaptor for building prompt_toolkit styles, starting from a Pygments style. 

3 

4Usage:: 

5 

6 from pygments.styles.tango import TangoStyle 

7 style = style_from_pygments_cls(pygments_style_cls=TangoStyle) 

8""" 

9from __future__ import annotations 

10 

11from typing import TYPE_CHECKING 

12 

13from .style import Style 

14 

15if TYPE_CHECKING: 

16 from pygments.style import Style as PygmentsStyle 

17 from pygments.token import Token 

18 

19 

20__all__ = [ 

21 "style_from_pygments_cls", 

22 "style_from_pygments_dict", 

23 "pygments_token_to_classname", 

24] 

25 

26 

27def style_from_pygments_cls(pygments_style_cls: type[PygmentsStyle]) -> Style: 

28 """ 

29 Shortcut to create a :class:`.Style` instance from a Pygments style class 

30 and a style dictionary. 

31 

32 Example:: 

33 

34 from prompt_toolkit.styles.from_pygments import style_from_pygments_cls 

35 from pygments.styles import get_style_by_name 

36 style = style_from_pygments_cls(get_style_by_name('monokai')) 

37 

38 :param pygments_style_cls: Pygments style class to start from. 

39 """ 

40 # Import inline. 

41 from pygments.style import Style as PygmentsStyle 

42 

43 assert issubclass(pygments_style_cls, PygmentsStyle) 

44 

45 return style_from_pygments_dict(pygments_style_cls.styles) 

46 

47 

48def style_from_pygments_dict(pygments_dict: dict[Token, str]) -> Style: 

49 """ 

50 Create a :class:`.Style` instance from a Pygments style dictionary. 

51 (One that maps Token objects to style strings.) 

52 """ 

53 pygments_style = [] 

54 

55 for token, style in pygments_dict.items(): 

56 pygments_style.append((pygments_token_to_classname(token), style)) 

57 

58 return Style(pygments_style) 

59 

60 

61def pygments_token_to_classname(token: Token) -> str: 

62 """ 

63 Turn e.g. `Token.Name.Exception` into `'pygments.name.exception'`. 

64 

65 (Our Pygments lexer will also turn the tokens that pygments produces in a 

66 prompt_toolkit list of fragments that match these styling rules.) 

67 """ 

68 parts = ("pygments",) + token 

69 return ".".join(parts).lower()