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

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

20 statements  

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""" 

9 

10from __future__ import annotations 

11 

12from typing import TYPE_CHECKING 

13 

14from .style import Style 

15 

16if TYPE_CHECKING: 

17 from pygments.style import Style as PygmentsStyle 

18 from pygments.token import Token 

19 

20 

21__all__ = [ 

22 "style_from_pygments_cls", 

23 "style_from_pygments_dict", 

24 "pygments_token_to_classname", 

25] 

26 

27 

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

29 """ 

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

31 and a style dictionary. 

32 

33 Example:: 

34 

35 from prompt_toolkit.styles.from_pygments import style_from_pygments_cls 

36 from pygments.styles import get_style_by_name 

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

38 

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

40 """ 

41 # Import inline. 

42 from pygments.style import Style as PygmentsStyle 

43 

44 assert issubclass(pygments_style_cls, PygmentsStyle) 

45 

46 return style_from_pygments_dict(pygments_style_cls.styles) 

47 

48 

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

50 """ 

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

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

53 """ 

54 pygments_style = [] 

55 

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

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

58 

59 return Style(pygments_style) 

60 

61 

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

63 """ 

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

65 

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

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

68 """ 

69 parts = ("pygments",) + token 

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