forked from Textualize/rich
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconsole.py
2122 lines (1808 loc) · 75.7 KB
/
console.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import inspect
import os
import platform
import shutil
import sys
import threading
from abc import ABC, abstractmethod
from collections import abc
from dataclasses import dataclass, field
from datetime import datetime
from functools import wraps
from getpass import getpass
from inspect import isclass
from itertools import islice
from time import monotonic
from types import FrameType, TracebackType
from typing import (
IO,
TYPE_CHECKING,
Any,
Callable,
Dict,
Iterable,
List,
Mapping,
NamedTuple,
Optional,
TextIO,
Tuple,
Type,
Union,
cast,
)
if sys.version_info >= (3, 8):
from typing import Literal, Protocol, runtime_checkable
else:
from typing_extensions import (
Literal,
Protocol,
runtime_checkable,
) # pragma: no cover
from . import errors, themes
from ._emoji_replace import _emoji_replace
from ._log_render import FormatTimeCallable, LogRender
from .align import Align, AlignMethod
from .color import ColorSystem
from .control import Control
from .emoji import EmojiVariant
from .highlighter import NullHighlighter, ReprHighlighter
from .markup import render as render_markup
from .measure import Measurement, measure_renderables
from .pager import Pager, SystemPager
from .pretty import Pretty, is_expandable
from .region import Region
from .scope import render_scope
from .screen import Screen
from .segment import Segment
from .style import Style, StyleType
from .styled import Styled
from .terminal_theme import DEFAULT_TERMINAL_THEME, TerminalTheme
from .text import Text, TextType
from .theme import Theme, ThemeStack
if TYPE_CHECKING:
from ._windows import WindowsConsoleFeatures
from .live import Live
from .status import Status
WINDOWS = platform.system() == "Windows"
HighlighterType = Callable[[Union[str, "Text"]], "Text"]
JustifyMethod = Literal["default", "left", "center", "right", "full"]
OverflowMethod = Literal["fold", "crop", "ellipsis", "ignore"]
class NoChange:
pass
NO_CHANGE = NoChange()
CONSOLE_HTML_FORMAT = """\
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<style>
{stylesheet}
body {{
color: {foreground};
background-color: {background};
}}
</style>
</head>
<html>
<body>
<code>
<pre style="font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace">{code}</pre>
</code>
</body>
</html>
"""
_TERM_COLORS = {"256color": ColorSystem.EIGHT_BIT, "16color": ColorSystem.STANDARD}
class ConsoleDimensions(NamedTuple):
"""Size of the terminal."""
width: int
"""The width of the console in 'cells'."""
height: int
"""The height of the console in lines."""
@dataclass
class ConsoleOptions:
"""Options for __rich_console__ method."""
size: ConsoleDimensions
"""Size of console."""
legacy_windows: bool
"""legacy_windows: flag for legacy windows."""
min_width: int
"""Minimum width of renderable."""
max_width: int
"""Maximum width of renderable."""
is_terminal: bool
"""True if the target is a terminal, otherwise False."""
encoding: str
"""Encoding of terminal."""
max_height: int
"""Height of container (starts as terminal)"""
justify: Optional[JustifyMethod] = None
"""Justify value override for renderable."""
overflow: Optional[OverflowMethod] = None
"""Overflow value override for renderable."""
no_wrap: Optional[bool] = False
"""Disable wrapping for text."""
highlight: Optional[bool] = None
"""Highlight override for render_str."""
markup: Optional[bool] = None
"""Enable markup when rendering strings."""
height: Optional[int] = None
@property
def ascii_only(self) -> bool:
"""Check if renderables should use ascii only."""
return not self.encoding.startswith("utf")
def copy(self) -> "ConsoleOptions":
"""Return a copy of the options.
Returns:
ConsoleOptions: a copy of self.
"""
options: ConsoleOptions = ConsoleOptions.__new__(ConsoleOptions)
options.__dict__ = self.__dict__.copy()
return options
def update(
self,
*,
width: Union[int, NoChange] = NO_CHANGE,
min_width: Union[int, NoChange] = NO_CHANGE,
max_width: Union[int, NoChange] = NO_CHANGE,
justify: Union[Optional[JustifyMethod], NoChange] = NO_CHANGE,
overflow: Union[Optional[OverflowMethod], NoChange] = NO_CHANGE,
no_wrap: Union[Optional[bool], NoChange] = NO_CHANGE,
highlight: Union[Optional[bool], NoChange] = NO_CHANGE,
markup: Union[Optional[bool], NoChange] = NO_CHANGE,
height: Union[Optional[int], NoChange] = NO_CHANGE,
) -> "ConsoleOptions":
"""Update values, return a copy."""
options = self.copy()
if not isinstance(width, NoChange):
options.min_width = options.max_width = max(0, width)
if not isinstance(min_width, NoChange):
options.min_width = min_width
if not isinstance(max_width, NoChange):
options.max_width = max_width
if not isinstance(justify, NoChange):
options.justify = justify
if not isinstance(overflow, NoChange):
options.overflow = overflow
if not isinstance(no_wrap, NoChange):
options.no_wrap = no_wrap
if not isinstance(highlight, NoChange):
options.highlight = highlight
if not isinstance(markup, NoChange):
options.markup = markup
if not isinstance(height, NoChange):
if height is not None:
options.max_height = height
options.height = None if height is None else max(0, height)
return options
def update_width(self, width: int) -> "ConsoleOptions":
"""Update just the width, return a copy.
Args:
width (int): New width (sets both min_width and max_width)
Returns:
~ConsoleOptions: New console options instance.
"""
options = self.copy()
options.min_width = options.max_width = max(0, width)
return options
def update_dimensions(self, width: int, height: int) -> "ConsoleOptions":
"""Update the width and height, and return a copy.
Args:
width (int): New width (sets both min_width and max_width).
height (int): New height.
Returns:
~ConsoleOptions: New console options instance.
"""
options = self.copy()
options.min_width = options.max_width = max(0, width)
options.height = height
options.max_height = height
return options
@runtime_checkable
class RichCast(Protocol):
"""An object that may be 'cast' to a console renderable."""
def __rich__(self) -> Union["ConsoleRenderable", str]: # pragma: no cover
...
@runtime_checkable
class ConsoleRenderable(Protocol):
"""An object that supports the console protocol."""
def __rich_console__(
self, console: "Console", options: "ConsoleOptions"
) -> "RenderResult": # pragma: no cover
...
RenderableType = Union[ConsoleRenderable, RichCast, str]
"""A type that may be rendered by Console."""
RenderResult = Iterable[Union[RenderableType, Segment]]
"""The result of calling a __rich_console__ method."""
_null_highlighter = NullHighlighter()
class CaptureError(Exception):
"""An error in the Capture context manager."""
class NewLine:
"""A renderable to generate new line(s)"""
def __init__(self, count: int = 1) -> None:
self.count = count
def __rich_console__(
self, console: "Console", options: "ConsoleOptions"
) -> Iterable[Segment]:
yield Segment("\n" * self.count)
class ScreenUpdate:
"""Render a list of lines at a given offset."""
def __init__(self, lines: List[List[Segment]], x: int, y: int) -> None:
self._lines = lines
self.x = x
self.y = y
def __rich_console__(
self, console: "Console", options: ConsoleOptions
) -> RenderResult:
x = self.x
move_to = Control.move_to
for offset, line in enumerate(self._lines, self.y):
yield move_to(x, offset)
yield from line
class Capture:
"""Context manager to capture the result of printing to the console.
See :meth:`~rich.console.Console.capture` for how to use.
Args:
console (Console): A console instance to capture output.
"""
def __init__(self, console: "Console") -> None:
self._console = console
self._result: Optional[str] = None
def __enter__(self) -> "Capture":
self._console.begin_capture()
return self
def __exit__(
self,
exc_type: Optional[Type[BaseException]],
exc_val: Optional[BaseException],
exc_tb: Optional[TracebackType],
) -> None:
self._result = self._console.end_capture()
def get(self) -> str:
"""Get the result of the capture."""
if self._result is None:
raise CaptureError(
"Capture result is not available until context manager exits."
)
return self._result
class ThemeContext:
"""A context manager to use a temporary theme. See :meth:`~rich.console.Console.use_theme` for usage."""
def __init__(self, console: "Console", theme: Theme, inherit: bool = True) -> None:
self.console = console
self.theme = theme
self.inherit = inherit
def __enter__(self) -> "ThemeContext":
self.console.push_theme(self.theme)
return self
def __exit__(
self,
exc_type: Optional[Type[BaseException]],
exc_val: Optional[BaseException],
exc_tb: Optional[TracebackType],
) -> None:
self.console.pop_theme()
class PagerContext:
"""A context manager that 'pages' content. See :meth:`~rich.console.Console.pager` for usage."""
def __init__(
self,
console: "Console",
pager: Optional[Pager] = None,
styles: bool = False,
links: bool = False,
) -> None:
self._console = console
self.pager = SystemPager() if pager is None else pager
self.styles = styles
self.links = links
def __enter__(self) -> "PagerContext":
self._console._enter_buffer()
return self
def __exit__(
self,
exc_type: Optional[Type[BaseException]],
exc_val: Optional[BaseException],
exc_tb: Optional[TracebackType],
) -> None:
if exc_type is None:
with self._console._lock:
buffer: List[Segment] = self._console._buffer[:]
del self._console._buffer[:]
segments: Iterable[Segment] = buffer
if not self.styles:
segments = Segment.strip_styles(segments)
elif not self.links:
segments = Segment.strip_links(segments)
content = self._console._render_buffer(segments)
self.pager.show(content)
self._console._exit_buffer()
class ScreenContext:
"""A context manager that enables an alternative screen. See :meth:`~rich.console.Console.screen` for usage."""
def __init__(
self, console: "Console", hide_cursor: bool, style: StyleType = ""
) -> None:
self.console = console
self.hide_cursor = hide_cursor
self.screen = Screen(style=style)
self._changed = False
def update(
self, *renderables: RenderableType, style: Optional[StyleType] = None
) -> None:
"""Update the screen.
Args:
renderable (RenderableType, optional): Optional renderable to replace current renderable,
or None for no change. Defaults to None.
style: (Style, optional): Replacement style, or None for no change. Defaults to None.
"""
if renderables:
self.screen.renderable = (
Group(*renderables) if len(renderables) > 1 else renderables[0]
)
if style is not None:
self.screen.style = style
self.console.print(self.screen, end="")
def __enter__(self) -> "ScreenContext":
self._changed = self.console.set_alt_screen(True)
if self._changed and self.hide_cursor:
self.console.show_cursor(False)
return self
def __exit__(
self,
exc_type: Optional[Type[BaseException]],
exc_val: Optional[BaseException],
exc_tb: Optional[TracebackType],
) -> None:
if self._changed:
self.console.set_alt_screen(False)
if self.hide_cursor:
self.console.show_cursor(True)
class Group:
"""Takes a group of renderables and returns a renderable object that renders the group.
Args:
renderables (Iterable[RenderableType]): An iterable of renderable objects.
fit (bool, optional): Fit dimension of group to contents, or fill available space. Defaults to True.
"""
def __init__(self, *renderables: "RenderableType", fit: bool = True) -> None:
self._renderables = renderables
self.fit = fit
self._render: Optional[List[RenderableType]] = None
@property
def renderables(self) -> List["RenderableType"]:
if self._render is None:
self._render = list(self._renderables)
return self._render
def __rich_measure__(
self, console: "Console", options: "ConsoleOptions"
) -> "Measurement":
if self.fit:
return measure_renderables(console, options, self.renderables)
else:
return Measurement(options.max_width, options.max_width)
def __rich_console__(
self, console: "Console", options: "ConsoleOptions"
) -> RenderResult:
yield from self.renderables
RenderGroup = Group # TODO: deprecate at some point
def group(fit: bool = True) -> Callable[..., Callable[..., Group]]:
"""A decorator that turns an iterable of renderables in to a group.
Args:
fit (bool, optional): Fit dimension of group to contents, or fill available space. Defaults to True.
"""
def decorator(
method: Callable[..., Iterable[RenderableType]]
) -> Callable[..., Group]:
"""Convert a method that returns an iterable of renderables in to a RenderGroup."""
@wraps(method)
def _replace(*args: Any, **kwargs: Any) -> Group:
renderables = method(*args, **kwargs)
return Group(*renderables, fit=fit)
return _replace
return decorator
render_group = group
def _is_jupyter() -> bool: # pragma: no cover
"""Check if we're running in a Jupyter notebook."""
try:
get_ipython # type: ignore
except NameError:
return False
ipython = get_ipython() # type: ignore
shell = ipython.__class__.__name__
if "google.colab" in str(ipython.__class__) or shell == "ZMQInteractiveShell":
return True # Jupyter notebook or qtconsole
elif shell == "TerminalInteractiveShell":
return False # Terminal running IPython
else:
return False # Other type (?)
COLOR_SYSTEMS = {
"standard": ColorSystem.STANDARD,
"256": ColorSystem.EIGHT_BIT,
"truecolor": ColorSystem.TRUECOLOR,
"windows": ColorSystem.WINDOWS,
}
_COLOR_SYSTEMS_NAMES = {system: name for name, system in COLOR_SYSTEMS.items()}
@dataclass
class ConsoleThreadLocals(threading.local):
"""Thread local values for Console context."""
theme_stack: ThemeStack
buffer: List[Segment] = field(default_factory=list)
buffer_index: int = 0
class RenderHook(ABC):
"""Provides hooks in to the render process."""
@abstractmethod
def process_renderables(
self, renderables: List[ConsoleRenderable]
) -> List[ConsoleRenderable]:
"""Called with a list of objects to render.
This method can return a new list of renderables, or modify and return the same list.
Args:
renderables (List[ConsoleRenderable]): A number of renderable objects.
Returns:
List[ConsoleRenderable]: A replacement list of renderables.
"""
_windows_console_features: Optional["WindowsConsoleFeatures"] = None
def get_windows_console_features() -> "WindowsConsoleFeatures": # pragma: no cover
global _windows_console_features
if _windows_console_features is not None:
return _windows_console_features
from ._windows import get_windows_console_features
_windows_console_features = get_windows_console_features()
return _windows_console_features
def detect_legacy_windows() -> bool:
"""Detect legacy Windows."""
return WINDOWS and not get_windows_console_features().vt
if detect_legacy_windows(): # pragma: no cover
from colorama import init
init(strip=False)
class Console:
"""A high level console interface.
Args:
color_system (str, optional): The color system supported by your terminal,
either ``"standard"``, ``"256"`` or ``"truecolor"``. Leave as ``"auto"`` to autodetect.
force_terminal (Optional[bool], optional): Enable/disable terminal control codes, or None to auto-detect terminal. Defaults to None.
force_jupyter (Optional[bool], optional): Enable/disable Jupyter rendering, or None to auto-detect Jupyter. Defaults to None.
force_interactive (Optional[bool], optional): Enable/disable interactive mode, or None to auto detect. Defaults to None.
soft_wrap (Optional[bool], optional): Set soft wrap default on print method. Defaults to False.
theme (Theme, optional): An optional style theme object, or ``None`` for default theme.
stderr (bool, optional): Use stderr rather than stdout if ``file`` is not specified. Defaults to False.
file (IO, optional): A file object where the console should write to. Defaults to stdout.
quiet (bool, Optional): Boolean to suppress all output. Defaults to False.
width (int, optional): The width of the terminal. Leave as default to auto-detect width.
height (int, optional): The height of the terminal. Leave as default to auto-detect height.
style (StyleType, optional): Style to apply to all output, or None for no style. Defaults to None.
no_color (Optional[bool], optional): Enabled no color mode, or None to auto detect. Defaults to None.
tab_size (int, optional): Number of spaces used to replace a tab character. Defaults to 8.
record (bool, optional): Boolean to enable recording of terminal output,
required to call :meth:`export_html` and :meth:`export_text`. Defaults to False.
markup (bool, optional): Boolean to enable :ref:`console_markup`. Defaults to True.
emoji (bool, optional): Enable emoji code. Defaults to True.
emoji_variant (str, optional): Optional emoji variant, either "text" or "emoji". Defaults to None.
highlight (bool, optional): Enable automatic highlighting. Defaults to True.
log_time (bool, optional): Boolean to enable logging of time by :meth:`log` methods. Defaults to True.
log_path (bool, optional): Boolean to enable the logging of the caller by :meth:`log`. Defaults to True.
log_time_format (Union[str, TimeFormatterCallable], optional): If ``log_time`` is enabled, either string for strftime or callable that formats the time. Defaults to "[%X] ".
highlighter (HighlighterType, optional): Default highlighter.
legacy_windows (bool, optional): Enable legacy Windows mode, or ``None`` to auto detect. Defaults to ``None``.
safe_box (bool, optional): Restrict box options that don't render on legacy Windows.
get_datetime (Callable[[], datetime], optional): Callable that gets the current time as a datetime.datetime object (used by Console.log),
or None for datetime.now.
get_time (Callable[[], time], optional): Callable that gets the current time in seconds, default uses time.monotonic.
"""
_environ: Mapping[str, str] = os.environ
def __init__(
self,
*,
color_system: Optional[
Literal["auto", "standard", "256", "truecolor", "windows"]
] = "auto",
force_terminal: Optional[bool] = None,
force_jupyter: Optional[bool] = None,
force_interactive: Optional[bool] = None,
soft_wrap: bool = False,
theme: Optional[Theme] = None,
stderr: bool = False,
file: Optional[IO[str]] = None,
quiet: bool = False,
width: Optional[int] = None,
height: Optional[int] = None,
style: Optional[StyleType] = None,
no_color: Optional[bool] = None,
tab_size: int = 8,
record: bool = False,
markup: bool = True,
emoji: bool = True,
emoji_variant: Optional[EmojiVariant] = None,
highlight: bool = True,
log_time: bool = True,
log_path: bool = True,
log_time_format: Union[str, FormatTimeCallable] = "[%X]",
highlighter: Optional["HighlighterType"] = ReprHighlighter(),
legacy_windows: Optional[bool] = None,
safe_box: bool = True,
get_datetime: Optional[Callable[[], datetime]] = None,
get_time: Optional[Callable[[], float]] = None,
_environ: Optional[Mapping[str, str]] = None,
):
# Copy of os.environ allows us to replace it for testing
if _environ is not None:
self._environ = _environ
self.is_jupyter = _is_jupyter() if force_jupyter is None else force_jupyter
if self.is_jupyter:
width = width or 93
height = height or 100
if width is None:
columns = self._environ.get("COLUMNS")
if columns is not None and columns.isdigit():
width = int(columns)
if height is None:
lines = self._environ.get("LINES")
if lines is not None and lines.isdigit():
height = int(lines)
self.soft_wrap = soft_wrap
self._width = width
self._height = height
self.tab_size = tab_size
self.record = record
self._markup = markup
self._emoji = emoji
self._emoji_variant = emoji_variant
self._highlight = highlight
self.legacy_windows: bool = (
(detect_legacy_windows() and not self.is_jupyter)
if legacy_windows is None
else legacy_windows
)
self._color_system: Optional[ColorSystem]
self._force_terminal = force_terminal
self._file = file
self.quiet = quiet
self.stderr = stderr
if color_system is None:
self._color_system = None
elif color_system == "auto":
self._color_system = self._detect_color_system()
else:
self._color_system = COLOR_SYSTEMS[color_system]
self._lock = threading.RLock()
self._log_render = LogRender(
show_time=log_time,
show_path=log_path,
time_format=log_time_format,
)
self.highlighter: HighlighterType = highlighter or _null_highlighter
self.safe_box = safe_box
self.get_datetime = get_datetime or datetime.now
self.get_time = get_time or monotonic
self.style = style
self.no_color = (
no_color if no_color is not None else "NO_COLOR" in self._environ
)
self.is_interactive = (
(self.is_terminal and not self.is_dumb_terminal)
if force_interactive is None
else force_interactive
)
self._record_buffer_lock = threading.RLock()
self._thread_locals = ConsoleThreadLocals(
theme_stack=ThemeStack(themes.DEFAULT if theme is None else theme)
)
self._record_buffer: List[Segment] = []
self._render_hooks: List[RenderHook] = []
self._live: Optional["Live"] = None
self._is_alt_screen = False
def __repr__(self) -> str:
return f"<console width={self.width} {str(self._color_system)}>"
@property
def file(self) -> IO[str]:
"""Get the file object to write to."""
file = self._file or (sys.stderr if self.stderr else sys.stdout)
file = getattr(file, "rich_proxied_file", file)
return file
@file.setter
def file(self, new_file: IO[str]) -> None:
"""Set a new file object."""
self._file = new_file
@property
def _buffer(self) -> List[Segment]:
"""Get a thread local buffer."""
return self._thread_locals.buffer
@property
def _buffer_index(self) -> int:
"""Get a thread local buffer."""
return self._thread_locals.buffer_index
@_buffer_index.setter
def _buffer_index(self, value: int) -> None:
self._thread_locals.buffer_index = value
@property
def _theme_stack(self) -> ThemeStack:
"""Get the thread local theme stack."""
return self._thread_locals.theme_stack
def _detect_color_system(self) -> Optional[ColorSystem]:
"""Detect color system from env vars."""
if self.is_jupyter:
return ColorSystem.TRUECOLOR
if not self.is_terminal or self.is_dumb_terminal:
return None
if WINDOWS: # pragma: no cover
if self.legacy_windows: # pragma: no cover
return ColorSystem.WINDOWS
windows_console_features = get_windows_console_features()
return (
ColorSystem.TRUECOLOR
if windows_console_features.truecolor
else ColorSystem.EIGHT_BIT
)
else:
color_term = self._environ.get("COLORTERM", "").strip().lower()
if color_term in ("truecolor", "24bit"):
return ColorSystem.TRUECOLOR
term = self._environ.get("TERM", "").strip().lower()
_term_name, _hyphen, colors = term.partition("-")
color_system = _TERM_COLORS.get(colors, ColorSystem.STANDARD)
return color_system
def _enter_buffer(self) -> None:
"""Enter in to a buffer context, and buffer all output."""
self._buffer_index += 1
def _exit_buffer(self) -> None:
"""Leave buffer context, and render content if required."""
self._buffer_index -= 1
self._check_buffer()
def set_live(self, live: "Live") -> None:
"""Set Live instance. Used by Live context manager.
Args:
live (Live): Live instance using this Console.
Raises:
errors.LiveError: If this Console has a Live context currently active.
"""
with self._lock:
if self._live is not None:
raise errors.LiveError("Only one live display may be active at once")
self._live = live
def clear_live(self) -> None:
"""Clear the Live instance."""
with self._lock:
self._live = None
def push_render_hook(self, hook: RenderHook) -> None:
"""Add a new render hook to the stack.
Args:
hook (RenderHook): Render hook instance.
"""
self._render_hooks.append(hook)
def pop_render_hook(self) -> None:
"""Pop the last renderhook from the stack."""
self._render_hooks.pop()
def __enter__(self) -> "Console":
"""Own context manager to enter buffer context."""
self._enter_buffer()
return self
def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None:
"""Exit buffer context."""
self._exit_buffer()
def begin_capture(self) -> None:
"""Begin capturing console output. Call :meth:`end_capture` to exit capture mode and return output."""
self._enter_buffer()
def end_capture(self) -> str:
"""End capture mode and return captured string.
Returns:
str: Console output.
"""
render_result = self._render_buffer(self._buffer)
del self._buffer[:]
self._exit_buffer()
return render_result
def push_theme(self, theme: Theme, *, inherit: bool = True) -> None:
"""Push a new theme on to the top of the stack, replacing the styles from the previous theme.
Generally speaking, you should call :meth:`~rich.console.Console.use_theme` to get a context manager, rather
than calling this method directly.
Args:
theme (Theme): A theme instance.
inherit (bool, optional): Inherit existing styles. Defaults to True.
"""
self._theme_stack.push_theme(theme, inherit=inherit)
def pop_theme(self) -> None:
"""Remove theme from top of stack, restoring previous theme."""
self._theme_stack.pop_theme()
def use_theme(self, theme: Theme, *, inherit: bool = True) -> ThemeContext:
"""Use a different theme for the duration of the context manager.
Args:
theme (Theme): Theme instance to user.
inherit (bool, optional): Inherit existing console styles. Defaults to True.
Returns:
ThemeContext: [description]
"""
return ThemeContext(self, theme, inherit)
@property
def color_system(self) -> Optional[str]:
"""Get color system string.
Returns:
Optional[str]: "standard", "256" or "truecolor".
"""
if self._color_system is not None:
return _COLOR_SYSTEMS_NAMES[self._color_system]
else:
return None
@property
def encoding(self) -> str:
"""Get the encoding of the console file, e.g. ``"utf-8"``.
Returns:
str: A standard encoding string.
"""
return (getattr(self.file, "encoding", "utf-8") or "utf-8").lower()
@property
def is_terminal(self) -> bool:
"""Check if the console is writing to a terminal.
Returns:
bool: True if the console writing to a device capable of
understanding terminal codes, otherwise False.
"""
if self._force_terminal is not None:
return self._force_terminal
isatty: Optional[Callable[[], bool]] = getattr(self.file, "isatty", None)
return False if isatty is None else isatty()
@property
def is_dumb_terminal(self) -> bool:
"""Detect dumb terminal.
Returns:
bool: True if writing to a dumb terminal, otherwise False.
"""
_term = self._environ.get("TERM", "")
is_dumb = _term.lower() in ("dumb", "unknown")
return self.is_terminal and is_dumb
@property
def options(self) -> ConsoleOptions:
"""Get default console options."""
return ConsoleOptions(
max_height=self.size.height,
size=self.size,
legacy_windows=self.legacy_windows,
min_width=1,
max_width=self.width,
encoding=self.encoding,
is_terminal=self.is_terminal,
)
@property
def size(self) -> ConsoleDimensions:
"""Get the size of the console.
Returns:
ConsoleDimensions: A named tuple containing the dimensions.
"""
if self._width is not None and self._height is not None:
return ConsoleDimensions(self._width, self._height)
if self.is_dumb_terminal:
return ConsoleDimensions(80, 25)
width: Optional[int] = None
height: Optional[int] = None
if WINDOWS: # pragma: no cover
width, height = shutil.get_terminal_size()
else:
try:
width, height = os.get_terminal_size(sys.__stdin__.fileno())
except (AttributeError, ValueError, OSError):
try:
width, height = os.get_terminal_size(sys.__stdout__.fileno())
except (AttributeError, ValueError, OSError):
pass
# get_terminal_size can report 0, 0 if run from pseudo-terminal
width = width or 80
height = height or 25
return ConsoleDimensions(
(width - self.legacy_windows) if self._width is None else self._width,
height if self._height is None else self._height,
)
@size.setter
def size(self, new_size: Tuple[int, int]) -> None:
"""Set a new size for the terminal.
Args:
new_size (Tuple[int, int]): New width and height.
"""
width, height = new_size
self._width = width
self._height = height
@property
def width(self) -> int:
"""Get the width of the console.
Returns:
int: The width (in characters) of the console.
"""
return self.size.width
@width.setter
def width(self, width: int) -> None:
"""Set width.
Args:
width (int): New width.
"""
self._width = width
@property
def height(self) -> int:
"""Get the height of the console.
Returns:
int: The height (in lines) of the console.
"""
return self.size.height