Debian Codegraph @

IPython/utils/PyColorize.py

raw
1 import keyword
2 import os
3 import sys
4 import token
5 import tokenize
6 import warnings
7 from io import StringIO
8 from typing import Any, Type, TypeAlias
9
10 import pygments
11 from pygments.formatters.terminal256 import Terminal256Formatter
12 from pygments.style import Style
13 from pygments.styles import get_style_by_name
14 from pygments.token import Token, _TokenType
15 from functools import cache
16
17 from typing import TypedDict
18
19
20 TokenStream: TypeAlias = list[tuple[_TokenType, str]]
21
22
23 __all__ = ["Parser", "Theme"]
24
25
26 class Symbols(TypedDict):
27 top_line: str
28 arrow_body: str
29 arrow_head: str
30
31
32 _default_symbols: Symbols = Symbols(
33 top_line="-",
34 arrow_body="-",
35 arrow_head=">",
36 )
37
38
39 class Theme:
40 name: str
41 base: str | None
42 extra_style: dict[_TokenType, str]
43 symbols: Symbols
44
45 def __init__(
46 self,
47 name: str,
48 base: str | None,
49 extra_style: dict[_TokenType, str],
50 *,
51 symbols: Symbols | None = None,
52 ) -> None:
53 self.name = name
54 self.base = base
55 self.extra_style = extra_style
56 s: Symbols = symbols if symbols is not None else _default_symbols
57 self.symbols = {**_default_symbols, **s}
58 self._formatter = Terminal256Formatter(style=self.as_pygments_style())
59
60 @cache
61 def as_pygments_style(self) -> Type[Style]:
62 if self.base is not None:
63 base_styles = get_style_by_name(self.base).styles
64 else:
65 base_styles = {}
66
67 class MyStyle(Style):
68 styles = {**base_styles, **self.extra_style}
69
70 return MyStyle
71
72 def format(self, stream: TokenStream) -> str:
73 return pygments.format(stream, self._formatter)
74
75 def make_arrow(self, width: int) -> str:
76 """generate the leading arrow in front of traceback or debugger"""
77 if width >= 2:
78 return (
79 self.symbols["arrow_body"] * (width - 2)
80 + self.symbols["arrow_head"]
81 + " "
82 )
83 elif width == 1:
84 return self.symbols["arrow_head"]
85 return ""
86
87
88 generate_tokens = tokenize.generate_tokens
89
90
91 #############################################################################
92 ### Python Source Parser (does Highlighting)
93 #############################################################################
94
95 _KEYWORD = token.NT_OFFSET + 1
96 _TEXT = token.NT_OFFSET + 2
97
98 # ****************************************************************************
99
100 _pygment_token_mapping: dict[int, _TokenType] = {
101 token.NUMBER: Token.Literal.Number,
102 token.OP: Token.Operator,
103 token.STRING: Token.Literal.String,
104 token.COMMENT: Token.Comment,
105 token.NAME: Token.Name,
106 token.ERRORTOKEN: Token.Error,
107 _KEYWORD: Token.Keyword,
108 _TEXT: Token.Text,
109 }
110
111 # technically BW is not nocolor, we should have a no-style, style
112 nocolors_theme = Theme("nocolor", None, {})
113
114
115 linux_theme = Theme(
116 "linux",
117 "monokai",
118 {
119 Token.Header: "ansibrightred",
120 Token.LinenoEm: "ansibrightgreen",
121 Token.Lineno: "ansigreen",
122 Token.ValEm: "ansibrightblue",
123 Token.VName: "ansicyan",
124 Token.Caret: "",
125 Token.Filename: "ansibrightgreen",
126 Token.ExcName: "ansibrightred",
127 Token.Topline: "ansibrightred",
128 Token.FilenameEm: "ansigreen",
129 Token.Normal: "",
130 Token.NormalEm: "ansibrightcyan",
131 Token.Line: "ansiyellow",
132 Token.TB.Name: "ansimagenta",
133 Token.TB.NameEm: "ansibrightmagenta",
134 Token.Breakpoint: "",
135 Token.Breakpoint.Enabled: "ansibrightred",
136 Token.Breakpoint.Disabled: "ansired",
137 Token.Prompt: "ansibrightgreen",
138 Token.PromptNum: "ansigreen bold",
139 Token.OutPrompt: "ansibrightred",
140 Token.OutPromptNum: "ansired bold",
141 },
142 )
143
144 neutral_pygments_equiv = {
145 Token.Header: "ansired",
146 Token.LinenoEm: "ansigreen",
147 Token.Lineno: "ansibrightgreen",
148 Token.ValEm: "ansiblue",
149 Token.VName: "ansicyan",
150 Token.Caret: "",
151 Token.Filename: "ansibrightgreen",
152 Token.FilenameEm: "ansigreen",
153 Token.ExcName: "ansired",
154 Token.Topline: "ansired",
155 Token.Normal: "",
156 Token.NormalEm: "ansicyan",
157 Token.Line: "ansired",
158 Token.TB.Name: "ansibrightmagenta",
159 Token.TB.NameEm: "ansimagenta",
160 Token.Breakpoint: "",
161 Token.Breakpoint.Enabled: "ansibrightred",
162 Token.Breakpoint.Disabled: "ansired",
163 ## specific override of pygments defaults for visibility
164 Token.Number: "ansigreen",
165 Token.Operator: "noinherit",
166 Token.String: "ansiyellow",
167 Token.Name.Function: "ansiblue",
168 Token.Name.Class: "bold ansiblue",
169 Token.Name.Namespace: "bold ansiblue",
170 Token.Name.Variable.Magic: "ansiblue",
171 Token.Prompt: "ansigreen",
172 Token.OutPrompt: "ansired",
173 }
174
175
176 neutral_pygments_nt = {
177 **neutral_pygments_equiv,
178 Token.PromptNum: "ansigreen bold",
179 Token.OutPromptNum: "ansired bold",
180 }
181 neutral_pygments_posix = {
182 **neutral_pygments_equiv,
183 Token.PromptNum: "ansibrightgreen bold",
184 Token.OutPromptNum: "ansibrightred bold",
185 }
186
187
188 neutral_nt = Theme("neutral:nt", "default", neutral_pygments_nt)
189 neutral_posix = Theme("neutral:posix", "default", neutral_pygments_posix)
190
191
192 # Hack: the 'neutral' colours are not very visible on a dark background on
193 # Windows. Since Windows command prompts have a dark background by default, and
194 # relatively few users are likely to alter that, we will use the 'Linux' colours,
195 # designed for a dark background, as the default on Windows. Changing it here
196 # avoids affecting the prompt colours rendered by prompt_toolkit, where the
197 # neutral defaults do work OK.
198 if os.name == "nt":
199 neutral_theme = neutral_nt
200 else:
201 neutral_theme = neutral_posix
202
203
204 lightbg_theme = Theme(
205 "lightbg",
206 "pastie",
207 {
208 Token.Header: "ansired",
209 Token.LinenoEm: "ansigreen",
210 Token.Lineno: "ansibrightgreen",
211 Token.ValEm: "ansiblue",
212 Token.VName: "ansicyan",
213 Token.Caret: "",
214 Token.Filename: "ansigreen",
215 Token.FilenameEm: "ansibrightgreen",
216 Token.ExcName: "ansired",
217 Token.Topline: "ansired",
218 Token.Normal: "",
219 Token.NormalEm: "ansicyan",
220 Token.Line: "ansired",
221 Token.TB.Name: "ansibrightmagenta",
222 Token.TB.NameEm: "ansimagenta",
223 Token.Breakpoint: "",
224 Token.Breakpoint.Enabled: "ansibrightred",
225 Token.Breakpoint.Disabled: "ansired",
226 Token.Prompt: "ansibrightblue",
227 Token.PromptNum: "ansiblue bold",
228 Token.OutPrompt: "ansibrightred",
229 Token.OutPromptNum: "ansired bold",
230 },
231 )
232
233 PRIDE_RED = "#E40303"
234 PRIDE_ORANGE = "#FF8C00"
235 PRIDE_YELLOW = "#FFED00"
236 PRIDE_GREEN = "#008026"
237 PRIDE_INDIGO = "#004CFF"
238 PRIDE_VIOLET = "#732982"
239 pride_theme = Theme(
240 "pride",
241 "pastie",
242 {
243 Token.Header: PRIDE_INDIGO,
244 Token.LinenoEm: f"{PRIDE_GREEN} italic",
245 Token.Lineno: f"{PRIDE_GREEN} bold",
246 Token.ValEm: f"{PRIDE_INDIGO} italic",
247 Token.VName: "ansicyan",
248 Token.Caret: "",
249 Token.Filename: f"{PRIDE_YELLOW}",
250 Token.FilenameEm: f"bg:{PRIDE_VIOLET}",
251 Token.ExcName: f"{PRIDE_ORANGE}",
252 Token.Topline: f"{PRIDE_RED}",
253 Token.Normal: "",
254 Token.NormalEm: "bold",
255 Token.Line: "ansired",
256 Token.TB.Name: "ansibrightmagenta",
257 Token.TB.NameEm: "ansimagenta",
258 Token.Breakpoint: "",
259 Token.Breakpoint.Enabled: "ansibrightred",
260 Token.Breakpoint.Disabled: "ansired",
261 Token.Prompt: "ansibrightblue",
262 Token.Prompt.Continuation.L1: f"ansiwhite bg:{PRIDE_RED}",
263 Token.Prompt.Continuation.L2: f"ansiwhite bg:{PRIDE_ORANGE}",
264 Token.Prompt.Continuation.L3: f"ansiblack bg:{PRIDE_YELLOW}",
265 Token.Prompt.Continuation.L4: f"ansiwhite bg:{PRIDE_GREEN}",
266 Token.Prompt.Continuation.L5: f"ansiwhite bg:{PRIDE_INDIGO}",
267 Token.Prompt.Continuation.L6: f"ansiwhite bg:{PRIDE_VIOLET}",
268 Token.PromptNum: "ansiblue bold",
269 Token.OutPrompt: "ansibrightred",
270 Token.OutPromptNum: "ansired bold",
271 },
272 symbols={"arrow_body": "\u2500", "arrow_head": "\u25b6", "top_line": "\u2500"},
273 )
274
275
276 C1 = "#D52D00"
277 C2 = "#EF7627"
278 C3 = "#FF9A56"
279 White = "#FFFFFF"
280 C5 = "#D162A4"
281 C6 = "#B55690"
282 C7 = "#A30262"
283
284 pl = {
285 # Token.Whitespace: "#bbbbbb",
286 Token.Comment: "#888888",
287 Token.String: C5,
288 Token.String.Escape: C1,
289 Token.Keyword: f"italic {C2}",
290 Token.Name.Class: C2,
291 Token.Name.Exception: C1,
292 Token.Name.Builtin: C3,
293 Token.Name.Variable: C6,
294 Token.Name.Constant: C7,
295 Token.Name.Decorator: C2,
296 Token.Number: C7,
297 Token.Generic.Deleted: f"bg:{C1} #000000",
298 Token.Generic.Emph: "italic",
299 Token.Generic.Strong: "bold",
300 Token.Generic.EmphStrong: "bold italic",
301 }
302
303 pridel_theme = Theme(
304 "pride:l",
305 None,
306 {
307 Token.Header: C3,
308 Token.LinenoEm: C3,
309 Token.Lineno: C2,
310 Token.ValEm: C2,
311 Token.VName: C2,
312 Token.Caret: "",
313 Token.Filename: C2,
314 Token.FilenameEm: C3,
315 Token.ExcName: C1,
316 Token.Topline: C1,
317 Token.Normal: "",
318 Token.NormalEm: "bold",
319 Token.Line: C2,
320 Token.TB.Name: C6,
321 Token.TB.NameEm: C7,
322 Token.Breakpoint: "",
323 Token.Breakpoint.Enabled: C1,
324 Token.Breakpoint.Disabled: C7,
325 Token.Prompt: C1,
326 Token.PromptNum: C2,
327 Token.Prompt.Continuation: C7,
328 Token.Prompt.Continuation.L1: C2,
329 Token.Prompt.Continuation.L2: C3,
330 Token.Prompt.Continuation.L3: White,
331 Token.Prompt.Continuation.L4: C5,
332 Token.Prompt.Continuation.L5: C6,
333 Token.Prompt.Continuation.L6: C7,
334 Token.OutPrompt: C6,
335 Token.OutPromptNum: C5,
336 **pl,
337 },
338 symbols={"arrow_body": "\u2500", "arrow_head": "\u25b6", "top_line": "\u2500"},
339 )
340
341 GRUVBOX_VAL_EM = "#D79921"
342 GRUVBOX_V_NAME = "#83A598"
343 GRUVBOX_FILENAME = "#FBF1C7"
344 GRUVBOX_EXCEPTION_NAME = "#FB4934"
345 GRUVBOX_TOPLINE = "#CC241D"
346 GRUVBOX_BREAKPOINT_ENABLED = "#FB4934"
347 GRUVBOX_BREAKPOINT_DISABLED = "#CC241D"
348 GRUVBOX_PROMPT = "#689D6A"
349 GRUVBOX_PROMPT_NUM = "#8EC07C"
350 GRUVBOX_OUT_PROMPT = "#B16286"
351 GRUVBOX_OUT_PROMPT_NUM = "#D3869B"
352 gruvbox_dark_theme = Theme(
353 "gruvbox-dark",
354 "gruvbox-dark",
355 {
356 Token.Lineno: GRUVBOX_PROMPT_NUM,
357 Token.LinenoEm: f"{GRUVBOX_PROMPT_NUM} bold",
358 Token.ValEm: f"{GRUVBOX_VAL_EM} bold",
359 Token.VName: GRUVBOX_V_NAME,
360 Token.Caret: "",
361 Token.Filename: GRUVBOX_FILENAME,
362 Token.FilenameEm: f"{GRUVBOX_FILENAME} bold",
363 Token.ExcName: f"{GRUVBOX_EXCEPTION_NAME} bold",
364 Token.Topline: GRUVBOX_TOPLINE,
365 Token.Breakpoint.Enabled: GRUVBOX_BREAKPOINT_ENABLED,
366 Token.Breakpoint.Disabled: GRUVBOX_BREAKPOINT_DISABLED,
367 Token.Prompt: GRUVBOX_PROMPT,
368 Token.PromptNum: f"{GRUVBOX_PROMPT_NUM} bold",
369 Token.OutPrompt: GRUVBOX_OUT_PROMPT,
370 Token.OutPromptNum: f"{GRUVBOX_OUT_PROMPT_NUM} bold",
371 },
372 symbols={"arrow_body": "\u2500", "arrow_head": "\u25b6", "top_line": "\u2500"},
373 )
374
375 theme_table: dict[str, Theme] = {
376 "nocolor": nocolors_theme,
377 "linux": linux_theme,
378 "neutral": neutral_theme,
379 "neutral:nt": neutral_nt,
380 "neutral:posix": neutral_posix,
381 "lightbg": lightbg_theme,
382 "pride": pride_theme,
383 "pride:l": pridel_theme,
384 "gruvbox-dark": gruvbox_dark_theme,
385 }
386
387
388 class Parser:
389 """Format colored Python source."""
390
391 _theme_name: str
392 out: Any
393 pos: int
394 lines: list[int]
395 raw: str
396
397 def __init__(self, out: Any = sys.stdout, *, theme_name: str | None = None) -> None:
398 """Create a parser with a specified color table and output channel.
399
400 Call format() to process code.
401 """
402
403 assert theme_name is not None
404
405 self.out = out
406 self.pos = 0
407 self.lines = []
408 self.raw = ""
409 if theme_name is not None:
410 if theme_name in ["Linux", "LightBG", "Neutral", "NoColor"]:
411 warnings.warn(
412 f"Theme names and color schemes are lowercase in IPython 9.0 use {theme_name.lower()} instead",
413 DeprecationWarning,
414 stacklevel=2,
415 )
416 theme_name = theme_name.lower()
417 if not theme_name:
418 self.theme_name = "nocolor"
419 else:
420 self.theme_name = theme_name
421
422 @property
423 def theme_name(self) -> str:
424 return self._theme_name
425
426 @theme_name.setter
427 def theme_name(self, value: str) -> None:
428 assert value == value.lower()
429 self._theme_name = value
430
431 @property
432 def style(self) -> str:
433 assert False
434 return self._theme_name
435
436 @style.setter
437 def style(self, val: str) -> None:
438 assert False
439 assert val == val.lower()
440 self._theme_name = val
441
442 def format(self, raw: str, out: Any = None) -> str | None:
443 return self.format2(raw, out)[0]
444
445 def format2(self, raw: str, out: Any = None) -> tuple[str | None, bool]:
446 """Parse and send the colored source.
447
448 If out is not specified, the defaults (given to constructor) are used.
449
450 out should be a file-type object. Optionally, out can be given as the
451 string 'str' and the parser will automatically return the output in a
452 string."""
453
454 string_output = 0
455 if out == "str" or self.out == "str" or isinstance(self.out, StringIO):
456 # XXX - I don't really like this state handling logic, but at this
457 # point I don't want to make major changes, so adding the
458 # isinstance() check is the simplest I can do to ensure correct
459 # behavior.
460 out_old = self.out
461 self.out = StringIO()
462 string_output = 1
463 elif out is not None:
464 self.out = out
465 else:
466 raise ValueError(
467 '`out` or `self.out` should be file-like or the value `"str"`'
468 )
469
470 # Fast return of the unmodified input for nocolor scheme
471 # TODO:
472 if self.theme_name == "nocolor":
473 error = False
474 self.out.write(raw)
475 if string_output:
476 return raw, error
477 return None, error
478
479 # local shorthands
480
481 # Remove trailing whitespace and normalize tabs
482 self.raw = raw.expandtabs().rstrip()
483
484 # store line offsets in self.lines
485 self.lines = [0, 0]
486 pos = 0
487 raw_find = self.raw.find
488 lines_append = self.lines.append
489 while True:
490 pos = raw_find("\n", pos) + 1
491 if not pos:
492 break
493 lines_append(pos)
494 lines_append(len(self.raw))
495
496 # parse the source and write it
497 self.pos = 0
498 text = StringIO(self.raw)
499
500 error = False
501 try:
502 for atoken in generate_tokens(text.readline):
503 self(*atoken)
504 except tokenize.TokenError as ex:
505 msg = ex.args[0]
506 line = ex.args[1][0]
507 self.out.write(
508 theme_table[self.theme_name].format(
509 [
510 (Token, "\n\n"),
511 (
512 Token.Error,
513 f"*** ERROR: {msg}{self.raw[self.lines[line] :]}",
514 ),
515 (Token, "\n"),
516 ]
517 )
518 )
519 error = True
520 self.out.write(
521 theme_table[self.theme_name].format(
522 [
523 (Token, "\n"),
524 ]
525 )
526 )
527
528 if string_output:
529 output = self.out.getvalue()
530 self.out = out_old
531 return (output, error)
532 return (None, error)
533
534 def _inner_call_(
535 self, toktype: int, toktext: str, start_pos: tuple[int, int]
536 ) -> str:
537 """like call but write to a temporary buffer"""
538 srow, scol = start_pos
539
540 # calculate new positions
541 oldpos = self.pos
542 newpos = self.lines[srow] + scol
543 self.pos = newpos + len(toktext)
544
545 # send the original whitespace, if needed
546 if newpos > oldpos:
547 acc = self.raw[oldpos:newpos]
548 else:
549 acc = ""
550
551 # skip indenting tokens
552 if toktype in [token.INDENT, token.DEDENT]:
553 self.pos = newpos
554 return acc
555
556 # map token type to a color group
557 if token.LPAR <= toktype <= token.OP:
558 toktype = token.OP
559 elif toktype == token.NAME and keyword.iskeyword(toktext):
560 toktype = _KEYWORD
561 pyg_tok_type = _pygment_token_mapping.get(toktype, Token.Text)
562
563 # send text, pygments should take care of splitting on newline and resending
564 # the correct self.colors after the new line, which is necessary for pagers
565 acc += theme_table[self.theme_name].format([(pyg_tok_type, toktext)])
566 return acc
567
568 def __call__(
569 self,
570 toktype: int,
571 toktext: str,
572 start_pos: tuple[int, int],
573 end_pos: tuple[int, int],
574 line: str,
575 ) -> None:
576 """Token handler, with syntax highlighting."""
577 self.out.write(self._inner_call_(toktype, toktext, start_pos))