From 75c646288a51eee5ced2a6cd5b0e078e99ce4b1b Mon Sep 17 00:00:00 2001 From: Jonathan Eunice Date: Thu, 29 Dec 2022 09:13:26 -0500 Subject: [PATCH 01/62] fix table rendering order of box elements * Previously "mid" box elements appeared in last line of table (footer), while "footer" box elements appeared mid table body. Reversed that order so mid is truly mid, footer is truly footer. * Tested with: ``` table.box.head_left = '1' table.box.head_vertical = '2' table.box.head_right = '3' table.box.mid_left = '4' table.box.mid_vertical = '5' table.box.mid_right = '6' table.box.foot_left = '7' table.box.foot_vertical = '8' table.box.foot_right = '9' ``` After change, correct ordering: ``` +--------------------------------------------------------------------------+ 1Date 2Title 2 Production2 Box Office3 |------------ --------------------------------- ------------ --------------| 4Dec 20, 20195Star Wars: The Rise of Skywalker 5$275,000,0005 $375,126,1186 4May 25, 20185Solo: A Star Wars Story 5$275,000,0005 $393,151,3476 7Dec 15, 20178Star Wars Ep. VIII: The Last Jedi8$262,000,0008$1,332,539,8899 +--------------------------------------------------------------------------+ ``` --- CHANGELOG.md | 1 + CONTRIBUTORS.md | 1 + rich/table.py | 10 +++++----- 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d294dc71..1fbf3b25 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Reversed `pre` and `code` tags in base HTML format https://github.com/Textualize/rich/pull/2642 - Improved detection of `attrs` library, that isn't confused by the presence of the `attr` library. +- Fixed `Table` rendering of box elements so "footer" elements truly appear at bottom of table, "mid" elements in main table body. ### Changed diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 7e61d010..eef0bda6 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -12,6 +12,7 @@ The following people have contributed to the development of Rich: - [Ed Davis](https://github.com/davised) - [Pete Davison](https://github.com/pd93) - [James Estevez](https://github.com/jstvz) +- [Jonathan Eunice](https://github.com/jonathan-3play) - [Oleksis Fraga](https://github.com/oleksis) - [Andy Gimblett](https://github.com/gimbo) - [Michał Górny](https://github.com/mgorny) diff --git a/rich/table.py b/rich/table.py index 578d3d63..cffb5e9e 100644 --- a/rich/table.py +++ b/rich/table.py @@ -777,16 +777,16 @@ class Table(JupyterMixin): _Segment(_box.head_right, border_style), _Segment(_box.head_vertical, border_style), ), - ( - _Segment(_box.foot_left, border_style), - _Segment(_box.foot_right, border_style), - _Segment(_box.foot_vertical, border_style), - ), ( _Segment(_box.mid_left, border_style), _Segment(_box.mid_right, border_style), _Segment(_box.mid_vertical, border_style), ), + ( + _Segment(_box.foot_left, border_style), + _Segment(_box.foot_right, border_style), + _Segment(_box.foot_vertical, border_style), + ), ] if show_edge: yield _Segment(_box.get_top(widths), border_style) From f58279a53539736665d185352fa958c8fb00252a Mon Sep 17 00:00:00 2001 From: Jonathan Eunice Date: Fri, 30 Dec 2022 09:51:01 -0500 Subject: [PATCH 02/62] added automated test --- tests/test_table.py | 129 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 129 insertions(+) diff --git a/tests/test_table.py b/tests/test_table.py index 4faf9d53..ee79991d 100644 --- a/tests/test_table.py +++ b/tests/test_table.py @@ -1,6 +1,7 @@ # encoding=utf-8 import io +from textwrap import dedent import pytest @@ -235,6 +236,134 @@ def test_section(): assert output == expected +@pytest.mark.parametrize( + "show_header,show_footer,expected", + [ + ( + False, + False, + dedent( + """ + abbbbbcbbbbbbbbbcbbbbcbbbbbd + 1Dec 2Skywalker2275M2375M 3 + 4May 5Solo 5275M5393M 6 + ijjjjjkjjjjjjjjjkjjjjkjjjjjl + 7Dec 8Last Jedi8262M81333M9 + qrrrrrsrrrrrrrrrsrrrrsrrrrrt + """ + ).lstrip(), + ), + ( + True, + False, + dedent( + """ + abbbbbcbbbbbbbbbcbbbbcbbbbbd + 1Month2Nickname 2Cost2Gross3 + efffffgfffffffffgffffgfffffh + 4Dec 5Skywalker5275M5375M 6 + 4May 5Solo 5275M5393M 6 + ijjjjjkjjjjjjjjjkjjjjkjjjjjl + 7Dec 8Last Jedi8262M81333M9 + qrrrrrsrrrrrrrrrsrrrrsrrrrrt + """ + ).lstrip(), + ), + ( + False, + True, + dedent( + """ + abbbbbcbbbbbbbbbcbbbbcbbbbbd + 1Dec 2Skywalker2275M2375M 3 + 4May 5Solo 5275M5393M 6 + ijjjjjkjjjjjjjjjkjjjjkjjjjjl + 4Dec 5Last Jedi5262M51333M6 + mnnnnnonnnnnnnnnonnnnonnnnnp + 7MONTH8NICKNAME 8COST8GROSS9 + qrrrrrsrrrrrrrrrsrrrrsrrrrrt + """ + ).lstrip(), + ), + ( + True, + True, + dedent( + """ + abbbbbcbbbbbbbbbcbbbbcbbbbbd + 1Month2Nickname 2Cost2Gross3 + efffffgfffffffffgffffgfffffh + 4Dec 5Skywalker5275M5375M 6 + 4May 5Solo 5275M5393M 6 + ijjjjjkjjjjjjjjjkjjjjkjjjjjl + 4Dec 5Last Jedi5262M51333M6 + mnnnnnonnnnnnnnnonnnnonnnnnp + 7MONTH8NICKNAME 8COST8GROSS9 + qrrrrrsrrrrrrrrrsrrrrsrrrrrt + """ + ).lstrip(), + ), + ], +) +def test_placement_table_box_elements(show_header, show_footer, expected): + """Ensure box drawing characters correctly positioned.""" + + table = Table( + box=box.ASCII, show_header=show_header, show_footer=show_footer, padding=0 + ) + + # content rows indicated by numerals, pure dividers by letters + table.box.__dict__.update( + top_left="a", + top="b", + top_divider="c", + top_right="d", + head_left="1", + head_vertical="2", + head_right="3", + head_row_left="e", + head_row_horizontal="f", + head_row_cross="g", + head_row_right="h", + mid_left="4", + mid_vertical="5", + mid_right="6", + row_left="i", + row_horizontal="j", + row_cross="k", + row_right="l", + foot_left="7", + foot_vertical="8", + foot_right="9", + foot_row_left="m", + foot_row_horizontal="n", + foot_row_cross="o", + foot_row_right="p", + bottom_left="q", + bottom="r", + bottom_divider="s", + bottom_right="t", + ) + + # add content - note headers title case, footers upper case + table.add_column("Month", "MONTH", width=5) + table.add_column("Nickname", "NICKNAME", width=9) + table.add_column("Cost", "COST", width=4) + table.add_column("Gross", "GROSS", width=5) + + table.add_row("Dec", "Skywalker", "275M", "375M") + table.add_row("May", "Solo", "275M", "393M") + table.add_section() + table.add_row("Dec", "Last Jedi", "262M", "1333M") + + console = Console(record=True, width=28) + console.print(table) + output = console.export_text() + print(repr(output)) + + assert output == expected + + if __name__ == "__main__": render = render_tables() print(render) From f65770dd0d661792b9ab21ce08e3e2cce3577eae Mon Sep 17 00:00:00 2001 From: Andre Hora Date: Mon, 30 Jan 2023 15:38:10 -0300 Subject: [PATCH 03/62] improving test_box_substitute to cover more inputs of substitute() --- tests/test_box.py | 33 ++++++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/tests/test_box.py b/tests/test_box.py index 21ba4fd0..9c6a6499 100644 --- a/tests/test_box.py +++ b/tests/test_box.py @@ -1,7 +1,19 @@ import pytest from rich.console import ConsoleOptions, ConsoleDimensions -from rich.box import ASCII, DOUBLE, ROUNDED, HEAVY, SQUARE +from rich.box import ( + ASCII, + DOUBLE, + ROUNDED, + HEAVY, + SQUARE, + MINIMAL_HEAVY_HEAD, + MINIMAL, + SIMPLE_HEAVY, + SIMPLE, + HEAVY_EDGE, + HEAVY_HEAD, +) def test_str(): @@ -46,10 +58,29 @@ def test_box_substitute(): encoding="utf-8", max_height=25, ) + + # A different Box due to legacy_windows + assert ROUNDED.substitute(options) == SQUARE + assert MINIMAL_HEAVY_HEAD.substitute(options) == MINIMAL + assert SIMPLE_HEAVY.substitute(options) == SIMPLE assert HEAVY.substitute(options) == SQUARE + assert HEAVY_EDGE.substitute(options) == SQUARE + assert HEAVY_HEAD.substitute(options) == SQUARE + # The same box options.legacy_windows = False + assert ROUNDED.substitute(options) == ROUNDED + assert MINIMAL_HEAVY_HEAD.substitute(options) == MINIMAL_HEAVY_HEAD + assert SIMPLE_HEAVY.substitute(options) == SIMPLE_HEAVY assert HEAVY.substitute(options) == HEAVY + assert HEAVY_EDGE.substitute(options) == HEAVY_EDGE + assert HEAVY_HEAD.substitute(options) == HEAVY_HEAD + # A different Box due to ascii encoding options.encoding = "ascii" + assert ROUNDED.substitute(options) == ASCII + assert MINIMAL_HEAVY_HEAD.substitute(options) == ASCII + assert SIMPLE_HEAVY.substitute(options) == ASCII assert HEAVY.substitute(options) == ASCII + assert HEAVY_EDGE.substitute(options) == ASCII + assert HEAVY_HEAD.substitute(options) == ASCII From 23a3f9e6206de831c4caa51841d0af9b1427a106 Mon Sep 17 00:00:00 2001 From: Andre Hora Date: Mon, 30 Jan 2023 17:55:20 -0300 Subject: [PATCH 04/62] refactoring test_box_substitute: smaller and focused tests are better than large ones --- tests/test_box.py | 43 +++++++++++++++++++++++++++++++------------ 1 file changed, 31 insertions(+), 12 deletions(-) diff --git a/tests/test_box.py b/tests/test_box.py index 9c6a6499..6d02f7b7 100644 --- a/tests/test_box.py +++ b/tests/test_box.py @@ -48,7 +48,26 @@ def test_get_bottom(): assert bottom == "┗━┻━━┻━━━┛" -def test_box_substitute(): +def test_box_substitute_for_same_box(): + options = ConsoleOptions( + ConsoleDimensions(80, 25), + legacy_windows=False, + min_width=1, + max_width=100, + is_terminal=True, + encoding="utf-8", + max_height=25, + ) + + assert ROUNDED.substitute(options) == ROUNDED + assert MINIMAL_HEAVY_HEAD.substitute(options) == MINIMAL_HEAVY_HEAD + assert SIMPLE_HEAVY.substitute(options) == SIMPLE_HEAVY + assert HEAVY.substitute(options) == HEAVY + assert HEAVY_EDGE.substitute(options) == HEAVY_EDGE + assert HEAVY_HEAD.substitute(options) == HEAVY_HEAD + + +def test_box_substitute_for_different_box_legacy_windows(): options = ConsoleOptions( ConsoleDimensions(80, 25), legacy_windows=True, @@ -59,7 +78,6 @@ def test_box_substitute(): max_height=25, ) - # A different Box due to legacy_windows assert ROUNDED.substitute(options) == SQUARE assert MINIMAL_HEAVY_HEAD.substitute(options) == MINIMAL assert SIMPLE_HEAVY.substitute(options) == SIMPLE @@ -67,17 +85,18 @@ def test_box_substitute(): assert HEAVY_EDGE.substitute(options) == SQUARE assert HEAVY_HEAD.substitute(options) == SQUARE - # The same box - options.legacy_windows = False - assert ROUNDED.substitute(options) == ROUNDED - assert MINIMAL_HEAVY_HEAD.substitute(options) == MINIMAL_HEAVY_HEAD - assert SIMPLE_HEAVY.substitute(options) == SIMPLE_HEAVY - assert HEAVY.substitute(options) == HEAVY - assert HEAVY_EDGE.substitute(options) == HEAVY_EDGE - assert HEAVY_HEAD.substitute(options) == HEAVY_HEAD - # A different Box due to ascii encoding - options.encoding = "ascii" +def test_box_substitute_for_different_box_ascii_encoding(): + options = ConsoleOptions( + ConsoleDimensions(80, 25), + legacy_windows=True, + min_width=1, + max_width=100, + is_terminal=True, + encoding="ascii", + max_height=25, + ) + assert ROUNDED.substitute(options) == ASCII assert MINIMAL_HEAVY_HEAD.substitute(options) == ASCII assert SIMPLE_HEAVY.substitute(options) == ASCII From 2a33a77eb78298cbed2ec0e4d9b007510caa882f Mon Sep 17 00:00:00 2001 From: Alex Date: Mon, 6 Mar 2023 09:51:51 +0100 Subject: [PATCH 05/62] Update "logging.level.warning" to yellow" --- CHANGELOG.md | 6 ++++++ rich/default_styles.py | 2 +- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 63d6f5e5..2640defc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,12 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## Unreleased + +### Fixed + +- `RichHandler` errors and warnings will now use different colors (red and yellow) https://github.com/Textualize/rich/issues/2825 + ## [13.3.2] - 2023-02-04 ### Fixed diff --git a/rich/default_styles.py b/rich/default_styles.py index ad72fff5..031b94a1 100644 --- a/rich/default_styles.py +++ b/rich/default_styles.py @@ -54,7 +54,7 @@ DEFAULT_STYLES: Dict[str, Style] = { "logging.level.notset": Style(dim=True), "logging.level.debug": Style(color="green"), "logging.level.info": Style(color="blue"), - "logging.level.warning": Style(color="red"), + "logging.level.warning": Style(color="yellow"), "logging.level.error": Style(color="red", bold=True), "logging.level.critical": Style(color="red", bold=True, reverse=True), "log.level": Style.null(), From fd77a473f622fbbf479b363db62b4d2a540d79dc Mon Sep 17 00:00:00 2001 From: Xuehai Pan Date: Tue, 7 Mar 2023 10:01:26 +0000 Subject: [PATCH 06/62] fix: fix get braces for `deque` --- rich/pretty.py | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/rich/pretty.py b/rich/pretty.py index fd12885b..d81711e7 100644 --- a/rich/pretty.py +++ b/rich/pretty.py @@ -15,6 +15,7 @@ from typing import ( Any, Callable, DefaultDict, + Deque, Dict, Iterable, List, @@ -352,6 +353,12 @@ def _get_braces_for_defaultdict(_object: DefaultDict[Any, Any]) -> Tuple[str, st ) +def _get_braces_for_deque(_object: Deque[Any]) -> Tuple[str, str, str]: + if _object.maxlen is None: + return ("deque([", "])", "deque()") + return ("deque([", f"], maxlen={_object.maxlen})", f"deque(maxlen={_object.maxlen})") + + def _get_braces_for_array(_object: "array[Any]") -> Tuple[str, str, str]: return (f"array({_object.typecode!r}, [", "])", f"array({_object.typecode!r})") @@ -361,7 +368,7 @@ _BRACES: Dict[type, Callable[[Any], Tuple[str, str, str]]] = { array: _get_braces_for_array, defaultdict: _get_braces_for_defaultdict, Counter: lambda _object: ("Counter({", "})", "Counter()"), - deque: lambda _object: ("deque([", "])", "deque()"), + deque: _get_braces_for_deque, dict: lambda _object: ("{", "}", "{}"), UserDict: lambda _object: ("{", "}", "{}"), frozenset: lambda _object: ("frozenset({", "})", "frozenset()"), From 02557dcbc38c5e0e2ba381b7ecb0ce26b138494a Mon Sep 17 00:00:00 2001 From: Xuehai Pan Date: Tue, 7 Mar 2023 10:07:35 +0000 Subject: [PATCH 07/62] test: add `test_deque` for `pretty_repr` --- tests/test_pretty.py | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/tests/test_pretty.py b/tests/test_pretty.py index c3f7967b..0edc60b2 100644 --- a/tests/test_pretty.py +++ b/tests/test_pretty.py @@ -2,7 +2,7 @@ import collections import io import sys from array import array -from collections import UserDict, defaultdict +from collections import UserDict, defaultdict, deque from dataclasses import dataclass, field from typing import Any, List, NamedTuple @@ -488,6 +488,33 @@ def test_defaultdict(): assert result == "defaultdict(, {'foo': 2})" +def test_deque(): + test_deque = deque([1, 2, 3]) + result = pretty_repr(test_deque) + assert result == "deque([1, 2, 3])" + test_deque = deque([1, 2, 3], maxlen=None) + result = pretty_repr(test_deque) + assert result == "deque([1, 2, 3])" + test_deque = deque([1, 2, 3], maxlen=5) + result = pretty_repr(test_deque) + assert result == "deque([1, 2, 3], maxlen=5)" + test_deque = deque([1, 2, 3], maxlen=0) + result = pretty_repr(test_deque) + assert result == "deque([], maxlen=0)" + test_deque = deque([]) + result = pretty_repr(test_deque) + assert result == "deque([])" + test_deque = deque([], maxlen=None) + result = pretty_repr(test_deque) + assert result == "deque([])" + test_deque = deque([], maxlen=5) + result = pretty_repr(test_deque) + assert result == "deque([], maxlen=5)" + test_deque = deque([], maxlen=0) + result = pretty_repr(test_deque) + assert result == "deque([], maxlen=0)" + + def test_array(): test_array = array("I", [1, 2, 3]) result = pretty_repr(test_array) From 4d32ac689ccb528b106a003c554bf350dc9073cf Mon Sep 17 00:00:00 2001 From: Xuehai Pan Date: Tue, 7 Mar 2023 10:13:39 +0000 Subject: [PATCH 08/62] docs(CHANGELOG): update CHANGELOG.md --- CHANGELOG.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 63d6f5e5..962916dc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,12 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## Unreleased + +### Fixed + +- Fix pretty repr for `collections.deque` https://github.com/Textualize/rich/pull/2864 + ## [13.3.2] - 2023-02-04 ### Fixed @@ -41,7 +47,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Fixed failing tests due to Pygments dependency https://github.com/Textualize/rich/issues/2757 - Relaxed ipywidgets https://github.com/Textualize/rich/issues/2767 -### Added +### Added - Added `encoding` parameter in `Theme.read` From 680d9d876e561f1e1ad511fcfe5f5f793a40bc2f Mon Sep 17 00:00:00 2001 From: Ceyda Cinarel <15624271+cceyda@users.noreply.github.com> Date: Wed, 8 Mar 2023 18:53:32 +0900 Subject: [PATCH 09/62] fix empty line print on jupyter --- CHANGELOG.md | 3 +++ CONTRIBUTORS.md | 1 + rich/progress.py | 2 +- 3 files changed, 5 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 63d6f5e5..be46f3b7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,9 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [Unreleased] + +- Removed the empty line printed in jupyter while using `Progress` https://github.com/Textualize/rich/pull/2616 ## [13.3.2] - 2023-02-04 diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 397fb8f0..69a2094c 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -9,6 +9,7 @@ The following people have contributed to the development of Rich: - [Artur Borecki](https://github.com/pufereq) - [Dennis Brakhane](https://github.com/brakhane) - [Darren Burns](https://github.com/darrenburns) +- [Ceyda Cinarel](https://github.com/cceyda) - [Jim Crist-Harif](https://github.com/jcrist) - [Ed Davis](https://github.com/davised) - [Pete Davison](https://github.com/pd93) diff --git a/rich/progress.py b/rich/progress.py index 43c47eb9..2a20e735 100644 --- a/rich/progress.py +++ b/rich/progress.py @@ -1162,7 +1162,7 @@ class Progress(JupyterMixin): def stop(self) -> None: """Stop the progress display.""" self.live.stop() - if not self.console.is_interactive: + if not self.console.is_interactive and not self.console.is_jupyter: self.console.print() def __enter__(self) -> "Progress": From 5104bf283e7ceab3e28e9915bb3231ef064113fc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=9D=B4=EC=B0=BD=ED=98=B8?= Date: Thu, 9 Mar 2023 15:33:21 +0900 Subject: [PATCH 10/62] add code_width in traceback --- rich/logging.py | 4 ++++ rich/traceback.py | 11 ++++++++++- 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/rich/logging.py b/rich/logging.py index 96859934..2e97fa16 100644 --- a/rich/logging.py +++ b/rich/logging.py @@ -36,6 +36,7 @@ class RichHandler(Handler): markup (bool, optional): Enable console markup in log messages. Defaults to False. rich_tracebacks (bool, optional): Enable rich tracebacks with syntax highlighting and formatting. Defaults to False. tracebacks_width (Optional[int], optional): Number of characters used to render tracebacks, or None for full width. Defaults to None. + tracebacks_code_width (int, optional): Number of code characters used to render tracebacks, or None for full width. Defaults to 88. tracebacks_extra_lines (int, optional): Additional lines of code to render tracebacks, or None for full width. Defaults to None. tracebacks_theme (str, optional): Override pygments theme used in traceback. tracebacks_word_wrap (bool, optional): Enable word wrapping of long tracebacks lines. Defaults to True. @@ -74,6 +75,7 @@ class RichHandler(Handler): markup: bool = False, rich_tracebacks: bool = False, tracebacks_width: Optional[int] = None, + tracebacks_code_width: int = 88, tracebacks_extra_lines: int = 3, tracebacks_theme: Optional[str] = None, tracebacks_word_wrap: bool = True, @@ -104,6 +106,7 @@ class RichHandler(Handler): self.tracebacks_word_wrap = tracebacks_word_wrap self.tracebacks_show_locals = tracebacks_show_locals self.tracebacks_suppress = tracebacks_suppress + self.tracebacks_code_width = tracebacks_code_width self.locals_max_length = locals_max_length self.locals_max_string = locals_max_string self.keywords = keywords @@ -140,6 +143,7 @@ class RichHandler(Handler): exc_value, exc_traceback, width=self.tracebacks_width, + code_width=self.tracebacks_code_width, extra_lines=self.tracebacks_extra_lines, theme=self.tracebacks_theme, word_wrap=self.tracebacks_word_wrap, diff --git a/rich/traceback.py b/rich/traceback.py index 341f7f41..4a437af7 100644 --- a/rich/traceback.py +++ b/rich/traceback.py @@ -49,6 +49,7 @@ def install( *, console: Optional[Console] = None, width: Optional[int] = 100, + code_width: Optional[int] = 88, extra_lines: int = 3, theme: Optional[str] = None, word_wrap: bool = False, @@ -69,6 +70,7 @@ def install( Args: console (Optional[Console], optional): Console to write exception to. Default uses internal Console instance. width (Optional[int], optional): Width (in characters) of traceback. Defaults to 100. + code_width (Optional[int], optional): Code width (in characters) of traceback. Defaults to 88. extra_lines (int, optional): Extra lines of code. Defaults to 3. theme (Optional[str], optional): Pygments theme to use in traceback. Defaults to ``None`` which will pick a theme appropriate for the platform. @@ -105,6 +107,7 @@ def install( value, traceback, width=width, + code_width=code_width, extra_lines=extra_lines, theme=theme, word_wrap=word_wrap, @@ -215,6 +218,7 @@ class Traceback: trace (Trace, optional): A `Trace` object produced from `extract`. Defaults to None, which uses the last exception. width (Optional[int], optional): Number of characters used to traceback. Defaults to 100. + code_width (Optional[int], optional): Number of code characters used to traceback. Defaults to 88. extra_lines (int, optional): Additional lines of code to render. Defaults to 3. theme (str, optional): Override pygments theme used in traceback. word_wrap (bool, optional): Enable word wrapping of long lines. Defaults to False. @@ -243,6 +247,7 @@ class Traceback: trace: Optional[Trace] = None, *, width: Optional[int] = 100, + code_width: Optional[int] = 88, extra_lines: int = 3, theme: Optional[str] = None, word_wrap: bool = False, @@ -266,6 +271,7 @@ class Traceback: ) self.trace = trace self.width = width + self.code_width = code_width self.extra_lines = extra_lines self.theme = Syntax.get_theme(theme or "ansi_dark") self.word_wrap = word_wrap @@ -297,6 +303,7 @@ class Traceback: traceback: Optional[TracebackType], *, width: Optional[int] = 100, + code_width: Optional[int] = 88, extra_lines: int = 3, theme: Optional[str] = None, word_wrap: bool = False, @@ -316,6 +323,7 @@ class Traceback: exc_value (BaseException): Exception value. traceback (TracebackType): Python Traceback object. width (Optional[int], optional): Number of characters used to traceback. Defaults to 100. + code_width (Optional[int], optional): Number of code characters used to traceback. Defaults to 88. extra_lines (int, optional): Additional lines of code to render. Defaults to 3. theme (str, optional): Override pygments theme used in traceback. word_wrap (bool, optional): Enable word wrapping of long lines. Defaults to False. @@ -346,6 +354,7 @@ class Traceback: return cls( rich_traceback, width=width, + code_width=code_width, extra_lines=extra_lines, theme=theme, word_wrap=word_wrap, @@ -696,7 +705,7 @@ class Traceback: ), highlight_lines={frame.lineno}, word_wrap=self.word_wrap, - code_width=88, + code_width=self.code_width, indent_guides=self.indent_guides, dedent=False, ) From e9c9e434203e936bbc9502396d43c80321560acd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rodrigo=20Gir=C3=A3o=20Serr=C3=A3o?= <5621605+rodrigogiraoserrao@users.noreply.github.com> Date: Fri, 28 Apr 2023 11:46:52 +0100 Subject: [PATCH 11/62] Clear hashed cache when clearing meta. Related issues: #2942 --- CHANGELOG.md | 7 +++++++ rich/style.py | 2 +- tests/test_style.py | 14 ++++++++++++++ 3 files changed, 22 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1792061d..15541edb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,13 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## Unreleased + +### Fixed + +- Fixed cached hash preservation upon clearing meta and links https://github.com/Textualize/rich/issues/2942 + ## [13.3.5] - 2023-04-27 ### Fixed diff --git a/rich/style.py b/rich/style.py index 313c8894..262fd6ec 100644 --- a/rich/style.py +++ b/rich/style.py @@ -663,7 +663,7 @@ class Style: style._set_attributes = self._set_attributes style._link = None style._link_id = "" - style._hash = self._hash + style._hash = None style._null = False style._meta = None return style diff --git a/tests/test_style.py b/tests/test_style.py index b5c01729..84a65a67 100644 --- a/tests/test_style.py +++ b/tests/test_style.py @@ -251,3 +251,17 @@ def test_clear_meta_and_links(): assert clear_style.bgcolor == Color.parse("black") assert clear_style.bold assert not clear_style.italic + + +def test_clear_meta_and_links_clears_hash(): + """Regression test for https://github.com/Textualize/rich/issues/2942.""" + + style = Style.parse("bold red on black link https://example.org") + Style.on( + click="CLICK" + ) + hash(style) # Force hash caching. + + assert style._hash is not None + + clear_style = style.clear_meta_and_links() + assert clear_style._hash is None From bff145f9aa16426fd1ae6bb679fd9b249b846104 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rodrigo=20Gir=C3=A3o=20Serr=C3=A3o?= <5621605+rodrigogiraoserrao@users.noreply.github.com> Date: Fri, 28 Apr 2023 11:48:40 +0100 Subject: [PATCH 12/62] Retroactively make CI happy. --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 15541edb..841ce77e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,7 +16,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Fixed italic indent guides in SVG ouput +- Fixed italic indent guides in SVG output ## [13.3.4] - 2023-04-12 From bf3c7c30368b8fb87e88469e65f3b2b7f5671c57 Mon Sep 17 00:00:00 2001 From: Jason Novinger Date: Thu, 1 Jun 2023 10:55:00 -0500 Subject: [PATCH 13/62] Fix release month for 13.4.0 & 13.4.1 --- CHANGELOG.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 974d2801..60d5b529 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,13 +5,13 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). -## [13.4.1] - 2023-06-31 +## [13.4.1] - 2023-05-31 ### Fixed - Fixed typing extensions import in markdown https://github.com/Textualize/rich/issues/2979 -## [13.4.0] - 2023-06-31 +## [13.4.0] - 2023-05-31 ### Added From 91b6e94a592b55d622ec7d913f76773be6fc654c Mon Sep 17 00:00:00 2001 From: zach valenta Date: Fri, 23 Jun 2023 09:57:19 -0400 Subject: [PATCH 14/62] rm broken links from README --- README.md | 8 -------- 1 file changed, 8 deletions(-) diff --git a/README.md b/README.md index f76def1b..3078de83 100644 --- a/README.md +++ b/README.md @@ -437,11 +437,3 @@ See also [Rich CLI](https://github.com/textualize/rich-cli) for a command line a See also Rich's sister project, [Textual](https://github.com/Textualize/textual), which you can use to build sophisticated User Interfaces in the terminal. ![Textual screenshot](https://raw.githubusercontent.com/Textualize/textual/main/imgs/textual.png) - -# Projects using Rich - -For some examples of projects using Rich, see the [Rich Gallery](https://www.textualize.io/rich/gallery) on [Textualize.io](https://www.textualize.io). - -Would you like to add your own project to the gallery? You can! Follow [these instructions](https://www.textualize.io/gallery-instructions). - - From 895464fee97f36a166dfc25fa57ef213b62ece64 Mon Sep 17 00:00:00 2001 From: Grant Ramsay Date: Fri, 30 Jun 2023 19:54:29 +0100 Subject: [PATCH 15/62] add 'case_insensitive' option to Prompt --- rich/prompt.py | 30 +++++++++++++++++++++++++++--- 1 file changed, 27 insertions(+), 3 deletions(-) diff --git a/rich/prompt.py b/rich/prompt.py index 064c959b..b23762ce 100644 --- a/rich/prompt.py +++ b/rich/prompt.py @@ -36,6 +36,7 @@ class PromptBase(Generic[PromptType]): console (Console, optional): A Console instance or None to use global console. Defaults to None. password (bool, optional): Enable password input. Defaults to False. choices (List[str], optional): A list of valid choices. Defaults to None. + case_insensitive (bool, optional): Enable case insensitive matching of choices. Defaults to False. show_default (bool, optional): Show default in prompt. Defaults to True. show_choices (bool, optional): Show choices in prompt. Defaults to True. """ @@ -57,6 +58,7 @@ class PromptBase(Generic[PromptType]): console: Optional[Console] = None, password: bool = False, choices: Optional[List[str]] = None, + case_insensitive: bool = False, show_default: bool = True, show_choices: bool = True, ) -> None: @@ -69,6 +71,7 @@ class PromptBase(Generic[PromptType]): self.password = password if choices is not None: self.choices = choices + self.case_insensitive = case_insensitive self.show_default = show_default self.show_choices = show_choices @@ -81,6 +84,7 @@ class PromptBase(Generic[PromptType]): console: Optional[Console] = None, password: bool = False, choices: Optional[List[str]] = None, + case_insensitive: bool = False, show_default: bool = True, show_choices: bool = True, default: DefaultType, @@ -97,6 +101,7 @@ class PromptBase(Generic[PromptType]): console: Optional[Console] = None, password: bool = False, choices: Optional[List[str]] = None, + case_insensitive: bool = False, show_default: bool = True, show_choices: bool = True, stream: Optional[TextIO] = None, @@ -111,6 +116,7 @@ class PromptBase(Generic[PromptType]): console: Optional[Console] = None, password: bool = False, choices: Optional[List[str]] = None, + case_insensitive: bool = False, show_default: bool = True, show_choices: bool = True, default: Any = ..., @@ -126,6 +132,7 @@ class PromptBase(Generic[PromptType]): console (Console, optional): A Console instance or None to use global console. Defaults to None. password (bool, optional): Enable password input. Defaults to False. choices (List[str], optional): A list of valid choices. Defaults to None. + case_insensitive (bool, optional): Enable case insensitive matching of choices. Defaults to False. show_default (bool, optional): Show default in prompt. Defaults to True. show_choices (bool, optional): Show choices in prompt. Defaults to True. stream (TextIO, optional): Optional text file open for reading to get input. Defaults to None. @@ -135,6 +142,7 @@ class PromptBase(Generic[PromptType]): console=console, password=password, choices=choices, + case_insensitive=case_insensitive, show_default=show_default, show_choices=show_choices, ) @@ -212,6 +220,8 @@ class PromptBase(Generic[PromptType]): bool: True if choice was valid, otherwise False. """ assert self.choices is not None + if self.case_insensitive: + return value.strip().lower() in [choice.lower() for choice in self.choices] return value.strip() in self.choices def process_response(self, value: str) -> PromptType: @@ -232,9 +242,17 @@ class PromptBase(Generic[PromptType]): except ValueError: raise InvalidResponse(self.validate_error_message) - if self.choices is not None and not self.check_choice(value): - raise InvalidResponse(self.illegal_choice_message) + if self.choices is not None: + if not self.check_choice(value): + raise InvalidResponse(self.illegal_choice_message) + if self.case_insensitive: + # return the original choice, not the lower case version + return_value = self.response_type( + self.choices[ + [choice.lower() for choice in self.choices].index(value.lower()) + ] + ) return return_value def on_validate_error(self, value: str, error: InvalidResponse) -> None: @@ -346,7 +364,6 @@ class Confirm(PromptBase[bool]): if __name__ == "__main__": # pragma: no cover - from rich import print if Confirm.ask("Run [i]prompt[/i] tests?", default=True): @@ -372,5 +389,12 @@ if __name__ == "__main__": # pragma: no cover fruit = Prompt.ask("Enter a fruit", choices=["apple", "orange", "pear"]) print(f"fruit={fruit!r}") + doggie = Prompt.ask( + "What's the best Dog? (Case INSENSITIVE)", + choices=["BT", "Collie", "Labradoodle"], + case_insensitive=True, + ) + print(f"doggie={doggie!r}") + else: print("[b]OK :loudly_crying_face:") From 8de138ea6aa4a67a91d2e3d084aa32dadfc96afa Mon Sep 17 00:00:00 2001 From: Grant Ramsay Date: Fri, 30 Jun 2023 20:10:10 +0100 Subject: [PATCH 16/62] add a test for the new prompt option --- tests/test_prompt.py | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/tests/test_prompt.py b/tests/test_prompt.py index 9a41cc39..d8faf7f0 100644 --- a/tests/test_prompt.py +++ b/tests/test_prompt.py @@ -1,7 +1,7 @@ import io from rich.console import Console -from rich.prompt import Prompt, IntPrompt, Confirm +from rich.prompt import Confirm, IntPrompt, Prompt def test_prompt_str(): @@ -21,6 +21,24 @@ def test_prompt_str(): assert output == expected +def test_prompt_str_case_insensitive(): + INPUT = "egg\nFoO" + console = Console(file=io.StringIO()) + name = Prompt.ask( + "what is your name", + console=console, + choices=["foo", "bar"], + default="baz", + case_insensitive=True, + stream=io.StringIO(INPUT), + ) + assert name == "foo" + expected = "what is your name [foo/bar] (baz): Please select one of the available options\nwhat is your name [foo/bar] (baz): " + output = console.file.getvalue() + print(repr(output)) + assert output == expected + + def test_prompt_str_default(): INPUT = "" console = Console(file=io.StringIO()) From 6df890cdcedbd0413aa67028b440a7c48355909c Mon Sep 17 00:00:00 2001 From: Grant Ramsay Date: Fri, 30 Jun 2023 20:42:15 +0100 Subject: [PATCH 17/62] update docs with new prompt option --- docs/source/prompt.rst | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/docs/source/prompt.rst b/docs/source/prompt.rst index 088aa8e7..ef708ca1 100644 --- a/docs/source/prompt.rst +++ b/docs/source/prompt.rst @@ -18,6 +18,13 @@ If you supply a list of choices, the prompt will loop until the user enters one >>> from rich.prompt import Prompt >>> name = Prompt.ask("Enter your name", choices=["Paul", "Jessica", "Duncan"], default="Paul") +By default this is case sensitive, but you can set `case_insensitive=True` to make it case sensitive:: + + >>> from rich.prompt import Prompt + >>> name = Prompt.ask("Enter your name", choices=["Paul", "Jessica", "Duncan"], default="Paul", case_insensitive=True) + +Now, it would accept "paul" or "Paul" as valid responses. + In addition to :class:`~rich.prompt.Prompt` which returns strings, you can also use :class:`~rich.prompt.IntPrompt` which asks the user for an integer, and :class:`~rich.prompt.FloatPrompt` for floats. The :class:`~rich.prompt.Confirm` class is a specialized prompt which may be used to ask the user a simple yes / no question. Here's an example:: @@ -30,4 +37,4 @@ The Prompt class was designed to be customizable via inheritance. See `prompt.py To see some of the prompts in action, run the following command from the command line:: - python -m rich.prompt \ No newline at end of file + python -m rich.prompt From 3430909031e89bb0d9da16376d7cb91b16ecf341 Mon Sep 17 00:00:00 2001 From: Grant Ramsay Date: Fri, 30 Jun 2023 20:43:30 +0100 Subject: [PATCH 18/62] update CHANGELOG, CONTRIBUTORS --- CHANGELOG.md | 385 ++++++++++++++++++++++++------------------------ CONTRIBUTORS.md | 3 +- 2 files changed, 197 insertions(+), 191 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 72f2d40f..ce3f7b75 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,13 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [Unreleased] + +### Added + +- Added a `case_insensitive` parameter to `prompt.Prompt`. This allows the + `choices` list to be accepted without regard to case. Defaults to `False`. + ## [13.4.2] - 2023-06-12 ### Changed @@ -15,13 +22,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Fixed typing extensions import in markdown https://github.com/Textualize/rich/issues/2979 +- Fixed typing extensions import in markdown ## [13.4.0] - 2023-05-31 ### Added -- Added support for tables in `Markdown` https://github.com/Textualize/rich/pull/2977 +- Added support for tables in `Markdown` ## [13.3.5] - 2023-04-27 @@ -33,7 +40,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Fixed for `is_terminal` ignoring FORCE_COLOR https://github.com/Textualize/rich/pull/2923 +- Fixed for `is_terminal` ignoring FORCE_COLOR ## [13.3.3] - 2023-02-27 @@ -45,15 +52,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Reversed `pre` and `code` tags in base HTML format https://github.com/Textualize/rich/pull/2642 -- Fix syntax error when building with nuitka https://github.com/Textualize/rich/pull/2635 -- Fixed pretty printing of empty dataclass https://github.com/Textualize/rich/issues/2819 +- Reversed `pre` and `code` tags in base HTML format +- Fix syntax error when building with nuitka +- Fixed pretty printing of empty dataclass - Use `Console(stderr=True)` in `rich.traceback.install` to support io redirection. -- Fixes superfluous spaces in html output https://github.com/Textualize/rich/issues/2832 -- Fixed duplicate output in Jupyter https://github.com/Textualize/rich/pulls/2804 +- Fixes superfluous spaces in html output +- Fixed duplicate output in Jupyter - Filter ANSI character-encoding-change codes in `Text.from_ansi` parser -- Fixes traceback failing when a frame filename is unreadable https://github.com/Textualize/rich/issues/2821 -- Fix for live update rendering console markup https://github.com/Textualize/rich/issues/2726 +- Fixes traceback failing when a frame filename is unreadable +- Fix for live update rendering console markup ### Added @@ -61,41 +68,40 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed -- `rich.progress.track()` will now show the elapsed time after finishing the task https://github.com/Textualize/rich/pull/2659 +- `rich.progress.track()` will now show the elapsed time after finishing the task ## [13.3.1] - 2023-01-28 ### Fixed -- Fixed truecolor to eight bit color conversion https://github.com/Textualize/rich/pull/2785 +- Fixed truecolor to eight bit color conversion ## [13.3.0] - 2023-01-27 ### Fixed -- Fixed failing tests due to Pygments dependency https://github.com/Textualize/rich/issues/2757 -- Relaxed ipywidgets https://github.com/Textualize/rich/issues/2767 +- Fixed failing tests due to Pygments dependency +- Relaxed ipywidgets -### Added +### Added - Added `encoding` parameter in `Theme.read` - ## [13.2.0] - 2023-01-19 ### Changed -- Switch Markdown parsing from commonmark to markdown-it-py https://github.com/Textualize/rich/pull/2439 +- Switch Markdown parsing from commonmark to markdown-it-py ## [13.1.0] - 2023-01-14 ### Fixed -- Fixed wrong filenames in Jupyter tracebacks https://github.com/Textualize/rich/issues/2271 +- Fixed wrong filenames in Jupyter tracebacks ### Added -- Added locals_hide_dunder and locals_hide_sunder to Tracebacks, to hide double underscore and single underscore locals. https://github.com/Textualize/rich/pull/2754 +- Added locals_hide_dunder and locals_hide_sunder to Tracebacks, to hide double underscore and single underscore locals. ### Changed @@ -111,46 +117,45 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Reversed `pre` and `code` tags in base HTML format https://github.com/Textualize/rich/pull/2642 +- Reversed `pre` and `code` tags in base HTML format - Improved detection of `attrs` library, that isn't confused by the presence of the `attr` library. -- Fixed issue with `locals_max_length` parameter not being respected in Traceback https://github.com/Textualize/rich/issues/2649 -- Handling of broken `fileno` made more robust. Fixes https://github.com/Textualize/rich/issues/2645 +- Fixed issue with `locals_max_length` parameter not being respected in Traceback +- Handling of broken `fileno` made more robust. Fixes - Fixed missing `fileno` on FileProxy ### Fixed -- Fix type of `spinner_style` argument in `Console.status` https://github.com/Textualize/rich/pull/2613. +- Fix type of `spinner_style` argument in `Console.status` . ### Changed -- Bumped minimum Python version to 3.7 https://github.com/Textualize/rich/pull/2567 -- Pretty-printing of "tagged" `__repr__` results is now greedy when matching tags https://github.com/Textualize/rich/pull/2565 +- Bumped minimum Python version to 3.7 +- Pretty-printing of "tagged" `__repr__` results is now greedy when matching tags - `progress.track` now supports deriving total from `__length_hint__` ### Added -- Add type annotation for key_separator of pretty.Node https://github.com/Textualize/rich/issues/2625 - +- Add type annotation for key_separator of pretty.Node ## [12.6.0] - 2022-10-02 ### Added -- Parse ANSI escape sequences in pretty repr https://github.com/Textualize/rich/pull/2470 -- Add support for `FORCE_COLOR` env var https://github.com/Textualize/rich/pull/2449 -- Allow a `max_depth` argument to be passed to the `install()` hook https://github.com/Textualize/rich/issues/2486 -- Document using `None` as name in `__rich_repr__` for tuple positional args https://github.com/Textualize/rich/pull/2379 -- Add `font_aspect_ratio` parameter in SVG export https://github.com/Textualize/rich/pull/2539/files -- Added `Table.add_section` method. https://github.com/Textualize/rich/pull/2544 +- Parse ANSI escape sequences in pretty repr +- Add support for `FORCE_COLOR` env var +- Allow a `max_depth` argument to be passed to the `install()` hook +- Document using `None` as name in `__rich_repr__` for tuple positional args +- Add `font_aspect_ratio` parameter in SVG export +- Added `Table.add_section` method. ### Fixed -- Handle stdout/stderr being null https://github.com/Textualize/rich/pull/2513 -- Fix NO_COLOR support on legacy Windows https://github.com/Textualize/rich/pull/2458 -- Fix pretty printer handling of cyclic references https://github.com/Textualize/rich/pull/2524 -- Fix missing `mode` property on file wrapper breaking uploads via `requests` https://github.com/Textualize/rich/pull/2495 -- Fix mismatching default value of parameter `ensure_ascii` https://github.com/Textualize/rich/pull/2538 -- Remove unused height parameter in `Layout` class https://github.com/Textualize/rich/pull/2540 +- Handle stdout/stderr being null +- Fix NO_COLOR support on legacy Windows +- Fix pretty printer handling of cyclic references +- Fix missing `mode` property on file wrapper breaking uploads via `requests` +- Fix mismatching default value of parameter `ensure_ascii` +- Remove unused height parameter in `Layout` class - Fixed exception in Syntax.__rich_measure__ for empty files ### Changed @@ -167,8 +172,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Fixed missing typing extensions dependency on 3.9 https://github.com/Textualize/rich/issues/2386 -- Fixed Databricks Notebook is not detected as Jupyter environment. https://github.com/Textualize/rich/issues/2422 +- Fixed missing typing extensions dependency on 3.9 +- Fixed Databricks Notebook is not detected as Jupyter environment. ## [12.5.0] - 2022-07-11 @@ -187,13 +192,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Fix Rich clobbering cursor style on Windows https://github.com/Textualize/rich/pull/2339 -- Fix text wrapping edge case https://github.com/Textualize/rich/pull/2296 -- Allow exceptions that are raised while a Live is rendered to be displayed and/or processed https://github.com/Textualize/rich/pull/2305 -- Fix crashes that can happen with `inspect` when docstrings contain some special control codes https://github.com/Textualize/rich/pull/2294 -- Fix edges used in first row of tables when `show_header=False` https://github.com/Textualize/rich/pull/2330 -- Fix interaction between `Capture` contexts and `Console(record=True)` https://github.com/Textualize/rich/pull/2343 -- Fixed hash issue in Styles class https://github.com/Textualize/rich/pull/2346 +- Fix Rich clobbering cursor style on Windows +- Fix text wrapping edge case +- Allow exceptions that are raised while a Live is rendered to be displayed and/or processed +- Fix crashes that can happen with `inspect` when docstrings contain some special control codes +- Fix edges used in first row of tables when `show_header=False` +- Fix interaction between `Capture` contexts and `Console(record=True)` +- Fixed hash issue in Styles class - Fixed bug in `Segment.split_and_crop_lines` ## [12.4.4] - 2022-05-24 @@ -224,7 +229,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Fix for default background color in SVG export https://github.com/Textualize/rich/issues/2260 +- Fix for default background color in SVG export ### Changed @@ -239,31 +244,31 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed - Rebuilt SVG export to create a simpler SVG that is more portable -- Fix render_lines crash when render height was negative https://github.com/Textualize/rich/pull/2246 -- Make objects from `rich.progress.open` forward the name of the internal handle https://github.com/Textualize/rich/pull/2254 +- Fix render_lines crash when render height was negative +- Make objects from `rich.progress.open` forward the name of the internal handle ### Added -- Add `padding` to Syntax constructor https://github.com/Textualize/rich/pull/2247 +- Add `padding` to Syntax constructor ## [12.3.0] - 2022-04-26 ### Added -- Ability to change terminal window title https://github.com/Textualize/rich/pull/2200 +- Ability to change terminal window title - Added show_speed parameter to progress.track which will show the speed when the total is not known -- Python blocks can now opt out from being rendered in tracebacks's frames, by setting a `_rich_traceback_omit = True` in their local scope https://github.com/Textualize/rich/issues/2207 +- Python blocks can now opt out from being rendered in tracebacks's frames, by setting a `_rich_traceback_omit = True` in their local scope ### Fixed - Fall back to `sys.__stderr__` on POSIX systems when trying to get the terminal size (fix issues when Rich is piped to another process) -- Fixed markup escaping issue https://github.com/Textualize/rich/issues/2187 -- Safari - Box appearing around SVG export https://github.com/Textualize/rich/pull/2201 -- Fixed recursion error in Jupyter progress bars https://github.com/Textualize/rich/issues/2047 -- Complex numbers are now identified by the highlighter https://github.com/Textualize/rich/issues/2214 -- Fix crash on IDLE and forced is_terminal detection to False because IDLE can't do escape codes https://github.com/Textualize/rich/issues/2222 -- Fixed missing blank line in traceback rendering https://github.com/Textualize/rich/issues/2206 -- Fixed running Rich with the current working dir was deleted https://github.com/Textualize/rich/issues/2197 +- Fixed markup escaping issue +- Safari - Box appearing around SVG export +- Fixed recursion error in Jupyter progress bars +- Complex numbers are now identified by the highlighter +- Fix crash on IDLE and forced is_terminal detection to False because IDLE can't do escape codes +- Fixed missing blank line in traceback rendering +- Fixed running Rich with the current working dir was deleted ### Changed @@ -281,55 +286,55 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added -- Progress.open and Progress.wrap_file method to track the progress while reading from a file or file-like object https://github.com/textualize/rich/pull/1759 -- SVG export functionality https://github.com/Textualize/rich/pull/2101 +- Progress.open and Progress.wrap_file method to track the progress while reading from a file or file-like object +- SVG export functionality - Adding Indonesian translation ### Fixed -- Add missing `end` keyword argument to `Text.from_markup` https://github.com/Textualize/rich/pull/2095 -- Fallback to text lexer when no lexer guessed https://github.com/Textualize/rich/pull/2133 -- Fixed issue with decoding ANSI reset https://github.com/Textualize/rich/issues/2112 +- Add missing `end` keyword argument to `Text.from_markup` +- Fallback to text lexer when no lexer guessed +- Fixed issue with decoding ANSI reset ## [12.0.1] - 2022-03-22 ### Changed -- Improve performance of cell_length https://github.com/Textualize/rich/pull/2061 -- Improve performance of chop_cells https://github.com/Textualize/rich/pull/2077 +- Improve performance of cell_length +- Improve performance of chop_cells ### Fixed -- Fix capturing stdout on legacy Windows https://github.com/Textualize/rich/pull/2066 +- Fix capturing stdout on legacy Windows ## [12.0.0] - 2022-03-10 ### Added - Added options to TimeRemainingColumn to render a compact time format and render elapsed time when a task is - finished. https://github.com/Textualize/rich/pull/1992 + finished. - Added ProgressColumn `MofNCompleteColumn` to display raw `completed/total` column (similar to DownloadColumn, but displays values as ints, does not convert to floats or add bit/bytes units). - https://github.com/Textualize/rich/pull/1941 -- Replace Colorama with win32 renderer https://github.com/Textualize/rich/pull/1993 -- Add support for namedtuples to `Pretty` https://github.com/Textualize/rich/pull/2031 + +- Replace Colorama with win32 renderer +- Add support for namedtuples to `Pretty` ### Fixed - In Jupyter mode make the link target be set to "\_blank" - Fix some issues with markup handling around "[" characters https://github.com/Textualize/rich/pull/1950 - Fix syntax lexer guessing. -- Fixed Pretty measure not respecting expand_all https://github.com/Textualize/rich/issues/1998 +- Fixed Pretty measure not respecting expand_all - Collapsed definitions for single-character spinners, to save memory and reduce import time. - Fix print_json indent type in `__init__.py` -- Fix error when inspecting object defined in REPL https://github.com/Textualize/rich/pull/2037 -- Fix incorrect highlighting of non-indented JSON https://github.com/Textualize/rich/pull/2038 -- Fixed height reset in complex renderables https://github.com/Textualize/rich/issues/2042 +- Fix error when inspecting object defined in REPL +- Fix incorrect highlighting of non-indented JSON +- Fixed height reset in complex renderables ### Changed -- Improved support for enum.Flag in ReprHighlighter https://github.com/Textualize/rich/pull/1920 -- Tree now respects justify=None, i.e. won't pad to right https://github.com/Textualize/rich/issues/1690 +- Improved support for enum.Flag in ReprHighlighter +- Tree now respects justify=None, i.e. won't pad to right - Removed rich.tabulate which was marked for deprecation - Deprecated rich.align.AlignValues in favor of AlignMethod @@ -337,9 +342,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added -- Add support for US spelling of "gray" in ANSI color names https://github.com/Textualize/rich/issues/1890 -- Added `rich.diagnose.report` to expose environment debugging logic as function https://github.com/Textualize/rich/pull/1917 -- Added classmethod `Progress.get_default_columns()` to get the default list of progress bar columns https://github.com/Textualize/rich/pull/1894 +- Add support for US spelling of "gray" in ANSI color names +- Added `rich.diagnose.report` to expose environment debugging logic as function +- Added classmethod `Progress.get_default_columns()` to get the default list of progress bar columns ### Fixed @@ -347,40 +352,40 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Fixed test failures on PyPy3 https://github.com/Textualize/rich/pull/1904 +- Fixed test failures on PyPy3 ## [11.1.0] - 2022-01-28 ### Added -- Workaround for edge case of object from Faiss with no `__class__` https://github.com/Textualize/rich/issues/1838 +- Workaround for edge case of object from Faiss with no `__class__` - Add Traditional Chinese readme -- Add `Syntax.guess_lexer`, add support for more lexers (e.g. Django templates etc.) https://github.com/Textualize/rich/pull/1869 -- Add `lexer` parameter to `Syntax.from_path` to allow for overrides https://github.com/Textualize/rich/pull/1873 +- Add `Syntax.guess_lexer`, add support for more lexers (e.g. Django templates etc.) +- Add `lexer` parameter to `Syntax.from_path` to allow for overrides ### Fixed -- Workaround for edge case of object from Faiss with no `__class__` https://github.com/Textualize/rich/issues/1838 -- Ensure `Syntax` always justifies left https://github.com/Textualize/rich/pull/1872 -- Handle classes in inspect when methods=True https://github.com/Textualize/rich/pull/1874 +- Workaround for edge case of object from Faiss with no `__class__` +- Ensure `Syntax` always justifies left +- Handle classes in inspect when methods=True ## [11.0.0] - 2022-01-09 ### Added -- Added max_depth arg to pretty printing https://github.com/Textualize/rich/issues/1585 -- Added `vertical_align` to Table.add_row https://github.com/Textualize/rich/issues/1590 +- Added max_depth arg to pretty printing +- Added `vertical_align` to Table.add_row ### Fixed -- Fixed issue with pretty repr in jupyter notebook https://github.com/Textualize/rich/issues/1717 -- Fix Traceback theme defaults override user supplied styles https://github.com/Textualize/rich/issues/1786 +- Fixed issue with pretty repr in jupyter notebook +- Fix Traceback theme defaults override user supplied styles ### Changed -- **breaking** Deprecated rich.console.RenderGroup, now named rich.console.Group -- **breaking** `Syntax.__init__` parameter `lexer_name` renamed to `lexer` -- Syntax constructor accepts both str and now a pygments lexer https://github.com/Textualize/rich/pull/1748 +- __breaking__ Deprecated rich.console.RenderGroup, now named rich.console.Group +- __breaking__ `Syntax.__init__` parameter `lexer_name` renamed to `lexer` +- Syntax constructor accepts both str and now a pygments lexer ## [10.16.2] - 2021-01-02 @@ -392,23 +397,23 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Fixed issues with overlapping tags https://github.com/textualize/rich/issues/1755 +- Fixed issues with overlapping tags ## [10.16.0] - 2021-12-12 ### Fixed -- Double print of progress bar in Jupyter https://github.com/textualize/rich/issues/1737 +- Double print of progress bar in Jupyter ### Added -- Added Text.markup property https://github.com/textualize/rich/issues/1751 +- Added Text.markup property ## [10.15.2] - 2021-12-02 ### Fixed -- Deadlock issue https://github.com/textualize/rich/issues/1734 +- Deadlock issue ## [10.15.1] - 2021-11-29 @@ -430,51 +435,51 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Fixed issue with progress bar not rendering markup https://github.com/textualize/rich/issues/1721 -- Fixed race condition when exiting Live https://github.com/textualize/rich/issues/1530 +- Fixed issue with progress bar not rendering markup +- Fixed race condition when exiting Live ## [10.14.0] - 2021-11-16 ### Fixed - Fixed progress speed not updating when total doesn't change -- Fixed superfluous new line in Status https://github.com/textualize/rich/issues/1662 +- Fixed superfluous new line in Status - Fixed Windows legacy width again -- Fixed infinite loop in set_cell_size https://github.com/textualize/rich/issues/1682 +- Fixed infinite loop in set_cell_size ### Added -- Added file protocol to URL highlighter https://github.com/textualize/rich/issues/1681 +- Added file protocol to URL highlighter - Added rich.protocol.rich_cast ### Changed - Allowed `__rich__` to work recursively -- Allowed Text classes to work with sep in print https://github.com/textualize/rich/issues/1689 +- Allowed Text classes to work with sep in print ### Added -- Added a `rich.text.Text.from_ansi` helper method for handling pre-formatted input strings https://github.com/textualize/rich/issues/1670 +- Added a `rich.text.Text.from_ansi` helper method for handling pre-formatted input strings ## [10.13.0] - 2021-11-07 ### Added -- Added json.dumps parameters to print_json https://github.com/textualize/rich/issues/1638 +- Added json.dumps parameters to print_json ### Fixed - Fixed an edge case bug when console module try to detect if they are in a tty at the end of a pytest run -- Fixed a bug where logging handler raises an exception when running with pythonw (related to https://bugs.python.org/issue13807) -- Fixed issue with TERM env vars that have more than one hyphen https://github.com/textualize/rich/issues/1640 -- Fixed missing new line after progress bar when terminal is not interactive https://github.com/textualize/rich/issues/1606 -- Fixed exception in IPython when disabling pprint with %pprint https://github.com/textualize/rich/issues/1646 -- Fixed issue where values longer than the console width produced invalid JSON https://github.com/textualize/rich/issues/1653 -- Fixes trailing comma when pretty printing dataclass with last field repr=False https://github.com/textualize/rich/issues/1599 +- Fixed a bug where logging handler raises an exception when running with pythonw (related to ) +- Fixed issue with TERM env vars that have more than one hyphen +- Fixed missing new line after progress bar when terminal is not interactive +- Fixed exception in IPython when disabling pprint with %pprint +- Fixed issue where values longer than the console width produced invalid JSON +- Fixes trailing comma when pretty printing dataclass with last field repr=False ## Changed -- Markdown codeblocks now word-wrap https://github.com/textualize/rich/issues/1515 +- Markdown codeblocks now word-wrap ## [10.12.0] - 2021-10-06 @@ -501,7 +506,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Fixed pretty printing of objects with fo magic with **getattr** https://github.com/textualize/rich/issues/1492 +- Fixed pretty printing of objects with fo magic with __getattr__ ## [10.9.0] - 2021-08-29 @@ -527,7 +532,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed - Fixed a bug where calling `rich.reconfigure` within a `pytest_configure` hook would lead to a crash -- Fixed highlight not being passed through options https://github.com/textualize/rich/issues/1404 +- Fixed highlight not being passed through options ## [10.7.0] - 2021-08-05 @@ -561,7 +566,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Fixed issue with adjoining color tags https://github.com/textualize/rich/issues/1334 +- Fixed issue with adjoining color tags ### Changed @@ -571,10 +576,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Fixed Pandas objects not pretty printing https://github.com/textualize/rich/issues/1305 -- Fixed https://github.com/textualize/rich/issues/1256 +- Fixed Pandas objects not pretty printing +- Fixed - Fixed typing with rich.repr.auto decorator -- Fixed repr error formatting https://github.com/textualize/rich/issues/1326 +- Fixed repr error formatting ### Added @@ -592,7 +597,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Fixed error pretty printing classes with special **rich_repr** method +- Fixed error pretty printing classes with special __rich_repr__ method ## [10.3.0] - 2021-06-09 @@ -612,13 +617,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Fixed status not rendering console markup https://github.com/textualize/rich/issues/1244 +- Fixed status not rendering console markup ## [10.2.1] - 2021-05-17 ### Fixed -- Fixed panel in Markdown exploding https://github.com/textualize/rich/issues/1234 +- Fixed panel in Markdown exploding ## [10.2.0] - 2021-05-12 @@ -637,7 +642,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Fixed initial blank lines removed from Syntax https://github.com/textualize/rich/issues/1214 +- Fixed initial blank lines removed from Syntax ## [10.1.0] - 2021-04-03 @@ -649,13 +654,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Fixed race condition that duplicated lines in progress https://github.com/textualize/rich/issues/1144 +- Fixed race condition that duplicated lines in progress ## [10.0.0] - 2021-03-27 ### Changed -- Made pydoc import lazy as at least one use found it slow to import https://github.com/textualize/rich/issues/1104 +- Made pydoc import lazy as at least one use found it slow to import - Modified string highlighting to not match in the middle of a word, so that apostrophes are not considered strings - New way of encoding control codes in Segment - New signature for Control class @@ -679,10 +684,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Fixed table style taking precedence over row style https://github.com/textualize/rich/issues/1129 -- Fixed incorrect measurement of Text with new lines and whitespace https://github.com/textualize/rich/issues/1133 +- Fixed table style taking precedence over row style +- Fixed incorrect measurement of Text with new lines and whitespace - Made type annotations consistent for various `total` keyword arguments in `rich.progress` and rich.`progress_bar` -- Disabled Progress no longer displays itself when starting https://github.com/textualize/rich/pull/1125 +- Disabled Progress no longer displays itself when starting - Animations no longer reset when updating rich.status.Status ## [9.13.0] - 2021-03-06 @@ -693,8 +698,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Fixed Syntax background https://github.com/textualize/rich/issues/1088 -- Fix for double tracebacks when no formatter https://github.com/textualize/rich/issues/1079 +- Fixed Syntax background +- Fix for double tracebacks when no formatter ### Changed @@ -704,7 +709,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Fixed custom formatters with rich tracebacks in RichHandler https://github.com/textualize/rich/issues/1079 +- Fixed custom formatters with rich tracebacks in RichHandler ### Changed @@ -731,7 +736,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Fixed deadlock in Progress https://github.com/textualize/rich/issues/1061 +- Fixed deadlock in Progress ### Added @@ -747,14 +752,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Fixed issue with Syntax and missing lines in Layout https://github.com/textualize/rich/issues/1050 -- Fixed issue with nested markdown elements https://github.com/textualize/rich/issues/1036 -- Fixed new lines not invoking render hooks https://github.com/textualize/rich/issues/1052 -- Fixed Align setting height to child https://github.com/textualize/rich/issues/1057 +- Fixed issue with Syntax and missing lines in Layout +- Fixed issue with nested markdown elements +- Fixed new lines not invoking render hooks +- Fixed Align setting height to child ### Changed -- Printing a table with no columns now result in a blank line https://github.com/textualize/rich/issues/1044 +- Printing a table with no columns now result in a blank line ### Added @@ -766,9 +771,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Fixed table with expand=False not expanding when justify="center" - Fixed single renderable in Layout not respecting height -- Fixed COLUMNS and LINES env var https://github.com/textualize/rich/issues/1019 +- Fixed COLUMNS and LINES env var - Layout now respects minimum_size when fixes sizes are greater than available space -- HTML export now changes link underline score to match terminal https://github.com/textualize/rich/issues/1009 +- HTML export now changes link underline score to match terminal ### Changed @@ -783,8 +788,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Fixed error message for tracebacks with broken `__str__` https://github.com/textualize/rich/issues/980 -- Fixed markup edge case https://github.com/textualize/rich/issues/987 +- Fixed error message for tracebacks with broken `__str__` +- Fixed markup edge case ### Added @@ -825,7 +830,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Fix double line tree guides on Windows - Fixed Tracebacks ignoring initial blank lines - Partial fix for tracebacks not finding source after chdir -- Fixed error message when code in tracebacks doesn't have an extension https://github.com/textualize/rich/issues/996 +- Fixed error message when code in tracebacks doesn't have an extension ### Added @@ -835,19 +840,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Fixed deadlock in live https://github.com/textualize/rich/issues/927 +- Fixed deadlock in live ## [9.8.1] - 2021-01-13 ### Fixed -- Fixed rich.inspect failing with attributes that claim to be callable but aren't https://github.com/textualize/rich/issues/916 +- Fixed rich.inspect failing with attributes that claim to be callable but aren't ## [9.8.0] - 2021-01-11 ### Added -- Added **rich_measure** for tree +- Added __rich_measure__ for tree - Added rich.align.VerticalCenter ### Changed @@ -860,7 +865,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Fixed panel cropping when shrunk too bar - Allow passing markdown over STDIN when using `python -m rich.markdown` -- Fix printing MagicMock.mock_calls https://github.com/textualize/rich/issues/903 +- Fix printing MagicMock.mock_calls ## [9.7.0] - 2021-01-09 @@ -873,9 +878,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Fixed markup escaping edge case https://github.com/textualize/rich/issues/878 +- Fixed markup escaping edge case - Double tag escape, i.e. `"\\[foo]"` results in a backslash plus `[foo]` tag -- Fixed header_style not applying to headers in positional args https://github.com/textualize/rich/issues/953 +- Fixed header_style not applying to headers in positional args ## [9.6.1] - 2020-12-31 @@ -904,7 +909,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Fixed terminal size detection on Windows https://github.com/textualize/rich/issues/836 +- Fixed terminal size detection on Windows - Fixed hex number highlighting ## [9.5.0] - 2020-12-18 @@ -928,15 +933,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Fixed double output in rich.live https://github.com/textualize/rich/issues/485 -- Fixed Console.out highlighting not reflecting defaults https://github.com/textualize/rich/issues/827 -- FileProxy now raises TypeError for empty non-str arguments https://github.com/textualize/rich/issues/828 +- Fixed double output in rich.live +- Fixed Console.out highlighting not reflecting defaults +- FileProxy now raises TypeError for empty non-str arguments ## [9.4.0] - 2020-12-12 ### Added -- Added rich.live https://github.com/textualize/rich/pull/382 +- Added rich.live - Added algin parameter to Rule and Console.rule - Added rich.Status class and Console.status - Added getitem to Text @@ -950,7 +955,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## Fixed -- Fixed suppressed traceback context https://github.com/textualize/rich/issues/468 +- Fixed suppressed traceback context ## [9.3.0] - 2020-12-1 @@ -971,9 +976,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed - Fixed redirecting of stderr in Progress -- Fixed broken expanded tuple of one https://github.com/textualize/rich/issues/445 +- Fixed broken expanded tuple of one - Fixed traceback message with `from` exceptions -- Fixed justify argument not working in console.log https://github.com/textualize/rich/issues/460 +- Fixed justify argument not working in console.log ## [9.2.0] - 2020-11-08 @@ -1010,13 +1015,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Fixed negative time remaining in Progress bars https://github.com/textualize/rich/issues/378 +- Fixed negative time remaining in Progress bars ## [9.0.1] - 2020-10-19 ### Fixed -- Fixed broken ANSI codes in input on windows legacy https://github.com/textualize/rich/issues/393 +- Fixed broken ANSI codes in input on windows legacy ## [9.0.0] - 2020-10-18 @@ -1036,14 +1041,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Added binary_units in progress download column - Added Progress.reset - Added Style.background_style property -- Added Bar renderable https://github.com/textualize/rich/pull/361 +- Added Bar renderable - Added Table.min_width - Added table.Column.min_width and table.Column.max_width, and same to Table.add_column ### Changed - Dropped box.get_safe_box function in favor of Box.substitute -- Changed default padding in Panel from 0 to (0, 1) https://github.com/textualize/rich/issues/385 +- Changed default padding in Panel from 0 to (0, 1) - Table with row_styles will extend background color between cells if the box has no vertical dividerhttps://github.com/textualize/rich/issues/383 - Changed default of fit kwarg in render_group() from False to True - Renamed rich.bar to rich.progress_bar, and Bar class to ProgressBar, rich.bar is now the new solid bar class @@ -1077,12 +1082,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added - Added Console.begin_capture, Console.end_capture and Console.capture -- Added Table.title_justify and Table.caption_justify https://github.com/textualize/rich/issues/301 +- Added Table.title_justify and Table.caption_justify ### Changed - Improved formatting of exceptions -- Enabled Rich exceptions in logging https://github.com/taliraj +- Enabled Rich exceptions in logging - UTF-8 encoding is now mentioned in HTML head section ### Removed @@ -1168,7 +1173,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Fixed underscore with display hook https://github.com/textualize/rich/issues/235 +- Fixed underscore with display hook ## [5.2.0] - 2020-08-14 @@ -1176,7 +1181,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Added crop argument to Console.print - Added "ignore" overflow method -- Added multiple characters per rule @hedythedev https://github.com/textualize/rich/pull/207 +- Added multiple characters per rule @hedythedev ## [5.1.2] - 2020-08-10 @@ -1195,12 +1200,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added - Added Text.cell_len -- Added helpful message regarding unicode decoding errors https://github.com/textualize/rich/issues/212 +- Added helpful message regarding unicode decoding errors - Added display hook with pretty.install() ### Fixed -- Fixed deprecation warnings re backslash https://github.com/textualize/rich/issues/210 +- Fixed deprecation warnings re backslash - Fixed repr highlighting of scientific notation, e.g. 1e100 ### Changed @@ -1221,30 +1226,30 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed - Added thread to automatically call update() in progress.track(). Replacing previous adaptive algorithm. -- Second attempt at working around https://bugs.python.org/issue37871 +- Second attempt at working around ## [4.2.1] - 2020-07-29 ### Added -- Added show_time and show_level parameters to RichHandler https://github.com/textualize/rich/pull/182 +- Added show_time and show_level parameters to RichHandler ### Fixed -- Fixed progress.track iterator exiting early https://github.com/textualize/rich/issues/189 -- Added workaround for Python bug https://bugs.python.org/issue37871, fixing https://github.com/textualize/rich/issues/186 +- Fixed progress.track iterator exiting early +- Added workaround for Python bug , fixing ### Changed -- Set overflow=fold for log messages https://github.com/textualize/rich/issues/190 +- Set overflow=fold for log messages ## [4.2.0] - 2020-07-27 ### Fixed -- Fixed missing new lines https://github.com/textualize/rich/issues/178 -- Fixed Progress.track https://github.com/textualize/rich/issues/184 -- Remove control codes from exported text https://github.com/textualize/rich/issues/181 +- Fixed missing new lines +- Fixed Progress.track +- Remove control codes from exported text - Implemented auto-detection and color rendition of 16-color mode ## [4.1.0] - 2020-07-26 @@ -1260,7 +1265,7 @@ Major version bump for a breaking change to `Text.stylize signature`, which corr ### Added -- Added markup switch to RichHandler https://github.com/textualize/rich/issues/171 +- Added markup switch to RichHandler ### Changed @@ -1269,7 +1274,7 @@ Major version bump for a breaking change to `Text.stylize signature`, which corr ### Fixed -- Fixed rendering of Confirm prompt https://github.com/textualize/rich/issues/170 +- Fixed rendering of Confirm prompt ## [3.4.1] - 2020-07-22 @@ -1364,7 +1369,7 @@ Major version bump for a breaking change to `Text.stylize signature`, which corr ### Changed -- More precise detection of Windows console https://github.com/textualize/rich/issues/140 +- More precise detection of Windows console ## [3.0.3] - 2020-07-03 @@ -1421,7 +1426,7 @@ Major version bump for a breaking change to `Text.stylize signature`, which corr ### Fixed -- Disabled legacy_windows if jupyter is detected https://github.com/textualize/rich/issues/125 +- Disabled legacy_windows if jupyter is detected ## [2.3.0] - 2020-06-26 @@ -1442,13 +1447,13 @@ Major version bump for a breaking change to `Text.stylize signature`, which corr ### Changed -- Store a "link id" on Style instance, so links containing different styles are highlighted together. (https://github.com/textualize/rich/pull/123) +- Store a "link id" on Style instance, so links containing different styles are highlighted together. () ## [2.2.5] - 2020-06-23 ### Fixed -- Fixed justify of tables (https://github.com/textualize/rich/issues/117) +- Fixed justify of tables () ## [2.2.4] - 2020-06-21 @@ -1576,7 +1581,7 @@ Major version bump for a breaking change to `Text.stylize signature`, which corr ### Fixed -- Fixed Progress deadlock https://github.com/textualize/rich/issues/90 +- Fixed Progress deadlock ### Changed @@ -1707,7 +1712,7 @@ Major version bump for a breaking change to `Text.stylize signature`, which corr ### Fixed -- Issue with Windows legacy support https://github.com/textualize/rich/issues/59 +- Issue with Windows legacy support ## [1.0.1] - 2020-05-08 @@ -1729,7 +1734,7 @@ Major version bump for a breaking change to `Text.stylize signature`, which corr ### Fixed -- Fixed Text.assemble not working with strings https://github.com/textualize/rich/issues/57 +- Fixed Text.assemble not working with strings - Fixed table when column widths must be compressed to fit ## [1.0.0] - 2020-05-03 @@ -1854,7 +1859,7 @@ Major version bump for a breaking change to `Text.stylize signature`, which corr ### Changed -- Dropped support for Windows command prompt (try https://www.microsoft.com/en-gb/p/windows-terminal-preview/) +- Dropped support for Windows command prompt (try ) - Added task_id to Progress.track ## [0.7.2] - 2020-03-15 @@ -1939,7 +1944,7 @@ Major version bump for a breaking change to `Text.stylize signature`, which corr ### Fixed - Fixed Windows color support -- Fixed line width on windows issue (https://github.com/textualize/rich/issues/7) +- Fixed line width on windows issue () - Fixed Pretty print on Windows ## [0.3.2] - 2020-01-26 @@ -1960,9 +1965,9 @@ Major version bump for a breaking change to `Text.stylize signature`, which corr - First official release, API still to be stabilized -[13.4.2]: https://github.com/textualize/rich/compare/v13.4.1...v13.4.2 -[13.4.1]: https://github.com/textualize/rich/compare/v13.4.0...v13.4.1 -[13.4.0]: https://github.com/textualize/rich/compare/v13.3.5...v13.4.0 +[13.4.2]: https://github.com/textualize/rich/compare/v13.4.1...v13.4.2 +[13.4.1]: https://github.com/textualize/rich/compare/v13.4.0...v13.4.1 +[13.4.0]: https://github.com/textualize/rich/compare/v13.3.5...v13.4.0 [13.3.5]: https://github.com/textualize/rich/compare/v13.3.4...v13.3.5 [13.3.4]: https://github.com/textualize/rich/compare/v13.3.3...v13.3.4 [13.3.3]: https://github.com/textualize/rich/compare/v13.3.2...v13.3.3 diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index fe88b789..13208158 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -45,6 +45,7 @@ The following people have contributed to the development of Rich: - [Kylian Point](https://github.com/p0lux) - [Kyle Pollina](https://github.com/kylepollina) - [Sebastián Ramírez](https://github.com/tiangolo) +- [Grant Ramsay](https://github.com/seapagan) - [Felipe Guedes](https://github.com/guedesfelipe) - [Min RK](https://github.com/minrk) - [Clément Robert](https://github.com/neutrinoceros) @@ -68,4 +69,4 @@ The following people have contributed to the development of Rich: - [Ke Sun](https://github.com/ksun212) - [Qiming Xu](https://github.com/xqm32) - [James Addison](https://github.com/jayaddison) -- [Pierro](https://github.com/xpierroz) \ No newline at end of file +- [Pierro](https://github.com/xpierroz) From 10705a43b26ecf0eb9c7ed3a687bc797b3e1b4d5 Mon Sep 17 00:00:00 2001 From: Grant Ramsay Date: Fri, 30 Jun 2023 20:57:03 +0100 Subject: [PATCH 19/62] fix typo in docs --- docs/source/prompt.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/source/prompt.rst b/docs/source/prompt.rst index ef708ca1..1909aafd 100644 --- a/docs/source/prompt.rst +++ b/docs/source/prompt.rst @@ -18,7 +18,7 @@ If you supply a list of choices, the prompt will loop until the user enters one >>> from rich.prompt import Prompt >>> name = Prompt.ask("Enter your name", choices=["Paul", "Jessica", "Duncan"], default="Paul") -By default this is case sensitive, but you can set `case_insensitive=True` to make it case sensitive:: +By default this is case sensitive, but you can set `case_insensitive=True` to make it case insensitive:: >>> from rich.prompt import Prompt >>> name = Prompt.ask("Enter your name", choices=["Paul", "Jessica", "Duncan"], default="Paul", case_insensitive=True) From fb556c7659af9626fca2ae4480a43f5f8dd232cc Mon Sep 17 00:00:00 2001 From: Grant Ramsay Date: Sun, 23 Jul 2023 18:32:25 +0100 Subject: [PATCH 20/62] This corrects commit 3430909031e89bb0d9da16376d7cb91b16ecf341. My Markdown formatter automatically changed the URL's in this to the more correct form by wrapping them with '<' and '>', probably shouldn't force my style choices on another project. --- CHANGELOG.md | 378 ++++++++++++++++++++++++++------------------------- 1 file changed, 190 insertions(+), 188 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ce3f7b75..fc552b1a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,13 +22,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Fixed typing extensions import in markdown +- Fixed typing extensions import in markdown https://github.com/Textualize/rich/issues/2979 ## [13.4.0] - 2023-05-31 ### Added -- Added support for tables in `Markdown` +- Added support for tables in `Markdown` https://github.com/Textualize/rich/pull/2977 ## [13.3.5] - 2023-04-27 @@ -40,7 +40,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Fixed for `is_terminal` ignoring FORCE_COLOR +- Fixed for `is_terminal` ignoring FORCE_COLOR https://github.com/Textualize/rich/pull/2923 ## [13.3.3] - 2023-02-27 @@ -52,15 +52,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Reversed `pre` and `code` tags in base HTML format -- Fix syntax error when building with nuitka -- Fixed pretty printing of empty dataclass +- Reversed `pre` and `code` tags in base HTML format https://github.com/Textualize/rich/pull/2642 +- Fix syntax error when building with nuitka https://github.com/Textualize/rich/pull/2635 +- Fixed pretty printing of empty dataclass https://github.com/Textualize/rich/issues/2819 - Use `Console(stderr=True)` in `rich.traceback.install` to support io redirection. -- Fixes superfluous spaces in html output -- Fixed duplicate output in Jupyter +- Fixes superfluous spaces in html output https://github.com/Textualize/rich/issues/2832 +- Fixed duplicate output in Jupyter https://github.com/Textualize/rich/pulls/2804 - Filter ANSI character-encoding-change codes in `Text.from_ansi` parser -- Fixes traceback failing when a frame filename is unreadable -- Fix for live update rendering console markup +- Fixes traceback failing when a frame filename is unreadable https://github.com/Textualize/rich/issues/2821 +- Fix for live update rendering console markup https://github.com/Textualize/rich/issues/2726 ### Added @@ -68,40 +68,41 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed -- `rich.progress.track()` will now show the elapsed time after finishing the task +- `rich.progress.track()` will now show the elapsed time after finishing the task https://github.com/Textualize/rich/pull/2659 ## [13.3.1] - 2023-01-28 ### Fixed -- Fixed truecolor to eight bit color conversion +- Fixed truecolor to eight bit color conversion https://github.com/Textualize/rich/pull/2785 ## [13.3.0] - 2023-01-27 ### Fixed -- Fixed failing tests due to Pygments dependency -- Relaxed ipywidgets +- Fixed failing tests due to Pygments dependency https://github.com/Textualize/rich/issues/2757 +- Relaxed ipywidgets https://github.com/Textualize/rich/issues/2767 -### Added +### Added - Added `encoding` parameter in `Theme.read` + ## [13.2.0] - 2023-01-19 ### Changed -- Switch Markdown parsing from commonmark to markdown-it-py +- Switch Markdown parsing from commonmark to markdown-it-py https://github.com/Textualize/rich/pull/2439 ## [13.1.0] - 2023-01-14 ### Fixed -- Fixed wrong filenames in Jupyter tracebacks +- Fixed wrong filenames in Jupyter tracebacks https://github.com/Textualize/rich/issues/2271 ### Added -- Added locals_hide_dunder and locals_hide_sunder to Tracebacks, to hide double underscore and single underscore locals. +- Added locals_hide_dunder and locals_hide_sunder to Tracebacks, to hide double underscore and single underscore locals. https://github.com/Textualize/rich/pull/2754 ### Changed @@ -117,45 +118,46 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Reversed `pre` and `code` tags in base HTML format +- Reversed `pre` and `code` tags in base HTML format https://github.com/Textualize/rich/pull/2642 - Improved detection of `attrs` library, that isn't confused by the presence of the `attr` library. -- Fixed issue with `locals_max_length` parameter not being respected in Traceback -- Handling of broken `fileno` made more robust. Fixes +- Fixed issue with `locals_max_length` parameter not being respected in Traceback https://github.com/Textualize/rich/issues/2649 +- Handling of broken `fileno` made more robust. Fixes https://github.com/Textualize/rich/issues/2645 - Fixed missing `fileno` on FileProxy ### Fixed -- Fix type of `spinner_style` argument in `Console.status` . +- Fix type of `spinner_style` argument in `Console.status` https://github.com/Textualize/rich/pull/2613. ### Changed -- Bumped minimum Python version to 3.7 -- Pretty-printing of "tagged" `__repr__` results is now greedy when matching tags +- Bumped minimum Python version to 3.7 https://github.com/Textualize/rich/pull/2567 +- Pretty-printing of "tagged" `__repr__` results is now greedy when matching tags https://github.com/Textualize/rich/pull/2565 - `progress.track` now supports deriving total from `__length_hint__` ### Added -- Add type annotation for key_separator of pretty.Node +- Add type annotation for key_separator of pretty.Node https://github.com/Textualize/rich/issues/2625 + ## [12.6.0] - 2022-10-02 ### Added -- Parse ANSI escape sequences in pretty repr -- Add support for `FORCE_COLOR` env var -- Allow a `max_depth` argument to be passed to the `install()` hook -- Document using `None` as name in `__rich_repr__` for tuple positional args -- Add `font_aspect_ratio` parameter in SVG export -- Added `Table.add_section` method. +- Parse ANSI escape sequences in pretty repr https://github.com/Textualize/rich/pull/2470 +- Add support for `FORCE_COLOR` env var https://github.com/Textualize/rich/pull/2449 +- Allow a `max_depth` argument to be passed to the `install()` hook https://github.com/Textualize/rich/issues/2486 +- Document using `None` as name in `__rich_repr__` for tuple positional args https://github.com/Textualize/rich/pull/2379 +- Add `font_aspect_ratio` parameter in SVG export https://github.com/Textualize/rich/pull/2539/files +- Added `Table.add_section` method. https://github.com/Textualize/rich/pull/2544 ### Fixed -- Handle stdout/stderr being null -- Fix NO_COLOR support on legacy Windows -- Fix pretty printer handling of cyclic references -- Fix missing `mode` property on file wrapper breaking uploads via `requests` -- Fix mismatching default value of parameter `ensure_ascii` -- Remove unused height parameter in `Layout` class +- Handle stdout/stderr being null https://github.com/Textualize/rich/pull/2513 +- Fix NO_COLOR support on legacy Windows https://github.com/Textualize/rich/pull/2458 +- Fix pretty printer handling of cyclic references https://github.com/Textualize/rich/pull/2524 +- Fix missing `mode` property on file wrapper breaking uploads via `requests` https://github.com/Textualize/rich/pull/2495 +- Fix mismatching default value of parameter `ensure_ascii` https://github.com/Textualize/rich/pull/2538 +- Remove unused height parameter in `Layout` class https://github.com/Textualize/rich/pull/2540 - Fixed exception in Syntax.__rich_measure__ for empty files ### Changed @@ -172,8 +174,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Fixed missing typing extensions dependency on 3.9 -- Fixed Databricks Notebook is not detected as Jupyter environment. +- Fixed missing typing extensions dependency on 3.9 https://github.com/Textualize/rich/issues/2386 +- Fixed Databricks Notebook is not detected as Jupyter environment. https://github.com/Textualize/rich/issues/2422 ## [12.5.0] - 2022-07-11 @@ -192,13 +194,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Fix Rich clobbering cursor style on Windows -- Fix text wrapping edge case -- Allow exceptions that are raised while a Live is rendered to be displayed and/or processed -- Fix crashes that can happen with `inspect` when docstrings contain some special control codes -- Fix edges used in first row of tables when `show_header=False` -- Fix interaction between `Capture` contexts and `Console(record=True)` -- Fixed hash issue in Styles class +- Fix Rich clobbering cursor style on Windows https://github.com/Textualize/rich/pull/2339 +- Fix text wrapping edge case https://github.com/Textualize/rich/pull/2296 +- Allow exceptions that are raised while a Live is rendered to be displayed and/or processed https://github.com/Textualize/rich/pull/2305 +- Fix crashes that can happen with `inspect` when docstrings contain some special control codes https://github.com/Textualize/rich/pull/2294 +- Fix edges used in first row of tables when `show_header=False` https://github.com/Textualize/rich/pull/2330 +- Fix interaction between `Capture` contexts and `Console(record=True)` https://github.com/Textualize/rich/pull/2343 +- Fixed hash issue in Styles class https://github.com/Textualize/rich/pull/2346 - Fixed bug in `Segment.split_and_crop_lines` ## [12.4.4] - 2022-05-24 @@ -229,7 +231,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Fix for default background color in SVG export +- Fix for default background color in SVG export https://github.com/Textualize/rich/issues/2260 ### Changed @@ -244,31 +246,31 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed - Rebuilt SVG export to create a simpler SVG that is more portable -- Fix render_lines crash when render height was negative -- Make objects from `rich.progress.open` forward the name of the internal handle +- Fix render_lines crash when render height was negative https://github.com/Textualize/rich/pull/2246 +- Make objects from `rich.progress.open` forward the name of the internal handle https://github.com/Textualize/rich/pull/2254 ### Added -- Add `padding` to Syntax constructor +- Add `padding` to Syntax constructor https://github.com/Textualize/rich/pull/2247 ## [12.3.0] - 2022-04-26 ### Added -- Ability to change terminal window title +- Ability to change terminal window title https://github.com/Textualize/rich/pull/2200 - Added show_speed parameter to progress.track which will show the speed when the total is not known -- Python blocks can now opt out from being rendered in tracebacks's frames, by setting a `_rich_traceback_omit = True` in their local scope +- Python blocks can now opt out from being rendered in tracebacks's frames, by setting a `_rich_traceback_omit = True` in their local scope https://github.com/Textualize/rich/issues/2207 ### Fixed - Fall back to `sys.__stderr__` on POSIX systems when trying to get the terminal size (fix issues when Rich is piped to another process) -- Fixed markup escaping issue -- Safari - Box appearing around SVG export -- Fixed recursion error in Jupyter progress bars -- Complex numbers are now identified by the highlighter -- Fix crash on IDLE and forced is_terminal detection to False because IDLE can't do escape codes -- Fixed missing blank line in traceback rendering -- Fixed running Rich with the current working dir was deleted +- Fixed markup escaping issue https://github.com/Textualize/rich/issues/2187 +- Safari - Box appearing around SVG export https://github.com/Textualize/rich/pull/2201 +- Fixed recursion error in Jupyter progress bars https://github.com/Textualize/rich/issues/2047 +- Complex numbers are now identified by the highlighter https://github.com/Textualize/rich/issues/2214 +- Fix crash on IDLE and forced is_terminal detection to False because IDLE can't do escape codes https://github.com/Textualize/rich/issues/2222 +- Fixed missing blank line in traceback rendering https://github.com/Textualize/rich/issues/2206 +- Fixed running Rich with the current working dir was deleted https://github.com/Textualize/rich/issues/2197 ### Changed @@ -286,55 +288,55 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added -- Progress.open and Progress.wrap_file method to track the progress while reading from a file or file-like object -- SVG export functionality +- Progress.open and Progress.wrap_file method to track the progress while reading from a file or file-like object https://github.com/textualize/rich/pull/1759 +- SVG export functionality https://github.com/Textualize/rich/pull/2101 - Adding Indonesian translation ### Fixed -- Add missing `end` keyword argument to `Text.from_markup` -- Fallback to text lexer when no lexer guessed -- Fixed issue with decoding ANSI reset +- Add missing `end` keyword argument to `Text.from_markup` https://github.com/Textualize/rich/pull/2095 +- Fallback to text lexer when no lexer guessed https://github.com/Textualize/rich/pull/2133 +- Fixed issue with decoding ANSI reset https://github.com/Textualize/rich/issues/2112 ## [12.0.1] - 2022-03-22 ### Changed -- Improve performance of cell_length -- Improve performance of chop_cells +- Improve performance of cell_length https://github.com/Textualize/rich/pull/2061 +- Improve performance of chop_cells https://github.com/Textualize/rich/pull/2077 ### Fixed -- Fix capturing stdout on legacy Windows +- Fix capturing stdout on legacy Windows https://github.com/Textualize/rich/pull/2066 ## [12.0.0] - 2022-03-10 ### Added - Added options to TimeRemainingColumn to render a compact time format and render elapsed time when a task is - finished. + finished. https://github.com/Textualize/rich/pull/1992 - Added ProgressColumn `MofNCompleteColumn` to display raw `completed/total` column (similar to DownloadColumn, but displays values as ints, does not convert to floats or add bit/bytes units). - -- Replace Colorama with win32 renderer -- Add support for namedtuples to `Pretty` + https://github.com/Textualize/rich/pull/1941 +- Replace Colorama with win32 renderer https://github.com/Textualize/rich/pull/1993 +- Add support for namedtuples to `Pretty` https://github.com/Textualize/rich/pull/2031 ### Fixed - In Jupyter mode make the link target be set to "\_blank" - Fix some issues with markup handling around "[" characters https://github.com/Textualize/rich/pull/1950 - Fix syntax lexer guessing. -- Fixed Pretty measure not respecting expand_all +- Fixed Pretty measure not respecting expand_all https://github.com/Textualize/rich/issues/1998 - Collapsed definitions for single-character spinners, to save memory and reduce import time. - Fix print_json indent type in `__init__.py` -- Fix error when inspecting object defined in REPL -- Fix incorrect highlighting of non-indented JSON -- Fixed height reset in complex renderables +- Fix error when inspecting object defined in REPL https://github.com/Textualize/rich/pull/2037 +- Fix incorrect highlighting of non-indented JSON https://github.com/Textualize/rich/pull/2038 +- Fixed height reset in complex renderables https://github.com/Textualize/rich/issues/2042 ### Changed -- Improved support for enum.Flag in ReprHighlighter -- Tree now respects justify=None, i.e. won't pad to right +- Improved support for enum.Flag in ReprHighlighter https://github.com/Textualize/rich/pull/1920 +- Tree now respects justify=None, i.e. won't pad to right https://github.com/Textualize/rich/issues/1690 - Removed rich.tabulate which was marked for deprecation - Deprecated rich.align.AlignValues in favor of AlignMethod @@ -342,9 +344,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added -- Add support for US spelling of "gray" in ANSI color names -- Added `rich.diagnose.report` to expose environment debugging logic as function -- Added classmethod `Progress.get_default_columns()` to get the default list of progress bar columns +- Add support for US spelling of "gray" in ANSI color names https://github.com/Textualize/rich/issues/1890 +- Added `rich.diagnose.report` to expose environment debugging logic as function https://github.com/Textualize/rich/pull/1917 +- Added classmethod `Progress.get_default_columns()` to get the default list of progress bar columns https://github.com/Textualize/rich/pull/1894 ### Fixed @@ -352,40 +354,40 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Fixed test failures on PyPy3 +- Fixed test failures on PyPy3 https://github.com/Textualize/rich/pull/1904 ## [11.1.0] - 2022-01-28 ### Added -- Workaround for edge case of object from Faiss with no `__class__` +- Workaround for edge case of object from Faiss with no `__class__` https://github.com/Textualize/rich/issues/1838 - Add Traditional Chinese readme -- Add `Syntax.guess_lexer`, add support for more lexers (e.g. Django templates etc.) -- Add `lexer` parameter to `Syntax.from_path` to allow for overrides +- Add `Syntax.guess_lexer`, add support for more lexers (e.g. Django templates etc.) https://github.com/Textualize/rich/pull/1869 +- Add `lexer` parameter to `Syntax.from_path` to allow for overrides https://github.com/Textualize/rich/pull/1873 ### Fixed -- Workaround for edge case of object from Faiss with no `__class__` -- Ensure `Syntax` always justifies left -- Handle classes in inspect when methods=True +- Workaround for edge case of object from Faiss with no `__class__` https://github.com/Textualize/rich/issues/1838 +- Ensure `Syntax` always justifies left https://github.com/Textualize/rich/pull/1872 +- Handle classes in inspect when methods=True https://github.com/Textualize/rich/pull/1874 ## [11.0.0] - 2022-01-09 ### Added -- Added max_depth arg to pretty printing -- Added `vertical_align` to Table.add_row +- Added max_depth arg to pretty printing https://github.com/Textualize/rich/issues/1585 +- Added `vertical_align` to Table.add_row https://github.com/Textualize/rich/issues/1590 ### Fixed -- Fixed issue with pretty repr in jupyter notebook -- Fix Traceback theme defaults override user supplied styles +- Fixed issue with pretty repr in jupyter notebook https://github.com/Textualize/rich/issues/1717 +- Fix Traceback theme defaults override user supplied styles https://github.com/Textualize/rich/issues/1786 ### Changed -- __breaking__ Deprecated rich.console.RenderGroup, now named rich.console.Group -- __breaking__ `Syntax.__init__` parameter `lexer_name` renamed to `lexer` -- Syntax constructor accepts both str and now a pygments lexer +- **breaking** Deprecated rich.console.RenderGroup, now named rich.console.Group +- **breaking** `Syntax.__init__` parameter `lexer_name` renamed to `lexer` +- Syntax constructor accepts both str and now a pygments lexer https://github.com/Textualize/rich/pull/1748 ## [10.16.2] - 2021-01-02 @@ -397,23 +399,23 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Fixed issues with overlapping tags +- Fixed issues with overlapping tags https://github.com/textualize/rich/issues/1755 ## [10.16.0] - 2021-12-12 ### Fixed -- Double print of progress bar in Jupyter +- Double print of progress bar in Jupyter https://github.com/textualize/rich/issues/1737 ### Added -- Added Text.markup property +- Added Text.markup property https://github.com/textualize/rich/issues/1751 ## [10.15.2] - 2021-12-02 ### Fixed -- Deadlock issue +- Deadlock issue https://github.com/textualize/rich/issues/1734 ## [10.15.1] - 2021-11-29 @@ -435,51 +437,51 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Fixed issue with progress bar not rendering markup -- Fixed race condition when exiting Live +- Fixed issue with progress bar not rendering markup https://github.com/textualize/rich/issues/1721 +- Fixed race condition when exiting Live https://github.com/textualize/rich/issues/1530 ## [10.14.0] - 2021-11-16 ### Fixed - Fixed progress speed not updating when total doesn't change -- Fixed superfluous new line in Status +- Fixed superfluous new line in Status https://github.com/textualize/rich/issues/1662 - Fixed Windows legacy width again -- Fixed infinite loop in set_cell_size +- Fixed infinite loop in set_cell_size https://github.com/textualize/rich/issues/1682 ### Added -- Added file protocol to URL highlighter +- Added file protocol to URL highlighter https://github.com/textualize/rich/issues/1681 - Added rich.protocol.rich_cast ### Changed - Allowed `__rich__` to work recursively -- Allowed Text classes to work with sep in print +- Allowed Text classes to work with sep in print https://github.com/textualize/rich/issues/1689 ### Added -- Added a `rich.text.Text.from_ansi` helper method for handling pre-formatted input strings +- Added a `rich.text.Text.from_ansi` helper method for handling pre-formatted input strings https://github.com/textualize/rich/issues/1670 ## [10.13.0] - 2021-11-07 ### Added -- Added json.dumps parameters to print_json +- Added json.dumps parameters to print_json https://github.com/textualize/rich/issues/1638 ### Fixed - Fixed an edge case bug when console module try to detect if they are in a tty at the end of a pytest run -- Fixed a bug where logging handler raises an exception when running with pythonw (related to ) -- Fixed issue with TERM env vars that have more than one hyphen -- Fixed missing new line after progress bar when terminal is not interactive -- Fixed exception in IPython when disabling pprint with %pprint -- Fixed issue where values longer than the console width produced invalid JSON -- Fixes trailing comma when pretty printing dataclass with last field repr=False +- Fixed a bug where logging handler raises an exception when running with pythonw (related to https://bugs.python.org/issue13807) +- Fixed issue with TERM env vars that have more than one hyphen https://github.com/textualize/rich/issues/1640 +- Fixed missing new line after progress bar when terminal is not interactive https://github.com/textualize/rich/issues/1606 +- Fixed exception in IPython when disabling pprint with %pprint https://github.com/textualize/rich/issues/1646 +- Fixed issue where values longer than the console width produced invalid JSON https://github.com/textualize/rich/issues/1653 +- Fixes trailing comma when pretty printing dataclass with last field repr=False https://github.com/textualize/rich/issues/1599 ## Changed -- Markdown codeblocks now word-wrap +- Markdown codeblocks now word-wrap https://github.com/textualize/rich/issues/1515 ## [10.12.0] - 2021-10-06 @@ -506,7 +508,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Fixed pretty printing of objects with fo magic with __getattr__ +- Fixed pretty printing of objects with fo magic with **getattr** https://github.com/textualize/rich/issues/1492 ## [10.9.0] - 2021-08-29 @@ -532,7 +534,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed - Fixed a bug where calling `rich.reconfigure` within a `pytest_configure` hook would lead to a crash -- Fixed highlight not being passed through options +- Fixed highlight not being passed through options https://github.com/textualize/rich/issues/1404 ## [10.7.0] - 2021-08-05 @@ -566,7 +568,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Fixed issue with adjoining color tags +- Fixed issue with adjoining color tags https://github.com/textualize/rich/issues/1334 ### Changed @@ -576,10 +578,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Fixed Pandas objects not pretty printing -- Fixed +- Fixed Pandas objects not pretty printing https://github.com/textualize/rich/issues/1305 +- Fixed https://github.com/textualize/rich/issues/1256 - Fixed typing with rich.repr.auto decorator -- Fixed repr error formatting +- Fixed repr error formatting https://github.com/textualize/rich/issues/1326 ### Added @@ -597,7 +599,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Fixed error pretty printing classes with special __rich_repr__ method +- Fixed error pretty printing classes with special **rich_repr** method ## [10.3.0] - 2021-06-09 @@ -617,13 +619,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Fixed status not rendering console markup +- Fixed status not rendering console markup https://github.com/textualize/rich/issues/1244 ## [10.2.1] - 2021-05-17 ### Fixed -- Fixed panel in Markdown exploding +- Fixed panel in Markdown exploding https://github.com/textualize/rich/issues/1234 ## [10.2.0] - 2021-05-12 @@ -642,7 +644,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Fixed initial blank lines removed from Syntax +- Fixed initial blank lines removed from Syntax https://github.com/textualize/rich/issues/1214 ## [10.1.0] - 2021-04-03 @@ -654,13 +656,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Fixed race condition that duplicated lines in progress +- Fixed race condition that duplicated lines in progress https://github.com/textualize/rich/issues/1144 ## [10.0.0] - 2021-03-27 ### Changed -- Made pydoc import lazy as at least one use found it slow to import +- Made pydoc import lazy as at least one use found it slow to import https://github.com/textualize/rich/issues/1104 - Modified string highlighting to not match in the middle of a word, so that apostrophes are not considered strings - New way of encoding control codes in Segment - New signature for Control class @@ -684,10 +686,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Fixed table style taking precedence over row style -- Fixed incorrect measurement of Text with new lines and whitespace +- Fixed table style taking precedence over row style https://github.com/textualize/rich/issues/1129 +- Fixed incorrect measurement of Text with new lines and whitespace https://github.com/textualize/rich/issues/1133 - Made type annotations consistent for various `total` keyword arguments in `rich.progress` and rich.`progress_bar` -- Disabled Progress no longer displays itself when starting +- Disabled Progress no longer displays itself when starting https://github.com/textualize/rich/pull/1125 - Animations no longer reset when updating rich.status.Status ## [9.13.0] - 2021-03-06 @@ -698,8 +700,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Fixed Syntax background -- Fix for double tracebacks when no formatter +- Fixed Syntax background https://github.com/textualize/rich/issues/1088 +- Fix for double tracebacks when no formatter https://github.com/textualize/rich/issues/1079 ### Changed @@ -709,7 +711,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Fixed custom formatters with rich tracebacks in RichHandler +- Fixed custom formatters with rich tracebacks in RichHandler https://github.com/textualize/rich/issues/1079 ### Changed @@ -736,7 +738,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Fixed deadlock in Progress +- Fixed deadlock in Progress https://github.com/textualize/rich/issues/1061 ### Added @@ -752,14 +754,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Fixed issue with Syntax and missing lines in Layout -- Fixed issue with nested markdown elements -- Fixed new lines not invoking render hooks -- Fixed Align setting height to child +- Fixed issue with Syntax and missing lines in Layout https://github.com/textualize/rich/issues/1050 +- Fixed issue with nested markdown elements https://github.com/textualize/rich/issues/1036 +- Fixed new lines not invoking render hooks https://github.com/textualize/rich/issues/1052 +- Fixed Align setting height to child https://github.com/textualize/rich/issues/1057 ### Changed -- Printing a table with no columns now result in a blank line +- Printing a table with no columns now result in a blank line https://github.com/textualize/rich/issues/1044 ### Added @@ -771,9 +773,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Fixed table with expand=False not expanding when justify="center" - Fixed single renderable in Layout not respecting height -- Fixed COLUMNS and LINES env var +- Fixed COLUMNS and LINES env var https://github.com/textualize/rich/issues/1019 - Layout now respects minimum_size when fixes sizes are greater than available space -- HTML export now changes link underline score to match terminal +- HTML export now changes link underline score to match terminal https://github.com/textualize/rich/issues/1009 ### Changed @@ -788,8 +790,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Fixed error message for tracebacks with broken `__str__` -- Fixed markup edge case +- Fixed error message for tracebacks with broken `__str__` https://github.com/textualize/rich/issues/980 +- Fixed markup edge case https://github.com/textualize/rich/issues/987 ### Added @@ -830,7 +832,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Fix double line tree guides on Windows - Fixed Tracebacks ignoring initial blank lines - Partial fix for tracebacks not finding source after chdir -- Fixed error message when code in tracebacks doesn't have an extension +- Fixed error message when code in tracebacks doesn't have an extension https://github.com/textualize/rich/issues/996 ### Added @@ -840,19 +842,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Fixed deadlock in live +- Fixed deadlock in live https://github.com/textualize/rich/issues/927 ## [9.8.1] - 2021-01-13 ### Fixed -- Fixed rich.inspect failing with attributes that claim to be callable but aren't +- Fixed rich.inspect failing with attributes that claim to be callable but aren't https://github.com/textualize/rich/issues/916 ## [9.8.0] - 2021-01-11 ### Added -- Added __rich_measure__ for tree +- Added **rich_measure** for tree - Added rich.align.VerticalCenter ### Changed @@ -865,7 +867,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Fixed panel cropping when shrunk too bar - Allow passing markdown over STDIN when using `python -m rich.markdown` -- Fix printing MagicMock.mock_calls +- Fix printing MagicMock.mock_calls https://github.com/textualize/rich/issues/903 ## [9.7.0] - 2021-01-09 @@ -878,9 +880,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Fixed markup escaping edge case +- Fixed markup escaping edge case https://github.com/textualize/rich/issues/878 - Double tag escape, i.e. `"\\[foo]"` results in a backslash plus `[foo]` tag -- Fixed header_style not applying to headers in positional args +- Fixed header_style not applying to headers in positional args https://github.com/textualize/rich/issues/953 ## [9.6.1] - 2020-12-31 @@ -909,7 +911,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Fixed terminal size detection on Windows +- Fixed terminal size detection on Windows https://github.com/textualize/rich/issues/836 - Fixed hex number highlighting ## [9.5.0] - 2020-12-18 @@ -933,15 +935,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Fixed double output in rich.live -- Fixed Console.out highlighting not reflecting defaults -- FileProxy now raises TypeError for empty non-str arguments +- Fixed double output in rich.live https://github.com/textualize/rich/issues/485 +- Fixed Console.out highlighting not reflecting defaults https://github.com/textualize/rich/issues/827 +- FileProxy now raises TypeError for empty non-str arguments https://github.com/textualize/rich/issues/828 ## [9.4.0] - 2020-12-12 ### Added -- Added rich.live +- Added rich.live https://github.com/textualize/rich/pull/382 - Added algin parameter to Rule and Console.rule - Added rich.Status class and Console.status - Added getitem to Text @@ -955,7 +957,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## Fixed -- Fixed suppressed traceback context +- Fixed suppressed traceback context https://github.com/textualize/rich/issues/468 ## [9.3.0] - 2020-12-1 @@ -976,9 +978,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed - Fixed redirecting of stderr in Progress -- Fixed broken expanded tuple of one +- Fixed broken expanded tuple of one https://github.com/textualize/rich/issues/445 - Fixed traceback message with `from` exceptions -- Fixed justify argument not working in console.log +- Fixed justify argument not working in console.log https://github.com/textualize/rich/issues/460 ## [9.2.0] - 2020-11-08 @@ -1015,13 +1017,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Fixed negative time remaining in Progress bars +- Fixed negative time remaining in Progress bars https://github.com/textualize/rich/issues/378 ## [9.0.1] - 2020-10-19 ### Fixed -- Fixed broken ANSI codes in input on windows legacy +- Fixed broken ANSI codes in input on windows legacy https://github.com/textualize/rich/issues/393 ## [9.0.0] - 2020-10-18 @@ -1041,14 +1043,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Added binary_units in progress download column - Added Progress.reset - Added Style.background_style property -- Added Bar renderable +- Added Bar renderable https://github.com/textualize/rich/pull/361 - Added Table.min_width - Added table.Column.min_width and table.Column.max_width, and same to Table.add_column ### Changed - Dropped box.get_safe_box function in favor of Box.substitute -- Changed default padding in Panel from 0 to (0, 1) +- Changed default padding in Panel from 0 to (0, 1) https://github.com/textualize/rich/issues/385 - Table with row_styles will extend background color between cells if the box has no vertical dividerhttps://github.com/textualize/rich/issues/383 - Changed default of fit kwarg in render_group() from False to True - Renamed rich.bar to rich.progress_bar, and Bar class to ProgressBar, rich.bar is now the new solid bar class @@ -1082,12 +1084,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added - Added Console.begin_capture, Console.end_capture and Console.capture -- Added Table.title_justify and Table.caption_justify +- Added Table.title_justify and Table.caption_justify https://github.com/textualize/rich/issues/301 ### Changed - Improved formatting of exceptions -- Enabled Rich exceptions in logging +- Enabled Rich exceptions in logging https://github.com/taliraj - UTF-8 encoding is now mentioned in HTML head section ### Removed @@ -1173,7 +1175,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Fixed underscore with display hook +- Fixed underscore with display hook https://github.com/textualize/rich/issues/235 ## [5.2.0] - 2020-08-14 @@ -1181,7 +1183,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Added crop argument to Console.print - Added "ignore" overflow method -- Added multiple characters per rule @hedythedev +- Added multiple characters per rule @hedythedev https://github.com/textualize/rich/pull/207 ## [5.1.2] - 2020-08-10 @@ -1200,12 +1202,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added - Added Text.cell_len -- Added helpful message regarding unicode decoding errors +- Added helpful message regarding unicode decoding errors https://github.com/textualize/rich/issues/212 - Added display hook with pretty.install() ### Fixed -- Fixed deprecation warnings re backslash +- Fixed deprecation warnings re backslash https://github.com/textualize/rich/issues/210 - Fixed repr highlighting of scientific notation, e.g. 1e100 ### Changed @@ -1226,30 +1228,30 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed - Added thread to automatically call update() in progress.track(). Replacing previous adaptive algorithm. -- Second attempt at working around +- Second attempt at working around https://bugs.python.org/issue37871 ## [4.2.1] - 2020-07-29 ### Added -- Added show_time and show_level parameters to RichHandler +- Added show_time and show_level parameters to RichHandler https://github.com/textualize/rich/pull/182 ### Fixed -- Fixed progress.track iterator exiting early -- Added workaround for Python bug , fixing +- Fixed progress.track iterator exiting early https://github.com/textualize/rich/issues/189 +- Added workaround for Python bug https://bugs.python.org/issue37871, fixing https://github.com/textualize/rich/issues/186 ### Changed -- Set overflow=fold for log messages +- Set overflow=fold for log messages https://github.com/textualize/rich/issues/190 ## [4.2.0] - 2020-07-27 ### Fixed -- Fixed missing new lines -- Fixed Progress.track -- Remove control codes from exported text +- Fixed missing new lines https://github.com/textualize/rich/issues/178 +- Fixed Progress.track https://github.com/textualize/rich/issues/184 +- Remove control codes from exported text https://github.com/textualize/rich/issues/181 - Implemented auto-detection and color rendition of 16-color mode ## [4.1.0] - 2020-07-26 @@ -1265,7 +1267,7 @@ Major version bump for a breaking change to `Text.stylize signature`, which corr ### Added -- Added markup switch to RichHandler +- Added markup switch to RichHandler https://github.com/textualize/rich/issues/171 ### Changed @@ -1274,7 +1276,7 @@ Major version bump for a breaking change to `Text.stylize signature`, which corr ### Fixed -- Fixed rendering of Confirm prompt +- Fixed rendering of Confirm prompt https://github.com/textualize/rich/issues/170 ## [3.4.1] - 2020-07-22 @@ -1369,7 +1371,7 @@ Major version bump for a breaking change to `Text.stylize signature`, which corr ### Changed -- More precise detection of Windows console +- More precise detection of Windows console https://github.com/textualize/rich/issues/140 ## [3.0.3] - 2020-07-03 @@ -1426,7 +1428,7 @@ Major version bump for a breaking change to `Text.stylize signature`, which corr ### Fixed -- Disabled legacy_windows if jupyter is detected +- Disabled legacy_windows if jupyter is detected https://github.com/textualize/rich/issues/125 ## [2.3.0] - 2020-06-26 @@ -1447,13 +1449,13 @@ Major version bump for a breaking change to `Text.stylize signature`, which corr ### Changed -- Store a "link id" on Style instance, so links containing different styles are highlighted together. () +- Store a "link id" on Style instance, so links containing different styles are highlighted together. (https://github.com/textualize/rich/pull/123) ## [2.2.5] - 2020-06-23 ### Fixed -- Fixed justify of tables () +- Fixed justify of tables (https://github.com/textualize/rich/issues/117) ## [2.2.4] - 2020-06-21 @@ -1581,7 +1583,7 @@ Major version bump for a breaking change to `Text.stylize signature`, which corr ### Fixed -- Fixed Progress deadlock +- Fixed Progress deadlock https://github.com/textualize/rich/issues/90 ### Changed @@ -1712,7 +1714,7 @@ Major version bump for a breaking change to `Text.stylize signature`, which corr ### Fixed -- Issue with Windows legacy support +- Issue with Windows legacy support https://github.com/textualize/rich/issues/59 ## [1.0.1] - 2020-05-08 @@ -1734,7 +1736,7 @@ Major version bump for a breaking change to `Text.stylize signature`, which corr ### Fixed -- Fixed Text.assemble not working with strings +- Fixed Text.assemble not working with strings https://github.com/textualize/rich/issues/57 - Fixed table when column widths must be compressed to fit ## [1.0.0] - 2020-05-03 @@ -1859,7 +1861,7 @@ Major version bump for a breaking change to `Text.stylize signature`, which corr ### Changed -- Dropped support for Windows command prompt (try ) +- Dropped support for Windows command prompt (try https://www.microsoft.com/en-gb/p/windows-terminal-preview/) - Added task_id to Progress.track ## [0.7.2] - 2020-03-15 @@ -1944,7 +1946,7 @@ Major version bump for a breaking change to `Text.stylize signature`, which corr ### Fixed - Fixed Windows color support -- Fixed line width on windows issue () +- Fixed line width on windows issue (https://github.com/textualize/rich/issues/7) - Fixed Pretty print on Windows ## [0.3.2] - 2020-01-26 @@ -1965,9 +1967,9 @@ Major version bump for a breaking change to `Text.stylize signature`, which corr - First official release, API still to be stabilized -[13.4.2]: https://github.com/textualize/rich/compare/v13.4.1...v13.4.2 -[13.4.1]: https://github.com/textualize/rich/compare/v13.4.0...v13.4.1 -[13.4.0]: https://github.com/textualize/rich/compare/v13.3.5...v13.4.0 +[13.4.2]: https://github.com/textualize/rich/compare/v13.4.1...v13.4.2 +[13.4.1]: https://github.com/textualize/rich/compare/v13.4.0...v13.4.1 +[13.4.0]: https://github.com/textualize/rich/compare/v13.3.5...v13.4.0 [13.3.5]: https://github.com/textualize/rich/compare/v13.3.4...v13.3.5 [13.3.4]: https://github.com/textualize/rich/compare/v13.3.3...v13.3.4 [13.3.3]: https://github.com/textualize/rich/compare/v13.3.2...v13.3.3 From fad55f7a2108d7a130f661803b55609d24b040de Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 7 Aug 2023 14:07:06 +0000 Subject: [PATCH 21/62] Bump snok/install-poetry from 1.3.3 to 1.3.4 Bumps [snok/install-poetry](https://github.com/snok/install-poetry) from 1.3.3 to 1.3.4. - [Release notes](https://github.com/snok/install-poetry/releases) - [Commits](https://github.com/snok/install-poetry/compare/v1.3.3...v1.3.4) --- updated-dependencies: - dependency-name: snok/install-poetry dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- .github/workflows/pythonpackage.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/pythonpackage.yml b/.github/workflows/pythonpackage.yml index 79ad51e6..a2f0de81 100644 --- a/.github/workflows/pythonpackage.yml +++ b/.github/workflows/pythonpackage.yml @@ -21,7 +21,7 @@ jobs: architecture: x64 - name: Install and configure Poetry # TODO: workaround for https://github.com/snok/install-poetry/issues/94 - uses: snok/install-poetry@v1.3.3 + uses: snok/install-poetry@v1.3.4 with: version: 1.3.1 virtualenvs-in-project: true From 1c426f40ed48bd9adcdfa008ae9724410f54132f Mon Sep 17 00:00:00 2001 From: Jakub <77514091+Coderbeep@users.noreply.github.com> Date: Tue, 3 Oct 2023 00:59:04 +0200 Subject: [PATCH 22/62] docstring supplement for Panel class --- rich/panel.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/rich/panel.py b/rich/panel.py index d522d80b..fce30d86 100644 --- a/rich/panel.py +++ b/rich/panel.py @@ -22,11 +22,13 @@ class Panel(JupyterMixin): Args: renderable (RenderableType): A console renderable object. - box (Box, optional): A Box instance that defines the look of the border (see :ref:`appendix_box`. - Defaults to box.ROUNDED. + box (Box, optional): A Box instance that defines the look of the border (see :ref:`appendix_box`. Defaults to box.ROUNDED. + title (Optional[TextType], optional): Optional title displayed in panel header. Defaults to None. + title_align (AlignMethod, optional): Alignment of title. Defaults to "center". + subtitle (Optional[TextType], optional): Optional subtitle displayed in panel footer. Defaults to None. + subtitle_align (AlignMethod, optional): Alignment of subtitle. Defaults to "center". safe_box (bool, optional): Disable box characters that don't display on windows legacy terminal with *raster* fonts. Defaults to True. - expand (bool, optional): If True the panel will stretch to fill the console - width, otherwise it will be sized to fit the contents. Defaults to True. + expand (bool, optional): If True the panel will stretch to fill the console width, otherwise it will be sized to fit the contents. Defaults to True. style (str, optional): The style of the panel (border and contents). Defaults to "none". border_style (str, optional): The style of the border. Defaults to "none". width (Optional[int], optional): Optional width of panel. Defaults to None to auto-detect. From 2df8b44732e609fdeff21ad97dd260135def82d3 Mon Sep 17 00:00:00 2001 From: Coderbeep <77514091+Coderbeep@users.noreply.github.com> Date: Tue, 3 Oct 2023 11:21:44 +0200 Subject: [PATCH 23/62] hide_root arg in the Tree class --- rich/tree.py | 1 + 1 file changed, 1 insertion(+) diff --git a/rich/tree.py b/rich/tree.py index b9b7bbe5..1c25adb9 100644 --- a/rich/tree.py +++ b/rich/tree.py @@ -18,6 +18,7 @@ class Tree(JupyterMixin): guide_style (StyleType, optional): Style of the guide lines. Defaults to "tree.line". expanded (bool, optional): Also display children. Defaults to True. highlight (bool, optional): Highlight renderable (if str). Defaults to False. + hide_root (bool, optional): Hide the root node. Defaults to False. """ def __init__( From 0ed4cabb7b17fc3373ed791981be9e351af31d5d Mon Sep 17 00:00:00 2001 From: Coderbeep <77514091+Coderbeep@users.noreply.github.com> Date: Tue, 3 Oct 2023 11:23:53 +0200 Subject: [PATCH 24/62] VerticalCenter - added style arg --- rich/align.py | 1 + 1 file changed, 1 insertion(+) diff --git a/rich/align.py b/rich/align.py index e8fc3062..ad939d9a 100644 --- a/rich/align.py +++ b/rich/align.py @@ -240,6 +240,7 @@ class VerticalCenter(JupyterMixin): Args: renderable (RenderableType): A renderable object. + style (StyleType, optional): An optional style to apply to the background. Defaults to None. """ def __init__( From 027703f6fbc64c2d8036c5577fe3dba8c76eb98f Mon Sep 17 00:00:00 2001 From: Coderbeep <77514091+Coderbeep@users.noreply.github.com> Date: Tue, 3 Oct 2023 11:35:07 +0200 Subject: [PATCH 25/62] used black tree.py --- rich/tree.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/rich/tree.py b/rich/tree.py index 1c25adb9..03f835c3 100644 --- a/rich/tree.py +++ b/rich/tree.py @@ -73,7 +73,6 @@ class Tree(JupyterMixin): def __rich_console__( self, console: "Console", options: "ConsoleOptions" ) -> "RenderResult": - stack: List[Iterator[Tuple[bool, Tree]]] = [] pop = stack.pop push = stack.append @@ -196,7 +195,6 @@ class Tree(JupyterMixin): if __name__ == "__main__": # pragma: no cover - from rich.console import Group from rich.markdown import Markdown from rich.panel import Panel From f00cadc5814ef6cf445945ce03230bcfaf3f5626 Mon Sep 17 00:00:00 2001 From: Gene Myslinsky <47491689+GeneMyslinsky@users.noreply.github.com> Date: Sun, 22 Oct 2023 18:52:21 -0400 Subject: [PATCH 26/62] added max_frames !f --- rich/logging.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/rich/logging.py b/rich/logging.py index 96859934..9c38384e 100644 --- a/rich/logging.py +++ b/rich/logging.py @@ -41,6 +41,7 @@ class RichHandler(Handler): tracebacks_word_wrap (bool, optional): Enable word wrapping of long tracebacks lines. Defaults to True. tracebacks_show_locals (bool, optional): Enable display of locals in tracebacks. Defaults to False. tracebacks_suppress (Sequence[Union[str, ModuleType]]): Optional sequence of modules or paths to exclude from traceback. + tracebacks_max_frames (int, optional): Optional maximum number of frames returned by traceback. locals_max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation. Defaults to 10. locals_max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to 80. @@ -79,6 +80,7 @@ class RichHandler(Handler): tracebacks_word_wrap: bool = True, tracebacks_show_locals: bool = False, tracebacks_suppress: Iterable[Union[str, ModuleType]] = (), + tracebacks_max_frames: int = 100, locals_max_length: int = 10, locals_max_string: int = 80, log_time_format: Union[str, FormatTimeCallable] = "[%x %X]", @@ -104,6 +106,7 @@ class RichHandler(Handler): self.tracebacks_word_wrap = tracebacks_word_wrap self.tracebacks_show_locals = tracebacks_show_locals self.tracebacks_suppress = tracebacks_suppress + self.tracebacks_max_frames = tracebacks_max_frames self.locals_max_length = locals_max_length self.locals_max_string = locals_max_string self.keywords = keywords @@ -147,6 +150,7 @@ class RichHandler(Handler): locals_max_length=self.locals_max_length, locals_max_string=self.locals_max_string, suppress=self.tracebacks_suppress, + max_frames=self.tracebacks_max_frames, ) message = record.getMessage() if self.formatter: From a9669b8859d53259494b5f4cccbff72987554104 Mon Sep 17 00:00:00 2001 From: Jules Gagnon-Marchand Date: Tue, 24 Oct 2023 14:37:18 -0400 Subject: [PATCH 27/62] Enable per-column enabling or disabling of highlighting Defaults to the value of the self.table when the default value of None is unchanged. It seems like the Column constructor didn't receive a `highlight` value, so I guess that it used to receive a highlight value at a later point. Someone who knows the project better could comment on that. --- rich/table.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/rich/table.py b/rich/table.py index 578d3d63..a6e29166 100644 --- a/rich/table.py +++ b/rich/table.py @@ -366,6 +366,7 @@ class Table(JupyterMixin): footer: "RenderableType" = "", *, header_style: Optional[StyleType] = None, + highlight: Optional[bool] = None, footer_style: Optional[StyleType] = None, style: Optional[StyleType] = None, justify: "JustifyMethod" = "left", @@ -385,6 +386,7 @@ class Table(JupyterMixin): footer (RenderableType, optional): Text or renderable for the footer. Defaults to "". header_style (Union[str, Style], optional): Style for the header, or None for default. Defaults to None. + highlight (bool, optional): Whether to highlight the text. The default of None uses the value of the table (self) object. footer_style (Union[str, Style], optional): Style for the footer, or None for default. Defaults to None. style (Union[str, Style], optional): Style for the column cells, or None for default. Defaults to None. justify (JustifyMethod, optional): Alignment for cells. Defaults to "left". @@ -402,6 +404,7 @@ class Table(JupyterMixin): header=header, footer=footer, header_style=header_style or "", + highlight=highlight if highlight is not None else self.highlight, footer_style=footer_style or "", style=style or "", justify=justify, From 15cc59b1a253fe9a4cbc3d4c770638bcf61558fe Mon Sep 17 00:00:00 2001 From: Grant Ramsay Date: Wed, 8 Nov 2023 08:12:49 +0000 Subject: [PATCH 28/62] refactor to 'case_sensitive' with default True --- CHANGELOG.md | 13 +++++++------ docs/source/prompt.rst | 4 ++-- rich/prompt.py | 28 ++++++++++++++-------------- tests/test_prompt.py | 2 +- 4 files changed, 24 insertions(+), 23 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 34e86652..1c25b6ac 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,7 +10,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added - Adds missing parameters to Panel.fit https://github.com/Textualize/rich/issues/3142 -- Adds a `case_insensitive` parameter to `prompt.Prompt`. This allows the `choices` list to be accepted without regard to case. Defaults to `False`. +- Adds a `case_sensitive` parameter to `prompt.Prompt`. This determines if the + response is treated as case-sensitive. Defaults to `True`. ### Fixed @@ -48,7 +49,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Fixed Text.expand_tabs not expanding spans. - Fixed TimeElapsedColumn from showing negative. - Fix for escaping strings with a trailing backslash https://github.com/Textualize/rich/issues/2987 -- Fixed exception in Markdown with partial table https://github.com/Textualize/rich/issues/3053 +- Fixed exception in Markdown with partial table https://github.com/Textualize/rich/issues/3053 - Fixed the HTML export template so that the `` tag comes before the `` tag https://github.com/Textualize/rich/issues/3021 - Fixed issue with custom classes overwriting `__eq__` https://github.com/Textualize/rich/issues/2875 - Fix rich.pretty.install breakage in iPython https://github.com/Textualize/rich/issues/3013 @@ -2021,10 +2022,10 @@ Major version bump for a breaking change to `Text.stylize signature`, which corr [13.5.3]: https://github.com/textualize/rich/compare/v13.5.2...v13.5.3 [13.5.2]: https://github.com/textualize/rich/compare/v13.5.1...v13.5.2 [13.5.1]: https://github.com/textualize/rich/compare/v13.5.0...v13.5.1 -[13.5.0]: https://github.com/textualize/rich/compare/v13.4.2...v13.5.0 -[13.4.2]: https://github.com/textualize/rich/compare/v13.4.1...v13.4.2 -[13.4.1]: https://github.com/textualize/rich/compare/v13.4.0...v13.4.1 -[13.4.0]: https://github.com/textualize/rich/compare/v13.3.5...v13.4.0 +[13.5.0]: https://github.com/textualize/rich/compare/v13.4.2...v13.5.0 +[13.4.2]: https://github.com/textualize/rich/compare/v13.4.1...v13.4.2 +[13.4.1]: https://github.com/textualize/rich/compare/v13.4.0...v13.4.1 +[13.4.0]: https://github.com/textualize/rich/compare/v13.3.5...v13.4.0 [13.3.5]: https://github.com/textualize/rich/compare/v13.3.4...v13.3.5 [13.3.4]: https://github.com/textualize/rich/compare/v13.3.3...v13.3.4 [13.3.3]: https://github.com/textualize/rich/compare/v13.3.2...v13.3.3 diff --git a/docs/source/prompt.rst b/docs/source/prompt.rst index 1909aafd..b998cdfa 100644 --- a/docs/source/prompt.rst +++ b/docs/source/prompt.rst @@ -18,10 +18,10 @@ If you supply a list of choices, the prompt will loop until the user enters one >>> from rich.prompt import Prompt >>> name = Prompt.ask("Enter your name", choices=["Paul", "Jessica", "Duncan"], default="Paul") -By default this is case sensitive, but you can set `case_insensitive=True` to make it case insensitive:: +By default this is case sensitive, but you can set `case_sensitive=False` to make it case insensitive:: >>> from rich.prompt import Prompt - >>> name = Prompt.ask("Enter your name", choices=["Paul", "Jessica", "Duncan"], default="Paul", case_insensitive=True) + >>> name = Prompt.ask("Enter your name", choices=["Paul", "Jessica", "Duncan"], default="Paul", case_sensitive=False) Now, it would accept "paul" or "Paul" as valid responses. diff --git a/rich/prompt.py b/rich/prompt.py index b23762ce..761584ba 100644 --- a/rich/prompt.py +++ b/rich/prompt.py @@ -36,7 +36,7 @@ class PromptBase(Generic[PromptType]): console (Console, optional): A Console instance or None to use global console. Defaults to None. password (bool, optional): Enable password input. Defaults to False. choices (List[str], optional): A list of valid choices. Defaults to None. - case_insensitive (bool, optional): Enable case insensitive matching of choices. Defaults to False. + case_sensitive (bool, optional): Matching of choices should be case-sensitive. Defaults to True. show_default (bool, optional): Show default in prompt. Defaults to True. show_choices (bool, optional): Show choices in prompt. Defaults to True. """ @@ -58,7 +58,7 @@ class PromptBase(Generic[PromptType]): console: Optional[Console] = None, password: bool = False, choices: Optional[List[str]] = None, - case_insensitive: bool = False, + case_sensitive: bool = True, show_default: bool = True, show_choices: bool = True, ) -> None: @@ -71,7 +71,7 @@ class PromptBase(Generic[PromptType]): self.password = password if choices is not None: self.choices = choices - self.case_insensitive = case_insensitive + self.case_sensitive = case_sensitive self.show_default = show_default self.show_choices = show_choices @@ -84,7 +84,7 @@ class PromptBase(Generic[PromptType]): console: Optional[Console] = None, password: bool = False, choices: Optional[List[str]] = None, - case_insensitive: bool = False, + case_sensitive: bool = True, show_default: bool = True, show_choices: bool = True, default: DefaultType, @@ -101,7 +101,7 @@ class PromptBase(Generic[PromptType]): console: Optional[Console] = None, password: bool = False, choices: Optional[List[str]] = None, - case_insensitive: bool = False, + case_sensitive: bool = True, show_default: bool = True, show_choices: bool = True, stream: Optional[TextIO] = None, @@ -116,7 +116,7 @@ class PromptBase(Generic[PromptType]): console: Optional[Console] = None, password: bool = False, choices: Optional[List[str]] = None, - case_insensitive: bool = False, + case_sensitive: bool = True, show_default: bool = True, show_choices: bool = True, default: Any = ..., @@ -132,7 +132,7 @@ class PromptBase(Generic[PromptType]): console (Console, optional): A Console instance or None to use global console. Defaults to None. password (bool, optional): Enable password input. Defaults to False. choices (List[str], optional): A list of valid choices. Defaults to None. - case_insensitive (bool, optional): Enable case insensitive matching of choices. Defaults to False. + case_sensitive (bool, optional): Matching of choices should be case-sensitive. Defaults to True. show_default (bool, optional): Show default in prompt. Defaults to True. show_choices (bool, optional): Show choices in prompt. Defaults to True. stream (TextIO, optional): Optional text file open for reading to get input. Defaults to None. @@ -142,7 +142,7 @@ class PromptBase(Generic[PromptType]): console=console, password=password, choices=choices, - case_insensitive=case_insensitive, + case_sensitive=case_sensitive, show_default=show_default, show_choices=show_choices, ) @@ -220,9 +220,9 @@ class PromptBase(Generic[PromptType]): bool: True if choice was valid, otherwise False. """ assert self.choices is not None - if self.case_insensitive: - return value.strip().lower() in [choice.lower() for choice in self.choices] - return value.strip() in self.choices + if self.case_sensitive: + return value.strip() in self.choices + return value.strip().lower() in [choice.lower() for choice in self.choices] def process_response(self, value: str) -> PromptType: """Process response from user, convert to prompt type. @@ -246,7 +246,7 @@ class PromptBase(Generic[PromptType]): if not self.check_choice(value): raise InvalidResponse(self.illegal_choice_message) - if self.case_insensitive: + if not self.case_sensitive: # return the original choice, not the lower case version return_value = self.response_type( self.choices[ @@ -391,8 +391,8 @@ if __name__ == "__main__": # pragma: no cover doggie = Prompt.ask( "What's the best Dog? (Case INSENSITIVE)", - choices=["BT", "Collie", "Labradoodle"], - case_insensitive=True, + choices=["Border Terrier", "Collie", "Labradoodle"], + case_sensitive=False, ) print(f"doggie={doggie!r}") diff --git a/tests/test_prompt.py b/tests/test_prompt.py index d8faf7f0..11bffa71 100644 --- a/tests/test_prompt.py +++ b/tests/test_prompt.py @@ -29,7 +29,7 @@ def test_prompt_str_case_insensitive(): console=console, choices=["foo", "bar"], default="baz", - case_insensitive=True, + case_sensitive=False, stream=io.StringIO(INPUT), ) assert name == "foo" From 9ba0dc10b18782cf29fee6c302147a5725ef268d Mon Sep 17 00:00:00 2001 From: alex-rakowski Date: Sun, 19 Nov 2023 21:33:21 -0800 Subject: [PATCH 29/62] use mypyc compiled black and update verison --- .pre-commit-config.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index a113c352..37db4643 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -30,8 +30,8 @@ repos: hooks: - id: pycln args: [--all] - - repo: https://github.com/psf/black - rev: 23.7.0 + - repo: https://github.com/psf/black-pre-commit-mirror + rev: 23.11.0 hooks: - id: black exclude: ^benchmarks/ From 0060a9eb7d0d130b7073f363840688983968f192 Mon Sep 17 00:00:00 2001 From: Haskely Date: Thu, 30 Nov 2023 21:22:24 +0800 Subject: [PATCH 30/62] Add 'completed' parameter to 'track' function for resumable progress This commit introduces a new 'completed' parameter to the 'track' function in order to support resumable progress. Now users can specify the starting point for progress, making it easier to implement progress resumption. --- rich/progress.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/rich/progress.py b/rich/progress.py index 8810aeac..90a5e1b2 100644 --- a/rich/progress.py +++ b/rich/progress.py @@ -104,6 +104,7 @@ def track( sequence: Union[Sequence[ProgressType], Iterable[ProgressType]], description: str = "Working...", total: Optional[float] = None, + completed: int = 0, auto_refresh: bool = True, console: Optional[Console] = None, transient: bool = False, @@ -123,6 +124,7 @@ def track( sequence (Iterable[ProgressType]): A sequence (must support "len") you wish to iterate over. description (str, optional): Description of task show next to progress bar. Defaults to "Working". total: (float, optional): Total number of steps. Default is len(sequence). + completed (int, optional): Number of steps completed so far. Defaults to 0. auto_refresh (bool, optional): Automatic refresh, disable to force a refresh after each iteration. Default is True. transient: (bool, optional): Clear the progress on exit. Defaults to False. console (Console, optional): Console to write to. Default creates internal Console instance. @@ -166,7 +168,7 @@ def track( with progress: yield from progress.track( - sequence, total=total, description=description, update_period=update_period + sequence, total=total, completed=completed, description=description, update_period=update_period ) @@ -1180,6 +1182,7 @@ class Progress(JupyterMixin): self, sequence: Union[Iterable[ProgressType], Sequence[ProgressType]], total: Optional[float] = None, + completed: int = 0, task_id: Optional[TaskID] = None, description: str = "Working...", update_period: float = 0.1, @@ -1189,6 +1192,7 @@ class Progress(JupyterMixin): Args: sequence (Sequence[ProgressType]): A sequence of values you want to iterate over and track progress. total: (float, optional): Total number of steps. Default is len(sequence). + completed (int, optional): Number of steps completed so far. Defaults to 0. task_id: (TaskID): Task to track. Default is new task. description: (str, optional): Description of task, if new task is created. update_period (float, optional): Minimum time (in seconds) between calls to update(). Defaults to 0.1. @@ -1200,7 +1204,7 @@ class Progress(JupyterMixin): total = float(length_hint(sequence)) or None if task_id is None: - task_id = self.add_task(description, total=total) + task_id = self.add_task(description, total=total, completed=completed) else: self.update(task_id, total=total) From d0a996204ab987fdceaaba35cdeae6a21da2c9fd Mon Sep 17 00:00:00 2001 From: Haskely Date: Thu, 30 Nov 2023 21:30:21 +0800 Subject: [PATCH 31/62] Update progress.py --- rich/progress.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rich/progress.py b/rich/progress.py index 90a5e1b2..63fd8d4a 100644 --- a/rich/progress.py +++ b/rich/progress.py @@ -1206,7 +1206,7 @@ class Progress(JupyterMixin): if task_id is None: task_id = self.add_task(description, total=total, completed=completed) else: - self.update(task_id, total=total) + self.update(task_id, total=total, completed=completed) if self.live.auto_refresh: with _TrackThread(self, task_id, update_period) as track_thread: From 7d79acbabf3d9836a4bd9e7296d6f6dd6a222fb7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20G=C3=B3rny?= Date: Sat, 9 Dec 2023 15:25:21 +0100 Subject: [PATCH 32/62] Fix running tests in environment with FORCE_COLOR or NO_COLOR set Ensure to unset FORCE_COLOR and NO_COLOR environment variables within the scope of individual tests, in order to fix test failures when these variables are set in the environment where tests are run, e.g. via: NO_COLOR=1 tox --- CHANGELOG.md | 6 ++++++ tests/conftest.py | 8 ++++++++ 2 files changed, 14 insertions(+) create mode 100644 tests/conftest.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 9b0eecd7..af7354b4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## Unreleased + +### Fixed + +- Running tests in environment with `FORCE_COLOR` or `NO_COLOR` environment variables + ## [13.7.0] - 2023-11-15 ### Added diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 00000000..52662964 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,8 @@ +import pytest + + +@pytest.fixture(autouse=True) +def reset_color_envvars(monkeypatch): + """Remove color-related envvars to fix test output""" + monkeypatch.delenv("FORCE_COLOR", raising=False) + monkeypatch.delenv("NO_COLOR", raising=False) From 68bcd049ee07133269845ba9fdaa773329571dae Mon Sep 17 00:00:00 2001 From: Karolina Surma Date: Tue, 12 Dec 2023 16:42:34 +0100 Subject: [PATCH 33/62] Skip tests failing with Python 3.13 --- CONTRIBUTORS.md | 1 + tests/test_inspect.py | 9 +++++++++ tests/test_pretty.py | 5 +++++ 3 files changed, 15 insertions(+) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 22b1be0d..ee4ed6ac 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -60,6 +60,7 @@ The following people have contributed to the development of Rich: - [Anthony Shaw](https://github.com/tonybaloney) - [Nicolas Simonds](https://github.com/0xDEC0DE) - [Aaron Stephens](https://github.com/aaronst) +- [Karolina Surma](https://github.com/befeleme) - [Gabriele N. Tornetta](https://github.com/p403n1x87) - [Nils Vu](https://github.com/nilsvu) - [Arian Mollik Wasi](https://github.com/wasi-master) diff --git a/tests/test_inspect.py b/tests/test_inspect.py index a9d55393..4f249443 100644 --- a/tests/test_inspect.py +++ b/tests/test_inspect.py @@ -43,6 +43,11 @@ skip_py312 = pytest.mark.skipif( reason="rendered differently on py3.12", ) +skip_py313 = pytest.mark.skipif( + sys.version_info.minor == 13 and sys.version_info.major == 3, + reason="rendered differently on py3.13", +) + skip_pypy3 = pytest.mark.skipif( hasattr(sys, "pypy_version_info"), reason="rendered differently on pypy3", @@ -140,6 +145,7 @@ def test_inspect_empty_dict(): assert render({}).startswith(expected) +@skip_py313 @skip_py312 @skip_py311 @skip_pypy3 @@ -219,6 +225,7 @@ def test_inspect_integer_with_value(): @skip_py310 @skip_py311 @skip_py312 +@skip_py313 def test_inspect_integer_with_methods_python38_and_python39(): expected = ( "╭──────────────── ─────────────────╮\n" @@ -257,6 +264,7 @@ def test_inspect_integer_with_methods_python38_and_python39(): @skip_py39 @skip_py311 @skip_py312 +@skip_py313 def test_inspect_integer_with_methods_python310only(): expected = ( "╭──────────────── ─────────────────╮\n" @@ -299,6 +307,7 @@ def test_inspect_integer_with_methods_python310only(): @skip_py39 @skip_py310 @skip_py312 +@skip_py313 def test_inspect_integer_with_methods_python311(): # to_bytes and from_bytes methods on int had minor signature change - # they now, as of 3.11, have default values for all of their parameters diff --git a/tests/test_pretty.py b/tests/test_pretty.py index e505ed4d..40fae2dc 100644 --- a/tests/test_pretty.py +++ b/tests/test_pretty.py @@ -38,6 +38,10 @@ skip_py312 = pytest.mark.skipif( sys.version_info.minor == 12 and sys.version_info.major == 3, reason="rendered differently on py3.12", ) +skip_py313 = pytest.mark.skipif( + sys.version_info.minor == 13 and sys.version_info.major == 3, + reason="rendered differently on py3.13", +) def test_install(): @@ -611,6 +615,7 @@ def test_attrs_empty(): @skip_py310 @skip_py311 @skip_py312 +@skip_py313 def test_attrs_broken(): @attr.define class Foo: From 55f12a013b2491d4a90568943312b38b0eaf116d Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 14 Dec 2023 13:58:25 +0000 Subject: [PATCH 34/62] Bump github/codeql-action from 2 to 3 Bumps [github/codeql-action](https://github.com/github/codeql-action) from 2 to 3. - [Release notes](https://github.com/github/codeql-action/releases) - [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md) - [Commits](https://github.com/github/codeql-action/compare/v2...v3) --- updated-dependencies: - dependency-name: github/codeql-action dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .github/workflows/codeql.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index 2a973c4c..55bbd0fb 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -33,7 +33,7 @@ jobs: # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL - uses: github/codeql-action/init@v2 + uses: github/codeql-action/init@v3 with: languages: ${{ matrix.language }} # If you wish to specify custom queries, you can do so here or in a config file. @@ -47,7 +47,7 @@ jobs: # Autobuild attempts to build any compiled languages (C/C++, C#, Go, Java, or Swift). # If this step fails, then you should remove it and run the build manually (see below) - name: Autobuild - uses: github/codeql-action/autobuild@v2 + uses: github/codeql-action/autobuild@v3 # ℹ️ Command-line programs to run using the OS shell. # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun @@ -60,6 +60,6 @@ jobs: # ./location_of_script_within_repo/buildscript.sh - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@v2 + uses: github/codeql-action/analyze@v3 with: category: "/language:${{matrix.language}}" From ee5ba3503be5a30d17913fed7f2776cc3004e79f Mon Sep 17 00:00:00 2001 From: askras Date: Tue, 9 Jan 2024 20:36:52 +0300 Subject: [PATCH 35/62] Improved file translation README.ru.md - Typos have been fixed - Fixed stylistic features of the translation --- README.ru.md | 102 ++++++++++++++++++++++++++++----------------------- 1 file changed, 57 insertions(+), 45 deletions(-) diff --git a/README.ru.md b/README.ru.md index 14cb6709..2498cfb7 100644 --- a/README.ru.md +++ b/README.ru.md @@ -27,23 +27,23 @@ Rich это Python библиотека, позволяющая отображать _красивый_ текст и форматировать терминал. -[Rich API](https://rich.readthedocs.io/en/latest/) упрощает добавление цветов и стилей к выводу терминала. Rich также позволяет отображать красивые таблицы, прогресс бары, markdown, код с отображением синтаксиса, ошибки, и т.д. — прямо после установки. +[Rich API](https://rich.readthedocs.io/en/latest/) упрощает добавление цветов и стилей к выводу терминала. Rich также позволяет отображать красивые таблицы, прогресс бары, markdown, код с подсветкой синтаксиса, ошибки, и т.д. — прямо после установки. ![Features](https://github.com/textualize/rich/raw/master/imgs/features.png) -Для видеоинструкции смотрите [calmcode.io](https://calmcode.io/rich/introduction.html) от [@fishnets88](https://twitter.com/fishnets88). +Смотрите видеоинструкцию [calmcode.io](https://calmcode.io/rich/introduction.html) от [@fishnets88](https://twitter.com/fishnets88). Посмотрите [что люди думают о Rich](https://www.willmcgugan.com/blog/pages/post/rich-tweets/). ## Cовместимость -Rich работает с Linux, OSX, и Windows. True color / эмоджи работают с новым терминалом Windows, классический терминал лимитирован 16 цветами. Rich требует Python 3.6.3 или более новый. +Rich работает с Linux, OSX и Windows. True color / эмоджи работают с новым терминалом Windows, классический терминал лимитирован 16 цветами. Rich требует Python 3.6.3 или более новый. Rich работает с [Jupyter notebooks](https://jupyter.org/) без дополнительной конфигурации. ## Установка -Установите с `pip` или вашим любимым PyPI менеджером пакетов. +Установите с помощью `pip` или вашего любимого PyPI менеджера пакетов. ```sh python -m pip install rich @@ -57,7 +57,7 @@ python -m rich ## Rich Print -Простейший способ получить красивый вывод это импортировать метод [rich print](https://rich.readthedocs.io/en/latest/introduction.html#quick-start), он принимает такие же аргументы что и стандартный метод print. Попробуйте: +Простейший способ получить красивый вывод это импортировать метод [rich print](https://rich.readthedocs.io/en/latest/introduction.html#quick-start), он принимает такие же аргументы что и стандартный метод `print`. Попробуйте: ```python from rich import print @@ -88,13 +88,13 @@ from rich.console import Console console = Console() ``` -У класса console есть метод `print` который имеет идентичный функционал к встроеной функции `print`. Вот пример использования: +У класса Сonsole есть метод `print` который имеет идентичный встроенной функции функционал `print`. Вот пример использования: ```python console.print("Hello", "World!") ``` -Как вы могли подумать, этот выведет `"Hello World!"` в терминал. Запомните что, в отличии от встроеной функции `print`, Rich увеличит ваш текст так, чтобы он распространялся на всю ширину терминала. +Как вы могли догадаться, это выведет `Hello World!` в терминал. Запомните что, в отличии от встроенной функции `print`, Rich настроит переносы слов так, чтобы ваш текст соответствовал ширине терминала. Есть несколько способов добавить цвет и стиль к вашему выводу. Вы можете выбрать стиль для всего вывода добавив аргумент `style`. Вот пример: @@ -102,11 +102,11 @@ console.print("Hello", "World!") console.print("Hello", "World!", style="bold red") ``` -Вывод будет выглядить примерно так: +Вывод будет выглядеть примерно так: ![Hello World](https://github.com/textualize/rich/raw/master/imgs/hello_world.png) -Этого достаточно чтобы стилизовать 1 строку. Для более детального стилизования, Rich использует специальную разметку похожую по синтаксису на [bbcode](https://en.wikipedia.org/wiki/BBCode). Вот пример: +Этого достаточно чтобы стилизовать 1 строку. Для более детальной стилизации, Rich использует специальную разметку похожую по синтаксису на [bbcode](https://en.wikipedia.org/wiki/BBCode). Вот пример: ```python console.print("Where there is a [bold cyan]Will[/bold cyan] there [u]is[/u] a [i]way[/i].") @@ -114,11 +114,11 @@ console.print("Where there is a [bold cyan]Will[/bold cyan] there [u]is[/u] a [i ![Console Markup](https://github.com/textualize/rich/raw/master/imgs/where_there_is_a_will.png) -Вы можете использовать класс Console чтобы генерировать утонченный вывод с минимальными усилиями. Смотрите [документацию Console API](https://rich.readthedocs.io/en/latest/console.html) для детального объяснения. +Вы можете использовать класс Console чтобы генерировать красивый вывод с минимальными усилиями. Для получения детальной информации смотрите [документацию Console API](https://rich.readthedocs.io/en/latest/console.html). ## Rich Inspect -В Rich есть функция [inspect](https://rich.readthedocs.io/en/latest/reference/init.html?highlight=inspect#rich.inspect) которая может украсить любой Python объект, например класс, переменная, или функция. +В Rich имеется функция [inspect](https://rich.readthedocs.io/en/latest/reference/init.html?highlight=inspect#rich.inspect) которая может украсить любой Python объект, например класс, переменную, или функцию. ```python >>> my_list = ["foo", "bar"] @@ -128,18 +128,18 @@ console.print("Where there is a [bold cyan]Will[/bold cyan] there [u]is[/u] a [i ![Log](https://github.com/textualize/rich/raw/master/imgs/inspect.png) -Смотрите [документацию inspect](https://rich.readthedocs.io/en/latest/reference/init.html#rich.inspect) для детального объяснения. +Для получения детальной информации смотрите [документацию inspect](https://rich.readthedocs.io/en/latest/reference/init.html#rich.inspect). # Библиотека Rich -Rich содержит несколько встроенных _визуализаций_ которые вы можете использовать чтобы сделать элегантный вывод в важем CLI или помочь в дебаггинге кода. +Rich содержит несколько встроенных _визуализаций_ которые вы можете использовать чтобы сделать красивый вывод в вашем CLI, а также они помогают в отладке кода. Вот несколько вещей которые может делать Rich (нажмите чтобы узнать больше):
Лог -В классе console есть метод `log()` который похож на `print()`, но также изображает столбец для текущего времени, файла и линии кода которая вызвала метод. По умолчанию Rich будет подсвечивать синтаксис для структур Python и для строк repr. Если вы передадите в метод коллекцию (т.е. dict или list) Rich выведет её так, чтобы она помещалась в доступном месте. Вот пример использования этого метода. +В классе Сonsole есть метод `log()` который имеет интерфейс, аналогичный `print()`, но также отображает колонку текущим временем, именем файла и номером строки кода в которой был вызван метод. По умолчанию Rich будет подсвечивать синтаксис для структур Python и для строк repr. Если вы передадите в метод коллекцию (т.е. dict или list) Rich выведет её так, чтобы она разместилась в доступном пространстве. Вот пример использования этого метода. ```python from rich.console import Console @@ -164,13 +164,14 @@ def test_log(): test_log() ``` -Код выше выведет это: +Приведенный выше код выведет это: ![Log](https://github.com/textualize/rich/raw/master/imgs/log.png) -Запомните аргумент `log_locals`, он выводит таблицу имеющую локальные переменные функции в которой метод был вызван. -Метод может быть использован для вывода данных в терминал в длинно-работающих программ, таких как сервера, но он также может помочь в дебаггинге. +Обратите внимание на аргумент `log_locals`, который выводит таблицу, содержащую локальные переменные функции, в которой был вызван метод log. + +Метод может быть использован для вывода данных в терминал в длительно работающих программ, таких как сервера, но он также может помочь в отладке.
@@ -185,25 +186,25 @@ test_log()
Эмоджи -Чтобы вставить эмоджи в вывод консоли поместите название между двумя двоеточиями. Вот пример: +Чтобы вставить эмоджи в вывод консоли, поместите его название между двумя двоеточиями. Вот пример: ```python >>> console.print(":smiley: :vampire: :pile_of_poo: :thumbs_up: :raccoon:") 😃 🧛 💩 👍 🦝 ``` -Пожалуйста, используйте это мудро. +Пожалуйста, используйте эту функцию с умом.
Таблицы -Rich может отображать гибкие [таблицы](https://rich.readthedocs.io/en/latest/tables.html) с символами unicode. Есть большое количество форматов границ, стилей, выравниваний ячеек и т.п. +Rich может отображать гибкие настраиваемые [таблицы](https://rich.readthedocs.io/en/latest/tables.html) с помощью символов unicode. Есть большое количество вариантов границ, стилей, выравниваний ячеек и т.п. ![table movie](https://github.com/textualize/rich/raw/master/imgs/table_movie.gif) -Эта анимация была сгенерирована с помощью [table_movie.py](https://github.com/textualize/rich/blob/master/examples/table_movie.py) в директории примеров. +Эта анимация была сгенерирована с помощью [table_movie.py](https://github.com/textualize/rich/blob/master/examples/table_movie.py) в папке примеров. Вот пример более простой таблицы: @@ -241,7 +242,7 @@ console.print(table) ![table](https://github.com/textualize/rich/raw/master/imgs/table.png) -Запомните что разметка консоли отображается таким же способом что и `print()` и `log()`. На самом деле, всё, что может отобразить Rich может быть в заголовках или рядах (даже другие таблицы). +Обратите внимание, что разметка осуществляется таким же способом, что и `print()` и `log()`. На самом деле, все, что может быть отображено Rich, может быть включено в заголовки / строки (даже в другие таблицы). Класс `Table` достаточно умный чтобы менять размер столбцов, так, чтобы они заполняли доступную ширину терминала, обёртывая текст как нужно. Вот тот же самый пример с терминалом меньше таблицы: @@ -254,7 +255,7 @@ console.print(table) Rich может отображать несколько плавных [прогресс](https://rich.readthedocs.io/en/latest/progress.html) баров чтобы отслеживать долго-идущие задания. -Для базового использования, оберните любую последовательность в функции `track` и переберите результат. Вот пример: +Для базового использования, оберните любую последовательность в функцию `track` и выполните итерации по результату. Вот пример: ```python from rich.progress import track @@ -263,22 +264,22 @@ for step in track(range(100)): do_step(step) ``` -Отслеживать больше чем 1 задание не сложнее. Вот пример взятый из документации: +Добавить несколько индикаторов выполнения не намного сложнее. Вот пример взятый из документации: ![progress](https://github.com/textualize/rich/raw/master/imgs/progress.gif) -Столбцы могут быть настроены чтобы показывать любые детали. Стандартные столбцы содержат проценты исполнения, размер файлы, скорость файла, и оставшееся время. Вот ещё пример показывающий загрузку в прогрессе: +Столбцы могут быть сконфигурированы таким образом, чтобы отображать любые сведения, которые вы хотите. Стандартные столбцы содержат проценты выполнения, размер файлы, скорость файла и оставшееся время. Вот ещё пример показывающий прогресс загрузки: ![progress](https://github.com/textualize/rich/raw/master/imgs/downloader.gif) -Чтобы попробовать самому, скачайте [examples/downloader.py](https://github.com/textualize/rich/blob/master/examples/downloader.py) который может скачать несколько URL одновременно пока отображая прогресс. +Чтобы попробовать самому, скачайте [examples/downloader.py](https://github.com/textualize/rich/blob/master/examples/downloader.py), который может загружать несколько URL-адресов одновременно, отображая прогресс.
Статус -Для ситуаций где сложно высчитать прогресс, вы можете использовать метод [статус](https://rich.readthedocs.io/en/latest/reference/console.html#rich.console.Console.status) который будет отображать крутящуюся анимацию и сообщение. Анимация не перекроет вам доступ к консоли. Вот пример: +Для ситуаций где сложно вычислить прогресс, вы можете использовать метод [статус](https://rich.readthedocs.io/en/latest/reference/console.html#rich.console.Console.status) который будет отображать крутящуюся анимацию и сообщение. Анимация не помешает вам использовать консоль в обычном режиме. Вот пример: ```python from time import sleep @@ -294,17 +295,17 @@ with console.status("[bold green]Working on tasks...") as status: console.log(f"{task} complete") ``` -Это генерирует вот такой вывод в консоль. +Это сгенерирует вот такой вывод в консоль. ![status](https://github.com/textualize/rich/raw/master/imgs/status.gif) -Крутящиеся анимации были взяты из [cli-spinners](https://www.npmjs.com/package/cli-spinners). Вы можете выбрать одну из них указав параметр `spinner`. Запустите следующую команду чтобы узнать доступные анимации: +Крутящиеся анимации были взяты из [cli-spinners](https://www.npmjs.com/package/cli-spinners). Вы можете выбрать одну из них указав параметр `spinner`. Введите следующую команду чтобы посмотреть доступные анимации: ``` python -m rich.spinner ``` -Эта команда выдаёт вот такой вывод в терминал: +Приведенная выше команда сгенерирует следующий вывод в терминале: ![spinners](https://github.com/textualize/rich/raw/master/imgs/spinners.gif) @@ -313,9 +314,9 @@ python -m rich.spinner
Дерево -Rich может отобразить [дерево](https://rich.readthedocs.io/en/latest/tree.html) с указаниями. Дерево идеально подходит для отображения структуры файлов или любых других иерархических данных. +Rich может отобразить [дерево](https://rich.readthedocs.io/en/latest/tree.html) с направляющими уровнями. Дерево идеально подходит для отображения структуры файлов или любых других иерархических данных. -Ярлыки дерева могут быть простым текстом или любой другой вещью Rich может отобразить. Запустите следующую команду для демонстрации: +Метки дерева могут быть содержать простой текст или чем-либо еще, что может отобразить Rich. Запустите следующую команду для демонстрации: ``` python -m rich.tree @@ -325,14 +326,14 @@ python -m rich.tree ![markdown](https://github.com/textualize/rich/raw/master/imgs/tree.png) -Смотрите пример [tree.py](https://github.com/textualize/rich/blob/master/examples/tree.py) для скрипта который отображает дерево любой директории, похоже на команду linux `tree`. +Смотрите пример [tree.py](https://github.com/textualize/rich/blob/master/examples/tree.py) скрипта,который отображает древовидное представление любого каталога, аналогично команде linux `tree`.
-Столбцы +Колонки -Rich может отображать контент в [столбцах](https://rich.readthedocs.io/en/latest/columns.html) с равной или оптимальной шириной. Вот очень простой пример клона команды `ls` (MacOS / Linux) который отображает a файлы директории в столбцах: +Rich может отображать контент в аккуратных [колонках](https://rich.readthedocs.io/en/latest/columns.html) с равной или оптимальной шириной. Вот очень простой пример клона команды `ls` (MacOS / Linux) который отображает список файлов из папки в виде колонок: ```python import os @@ -345,7 +346,7 @@ directory = os.listdir(sys.argv[1]) print(Columns(directory)) ``` -Следующий скриншот это вывод из [примера столбцов](https://github.com/textualize/rich/blob/master/examples/columns.py) который изображает данные взятые из API в столбцах: +Следующий снимок экрана является [примером колонок](https://github.com/textualize/rich/blob/master/examples/columns.py) который изображает данные взятые из API в столбцах: ![columns](https://github.com/textualize/rich/raw/master/imgs/columns.png) @@ -354,9 +355,9 @@ print(Columns(directory))
Markdown -Rich может отображать [markdown](https://rich.readthedocs.io/en/latest/markdown.html) и делает неплохую работу в форматировании под терминал. +Rich может отображать [markdown](https://rich.readthedocs.io/en/latest/markdown.html), проделывая неплохую работу в форматировании под терминал. -Чтобы отобразить markdown импортируйте класс `Markdown` и инициализируйте его с помощью строки содержащей код markdown. После чего выведите его в консоль. Вот пример: +Чтобы отобразить markdown импортируйте класс `Markdown` и инициализируйте его с помощью строки содержащей код markdown. Затем распечатайте его в консоли. Вот пример: ```python from rich.console import Console @@ -375,9 +376,9 @@ console.print(markdown)
-Подсвечивание Синтаксиса +Подсветка синтаксиса -Rich использует библиотеку [pygments](https://pygments.org/) чтобы имплементировать [подсвечивание синтаксиса](https://rich.readthedocs.io/en/latest/syntax.html). Использование похоже на отображение markdown; инициализируйте класс `Syntax` и выводите его в консоль. Вот пример: +Rich использует библиотеку [pygments](https://pygments.org/) чтобы выполнить [подсветку синтаксиса](https://rich.readthedocs.io/en/latest/syntax.html). Использование аналогично рендерингу markdown; создайте объект `Syntax` и выведите его на консоль. Вот пример: ```python from rich.console import Console @@ -412,7 +413,7 @@ console.print(syntax)
Ошибки -Rich может отображать [красивые ошибки](https://rich.readthedocs.io/en/latest/traceback.html) которые проще читать и показывают больше кода чем стандартные ошибки Python. Вы можете установить Rich как стандартный обработчик ошибок чтобы все непойманные ошибки отображал Rich. +Rich может отображать [красивый стек ошибок](https://rich.readthedocs.io/en/latest/traceback.html), который проще читать, и показывает больше информации чем стандартные стек ошибок Python. Вы можете установить Rich как стандартный обработчик ошибок чтобы все не перехваченные исключения отображались Rich. Вот как это выглядит на OSX (похоже на Linux): @@ -420,17 +421,28 @@ Rich может отображать [красивые ошибки](https://ric
-Все визуализации Rich используют [протокол Console](https://rich.readthedocs.io/en/latest/protocol.html), который также позволяет вам добавлять свой Rich контент. +Все визуализации Rich используют [протокол Console](https://rich.readthedocs.io/en/latest/protocol.html), который позволяет вам добавлять свой собственный Rich контент. + +# Rich CLI + +Смотрите также [Rich CLI](https://github.com/textualize/rich-cli) для получения информации о приложении командной строки, работающего на базе Rich. Подсветка синтаксиса кода, рендеринг markdown, отображение CSV-файлов в таблицах и многое другое доступно непосредственно из командной строки. + + +![Rich CLI](https://raw.githubusercontent.com/Textualize/rich-cli/main/imgs/rich-cli-splash.jpg) + +# Textual + +Смотрите также дочерний проект Rich, [Textual](https://github.com/Textualize/textual), который вы можете использовать для создания сложных пользовательских интерфейсов в терминале. # Rich для предприятий Rich доступен как часть подписки Tidelift. -Поддержатели проекта Rich и тысячи других работают над подпиской Tidelift чтобы предоставить коммерческую поддержку и поддержание для проектов с открытым кодом вы используете чтобы построить своё приложение. Сохраните время, избавьтесь от риска, и улучшите состояние кода, пока вы платите поддержателям проектов вы используете. [Узнайте больше.](https://tidelift.com/subscription/pkg/pypi-rich?utm_source=pypi-rich&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) +Ментейнеры проекта Rich, как и тысячи других разработчиков работают с подпиской Tidelift чтобы предоставить коммерческую поддержку и поддержку для проектов с открытым кодом, которые вы используете для создания своих приложений. Экономьте время, устраняйте риски и улучшайте состояние вашего кода, одновременно платя спонсорам проектов, которые вы используете. [Узнайте больше.](https://tidelift.com/subscription/pkg/pypi-rich?utm_source=pypi-rich&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) # Проекты использующие Rich -Вот пару проектов использующих Rich: +Вот несколько проектов использующих Rich: - [BrancoLab/BrainRender](https://github.com/BrancoLab/BrainRender) библиотека Python для визуализации нейроанатомических данных в 3 измерениях @@ -441,7 +453,7 @@ Rich доступен как часть подписки Tidelift. - [hedythedev/StarCli](https://github.com/hedythedev/starcli) Просматривайте трендовые проекты GitHub прямо из вашего терминала - [intel/cve-bin-tool](https://github.com/intel/cve-bin-tool) - Эта утилита сканирует известные уязвимости (openssl, libpng, libxml2, expat and a few others) чтобы уведомить вас если ваша система использует библиотеки с известными уязвимостями. + Эта утилита сканирует известные уязвимости (openssl, libpng, libxml2, expat and a few others) чтобы уведомить вас, если ваша система использует библиотеки с известными уязвимостями. - [nf-core/tools](https://github.com/nf-core/tools) Библиотека Python с полезными инструментами для сообщества nf-core. - [cansarigol/pdbr](https://github.com/cansarigol/pdbr) From 3ec9fafc0c58804cc435c4852e0fb55beb178fc8 Mon Sep 17 00:00:00 2001 From: askras Date: Tue, 9 Jan 2024 20:47:55 +0300 Subject: [PATCH 36/62] Improved file translation README.ru.md - Typos have been fixed - Fixed stylistic errors of the translation --- CHANGELOG.md | 9 +++++++++ CONTRIBUTORS.md | 1 + 2 files changed, 10 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9b0eecd7..894684bb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,15 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [13.7.1] - 2024-01-09 + +### Fixed + +- Исправлены опечатки в файле README.ru.md. +- Исправлены стилистические ошибки перевода в файле README.ru.md. + + ## [13.7.0] - 2023-11-15 ### Added diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 22b1be0d..c2dbef1d 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -30,6 +30,7 @@ The following people have contributed to the development of Rich: - [Jan Katins](https://github.com/jankatins) - [Hugo van Kemenade](https://github.com/hugovk) - [Andrew Kettmann](https://github.com/akettmann) +- [Alexander Krasnikov](https://github.com/askras) - [Martin Larralde](https://github.com/althonos) - [Hedy Li](https://github.com/hedythedev) - [Henry Mai](https://github.com/tanducmai) From 06bf00991bc9b29c736d5e5f80d9ff15e349b16c Mon Sep 17 00:00:00 2001 From: askras Date: Tue, 9 Jan 2024 20:56:01 +0300 Subject: [PATCH 37/62] Improved file translation README.ru.md - Typos have been fixed - Fixed stylistic errors of the translation --- CHANGELOG.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 894684bb..2a70d811 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,8 +10,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Исправлены опечатки в файле README.ru.md. -- Исправлены стилистические ошибки перевода в файле README.ru.md. +- Fixed typos in the file README.ru.md . +- Fixed stylistic translation errors in the file README.ru.md . ## [13.7.0] - 2023-11-15 From 7ea6285a12399ec0ac092cb38dc4f60add4fc838 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 1 Feb 2024 13:46:26 +0000 Subject: [PATCH 38/62] Bump codecov/codecov-action from 3 to 4 Bumps [codecov/codecov-action](https://github.com/codecov/codecov-action) from 3 to 4. - [Release notes](https://github.com/codecov/codecov-action/releases) - [Changelog](https://github.com/codecov/codecov-action/blob/main/CHANGELOG.md) - [Commits](https://github.com/codecov/codecov-action/compare/v3...v4) --- updated-dependencies: - dependency-name: codecov/codecov-action dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .github/workflows/pythonpackage.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/pythonpackage.yml b/.github/workflows/pythonpackage.yml index 21aafe27..b3bfa5d7 100644 --- a/.github/workflows/pythonpackage.yml +++ b/.github/workflows/pythonpackage.yml @@ -41,7 +41,7 @@ jobs: source $VENV pytest tests -v --cov=./rich --cov-report=xml:./coverage.xml --cov-report term-missing - name: Upload code coverage - uses: codecov/codecov-action@v3 + uses: codecov/codecov-action@v4 with: token: ${{ secrets.CODECOV_TOKEN }} file: ./coverage.xml From f021979c79f57163a68e68f708278ca6c10b7805 Mon Sep 17 00:00:00 2001 From: dosisod <39638017+dosisod@users.noreply.github.com> Date: Mon, 12 Feb 2024 16:35:27 -0800 Subject: [PATCH 39/62] Strip problematic private escape sequences: ["Private escape sequences"](https://en.wikipedia.org/wiki/ANSI_escape_code#Fp_Escape_sequences) are escape sequences that are reserved for private use, though `\x1b7` and `\x1b8` are commonly used for storing and restoring the current cursor position. When those escape codes are not stripped the cursor jumps around and causes Rich to write garbage output. An example of a program that uses this cursor store/restore functionality is the APK package manager in Alpine Linux: https://gitlab.alpinelinux.org/alpine/apk-tools/-/blob/48d91f482eb48a0a107b714ee183bb7e07782e14/src/print.c#L232-240 This commit updates the ANSI parser to ignore the `\x1b0`-`\x1b?` escape sequences, thus preventing them from being printed and causing havoc. --- CHANGELOG.md | 6 ++++++ CONTRIBUTORS.md | 1 + rich/ansi.py | 1 + tests/test_ansi.py | 14 ++++++++++++++ 4 files changed, 22 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9b0eecd7..a359a1ad 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## Unreleased + +### Fixed + +- Strip problematic private escape sequences (like `\x1b7`) + ## [13.7.0] - 2023-11-15 ### Added diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 22b1be0d..51375d0d 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -25,6 +25,7 @@ The following people have contributed to the development of Rich: - [Kenneth Hoste](https://github.com/boegel) - [Lanqing Huang](https://github.com/lqhuang) - [Finn Hughes](https://github.com/finnhughes) +- [Logan Hunt](https://github.com/dosisod) - [Ionite](https://github.com/ionite34) - [Josh Karpel](https://github.com/JoshKarpel) - [Jan Katins](https://github.com/jankatins) diff --git a/rich/ansi.py b/rich/ansi.py index 66365e65..7de86ce5 100644 --- a/rich/ansi.py +++ b/rich/ansi.py @@ -9,6 +9,7 @@ from .text import Text re_ansi = re.compile( r""" +(?:\x1b[0-?])| (?:\x1b\](.*?)\x1b\\)| (?:\x1b([(@-Z\\-_]|\[[0-?]*[ -/]*[@-~])) """, diff --git a/tests/test_ansi.py b/tests/test_ansi.py index ae87cde1..d81f6459 100644 --- a/tests/test_ansi.py +++ b/tests/test_ansi.py @@ -68,3 +68,17 @@ def test_decode_issue_2688(ansi_bytes, expected_text): text = Text.from_ansi(ansi_bytes.decode()) assert str(text) == expected_text + + +@pytest.mark.parametrize("code", [*"0123456789:;<=>?"]) +def test_strip_private_escape_sequences(code): + text = Text.from_ansi(f"\x1b{code}x") + + console = Console(force_terminal=True) + + with console.capture() as capture: + console.print(text) + + expected = "x\n" + + assert capture.get() == expected From 52f3deb2c709836b67bf47e7b2999dadafcb8521 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Zolt=C3=A1n=20Nagy?= Date: Tue, 16 Apr 2024 16:00:02 +0100 Subject: [PATCH 40/62] chore(changelog): fix release date for 13.7.1 --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 12512dc3..8735bb47 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,7 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). -## [13.7.1] - 2023-02-28 +## [13.7.1] - 2024-02-28 ### Fixed From aebc1158fcb457f5e1a691591a121613a5417322 Mon Sep 17 00:00:00 2001 From: Will McGugan Date: Tue, 30 Apr 2024 09:46:20 +0100 Subject: [PATCH 41/62] faqs --- FAQ.md | 88 ++++++++++++------- questions/ansi_escapes.question.md | 11 +++ ...ing_color.md => logging_color.question.md} | 0 questions/rich_spinner.question.md | 2 +- questions/tracebacks_installed.question.md | 9 ++ rich/pretty.py | 48 +++++----- 6 files changed, 104 insertions(+), 54 deletions(-) create mode 100644 questions/ansi_escapes.question.md rename questions/{logging_color.md => logging_color.question.md} (100%) create mode 100644 questions/tracebacks_installed.question.md diff --git a/FAQ.md b/FAQ.md index 01935f67..e8129f42 100644 --- a/FAQ.md +++ b/FAQ.md @@ -1,36 +1,13 @@ # Frequently Asked Questions -- [Why does emoji break alignment in a Table or Panel?](#why-does-emoji-break-alignment-in-a-table-or-panel) -- [Why does content in square brackets disappear?](#why-does-content-in-square-brackets-disappear) -- [python -m rich.spinner shows extra lines](#python--m-rich.spinner-shows-extra-lines) - [How do I log a renderable?](#how-do-i-log-a-renderable) -- [Strange colors in console output.](#strange-colors-in-console-output.) - - -## Why does emoji break alignment in a Table or Panel? - -Certain emoji take up double space within the terminal. Unfortunately, terminals don't always agree how wide a given character should be. - -Rich has no way of knowing how wide a character will be on any given terminal. This can break alignment in containers like Table and Panel, where Rich needs to know the width of the content. - -There are also *multiple codepoints* characters, such as country flags, and emoji modifiers, which produce wildly different results across terminal emulators. - -Fortunately, most characters will work just fine. But you may have to avoid using the emojis that break alignment. You will get good results if you stick to emoji released on or before version 9 of the Unicode database, - - -## Why does content in square brackets disappear? - -Rich will treat text within square brackets as *markup tags*, for instance `"[bold]This is bold[/bold]"`. - -If you are printing strings with literally square brackets you can either disable markup, or escape your strings. -See the docs on [console markup](https://rich.readthedocs.io/en/latest/markup.html) for how to do this. - - -## python -m rich.spinner shows extra lines - -The spinner example is know to break on some terminals (Windows in particular). - -Some terminals don't display emoji with the correct width, which means Rich can't always align them accurately inside a panel. +- [How do I render console markup in RichHandler?](#how-do-i-render-console-markup-in-richhandler) +- [Natively inserted ANSI escape sequence characters break alignment of Panel](#natively-inserted-ansi-escape-sequence-characters-break-alignment-of-panel) +- [python -m rich.spinner shows extra lines.](#python--m-richspinner-shows-extra-lines) +- [Rich is automatically installing traceback handler.](#rich-is-automatically-installing-traceback-handler) +- [Strange colors in console output.](#strange-colors-in-console-output) +- [Why does content in square brackets disappear?](#why-does-content-in-square-brackets-disappear) +- [Why does emoji break alignment in a Table or Panel?](#why-does-emoji-break-alignment-in-a-table-or-panel) ## How do I log a renderable? @@ -43,13 +20,62 @@ Logging supports configurable back-ends, which means that a log message could go If you are only logging with a file-handler to stdout, then you probably don't need to use the logging module at all. Consider using [Console.log](https://rich.readthedocs.io/en/latest/reference/console.html#rich.console.Console.log) which will render anything that you can print with Rich, with a timestamp. - + +## How do I render console markup in RichHandler? + +Console markup won't work anywhere else, other than `RichHandler` -- which is why they are disabled by default. + +See the docs if you want to [enable console markup](https://rich.readthedocs.io/en/latest/logging.html#logging-handler) in the logging handler. + + +## Natively inserted ANSI escape sequence characters break alignment of Panel + +If you print ansi escape sequences for color and style you may find the output breaks your output. +You may find that border characters in Panel and Table are in the wrong place, for example. + +As a general rule, you should allow Rich to generate all ansi escape sequences, so it can correctly account for these invisible characters. +If you can't avoid a string with escape codes, you can convert it to an equivalent `Text` instance with `Text.from_ansi`. + + +## python -m rich.spinner shows extra lines. + +The spinner example is know to break on some terminals (Windows in particular). + +Some terminals don't display emoji with the correct width, which means Rich can't always align them accurately inside a panel. + + +## Rich is automatically installing traceback handler. + +Rich will never install the traceback handler automatically. + +If you are getting Rich tracebacks and you don't want them, then some other piece of software is calling `rich.traceback.install()`. + + ## Strange colors in console output. Rich will highlight certain patterns in your output such as numbers, strings, and other objects like IP addresses. Occasionally this may also highlight parts of your output you didn't intend. See the [docs on highlighting](https://rich.readthedocs.io/en/latest/highlighting.html) for how to disable highlighting. + +## Why does content in square brackets disappear? + +Rich will treat text within square brackets as *markup tags*, for instance `"[bold]This is bold[/bold]"`. + +If you are printing strings with literally square brackets you can either disable markup, or escape your strings. +See the docs on [console markup](https://rich.readthedocs.io/en/latest/markup.html) for how to do this. + + +## Why does emoji break alignment in a Table or Panel? + +Certain emoji take up double space within the terminal. Unfortunately, terminals don't always agree how wide a given character should be. + +Rich has no way of knowing how wide a character will be on any given terminal. This can break alignment in containers like Table and Panel, where Rich needs to know the width of the content. + +There are also *multiple codepoints* characters, such as country flags, and emoji modifiers, which produce wildly different results across terminal emulators. + +Fortunately, most characters will work just fine. But you may have to avoid using the emojis that break alignment. You will get good results if you stick to emoji released on or before version 9 of the Unicode database, +
Generated by [FAQtory](https://github.com/willmcgugan/faqtory) diff --git a/questions/ansi_escapes.question.md b/questions/ansi_escapes.question.md new file mode 100644 index 00000000..c32b0b21 --- /dev/null +++ b/questions/ansi_escapes.question.md @@ -0,0 +1,11 @@ +--- +title: "Natively inserted ANSI escape sequence characters break alignment of Panel" +alt_titles: + - "Escape codes break alignment." +--- + +If you print ansi escape sequences for color and style you may find the output breaks your output. +You may find that border characters in Panel and Table are in the wrong place, for example. + +As a general rule, you should allow Rich to generate all ansi escape sequences, so it can correctly account for these invisible characters. +If you can't avoid a string with escape codes, you can convert it to an equivalent `Text` instance with `Text.from_ansi`. diff --git a/questions/logging_color.md b/questions/logging_color.question.md similarity index 100% rename from questions/logging_color.md rename to questions/logging_color.question.md diff --git a/questions/rich_spinner.question.md b/questions/rich_spinner.question.md index 77174635..09327f5d 100644 --- a/questions/rich_spinner.question.md +++ b/questions/rich_spinner.question.md @@ -1,5 +1,5 @@ --- -title: "python -m rich.spinner shows extra lines" +title: "python -m rich.spinner shows extra lines." --- The spinner example is know to break on some terminals (Windows in particular). diff --git a/questions/tracebacks_installed.question.md b/questions/tracebacks_installed.question.md new file mode 100644 index 00000000..17f0da24 --- /dev/null +++ b/questions/tracebacks_installed.question.md @@ -0,0 +1,9 @@ +--- +title: "Rich is automatically installing traceback handler." +alt_titles: + - "Can you stop overriding traceback message formatting by default?" +--- + +Rich will never install the traceback handler automatically. + +If you are getting Rich tracebacks and you don't want them, then some other piece of software is calling `rich.traceback.install()`. diff --git a/rich/pretty.py b/rich/pretty.py index 5c48cfd9..3172f355 100644 --- a/rich/pretty.py +++ b/rich/pretty.py @@ -130,17 +130,19 @@ def _ipy_display_hook( if _safe_isinstance(value, ConsoleRenderable): console.line() console.print( - value - if _safe_isinstance(value, RichRenderable) - else Pretty( - value, - overflow=overflow, - indent_guides=indent_guides, - max_length=max_length, - max_string=max_string, - max_depth=max_depth, - expand_all=expand_all, - margin=12, + ( + value + if _safe_isinstance(value, RichRenderable) + else Pretty( + value, + overflow=overflow, + indent_guides=indent_guides, + max_length=max_length, + max_string=max_string, + max_depth=max_depth, + expand_all=expand_all, + margin=12, + ) ), crop=crop, new_line_start=True, @@ -196,16 +198,18 @@ def install( assert console is not None builtins._ = None # type: ignore[attr-defined] console.print( - value - if _safe_isinstance(value, RichRenderable) - else Pretty( - value, - overflow=overflow, - indent_guides=indent_guides, - max_length=max_length, - max_string=max_string, - max_depth=max_depth, - expand_all=expand_all, + ( + value + if _safe_isinstance(value, RichRenderable) + else Pretty( + value, + overflow=overflow, + indent_guides=indent_guides, + max_length=max_length, + max_string=max_string, + max_depth=max_depth, + expand_all=expand_all, + ) ), crop=crop, ) @@ -846,7 +850,7 @@ def traverse( pop_visited(obj_id) else: node = Node(value_repr=to_repr(obj), last=root) - node.is_tuple = _safe_isinstance(obj, tuple) + node.is_tuple = type(obj) == tuple node.is_namedtuple = _is_namedtuple(obj) return node From 245649b3e2d6e16aef315d95904df26bee7b8550 Mon Sep 17 00:00:00 2001 From: Will McGugan Date: Tue, 30 Apr 2024 09:47:29 +0100 Subject: [PATCH 42/62] punctuation --- FAQ.md | 4 ++-- questions/ansi_escapes.question.md | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/FAQ.md b/FAQ.md index e8129f42..72ce2b31 100644 --- a/FAQ.md +++ b/FAQ.md @@ -2,7 +2,7 @@ # Frequently Asked Questions - [How do I log a renderable?](#how-do-i-log-a-renderable) - [How do I render console markup in RichHandler?](#how-do-i-render-console-markup-in-richhandler) -- [Natively inserted ANSI escape sequence characters break alignment of Panel](#natively-inserted-ansi-escape-sequence-characters-break-alignment-of-panel) +- [Natively inserted ANSI escape sequence characters break alignment of Panel.](#natively-inserted-ansi-escape-sequence-characters-break-alignment-of-panel) - [python -m rich.spinner shows extra lines.](#python--m-richspinner-shows-extra-lines) - [Rich is automatically installing traceback handler.](#rich-is-automatically-installing-traceback-handler) - [Strange colors in console output.](#strange-colors-in-console-output) @@ -28,7 +28,7 @@ Console markup won't work anywhere else, other than `RichHandler` -- which is wh See the docs if you want to [enable console markup](https://rich.readthedocs.io/en/latest/logging.html#logging-handler) in the logging handler. -## Natively inserted ANSI escape sequence characters break alignment of Panel +## Natively inserted ANSI escape sequence characters break alignment of Panel. If you print ansi escape sequences for color and style you may find the output breaks your output. You may find that border characters in Panel and Table are in the wrong place, for example. diff --git a/questions/ansi_escapes.question.md b/questions/ansi_escapes.question.md index c32b0b21..cb60ed93 100644 --- a/questions/ansi_escapes.question.md +++ b/questions/ansi_escapes.question.md @@ -1,5 +1,5 @@ --- -title: "Natively inserted ANSI escape sequence characters break alignment of Panel" +title: "Natively inserted ANSI escape sequence characters break alignment of Panel." alt_titles: - "Escape codes break alignment." --- From eb357884ad7fc677854396e107a1652f3c8d4aa3 Mon Sep 17 00:00:00 2001 From: Ofek Lev Date: Wed, 1 May 2024 09:18:57 -0400 Subject: [PATCH 43/62] Fix warning in test suite --- docs/requirements.txt | 1 + docs/source/conf.py | 9 +++++++-- pyproject.toml | 1 + tests/test_syntax.py | 8 ++++++-- 4 files changed, 15 insertions(+), 4 deletions(-) diff --git a/docs/requirements.txt b/docs/requirements.txt index 4e029845..4b7b608e 100644 --- a/docs/requirements.txt +++ b/docs/requirements.txt @@ -2,3 +2,4 @@ alabaster==0.7.12 Sphinx==5.1.1 sphinx-rtd-theme==1.0.0 sphinx-copybutton==0.5.1 +importlib-metadata; python_version < '3.8' diff --git a/docs/source/conf.py b/docs/source/conf.py index d1078d61..451a1345 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -17,10 +17,15 @@ # -- Project information ----------------------------------------------------- +import sys -import pkg_resources import sphinx_rtd_theme +if sys.version_info >= (3, 8): + from importlib.metadata import Distribution +else: + from importlib_metadata import Distribution + html_theme = "sphinx_rtd_theme" html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] @@ -30,7 +35,7 @@ copyright = "Will McGugan" author = "Will McGugan" # The full version, including alpha/beta/rc tags -release = pkg_resources.get_distribution("rich").version +release = Distribution.from_name("rich").version # -- General configuration --------------------------------------------------- diff --git a/pyproject.toml b/pyproject.toml index 0e9a3b74..e589ba9d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -44,6 +44,7 @@ pytest-cov = "^3.0.0" attrs = "^21.4.0" pre-commit = "^2.17.0" asv = "^0.5.1" +importlib-metadata = { version = "*", python = "<3.8" } [build-system] requires = ["poetry-core>=1.0.0"] diff --git a/tests/test_syntax.py b/tests/test_syntax.py index f3f0f41f..37cc293e 100644 --- a/tests/test_syntax.py +++ b/tests/test_syntax.py @@ -3,7 +3,6 @@ import os import sys import tempfile -import pkg_resources import pytest from pygments.lexers import PythonLexer @@ -21,7 +20,12 @@ from rich.syntax import ( from .render import render -PYGMENTS_VERSION = pkg_resources.get_distribution("pygments").version +if sys.version_info >= (3, 8): + from importlib.metadata import Distribution +else: + from importlib_metadata import Distribution + +PYGMENTS_VERSION = Distribution.from_name("pygments").version OLD_PYGMENTS = PYGMENTS_VERSION == "2.13.0" CODE = '''\ From 4bb501176cf786274ed12d06c19a7956cec652e7 Mon Sep 17 00:00:00 2001 From: Ofek Lev Date: Wed, 1 May 2024 10:00:35 -0400 Subject: [PATCH 44/62] Update actions/setup-python action --- .github/workflows/pythonpackage.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/pythonpackage.yml b/.github/workflows/pythonpackage.yml index 21aafe27..aafe14ae 100644 --- a/.github/workflows/pythonpackage.yml +++ b/.github/workflows/pythonpackage.yml @@ -15,7 +15,7 @@ jobs: steps: - uses: actions/checkout@v4 - name: Set up Python ${{ matrix.python-version }} - uses: actions/setup-python@v4 + uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-version }} architecture: x64 From 248ce145860c8e6fce390038c26944fe690a5d85 Mon Sep 17 00:00:00 2001 From: Ofek Lev Date: Wed, 1 May 2024 10:05:30 -0400 Subject: [PATCH 45/62] Apply suggestions from code review --- .github/workflows/pythonpackage.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/pythonpackage.yml b/.github/workflows/pythonpackage.yml index aafe14ae..b45921ed 100644 --- a/.github/workflows/pythonpackage.yml +++ b/.github/workflows/pythonpackage.yml @@ -18,7 +18,6 @@ jobs: uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-version }} - architecture: x64 - name: Install and configure Poetry # TODO: workaround for https://github.com/snok/install-poetry/issues/94 uses: snok/install-poetry@v1.3.3 From a895220409fe505d49344be39c789dc332d56df5 Mon Sep 17 00:00:00 2001 From: Ofek Lev Date: Wed, 1 May 2024 10:11:41 -0400 Subject: [PATCH 46/62] Update pythonpackage.yml --- .github/workflows/pythonpackage.yml | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/.github/workflows/pythonpackage.yml b/.github/workflows/pythonpackage.yml index b45921ed..2d414ed2 100644 --- a/.github/workflows/pythonpackage.yml +++ b/.github/workflows/pythonpackage.yml @@ -8,7 +8,11 @@ jobs: strategy: matrix: os: [windows-latest, ubuntu-latest, macos-latest] - python-version: ["3.7", "3.8", "3.9", "3.10", "3.11.0", "3.12.0-rc.3"] + python-version: ["3.8", "3.9", "3.10", "3.11", "3.12"] + include: + - { os: ubuntu-latest, python-version: "3.7" } + - { os: windows-latest, python-version: "3.7" } + - { os: macos-12, python-version: "3.7" } defaults: run: shell: bash From f8b9ba143a8a9381cd18faa5cb8bddb1a9c22456 Mon Sep 17 00:00:00 2001 From: "J.P. Hutchins" Date: Sat, 29 Jun 2024 17:05:26 -0700 Subject: [PATCH 47/62] feat: speedup import time using sys.platform --- CONTRIBUTORS.md | 1 + rich/color.py | 4 ++-- rich/console.py | 3 +-- rich/syntax.py | 3 +-- rich/traceback.py | 3 +-- 5 files changed, 6 insertions(+), 8 deletions(-) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 22b1be0d..3d76a6aa 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -25,6 +25,7 @@ The following people have contributed to the development of Rich: - [Kenneth Hoste](https://github.com/boegel) - [Lanqing Huang](https://github.com/lqhuang) - [Finn Hughes](https://github.com/finnhughes) +- [JP Hutchins](https://github.com/JPhutchins) - [Ionite](https://github.com/ionite34) - [Josh Karpel](https://github.com/JoshKarpel) - [Jan Katins](https://github.com/jankatins) diff --git a/rich/color.py b/rich/color.py index 4270a278..e2c23a6a 100644 --- a/rich/color.py +++ b/rich/color.py @@ -1,5 +1,5 @@ -import platform import re +import sys from colorsys import rgb_to_hls from enum import IntEnum from functools import lru_cache @@ -15,7 +15,7 @@ if TYPE_CHECKING: # pragma: no cover from .text import Text -WINDOWS = platform.system() == "Windows" +WINDOWS = sys.platform == "win32" class ColorSystem(IntEnum): diff --git a/rich/console.py b/rich/console.py index 1232cd5c..67fd2879 100644 --- a/rich/console.py +++ b/rich/console.py @@ -1,6 +1,5 @@ import inspect import os -import platform import sys import threading import zlib @@ -76,7 +75,7 @@ if TYPE_CHECKING: JUPYTER_DEFAULT_COLUMNS = 115 JUPYTER_DEFAULT_LINES = 100 -WINDOWS = platform.system() == "Windows" +WINDOWS = sys.platform == "win32" HighlighterType = Callable[[Union[str, "Text"]], "Text"] JustifyMethod = Literal["default", "left", "center", "right", "full"] diff --git a/rich/syntax.py b/rich/syntax.py index 618e0459..f3ceff75 100644 --- a/rich/syntax.py +++ b/rich/syntax.py @@ -1,5 +1,4 @@ import os.path -import platform import re import sys import textwrap @@ -52,7 +51,7 @@ from .text import Text TokenType = Tuple[str, ...] -WINDOWS = platform.system() == "Windows" +WINDOWS = sys.platform == "win32" DEFAULT_THEME = "monokai" # The following styles are based on https://github.com/pygments/pygments/blob/master/pygments/formatters/terminal.py diff --git a/rich/traceback.py b/rich/traceback.py index 821c7501..e3232e0b 100644 --- a/rich/traceback.py +++ b/rich/traceback.py @@ -2,7 +2,6 @@ from __future__ import absolute_import import linecache import os -import platform import sys from dataclasses import dataclass, field from traceback import walk_tb @@ -39,7 +38,7 @@ from .syntax import Syntax from .text import Text from .theme import Theme -WINDOWS = platform.system() == "Windows" +WINDOWS = sys.platform == "win32" LOCALS_MAX_LENGTH = 10 LOCALS_MAX_STRING = 80 From 26479c17e9f3e32cab9a913713e0405743665552 Mon Sep 17 00:00:00 2001 From: Will McGugan Date: Mon, 1 Jul 2024 11:16:39 +0100 Subject: [PATCH 48/62] fix changelog --- CHANGELOG.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6b1df57e..a6324a3a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,9 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## Unreleased -### Fixed +### Fixed -- Improved detection of `attrs` library, that isn't confused by the presence of the `attr` library. - Fixed `Table` rendering of box elements so "footer" elements truly appear at bottom of table, "mid" elements in main table body. ## [13.7.1] - 2024-02-28 From 7a38204cb51dee761792a6b086784602899f06df Mon Sep 17 00:00:00 2001 From: Will McGugan Date: Mon, 1 Jul 2024 11:38:23 +0100 Subject: [PATCH 49/62] fix for panel title --- rich/panel.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/rich/panel.py b/rich/panel.py index 95f4c84c..cc7dcddf 100644 --- a/rich/panel.py +++ b/rich/panel.py @@ -144,7 +144,8 @@ class Panel(JupyterMixin): Padding(self.renderable, _padding) if any(_padding) else self.renderable ) style = console.get_style(self.style) - border_style = style + console.get_style(self.border_style) + partial_border_style = console.get_style(self.border_style) + border_style = style + partial_border_style width = ( options.max_width if self.width is None @@ -200,7 +201,7 @@ class Panel(JupyterMixin): title_text = self._title if title_text is not None: - title_text.stylize_before(border_style) + title_text.stylize_before(partial_border_style) child_width = ( width - 2 @@ -249,7 +250,7 @@ class Panel(JupyterMixin): subtitle_text = self._subtitle if subtitle_text is not None: - subtitle_text.stylize_before(border_style) + subtitle_text.stylize_before(partial_border_style) if subtitle_text is None or width <= 4: yield Segment(box.get_bottom([width - 2]), border_style) From 193c49247c34a4034775250e9aff187cadba6f8b Mon Sep 17 00:00:00 2001 From: Will McGugan Date: Mon, 1 Jul 2024 11:40:07 +0100 Subject: [PATCH 50/62] changelog --- CHANGELOG.md | 1 + CODE_OF_CONDUCT.md | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a6324a3a..ad46fbb6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed - Fixed `Table` rendering of box elements so "footer" elements truly appear at bottom of table, "mid" elements in main table body. +- Fix styles in Panel when Text objects are used for title https://github.com/Textualize/rich/pull/3401 ## [13.7.1] - 2024-02-28 diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index 5d048990..44171b77 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -6,7 +6,7 @@ In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, sex characteristics, gender identity and expression, -level of experience, education, socio-economic status, nationality, personal +level of experience, education, socioeconomic status, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards From f14920de99cd5a92f1657c3603739ebb57e1ac4e Mon Sep 17 00:00:00 2001 From: Will McGugan Date: Mon, 1 Jul 2024 11:44:53 +0100 Subject: [PATCH 51/62] changelog --- CHANGELOG.md | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 02dd2cae..3027945e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,7 +10,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed - Fixed `Table` rendering of box elements so "footer" elements truly appear at bottom of table, "mid" elements in main table body. -- Fix styles in Panel when Text objects are used for title https://github.com/Textualize/rich/pull/3401 +- Fixed styles in Panel when Text objects are used for title https://github.com/Textualize/rich/pull/3401 + +### Changed + +- `RichHandler` errors and warnings will now use different colors (red and yellow) https://github.com/Textualize/rich/issues/2825 ## [13.7.1] - 2024-02-28 @@ -113,12 +117,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Added Style.clear_meta_and_links -## Unreleased - -### Fixed - -- `RichHandler` errors and warnings will now use different colors (red and yellow) https://github.com/Textualize/rich/issues/2825 - ## [13.3.2] - 2023-02-04 ### Fixed From 5568de4fa30cabffeefc0a5bdd772bfa957bcd85 Mon Sep 17 00:00:00 2001 From: Will McGugan Date: Mon, 1 Jul 2024 11:53:24 +0100 Subject: [PATCH 52/62] changelog --- CHANGELOG.md | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 78b7182a..0cf9eafd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Fixed `Table` rendering of box elements so "footer" elements truly appear at bottom of table, "mid" elements in main table body. - Fixed styles in Panel when Text objects are used for title https://github.com/Textualize/rich/pull/3401 +- Fix pretty repr for `collections.deque` https://github.com/Textualize/rich/pull/2864 ### Changed @@ -117,12 +118,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Added Style.clear_meta_and_links -## Unreleased - -### Fixed - -- Fix pretty repr for `collections.deque` https://github.com/Textualize/rich/pull/2864 - ## [13.3.2] - 2023-02-04 ### Fixed From 01f708e7977fadc7f3b397b09249bb841bb27248 Mon Sep 17 00:00:00 2001 From: Will McGugan Date: Mon, 1 Jul 2024 12:38:22 +0100 Subject: [PATCH 53/62] test fix --- tests/test_pretty.py | 112 +++++++++++++++++++++---------------------- 1 file changed, 56 insertions(+), 56 deletions(-) diff --git a/tests/test_pretty.py b/tests/test_pretty.py index 60534762..fcb9b209 100644 --- a/tests/test_pretty.py +++ b/tests/test_pretty.py @@ -40,7 +40,7 @@ skip_py312 = pytest.mark.skipif( ) -def test_install(): +def test_install() -> None: console = Console(file=io.StringIO()) dh = sys.displayhook install(console) @@ -49,7 +49,7 @@ def test_install(): assert sys.displayhook is not dh -def test_install_max_depth(): +def test_install_max_depth() -> None: console = Console(file=io.StringIO()) dh = sys.displayhook install(console, max_depth=1) @@ -58,7 +58,7 @@ def test_install_max_depth(): assert sys.displayhook is not dh -def test_ipy_display_hook__repr_html(): +def test_ipy_display_hook__repr_html() -> None: console = Console(file=io.StringIO(), force_jupyter=True) class Thing: @@ -72,7 +72,7 @@ def test_ipy_display_hook__repr_html(): assert console.end_capture() == "" -def test_ipy_display_hook__multiple_special_reprs(): +def test_ipy_display_hook__multiple_special_reprs() -> None: """ The case where there are multiple IPython special _repr_*_ methods on the object, and one of them returns None but another @@ -94,7 +94,7 @@ def test_ipy_display_hook__multiple_special_reprs(): assert result == "A Thing" -def test_ipy_display_hook__no_special_repr_methods(): +def test_ipy_display_hook__no_special_repr_methods() -> None: console = Console(file=io.StringIO(), force_jupyter=True) class Thing: @@ -106,7 +106,7 @@ def test_ipy_display_hook__no_special_repr_methods(): assert result == "hello" -def test_ipy_display_hook__special_repr_raises_exception(): +def test_ipy_display_hook__special_repr_raises_exception() -> None: """ When an IPython special repr method raises an exception, we treat it as if it doesn't exist and look for the next. @@ -130,14 +130,14 @@ def test_ipy_display_hook__special_repr_raises_exception(): assert result == "therepr" -def test_ipy_display_hook__console_renderables_on_newline(): +def test_ipy_display_hook__console_renderables_on_newline() -> None: console = Console(file=io.StringIO(), force_jupyter=True) console.begin_capture() result = _ipy_display_hook(Text("hello"), console=console) assert result == "\nhello" -def test_pretty(): +def test_pretty() -> None: test = { "foo": [1, 2, 3, (4, 5, {6}, 7, 8, {9}), {}], "bar": {"egg": "baz", "words": ["Hello World"] * 10}, @@ -167,7 +167,7 @@ class Empty: pass -def test_pretty_dataclass(): +def test_pretty_dataclass() -> None: dc = ExampleDataclass(1000, "Hello, World", 999, ["foo", "bar", "baz"]) result = pretty_repr(dc, max_width=80) print(repr(result)) @@ -187,7 +187,7 @@ def test_pretty_dataclass(): assert result == "ExampleDataclass(foo=1000, bar=..., baz=['foo', 'bar', 'baz'])" -def test_empty_dataclass(): +def test_empty_dataclass() -> None: assert pretty_repr(Empty()) == "Empty()" assert pretty_repr([Empty()]) == "[Empty()]" @@ -200,7 +200,7 @@ class StockKeepingUnit(NamedTuple): reviews: List[str] -def test_pretty_namedtuple(): +def test_pretty_namedtuple() -> None: console = Console(color_system=None) console.begin_capture() @@ -227,17 +227,17 @@ def test_pretty_namedtuple(): ) -def test_pretty_namedtuple_length_one_no_trailing_comma(): +def test_pretty_namedtuple_length_one_no_trailing_comma() -> None: instance = collections.namedtuple("Thing", ["name"])(name="Bob") assert pretty_repr(instance) == "Thing(name='Bob')" -def test_pretty_namedtuple_empty(): +def test_pretty_namedtuple_empty() -> None: instance = collections.namedtuple("Thing", [])() assert pretty_repr(instance) == "Thing()" -def test_pretty_namedtuple_custom_repr(): +def test_pretty_namedtuple_custom_repr() -> None: class Thing(NamedTuple): def __repr__(self): return "XX" @@ -245,7 +245,7 @@ def test_pretty_namedtuple_custom_repr(): assert pretty_repr(Thing()) == "XX" -def test_pretty_namedtuple_fields_invalid_type(): +def test_pretty_namedtuple_fields_invalid_type() -> None: class LooksLikeANamedTupleButIsnt(tuple): _fields = "blah" @@ -254,20 +254,20 @@ def test_pretty_namedtuple_fields_invalid_type(): assert result == "()" # Treated as tuple -def test_pretty_namedtuple_max_depth(): +def test_pretty_namedtuple_max_depth() -> None: instance = {"unit": StockKeepingUnit("a", "b", 1.0, "c", ["d", "e"])} result = pretty_repr(instance, max_depth=1) assert result == "{'unit': StockKeepingUnit(...)}" -def test_small_width(): +def test_small_width() -> None: test = ["Hello world! 12345"] result = pretty_repr(test, max_width=10) expected = "[\n 'Hello world! 12345'\n]" assert result == expected -def test_ansi_in_pretty_repr(): +def test_ansi_in_pretty_repr() -> None: class Hello: def __repr__(self): return "Hello \x1b[38;5;239mWorld!" @@ -281,7 +281,7 @@ def test_ansi_in_pretty_repr(): assert result == "Hello World!\n" -def test_broken_repr(): +def test_broken_repr() -> None: class BrokenRepr: def __repr__(self): 1 / 0 @@ -292,7 +292,7 @@ def test_broken_repr(): assert result == expected -def test_broken_getattr(): +def test_broken_getattr() -> None: class BrokenAttr: def __getattr__(self, name): 1 / 0 @@ -305,7 +305,7 @@ def test_broken_getattr(): assert result == "BrokenAttr()" -def test_reference_cycle_container(): +def test_reference_cycle_container() -> None: test = [] test.append(test) res = pretty_repr(test) @@ -323,7 +323,7 @@ def test_reference_cycle_container(): assert res == "[1, [[2], [2]]]" -def test_reference_cycle_namedtuple(): +def test_reference_cycle_namedtuple() -> None: class Example(NamedTuple): x: int y: Any @@ -340,7 +340,7 @@ def test_reference_cycle_namedtuple(): assert res == "Example(x=1, y=[Example(x=2, y=None), Example(x=2, y=None)])" -def test_reference_cycle_dataclass(): +def test_reference_cycle_dataclass() -> None: @dataclass class Example: x: int @@ -363,7 +363,7 @@ def test_reference_cycle_dataclass(): assert res == "Example(x=1, y=[Example(x=2, y=None), Example(x=2, y=None)])" -def test_reference_cycle_attrs(): +def test_reference_cycle_attrs() -> None: @attr.define class Example: x: int @@ -386,7 +386,7 @@ def test_reference_cycle_attrs(): assert res == "Example(x=1, y=[Example(x=2, y=None), Example(x=2, y=None)])" -def test_reference_cycle_custom_repr(): +def test_reference_cycle_custom_repr() -> None: class Example: def __init__(self, x, y): self.x = x @@ -413,7 +413,7 @@ def test_reference_cycle_custom_repr(): assert res == "Example(x=1, y=[Example(x=2, y=None), Example(x=2, y=None)])" -def test_max_depth(): +def test_max_depth() -> None: d = {} d["foo"] = {"fob": {"a": [1, 2, 3], "b": {"z": "x", "y": ["a", "b", "c"]}}} @@ -435,7 +435,7 @@ def test_max_depth(): ) -def test_max_depth_rich_repr(): +def test_max_depth_rich_repr() -> None: class Foo: def __init__(self, foo): self.foo = foo @@ -456,7 +456,7 @@ def test_max_depth_rich_repr(): ) -def test_max_depth_attrs(): +def test_max_depth_attrs() -> None: @attr.define class Foo: foo = attr.field() @@ -471,7 +471,7 @@ def test_max_depth_attrs(): ) -def test_max_depth_dataclass(): +def test_max_depth_dataclass() -> None: @dataclass class Foo: foo: object @@ -486,13 +486,13 @@ def test_max_depth_dataclass(): ) -def test_defaultdict(): +def test_defaultdict() -> None: test_dict = defaultdict(int, {"foo": 2}) result = pretty_repr(test_dict) assert result == "defaultdict(, {'foo': 2})" -def test_deque(): +def test_deque() -> None: test_deque = deque([1, 2, 3]) result = pretty_repr(test_deque) assert result == "deque([1, 2, 3])" @@ -504,37 +504,37 @@ def test_deque(): assert result == "deque([1, 2, 3], maxlen=5)" test_deque = deque([1, 2, 3], maxlen=0) result = pretty_repr(test_deque) - assert result == "deque([], maxlen=0)" + assert result == "deque(maxlen=0)" test_deque = deque([]) result = pretty_repr(test_deque) - assert result == "deque([])" + assert result == "deque()" test_deque = deque([], maxlen=None) result = pretty_repr(test_deque) - assert result == "deque([])" + assert result == "deque()" test_deque = deque([], maxlen=5) result = pretty_repr(test_deque) - assert result == "deque([], maxlen=5)" + assert result == "deque(maxlen=5)" test_deque = deque([], maxlen=0) result = pretty_repr(test_deque) - assert result == "deque([], maxlen=0)" + assert result == "deque(maxlen=0)" -def test_array(): +def test_array() -> None: test_array = array("I", [1, 2, 3]) result = pretty_repr(test_array) assert result == "array('I', [1, 2, 3])" -def test_tuple_of_one(): +def test_tuple_of_one() -> None: assert pretty_repr((1,)) == "(1,)" -def test_node(): +def test_node() -> None: node = Node("abc") assert pretty_repr(node) == "abc: " -def test_indent_lines(): +def test_indent_lines() -> None: console = Console(width=100, color_system=None) console.begin_capture() console.print(Pretty([100, 200], indent_guides=True), width=8) @@ -550,35 +550,35 @@ def test_indent_lines(): assert result == expected -def test_pprint(): +def test_pprint() -> None: console = Console(color_system=None) console.begin_capture() pprint(1, console=console) assert console.end_capture() == "1\n" -def test_pprint_max_values(): +def test_pprint_max_values() -> None: console = Console(color_system=None) console.begin_capture() pprint([1, 2, 3, 4, 5, 6, 7, 8, 9, 0], console=console, max_length=2) assert console.end_capture() == "[1, 2, ... +8]\n" -def test_pprint_max_items(): +def test_pprint_max_items() -> None: console = Console(color_system=None) console.begin_capture() pprint({"foo": 1, "bar": 2, "egg": 3}, console=console, max_length=2) assert console.end_capture() == """{'foo': 1, 'bar': 2, ... +1}\n""" -def test_pprint_max_string(): +def test_pprint_max_string() -> None: console = Console(color_system=None) console.begin_capture() pprint(["Hello" * 20], console=console, max_string=8) assert console.end_capture() == """['HelloHel'+92]\n""" -def test_tuples(): +def test_tuples() -> None: console = Console(color_system=None) console.begin_capture() pprint((1,), console=console) @@ -593,7 +593,7 @@ def test_tuples(): assert result == expected -def test_newline(): +def test_newline() -> None: console = Console(color_system=None) console.begin_capture() console.print(Pretty((1,), insert_line=True, expand_all=True)) @@ -602,7 +602,7 @@ def test_newline(): assert result == expected -def test_empty_repr(): +def test_empty_repr() -> None: class Foo: def __repr__(self): return "" @@ -610,7 +610,7 @@ def test_empty_repr(): assert pretty_repr(Foo()) == "" -def test_attrs(): +def test_attrs() -> None: @attr.define class Point: x: int @@ -624,7 +624,7 @@ def test_attrs(): assert result == expected -def test_attrs_empty(): +def test_attrs_empty() -> None: @attr.define class Nada: pass @@ -638,7 +638,7 @@ def test_attrs_empty(): @skip_py310 @skip_py311 @skip_py312 -def test_attrs_broken(): +def test_attrs_broken() -> None: @attr.define class Foo: bar: int @@ -654,7 +654,7 @@ def test_attrs_broken(): @skip_py37 @skip_py38 @skip_py39 -def test_attrs_broken_310(): +def test_attrs_broken_310() -> None: @attr.define class Foo: bar: int @@ -667,7 +667,7 @@ def test_attrs_broken_310(): assert result == expected -def test_user_dict(): +def test_user_dict() -> None: class D1(UserDict): pass @@ -685,7 +685,7 @@ def test_user_dict(): assert result == "FOO" -def test_lying_attribute(): +def test_lying_attribute() -> None: """Test getattr doesn't break rich repr protocol""" class Foo: @@ -697,7 +697,7 @@ def test_lying_attribute(): assert "Foo" in result -def test_measure_pretty(): +def test_measure_pretty() -> None: """Test measure respects expand_all""" # https://github.com/Textualize/rich/issues/1998 console = Console() @@ -707,7 +707,7 @@ def test_measure_pretty(): assert measurement == Measurement(12, 12) -def test_tuple_rich_repr(): +def test_tuple_rich_repr() -> None: """ Test that can use None as key to have tuple positional values. """ @@ -719,7 +719,7 @@ def test_tuple_rich_repr(): assert pretty_repr(Foo()) == "Foo((1,))" -def test_tuple_rich_repr_default(): +def test_tuple_rich_repr_default() -> None: """ Test that can use None as key to have tuple positional values and with a default. """ From f03113697395c46c1bb9970412a29bd18248cf6d Mon Sep 17 00:00:00 2001 From: Will McGugan Date: Mon, 1 Jul 2024 13:35:03 +0100 Subject: [PATCH 54/62] exit track thread --- CHANGELOG.md | 2 ++ rich/progress.py | 4 ++-- tests/test_progress.py | 2 +- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b80f65c3..5ed6e0a1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed - Updated the widths of some characters https://github.com/Textualize/rich/pull/3289 +- Thread used in progress.track will exit if an exception occurs in a generator +- Progress track thread is now a daemon thread ## [13.7.0] - 2023-11-15 diff --git a/rich/progress.py b/rich/progress.py index 8c3563bf..94f12395 100644 --- a/rich/progress.py +++ b/rich/progress.py @@ -70,7 +70,7 @@ class _TrackThread(Thread): self.done = Event() self.completed = 0 - super().__init__() + super().__init__(daemon=True) def run(self) -> None: task_id = self.task_id @@ -78,7 +78,7 @@ class _TrackThread(Thread): update_period = self.update_period last_completed = 0 wait = self.done.wait - while not wait(update_period): + while not wait(update_period) and self.progress.live._started: completed = self.completed if last_completed != completed: advance(task_id, completed - last_completed) diff --git a/tests/test_progress.py b/tests/test_progress.py index 72497a0c..0be683c3 100644 --- a/tests/test_progress.py +++ b/tests/test_progress.py @@ -646,7 +646,7 @@ def test_wrap_file_task_total() -> None: os.remove(filename) -def test_task_progress_column_speed(): +def test_task_progress_column_speed() -> None: speed_text = TaskProgressColumn.render_speed(None) assert speed_text.plain == "" From 2cfdd4dd4037c93f3117e81ea1bd8269e6710151 Mon Sep 17 00:00:00 2001 From: Will McGugan Date: Mon, 1 Jul 2024 13:36:50 +0100 Subject: [PATCH 55/62] changelog --- CHANGELOG.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5ed6e0a1..e47aa39a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Fixed `Table` rendering of box elements so "footer" elements truly appear at bottom of table, "mid" elements in main table body. - Fixed styles in Panel when Text objects are used for title https://github.com/Textualize/rich/pull/3401 - Fix pretty repr for `collections.deque` https://github.com/Textualize/rich/pull/2864 +- Thread used in progress.track will exit if an exception occurs in a generator https://github.com/Textualize/rich/pull/3402 +- Progress track thread is now a daemon thread https://github.com/Textualize/rich/pull/3402 ### Changed @@ -24,8 +26,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed - Updated the widths of some characters https://github.com/Textualize/rich/pull/3289 -- Thread used in progress.track will exit if an exception occurs in a generator -- Progress track thread is now a daemon thread ## [13.7.0] - 2023-11-15 From 06c122867bb88bd8fbdaba32036239a3c87d32c5 Mon Sep 17 00:00:00 2001 From: Will McGugan Date: Mon, 1 Jul 2024 13:37:57 +0100 Subject: [PATCH 56/62] progress --- rich/progress.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rich/progress.py b/rich/progress.py index 94f12395..aa966495 100644 --- a/rich/progress.py +++ b/rich/progress.py @@ -78,7 +78,7 @@ class _TrackThread(Thread): update_period = self.update_period last_completed = 0 wait = self.done.wait - while not wait(update_period) and self.progress.live._started: + while not wait(update_period) and self.progress.live.is_started: completed = self.completed if last_completed != completed: advance(task_id, completed - last_completed) From 579b6ac0533779eb0d0fee4d837d08d0a218c529 Mon Sep 17 00:00:00 2001 From: Will McGugan Date: Mon, 1 Jul 2024 14:08:21 +0100 Subject: [PATCH 57/62] pyupgrade --- rich/_inspect.py | 2 - rich/console.py | 6 +-- rich/filesize.py | 3 +- rich/markdown.py | 98 ++++++++++++++++++-------------------------- rich/progress.py | 2 +- rich/progress_bar.py | 2 +- rich/theme.py | 4 +- rich/traceback.py | 2 - 8 files changed, 49 insertions(+), 70 deletions(-) diff --git a/rich/_inspect.py b/rich/_inspect.py index 30446ceb..e87698d1 100644 --- a/rich/_inspect.py +++ b/rich/_inspect.py @@ -1,5 +1,3 @@ -from __future__ import absolute_import - import inspect from inspect import cleandoc, getdoc, getfile, isclass, ismodule, signature from typing import Any, Collection, Iterable, Optional, Tuple, Type, Union diff --git a/rich/console.py b/rich/console.py index 67fd2879..23cc44d5 100644 --- a/rich/console.py +++ b/rich/console.py @@ -2165,7 +2165,7 @@ class Console: """ text = self.export_text(clear=clear, styles=styles) - with open(path, "wt", encoding="utf-8") as write_file: + with open(path, "w", encoding="utf-8") as write_file: write_file.write(text) def export_html( @@ -2271,7 +2271,7 @@ class Console: code_format=code_format, inline_styles=inline_styles, ) - with open(path, "wt", encoding="utf-8") as write_file: + with open(path, "w", encoding="utf-8") as write_file: write_file.write(html) def export_svg( @@ -2560,7 +2560,7 @@ class Console: font_aspect_ratio=font_aspect_ratio, unique_id=unique_id, ) - with open(path, "wt", encoding="utf-8") as write_file: + with open(path, "w", encoding="utf-8") as write_file: write_file.write(svg) diff --git a/rich/filesize.py b/rich/filesize.py index 99f118e2..83bc9118 100644 --- a/rich/filesize.py +++ b/rich/filesize.py @@ -1,4 +1,3 @@ -# coding: utf-8 """Functions for reporting filesizes. Borrowed from https://github.com/PyFilesystem/pyfilesystem2 The functions declared in this module should cover the different @@ -27,7 +26,7 @@ def _to_str( if size == 1: return "1 byte" elif size < base: - return "{:,} bytes".format(size) + return f"{size:,} bytes" for i, suffix in enumerate(suffixes, 2): # noqa: B007 unit = base**i diff --git a/rich/markdown.py b/rich/markdown.py index 9b5ceacd..f0913267 100644 --- a/rich/markdown.py +++ b/rich/markdown.py @@ -1,7 +1,7 @@ from __future__ import annotations import sys -from typing import ClassVar, Dict, Iterable, List, Optional, Type, Union +from typing import ClassVar, Iterable from markdown_it import MarkdownIt from markdown_it.token import Token @@ -31,7 +31,7 @@ class MarkdownElement: new_line: ClassVar[bool] = True @classmethod - def create(cls, markdown: "Markdown", token: Token) -> "MarkdownElement": + def create(cls, markdown: Markdown, token: Token) -> MarkdownElement: """Factory to create markdown element, Args: @@ -43,30 +43,28 @@ class MarkdownElement: """ return cls() - def on_enter(self, context: "MarkdownContext") -> None: + def on_enter(self, context: MarkdownContext) -> None: """Called when the node is entered. Args: context (MarkdownContext): The markdown context. """ - def on_text(self, context: "MarkdownContext", text: TextType) -> None: + def on_text(self, context: MarkdownContext, text: TextType) -> None: """Called when text is parsed. Args: context (MarkdownContext): The markdown context. """ - def on_leave(self, context: "MarkdownContext") -> None: + def on_leave(self, context: MarkdownContext) -> None: """Called when the parser leaves the element. Args: context (MarkdownContext): [description] """ - def on_child_close( - self, context: "MarkdownContext", child: "MarkdownElement" - ) -> bool: + def on_child_close(self, context: MarkdownContext, child: MarkdownElement) -> bool: """Called when a child element is closed. This method allows a parent element to take over rendering of its children. @@ -81,8 +79,8 @@ class MarkdownElement: return True def __rich_console__( - self, console: "Console", options: "ConsoleOptions" - ) -> "RenderResult": + self, console: Console, options: ConsoleOptions + ) -> RenderResult: return () @@ -100,14 +98,14 @@ class TextElement(MarkdownElement): style_name = "none" - def on_enter(self, context: "MarkdownContext") -> None: + def on_enter(self, context: MarkdownContext) -> None: self.style = context.enter_style(self.style_name) self.text = Text(justify="left") - def on_text(self, context: "MarkdownContext", text: TextType) -> None: + def on_text(self, context: MarkdownContext, text: TextType) -> None: self.text.append(text, context.current_style if isinstance(text, str) else None) - def on_leave(self, context: "MarkdownContext") -> None: + def on_leave(self, context: MarkdownContext) -> None: context.leave_style() @@ -118,7 +116,7 @@ class Paragraph(TextElement): justify: JustifyMethod @classmethod - def create(cls, markdown: "Markdown", token: Token) -> "Paragraph": + def create(cls, markdown: Markdown, token: Token) -> Paragraph: return cls(justify=markdown.justify or "left") def __init__(self, justify: JustifyMethod) -> None: @@ -135,10 +133,10 @@ class Heading(TextElement): """A heading.""" @classmethod - def create(cls, markdown: "Markdown", token: Token) -> "Heading": + def create(cls, markdown: Markdown, token: Token) -> Heading: return cls(token.tag) - def on_enter(self, context: "MarkdownContext") -> None: + def on_enter(self, context: MarkdownContext) -> None: self.text = Text() context.enter_style(self.style_name) @@ -172,7 +170,7 @@ class CodeBlock(TextElement): style_name = "markdown.code_block" @classmethod - def create(cls, markdown: "Markdown", token: Token) -> "CodeBlock": + def create(cls, markdown: Markdown, token: Token) -> CodeBlock: node_info = token.info or "" lexer_name = node_info.partition(" ")[0] return cls(lexer_name or "text", markdown.code_theme) @@ -199,9 +197,7 @@ class BlockQuote(TextElement): def __init__(self) -> None: self.elements: Renderables = Renderables() - def on_child_close( - self, context: "MarkdownContext", child: "MarkdownElement" - ) -> bool: + def on_child_close(self, context: MarkdownContext, child: MarkdownElement) -> bool: self.elements.append(child) return False @@ -238,9 +234,7 @@ class TableElement(MarkdownElement): self.header: TableHeaderElement | None = None self.body: TableBodyElement | None = None - def on_child_close( - self, context: "MarkdownContext", child: "MarkdownElement" - ) -> bool: + def on_child_close(self, context: MarkdownContext, child: MarkdownElement) -> bool: if isinstance(child, TableHeaderElement): self.header = child elif isinstance(child, TableBodyElement): @@ -272,9 +266,7 @@ class TableHeaderElement(MarkdownElement): def __init__(self) -> None: self.row: TableRowElement | None = None - def on_child_close( - self, context: "MarkdownContext", child: "MarkdownElement" - ) -> bool: + def on_child_close(self, context: MarkdownContext, child: MarkdownElement) -> bool: assert isinstance(child, TableRowElement) self.row = child return False @@ -286,9 +278,7 @@ class TableBodyElement(MarkdownElement): def __init__(self) -> None: self.rows: list[TableRowElement] = [] - def on_child_close( - self, context: "MarkdownContext", child: "MarkdownElement" - ) -> bool: + def on_child_close(self, context: MarkdownContext, child: MarkdownElement) -> bool: assert isinstance(child, TableRowElement) self.rows.append(child) return False @@ -298,11 +288,9 @@ class TableRowElement(MarkdownElement): """MarkdownElement corresponding to `tr_open` and `tr_close`.""" def __init__(self) -> None: - self.cells: List[TableDataElement] = [] + self.cells: list[TableDataElement] = [] - def on_child_close( - self, context: "MarkdownContext", child: "MarkdownElement" - ) -> bool: + def on_child_close(self, context: MarkdownContext, child: MarkdownElement) -> bool: assert isinstance(child, TableDataElement) self.cells.append(child) return False @@ -313,7 +301,7 @@ class TableDataElement(MarkdownElement): and `th_open` and `th_close`.""" @classmethod - def create(cls, markdown: "Markdown", token: Token) -> "MarkdownElement": + def create(cls, markdown: Markdown, token: Token) -> MarkdownElement: style = str(token.attrs.get("style")) or "" justify: JustifyMethod @@ -333,7 +321,7 @@ class TableDataElement(MarkdownElement): self.content: Text = Text("", justify=justify) self.justify = justify - def on_text(self, context: "MarkdownContext", text: TextType) -> None: + def on_text(self, context: MarkdownContext, text: TextType) -> None: text = Text(text) if isinstance(text, str) else text text.stylize(context.current_style) self.content.append_text(text) @@ -343,17 +331,15 @@ class ListElement(MarkdownElement): """A list element.""" @classmethod - def create(cls, markdown: "Markdown", token: Token) -> "ListElement": + def create(cls, markdown: Markdown, token: Token) -> ListElement: return cls(token.type, int(token.attrs.get("start", 1))) def __init__(self, list_type: str, list_start: int | None) -> None: - self.items: List[ListItem] = [] + self.items: list[ListItem] = [] self.list_type = list_type self.list_start = list_start - def on_child_close( - self, context: "MarkdownContext", child: "MarkdownElement" - ) -> bool: + def on_child_close(self, context: MarkdownContext, child: MarkdownElement) -> bool: assert isinstance(child, ListItem) self.items.append(child) return False @@ -381,9 +367,7 @@ class ListItem(TextElement): def __init__(self) -> None: self.elements: Renderables = Renderables() - def on_child_close( - self, context: "MarkdownContext", child: "MarkdownElement" - ) -> bool: + def on_child_close(self, context: MarkdownContext, child: MarkdownElement) -> bool: self.elements.append(child) return False @@ -419,7 +403,7 @@ class ListItem(TextElement): class Link(TextElement): @classmethod - def create(cls, markdown: "Markdown", token: Token) -> "MarkdownElement": + def create(cls, markdown: Markdown, token: Token) -> MarkdownElement: url = token.attrs.get("href", "#") return cls(token.content, str(url)) @@ -434,7 +418,7 @@ class ImageItem(TextElement): new_line = False @classmethod - def create(cls, markdown: "Markdown", token: Token) -> "MarkdownElement": + def create(cls, markdown: Markdown, token: Token) -> MarkdownElement: """Factory to create markdown element, Args: @@ -449,10 +433,10 @@ class ImageItem(TextElement): def __init__(self, destination: str, hyperlinks: bool) -> None: self.destination = destination self.hyperlinks = hyperlinks - self.link: Optional[str] = None + self.link: str | None = None super().__init__() - def on_enter(self, context: "MarkdownContext") -> None: + def on_enter(self, context: MarkdownContext) -> None: self.link = context.current_style.link self.text = Text(justify="left") super().on_enter(context) @@ -476,7 +460,7 @@ class MarkdownContext: console: Console, options: ConsoleOptions, style: Style, - inline_code_lexer: Optional[str] = None, + inline_code_lexer: str | None = None, inline_code_theme: str = "monokai", ) -> None: self.console = console @@ -484,7 +468,7 @@ class MarkdownContext: self.style_stack: StyleStack = StyleStack(style) self.stack: Stack[MarkdownElement] = Stack() - self._syntax: Optional[Syntax] = None + self._syntax: Syntax | None = None if inline_code_lexer is not None: self._syntax = Syntax("", inline_code_lexer, theme=inline_code_theme) @@ -504,7 +488,7 @@ class MarkdownContext: else: self.stack.top.on_text(self, text) - def enter_style(self, style_name: Union[str, Style]) -> Style: + def enter_style(self, style_name: str | Style) -> Style: """Enter a style context.""" style = self.console.get_style(style_name, default="none") self.style_stack.push(style) @@ -531,7 +515,7 @@ class Markdown(JupyterMixin): highlighting, or None for no highlighting. Defaults to None. """ - elements: ClassVar[Dict[str, Type[MarkdownElement]]] = { + elements: ClassVar[dict[str, type[MarkdownElement]]] = { "paragraph_open": Paragraph, "heading_open": Heading, "fence": CodeBlock, @@ -556,17 +540,17 @@ class Markdown(JupyterMixin): self, markup: str, code_theme: str = "monokai", - justify: Optional[JustifyMethod] = None, - style: Union[str, Style] = "none", + justify: JustifyMethod | None = None, + style: str | Style = "none", hyperlinks: bool = True, - inline_code_lexer: Optional[str] = None, - inline_code_theme: Optional[str] = None, + inline_code_lexer: str | None = None, + inline_code_theme: str | None = None, ) -> None: parser = MarkdownIt().enable("strikethrough").enable("table") self.markup = markup self.parsed = parser.parse(markup) self.code_theme = code_theme - self.justify: Optional[JustifyMethod] = justify + self.justify: JustifyMethod | None = justify self.style = style self.hyperlinks = hyperlinks self.inline_code_lexer = inline_code_lexer @@ -772,7 +756,7 @@ if __name__ == "__main__": # pragma: no cover if args.path == "-": markdown_body = sys.stdin.read() else: - with open(args.path, "rt", encoding="utf-8") as markdown_file: + with open(args.path, encoding="utf-8") as markdown_file: markdown_body = markdown_file.read() markdown = Markdown( diff --git a/rich/progress.py b/rich/progress.py index aa966495..13b2750a 100644 --- a/rich/progress.py +++ b/rich/progress.py @@ -1326,7 +1326,7 @@ class Progress(JupyterMixin): # normalize the mode (always rb, rt) _mode = "".join(sorted(mode, reverse=False)) if _mode not in ("br", "rt", "r"): - raise ValueError("invalid mode {!r}".format(mode)) + raise ValueError(f"invalid mode {mode!r}") # patch buffering to provide the same behaviour as the builtin `open` line_buffering = buffering == 1 diff --git a/rich/progress_bar.py b/rich/progress_bar.py index a2bf3261..41794f76 100644 --- a/rich/progress_bar.py +++ b/rich/progress_bar.py @@ -108,7 +108,7 @@ class ProgressBar(JupyterMixin): for index in range(PULSE_SIZE): position = index / PULSE_SIZE - fade = 0.5 + cos((position * pi * 2)) / 2.0 + fade = 0.5 + cos(position * pi * 2) / 2.0 color = blend_rgb(fore_color, back_color, cross_fade=fade) append(_Segment(bar, _Style(color=from_triplet(color)))) return segments diff --git a/rich/theme.py b/rich/theme.py index 471dfb2f..227f1d86 100644 --- a/rich/theme.py +++ b/rich/theme.py @@ -1,5 +1,5 @@ import configparser -from typing import Dict, List, IO, Mapping, Optional +from typing import IO, Dict, List, Mapping, Optional from .default_styles import DEFAULT_STYLES from .style import Style, StyleType @@ -69,7 +69,7 @@ class Theme: Returns: Theme: A new theme instance. """ - with open(path, "rt", encoding=encoding) as config_file: + with open(path, encoding=encoding) as config_file: return cls.from_file(config_file, source=path, inherit=inherit) diff --git a/rich/traceback.py b/rich/traceback.py index 4606e0b3..fcefeb23 100644 --- a/rich/traceback.py +++ b/rich/traceback.py @@ -1,5 +1,3 @@ -from __future__ import absolute_import - import linecache import os import sys From 5f4f6966a10e21267b22da9d6fe712b366a5e2e8 Mon Sep 17 00:00:00 2001 From: Will McGugan Date: Mon, 1 Jul 2024 14:28:10 +0100 Subject: [PATCH 58/62] changelog --- CHANGELOG.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7be80ffe..9316a342 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - `RichHandler` errors and warnings will now use different colors (red and yellow) https://github.com/Textualize/rich/issues/2825 - Removed the empty line printed in jupyter while using `Progress` https://github.com/Textualize/rich/pull/2616 +### Added + +- Adds a `case_sensitive` parameter to `prompt.Prompt`. This determines if the + response is treated as case-sensitive. Defaults to `True`. + ## [13.7.1] - 2024-02-28 ### Fixed @@ -32,8 +37,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added - Adds missing parameters to Panel.fit https://github.com/Textualize/rich/issues/3142 -- Adds a `case_sensitive` parameter to `prompt.Prompt`. This determines if the - response is treated as case-sensitive. Defaults to `True`. ### Fixed From 6a3e9e817ff327876b1bec45b741450199de996b Mon Sep 17 00:00:00 2001 From: Will McGugan Date: Mon, 1 Jul 2024 15:09:28 +0100 Subject: [PATCH 59/62] docstring --- rich/markdown.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rich/markdown.py b/rich/markdown.py index f0913267..a58a04fc 100644 --- a/rich/markdown.py +++ b/rich/markdown.py @@ -505,7 +505,7 @@ class Markdown(JupyterMixin): Args: markup (str): A string containing markdown. - code_theme (str, optional): Pygments theme for code blocks. Defaults to "monokai". + code_theme (str, optional): Pygments theme for code blocks. Defaults to "monokai". See https://pygments.org/styles/ for code themes. justify (JustifyMethod, optional): Justify value for paragraphs. Defaults to None. style (Union[str, Style], optional): Optional style to apply to markdown. hyperlinks (bool, optional): Enable hyperlinks. Defaults to ``True``. From 927d06669d82e05cfc31abf30cc9f8cede9ebfd3 Mon Sep 17 00:00:00 2001 From: Will McGugan Date: Mon, 1 Jul 2024 16:01:10 +0100 Subject: [PATCH 60/62] docs --- docs/source/progress.rst | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/docs/source/progress.rst b/docs/source/progress.rst index 272687d9..7a771c8d 100644 --- a/docs/source/progress.rst +++ b/docs/source/progress.rst @@ -55,6 +55,34 @@ Here's a simple example:: The ``total`` value associated with a task is the number of steps that must be completed for the progress to reach 100%. A *step* in this context is whatever makes sense for your application; it could be number of bytes of a file read, or number of images processed, etc. +Starting and stopping +~~~~~~~~~~~~~~~~~~~~~ + +The context manager is recommended if you can use it. If you don't use the context manager, be sure to call :meth:`~rich.progress.Progress.start` to start the progress display, and :meth:`~rich.progress.Progress.stop` to stop it. + +Here's an example that doesn't use the context manager:: + + import time + + from rich.progress import Progress + + progress = Progress() + progress.start() + try: + task1 = progress.add_task("[red]Downloading...", total=1000) + task2 = progress.add_task("[green]Processing...", total=1000) + task3 = progress.add_task("[cyan]Cooking...", total=1000) + + while not progress.finished: + progress.update(task1, advance=0.5) + progress.update(task2, advance=0.3) + progress.update(task3, advance=0.9) + time.sleep(0.02) + finally: + progress.stop() + +Note the use of the try / finally, to ensure that ``stop()`` is called. + Updating tasks ~~~~~~~~~~~~~~ From dcbe0ec6bb78eb023c6810d6a07dc1bb3e69c8b1 Mon Sep 17 00:00:00 2001 From: Will McGugan Date: Mon, 1 Jul 2024 20:45:58 +0100 Subject: [PATCH 61/62] highlight column --- rich/table.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/rich/table.py b/rich/table.py index 05084860..10af2e6f 100644 --- a/rich/table.py +++ b/rich/table.py @@ -106,6 +106,9 @@ class Column: no_wrap: bool = False """bool: Prevent wrapping of text within the column. Defaults to ``False``.""" + highlight: bool = False + """bool: Apply highlighter to column. Defaults to ``False``.""" + _index: int = 0 """Index of column.""" @@ -821,6 +824,7 @@ class Table(JupyterMixin): no_wrap=column.no_wrap, overflow=column.overflow, height=None, + highlight=column.highlight, ) lines = console.render_lines( cell.renderable, From fde5d6eee3b0437eaecdcbf6f8b11aeab3a5d503 Mon Sep 17 00:00:00 2001 From: Will McGugan Date: Mon, 1 Jul 2024 20:47:13 +0100 Subject: [PATCH 62/62] format --- rich/pretty.py | 6 +++++- rich/progress.py | 6 +++++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/rich/pretty.py b/rich/pretty.py index c88f90c3..fa340212 100644 --- a/rich/pretty.py +++ b/rich/pretty.py @@ -361,7 +361,11 @@ def _get_braces_for_defaultdict(_object: DefaultDict[Any, Any]) -> Tuple[str, st def _get_braces_for_deque(_object: Deque[Any]) -> Tuple[str, str, str]: if _object.maxlen is None: return ("deque([", "])", "deque()") - return ("deque([", f"], maxlen={_object.maxlen})", f"deque(maxlen={_object.maxlen})") + return ( + "deque([", + f"], maxlen={_object.maxlen})", + f"deque(maxlen={_object.maxlen})", + ) def _get_braces_for_array(_object: "array[Any]") -> Tuple[str, str, str]: diff --git a/rich/progress.py b/rich/progress.py index 5353ca32..effcab40 100644 --- a/rich/progress.py +++ b/rich/progress.py @@ -168,7 +168,11 @@ def track( with progress: yield from progress.track( - sequence, total=total, completed=completed, description=description, update_period=update_period + sequence, + total=total, + completed=completed, + description=description, + update_period=update_period, )