mirror of
https://github.com/Textualize/rich.git
synced 2025-08-04 18:18:22 +00:00
new black
This commit is contained in:
parent
96ea5feddf
commit
60e813379b
40 changed files with 285 additions and 228 deletions
|
@ -1,4 +1,4 @@
|
|||
black==19.10b0
|
||||
black==20.8b1
|
||||
mypy==0.782
|
||||
poetry==1.0.10
|
||||
pytest==5.4.3
|
||||
|
|
|
@ -23,7 +23,11 @@ def get_console() -> "Console":
|
|||
|
||||
|
||||
def print(
|
||||
*objects: Any, sep=" ", end="\n", file: IO[str] = None, flush: bool = False,
|
||||
*objects: Any,
|
||||
sep=" ",
|
||||
end="\n",
|
||||
file: IO[str] = None,
|
||||
flush: bool = False,
|
||||
):
|
||||
from .console import Console
|
||||
|
||||
|
|
|
@ -91,7 +91,10 @@ def make_test_card() -> Table:
|
|||
table.add_row(
|
||||
"CJK support",
|
||||
Panel(
|
||||
"该库支持中文,日文和韩文文本!", expand=False, border_style="red", box=box.DOUBLE_EDGE,
|
||||
"该库支持中文,日文和韩文文本!",
|
||||
expand=False,
|
||||
border_style="red",
|
||||
box=box.DOUBLE_EDGE,
|
||||
),
|
||||
)
|
||||
|
||||
|
@ -102,7 +105,8 @@ def make_test_card() -> Table:
|
|||
|
||||
markup_example = "[bold magenta]Rich[/] supports a simple [i]bbcode[/i] like [b]markup[/b], you can use to insert [yellow]color[/] and [underline]style[/]."
|
||||
table.add_row(
|
||||
"Console markup", comparison(Text(markup_example), markup_example),
|
||||
"Console markup",
|
||||
comparison(Text(markup_example), markup_example),
|
||||
)
|
||||
|
||||
example_table = Table(
|
||||
|
|
|
@ -5,7 +5,7 @@ def pick_bool(*values: Optional[bool]) -> bool:
|
|||
"""Pick the first non-none bool or return the last value.
|
||||
|
||||
Args:
|
||||
*values (bool): Any number of boolean or None values.
|
||||
*values (bool): Any number of boolean or None values.
|
||||
|
||||
Returns:
|
||||
bool: First non-none boolean.
|
||||
|
|
|
@ -6,13 +6,13 @@ def ratio_reduce(
|
|||
total: int, ratios: List[int], maximums: List[int], values: List[int]
|
||||
) -> List[int]:
|
||||
"""Divide an integer total in to parts based on ratios.
|
||||
|
||||
|
||||
Args:
|
||||
total (int): The total to divide.
|
||||
ratios (List[int]): A list of integer ratios.
|
||||
maximums (List[int]): List of maximums values for each slot.
|
||||
maximums (List[int]): List of maximums values for each slot.
|
||||
values (List[int]): List of values
|
||||
|
||||
|
||||
Returns:
|
||||
List[int]: A list of integers garanteed to sum to total.
|
||||
"""
|
||||
|
@ -38,12 +38,12 @@ def ratio_distribute(
|
|||
total: int, ratios: List[int], minimums: List[int] = None
|
||||
) -> List[int]:
|
||||
"""Distribute an integer total in to parts based on ratios.
|
||||
|
||||
|
||||
Args:
|
||||
total (int): The total to divide.
|
||||
ratios (List[int]): A list of integer ratios.
|
||||
minimums (List[int]): List of minimum values for each slot.
|
||||
|
||||
minimums (List[int]): List of minimum values for each slot.
|
||||
|
||||
Returns:
|
||||
List[int]: A list of integers garanteed to sum to total.
|
||||
"""
|
||||
|
|
|
@ -18,7 +18,7 @@ PULSE_SIZE = 20
|
|||
|
||||
class Bar(JupyterMixin):
|
||||
"""Renders a (progress) bar.
|
||||
|
||||
|
||||
Args:
|
||||
total (float, optional): Number of steps in the bar. Defaults to 100.
|
||||
completed (float, optional): Number of steps completed. Defaults to 0.
|
||||
|
@ -114,7 +114,7 @@ class Bar(JupyterMixin):
|
|||
|
||||
def update(self, completed: float, total: float = None) -> None:
|
||||
"""Update progress with new values.
|
||||
|
||||
|
||||
Args:
|
||||
completed (float): Number of steps completed.
|
||||
total (float, optional): Total number of steps, or ``None`` to not change. Defaults to None.
|
||||
|
|
16
rich/box.py
16
rich/box.py
|
@ -6,7 +6,7 @@ from ._loop import loop_last
|
|||
|
||||
class Box:
|
||||
"""Defines characters to render boxes.
|
||||
|
||||
|
||||
┌─┬┐ top
|
||||
│ ││ head
|
||||
├─┼┤ head_row
|
||||
|
@ -16,7 +16,7 @@ class Box:
|
|||
│ ││ foot
|
||||
└─┴┘ bottom
|
||||
|
||||
|
||||
|
||||
"""
|
||||
|
||||
def __init__(self, box: str) -> None:
|
||||
|
@ -60,10 +60,10 @@ class Box:
|
|||
|
||||
def get_top(self, widths: Iterable[int]) -> str:
|
||||
"""Get the top of a simple box.
|
||||
|
||||
|
||||
Args:
|
||||
widths (List[int]): Widths of columns.
|
||||
|
||||
|
||||
Returns:
|
||||
str: A string of box characters.
|
||||
"""
|
||||
|
@ -85,10 +85,10 @@ class Box:
|
|||
edge: bool = True,
|
||||
) -> str:
|
||||
"""Get the top of a simple box.
|
||||
|
||||
|
||||
Args:
|
||||
width (List[int]): Widths of columns.
|
||||
|
||||
|
||||
Returns:
|
||||
str: A string of box characters.
|
||||
"""
|
||||
|
@ -129,10 +129,10 @@ class Box:
|
|||
|
||||
def get_bottom(self, widths: Iterable[int]) -> str:
|
||||
"""Get the bottom of a simple box.
|
||||
|
||||
|
||||
Args:
|
||||
widths (List[int]): Widths of columns.
|
||||
|
||||
|
||||
Returns:
|
||||
str: A string of box characters.
|
||||
"""
|
||||
|
|
|
@ -7,10 +7,10 @@ from ._lru_cache import LRUCache
|
|||
|
||||
def cell_len(text: str, _cache: Dict[str, int] = LRUCache(1024 * 4)) -> int:
|
||||
"""Get the number of cells required to display text.
|
||||
|
||||
|
||||
Args:
|
||||
text (str): Text to display.
|
||||
|
||||
|
||||
Returns:
|
||||
int: Number of cells required to display the text.
|
||||
"""
|
||||
|
@ -27,10 +27,10 @@ def cell_len(text: str, _cache: Dict[str, int] = LRUCache(1024 * 4)) -> int:
|
|||
|
||||
def get_character_cell_size(character: str) -> int:
|
||||
"""Get the cell size of a character.
|
||||
|
||||
|
||||
Args:
|
||||
character (str): A single character.
|
||||
|
||||
|
||||
Returns:
|
||||
int: Number of cells (0, 1 or 2) occupied by that character.
|
||||
"""
|
||||
|
@ -45,10 +45,10 @@ def get_character_cell_size(character: str) -> int:
|
|||
@lru_cache(maxsize=4096)
|
||||
def _get_codepoint_cell_size(codepoint: int) -> int:
|
||||
"""Get the cell size of a character.
|
||||
|
||||
|
||||
Args:
|
||||
character (str): A single character.
|
||||
|
||||
|
||||
Returns:
|
||||
int: Number of cells (0, 1 or 2) occupied by that character.
|
||||
"""
|
||||
|
|
|
@ -311,10 +311,10 @@ class Color(NamedTuple):
|
|||
@classmethod
|
||||
def from_triplet(cls, triplet: "ColorTriplet") -> "Color":
|
||||
"""Create a truecolor RGB color from a triplet of values.
|
||||
|
||||
|
||||
Args:
|
||||
triplet (ColorTriplet): A color triplet containing red, green and blue components.
|
||||
|
||||
|
||||
Returns:
|
||||
Color: A new color object.
|
||||
"""
|
||||
|
@ -323,7 +323,7 @@ class Color(NamedTuple):
|
|||
@classmethod
|
||||
def default(cls) -> "Color":
|
||||
"""Get a Color instance representing the default color.
|
||||
|
||||
|
||||
Returns:
|
||||
Color: Default color.
|
||||
"""
|
||||
|
|
|
@ -17,7 +17,7 @@ class Columns(JupyterMixin):
|
|||
"""Display renderables in neat columns.
|
||||
|
||||
Args:
|
||||
renderables (Iterable[RenderableType]): Any number of Rich renderables (including str).
|
||||
renderables (Iterable[RenderableType]): Any number of Rich renderables (including str).
|
||||
width (int, optional): The desired width of the columns, or None to auto detect. Defaults to None.
|
||||
padding (PaddingDimensions, optional): Optional padding around cells. Defaults to (0, 1).
|
||||
expand (bool, optional): Expand columns to full width. Defaults to False.
|
||||
|
|
|
@ -293,7 +293,7 @@ class Console:
|
|||
width (int, optional): The width of the terminal. Leave as default to auto-detect width.
|
||||
height (int, optional): The height of the terminal. Leave as default to auto-detect height.
|
||||
record (bool, optional): Boolean to enable recording of terminal output,
|
||||
required to call :meth:`export_html` and :meth:`export_text`. Defaults to False.
|
||||
required to call :meth:`export_html` and :meth:`export_text`. Defaults to False.
|
||||
markup (bool, optional): Boolean to enable :ref:`console_markup`. Defaults to True.
|
||||
emoji (bool, optional): Enable emoji code. Defaults to True.
|
||||
highlight (bool, optional): Enable automatic highlighting. Defaults to True.
|
||||
|
@ -364,7 +364,9 @@ class Console:
|
|||
|
||||
self._lock = threading.RLock()
|
||||
self._log_render = LogRender(
|
||||
show_time=log_time, show_path=log_path, time_format=log_time_format,
|
||||
show_time=log_time,
|
||||
show_path=log_path,
|
||||
time_format=log_time_format,
|
||||
)
|
||||
self.highlighter: HighlighterType = highlighter or _null_highlighter
|
||||
self.safe_box = safe_box
|
||||
|
@ -484,10 +486,10 @@ class Console:
|
|||
@property
|
||||
def is_dumb_terminal(self) -> bool:
|
||||
"""Detect dumb terminal.
|
||||
|
||||
|
||||
Returns:
|
||||
bool: True if writing to a dumb terminal, otherwise False.
|
||||
|
||||
|
||||
"""
|
||||
is_dumb = "TERM" in self._environ and self._environ["TERM"].lower() in (
|
||||
"dumb",
|
||||
|
@ -560,7 +562,7 @@ class Console:
|
|||
|
||||
def show_cursor(self, show: bool = True) -> None:
|
||||
"""Show or hide the cursor.
|
||||
|
||||
|
||||
Args:
|
||||
show (bool, optional): Set visibility of the cursor.
|
||||
"""
|
||||
|
@ -735,7 +737,7 @@ class Console:
|
|||
renderables (Iterable[Union[str, ConsoleRenderable]]): Anyting that Rich can render.
|
||||
sep (str, optional): String to write between print data. Defaults to " ".
|
||||
end (str, optional): String to write at end of print data. Defaults to "\\n".
|
||||
justify (str, optional): One of "left", "right", "center", or "full". Defaults to ``None``.
|
||||
justify (str, optional): One of "left", "right", "center", or "full". Defaults to ``None``.
|
||||
emoji (Optional[bool], optional): Enable emoji code, or ``None`` to use console default.
|
||||
markup (Optional[bool], optional): Enable markup, or ``None`` to use console default.
|
||||
highlight (Optional[bool], optional): Enable automatic highlighting, or ``None`` to use console default.
|
||||
|
@ -800,9 +802,9 @@ class Console:
|
|||
style: Union[str, Style] = "rule.line",
|
||||
) -> None:
|
||||
"""Draw a line with optional centered title.
|
||||
|
||||
|
||||
Args:
|
||||
title (str, optional): Text to render over the rule. Defaults to "".
|
||||
title (str, optional): Text to render over the rule. Defaults to "".
|
||||
characters (str, optional): Character(s) to form the line. Defaults to "─".
|
||||
"""
|
||||
from .rule import Rule
|
||||
|
@ -910,7 +912,7 @@ class Console:
|
|||
word_wrap: bool = False,
|
||||
) -> None:
|
||||
"""Prints a rich render of the last exception and traceback.
|
||||
|
||||
|
||||
Args:
|
||||
code_width (Optional[int], optional): Number of characters used to render code. Defaults to 88.
|
||||
extra_lines (int, optional): Additional lines of code to render. Defaults to 3.
|
||||
|
@ -983,7 +985,11 @@ class Console:
|
|||
|
||||
renderables = [
|
||||
self._log_render(
|
||||
self, renderables, path=path, line_no=line_no, link_path=link_path,
|
||||
self,
|
||||
renderables,
|
||||
path=path,
|
||||
line_no=line_no,
|
||||
link_path=link_path,
|
||||
)
|
||||
]
|
||||
for hook in self._render_hooks:
|
||||
|
@ -1041,7 +1047,9 @@ class Console:
|
|||
if style and not is_control:
|
||||
append(
|
||||
style.render(
|
||||
text, color_system=color_system, legacy_windows=legacy_windows,
|
||||
text,
|
||||
color_system=color_system,
|
||||
legacy_windows=legacy_windows,
|
||||
)
|
||||
)
|
||||
else:
|
||||
|
@ -1060,7 +1068,7 @@ class Console:
|
|||
password: bool = False,
|
||||
stream: TextIO = None,
|
||||
) -> str:
|
||||
"""Displays a prompt and waits for input from the user. The prompt may contain color / style.
|
||||
"""Displays a prompt and waits for input from the user. The prompt may contain color / style.
|
||||
|
||||
Args:
|
||||
prompt (Union[str, Text]): Text to render in the prompt.
|
||||
|
@ -1068,7 +1076,7 @@ class Console:
|
|||
emoji (bool, optional): Enable emoji (requires a str prompt). Defaults to True.
|
||||
password: (bool, optional): Hide typed text. Defaults to False.
|
||||
stream: (TextIO, optional): Optional file to read input from (rather than stdin). Defaults to None.
|
||||
|
||||
|
||||
Returns:
|
||||
str: Text read from stdin.
|
||||
"""
|
||||
|
|
|
@ -9,7 +9,7 @@ if TYPE_CHECKING:
|
|||
|
||||
class Constrain(JupyterMixin):
|
||||
"""Constrain the width of a renderable to a given number of characters.
|
||||
|
||||
|
||||
Args:
|
||||
renderable (RenderableType): A renderable object.
|
||||
width (int, optional): The maximum width (in characters) to render. Defaults to 80.
|
||||
|
|
|
@ -110,13 +110,13 @@ class Lines:
|
|||
overflow: "OverflowMethod" = "fold",
|
||||
) -> None:
|
||||
"""Justify and overflow text to a given width.
|
||||
|
||||
|
||||
Args:
|
||||
console (Console): Console instance.
|
||||
width (int): Number of characters per line.
|
||||
justify (str, optional): Default justify method for text: "left", "center", "full" or "right". Defaults to "left".
|
||||
overflow (str, optional): Default overflow for text: "crop", "fold", or "ellipisis". Defaults to "fold".
|
||||
|
||||
overflow (str, optional): Default overflow for text: "crop", "fold", or "ellipisis". Defaults to "fold".
|
||||
|
||||
"""
|
||||
from .text import Text
|
||||
|
||||
|
|
|
@ -39,7 +39,7 @@ def strip_control_codes(text: str, _translate_table=_CONTROL_TRANSLATE) -> str:
|
|||
"""Remove control codes from text.
|
||||
|
||||
Args:
|
||||
text (str): A string possibly contain control codes.
|
||||
text (str): A string possibly contain control codes.
|
||||
|
||||
Returns:
|
||||
str: String with control codes removed.
|
||||
|
|
|
@ -17,11 +17,11 @@ class Emoji(JupyterMixin):
|
|||
|
||||
def __init__(self, name: str, style: Union[str, Style] = "none") -> None:
|
||||
"""A single emoji character.
|
||||
|
||||
|
||||
Args:
|
||||
name (str): Name of emoji.
|
||||
style (Union[str, Style], optional): Optional style. Defaults to None.
|
||||
|
||||
|
||||
Raises:
|
||||
NoEmoji: If the emoji doesn't exist.
|
||||
"""
|
||||
|
@ -35,10 +35,10 @@ class Emoji(JupyterMixin):
|
|||
@classmethod
|
||||
def replace(cls, text: str) -> str:
|
||||
"""Replace emoji markup with coresponding unicode characters.
|
||||
|
||||
|
||||
Args:
|
||||
text (str): A string with emojis codes, e.g. "Hello :smiley:!"
|
||||
|
||||
|
||||
Returns:
|
||||
str: A string with emoji codes replaces with actual emoji.
|
||||
"""
|
||||
|
|
|
@ -9,13 +9,13 @@ class Highlighter(ABC):
|
|||
|
||||
def __call__(self, text: Union[str, Text]) -> Text:
|
||||
"""Highlight a str or Text instance.
|
||||
|
||||
|
||||
Args:
|
||||
text (Union[str, ~Text]): Text to highlight.
|
||||
|
||||
|
||||
Raises:
|
||||
TypeError: If not called with text or str.
|
||||
|
||||
|
||||
Returns:
|
||||
Text: A test instance with highlighting applied.
|
||||
"""
|
||||
|
@ -31,7 +31,7 @@ class Highlighter(ABC):
|
|||
@abstractmethod
|
||||
def highlight(self, text: Text) -> None:
|
||||
"""Apply highlighting in place to text.
|
||||
|
||||
|
||||
Args:
|
||||
text (~Text): A text object highlight.
|
||||
"""
|
||||
|
@ -39,9 +39,9 @@ class Highlighter(ABC):
|
|||
|
||||
class NullHighlighter(Highlighter):
|
||||
"""A highlighter object that doesn't highlight.
|
||||
|
||||
|
||||
May be used to disable highlighting entirely.
|
||||
|
||||
|
||||
"""
|
||||
|
||||
def highlight(self, text: Text) -> None:
|
||||
|
@ -56,10 +56,10 @@ class RegexHighlighter(Highlighter):
|
|||
|
||||
def highlight(self, text: Text) -> None:
|
||||
"""Highlight :class:`rich.text.Text` using regular expressions.
|
||||
|
||||
|
||||
Args:
|
||||
text (~Text): Text to highlighted.
|
||||
|
||||
|
||||
"""
|
||||
highlight_regex = text.highlight_regex
|
||||
for re_highlight in self.highlights:
|
||||
|
|
|
@ -13,10 +13,10 @@ from .text import Text
|
|||
|
||||
class RichHandler(Handler):
|
||||
"""A logging handler that renders output with Rich. The time / level / message and file are displayed in columns.
|
||||
The level is color coded, and the message is syntax highlighted.
|
||||
The level is color coded, and the message is syntax highlighted.
|
||||
|
||||
Note:
|
||||
Be careful when enabling console markup in log messages if you have configured logging for libraries not
|
||||
Be careful when enabling console markup in log messages if you have configured logging for libraries not
|
||||
under your control. If a dependency writes messages containing square brackets, it may not produce the intended output.
|
||||
|
||||
Args:
|
||||
|
@ -29,7 +29,7 @@ class RichHandler(Handler):
|
|||
enable_link_path (bool, optional): Enable terminal link of path column to file. Defaults to True.
|
||||
highlighter (Highlighter, optional): Highlighter to style log messages, or None to use ReprHighlighter. Defaults to None.
|
||||
markup (bool, optional): Enable console markup in log messages. Defaults to False.
|
||||
|
||||
|
||||
"""
|
||||
|
||||
KEYWORDS: ClassVar[Optional[List[str]]] = [
|
||||
|
@ -109,7 +109,10 @@ if __name__ == "__main__": # pragma: no cover
|
|||
FORMAT = "%(message)s"
|
||||
# FORMAT = "%(asctime)-15s - %(level) - %(message)s"
|
||||
logging.basicConfig(
|
||||
level="NOTSET", format=FORMAT, datefmt="[%X]", handlers=[RichHandler()],
|
||||
level="NOTSET",
|
||||
format=FORMAT,
|
||||
datefmt="[%X]",
|
||||
handlers=[RichHandler()],
|
||||
)
|
||||
log = logging.getLogger("rich")
|
||||
|
||||
|
|
|
@ -28,11 +28,11 @@ class MarkdownElement:
|
|||
@classmethod
|
||||
def create(cls, markdown: "Markdown", node: Any) -> "MarkdownElement":
|
||||
"""Factory to create markdown element,
|
||||
|
||||
|
||||
Args:
|
||||
markdown (Markdown): THe parent Markdown object.
|
||||
node (Any): A node from Pygments.
|
||||
|
||||
|
||||
Returns:
|
||||
MarkdownElement: A new markdown element
|
||||
"""
|
||||
|
@ -40,21 +40,21 @@ class MarkdownElement:
|
|||
|
||||
def on_enter(self, context: "MarkdownContext"):
|
||||
"""Called when the node is entered.
|
||||
|
||||
|
||||
Args:
|
||||
context (MarkdownContext): The markdown context.
|
||||
"""
|
||||
|
||||
def on_text(self, context: "MarkdownContext", text: str) -> None:
|
||||
"""Called when text is parsed.
|
||||
|
||||
|
||||
Args:
|
||||
context (MarkdownContext): The markdown context.
|
||||
"""
|
||||
|
||||
def on_leave(self, context: "MarkdownContext") -> None:
|
||||
"""Called when the parser leaves the element.
|
||||
|
||||
|
||||
Args:
|
||||
context (MarkdownContext): [description]
|
||||
"""
|
||||
|
@ -65,11 +65,11 @@ class MarkdownElement:
|
|||
"""Called when a child element is closed.
|
||||
|
||||
This method allows a parent element to take over rendering of its children.
|
||||
|
||||
|
||||
Args:
|
||||
context (MarkdownContext): The markdown context.
|
||||
child (MarkdownElement): The child markdown element.
|
||||
|
||||
|
||||
Returns:
|
||||
bool: Return True to render the element, or False to not render the element.
|
||||
"""
|
||||
|
@ -83,10 +83,10 @@ class MarkdownElement:
|
|||
|
||||
class UnknownElement(MarkdownElement):
|
||||
"""An unknown element.
|
||||
|
||||
|
||||
Hopefully there will be no unknown elements, and we will have a MarkdownElement for
|
||||
everything in the document.
|
||||
|
||||
|
||||
"""
|
||||
|
||||
|
||||
|
@ -151,7 +151,9 @@ class Heading(TextElement):
|
|||
if self.level == 1:
|
||||
# Draw a border around h1s
|
||||
yield Panel(
|
||||
text, box=box.DOUBLE, style="markdown.h1.border",
|
||||
text,
|
||||
box=box.DOUBLE,
|
||||
style="markdown.h1.border",
|
||||
)
|
||||
else:
|
||||
# Styled text for h2 and beyond
|
||||
|
@ -313,11 +315,11 @@ class ImageItem(TextElement):
|
|||
@classmethod
|
||||
def create(cls, markdown: "Markdown", node: Any) -> "MarkdownElement":
|
||||
"""Factory to create markdown element,
|
||||
|
||||
|
||||
Args:
|
||||
markdown (Markdown): THe parent Markdown object.
|
||||
node (Any): A node from Pygments.
|
||||
|
||||
|
||||
Returns:
|
||||
MarkdownElement: A new markdown element
|
||||
"""
|
||||
|
|
|
@ -39,7 +39,7 @@ class Tag(NamedTuple):
|
|||
|
||||
|
||||
def escape(markup: str) -> str:
|
||||
"""Escapes text so that it won't be interpreted as markup.
|
||||
"""Escapes text so that it won't be interpreted as markup.
|
||||
|
||||
Args:
|
||||
markup (str): Content to be inserted in to markup.
|
||||
|
@ -52,10 +52,10 @@ def escape(markup: str) -> str:
|
|||
|
||||
def _parse(markup: str) -> Iterable[Tuple[int, Optional[str], Optional[Tag]]]:
|
||||
"""Parse markup in to an iterable of tuples of (position, text, tag).
|
||||
|
||||
|
||||
Args:
|
||||
markup (str): A string containing console markup
|
||||
|
||||
|
||||
"""
|
||||
position = 0
|
||||
for match in RE_TAGS.finditer(markup):
|
||||
|
@ -82,10 +82,10 @@ def render(markup: str, style: Union[str, Style] = "", emoji: bool = True) -> Te
|
|||
Args:
|
||||
markup (str): A string containing console markup.
|
||||
emoji (bool, optional): Also render emoji code. Defaults to True.
|
||||
|
||||
|
||||
Raises:
|
||||
MarkupError: If there is a syntax error in the markup.
|
||||
|
||||
|
||||
Returns:
|
||||
Text: A test instance.
|
||||
"""
|
||||
|
|
|
@ -33,10 +33,10 @@ class Measurement(NamedTuple):
|
|||
|
||||
def with_maximum(self, width: int) -> "Measurement":
|
||||
"""Get a RenderableWith where the widths are <= width.
|
||||
|
||||
|
||||
Args:
|
||||
width (int): Maximum desired width.
|
||||
|
||||
|
||||
Returns:
|
||||
RenderableWidth: new RenderableWidth object.
|
||||
"""
|
||||
|
@ -52,7 +52,7 @@ class Measurement(NamedTuple):
|
|||
Args:
|
||||
console (~rich.console.Console): Console instance.
|
||||
renderable (RenderableType): An object that may be rendered with Rich.
|
||||
max_width (int, optional): The maximum width available, or None to use console.width.
|
||||
max_width (int, optional): The maximum width available, or None to use console.width.
|
||||
Defaults to None.
|
||||
|
||||
Raises:
|
||||
|
|
|
@ -19,7 +19,7 @@ PaddingDimensions = Union[int, Tuple[int], Tuple[int, int], Tuple[int, int, int,
|
|||
class Padding(JupyterMixin):
|
||||
"""Draw space around content.
|
||||
|
||||
Example:
|
||||
Example:
|
||||
>>> print(Padding("Hello", (2, 4), style="on blue"))
|
||||
|
||||
Args:
|
||||
|
|
|
@ -16,7 +16,7 @@ if TYPE_CHECKING:
|
|||
|
||||
class Panel(JupyterMixin):
|
||||
"""A console renderable that draws a border around its contents.
|
||||
|
||||
|
||||
Example:
|
||||
>>> console.print(Panel("Hello, World!"))
|
||||
|
||||
|
@ -25,7 +25,7 @@ class Panel(JupyterMixin):
|
|||
box (Box, optional): A Box instance that defines the look of the border (see :ref:`appendix_box`.
|
||||
Defaults to box.ROUNDED.
|
||||
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
|
||||
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".
|
||||
|
|
|
@ -43,7 +43,7 @@ def install(
|
|||
"""Install automatic pretty printing in the Python REPL.
|
||||
|
||||
Args:
|
||||
console (Console, optional): Console instance or ``None`` to use global console. Defaults to None.
|
||||
console (Console, optional): Console instance or ``None`` to use global console. Defaults to None.
|
||||
overflow (Optional[OverflowMethod], optional): Overflow method. Defaults to "ignore".
|
||||
crop (Optional[bool], optional): Enable cropping of long lines. Defaults to False.
|
||||
"""
|
||||
|
@ -70,14 +70,14 @@ def install(
|
|||
class Pretty:
|
||||
"""A rich renderable that pretty prints an object.
|
||||
|
||||
Args:
|
||||
_object (Any): An object to pretty print.
|
||||
highlighter (HighlighterType, optional): Highlighter object to apply to result, or None for ReprHighlighter. Defaults to None.
|
||||
indent_size (int, optional): Number of spaces in indent. Defaults to 4.
|
||||
justify (JustifyMethod, optional): Justify method, or None for default. Defaults to None.
|
||||
overflow (OverflowMethod, optional): Overflow method, or None for default. Defaults to None.
|
||||
no_wrap (Optional[bool], optional): Disable word wrapping. Defaults to False.
|
||||
"""
|
||||
Args:
|
||||
_object (Any): An object to pretty print.
|
||||
highlighter (HighlighterType, optional): Highlighter object to apply to result, or None for ReprHighlighter. Defaults to None.
|
||||
indent_size (int, optional): Number of spaces in indent. Defaults to 4.
|
||||
justify (JustifyMethod, optional): Justify method, or None for default. Defaults to None.
|
||||
overflow (OverflowMethod, optional): Overflow method, or None for default. Defaults to None.
|
||||
no_wrap (Optional[bool], optional): Disable word wrapping. Defaults to False.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
|
@ -360,7 +360,14 @@ if __name__ == "__main__": # pragma: no cover
|
|||
list, {"crumble": ["apple", "rhubarb", "butter", "sugar", "flour"]}
|
||||
),
|
||||
"counter": Counter(
|
||||
["apple", "orange", "pear", "kumquat", "kumquat", "durian",]
|
||||
[
|
||||
"apple",
|
||||
"orange",
|
||||
"pear",
|
||||
"kumquat",
|
||||
"kumquat",
|
||||
"durian",
|
||||
]
|
||||
),
|
||||
"atomic": (False, True, None),
|
||||
"Broken": BrokenRepr(),
|
||||
|
|
|
@ -102,7 +102,7 @@ def track(
|
|||
update_period: float = 0.1,
|
||||
) -> Iterable[ProgressType]:
|
||||
"""Track progress by iterating over a sequence.
|
||||
|
||||
|
||||
Args:
|
||||
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".
|
||||
|
@ -113,12 +113,12 @@ def track(
|
|||
refresh_per_second (Optional[int], optional): Number of times per second to refresh the progress information, or None to use default. Defaults to None.
|
||||
style (StyleType, optional): Style for the bar background. Defaults to "bar.back".
|
||||
complete_style (StyleType, optional): Style for the completed bar. Defaults to "bar.complete".
|
||||
finished_style (StyleType, optional): Style for a finished bar. Defaults to "bar.done".
|
||||
pulse_style (StyleType, optional): Style for pulsing bars. Defaults to "bar.pulse".
|
||||
finished_style (StyleType, optional): Style for a finished bar. Defaults to "bar.done".
|
||||
pulse_style (StyleType, optional): Style for pulsing bars. Defaults to "bar.pulse".
|
||||
update_period (float, optional): Minimum time (in seconds) between calls to update(). Defaults to 0.1.
|
||||
Returns:
|
||||
Iterable[ProgressType]: An iterable of the values in the sequence.
|
||||
|
||||
|
||||
"""
|
||||
|
||||
columns: List["ProgressColumn"] = (
|
||||
|
@ -161,10 +161,10 @@ class ProgressColumn(ABC):
|
|||
|
||||
def __call__(self, task: "Task") -> RenderableType:
|
||||
"""Called by the Progress object to return a renderable for the given task.
|
||||
|
||||
|
||||
Args:
|
||||
task (Task): An object containing information regarding the task.
|
||||
|
||||
|
||||
Returns:
|
||||
RenderableType: Anything renderable (including str).
|
||||
"""
|
||||
|
@ -334,7 +334,7 @@ class ProgressSample(NamedTuple):
|
|||
@dataclass
|
||||
class Task:
|
||||
"""Information regarding a progress task.
|
||||
|
||||
|
||||
This object should be considered read-only outside of the :class:`~Progress` class.
|
||||
|
||||
"""
|
||||
|
@ -491,7 +491,7 @@ class _FileProxy(io.TextIOBase):
|
|||
|
||||
class Progress(JupyterMixin, RenderHook):
|
||||
"""Renders an auto-updating progress bar(s).
|
||||
|
||||
|
||||
Args:
|
||||
console (Console, optional): Optional Console instance. Default will an internal Console instance writing to stdout.
|
||||
auto_refresh (bool, optional): Enable auto refresh. If disabled, you will need to call `refresh()`.
|
||||
|
@ -638,14 +638,14 @@ class Progress(JupyterMixin, RenderHook):
|
|||
update_period: float = 0.1,
|
||||
) -> Iterable[ProgressType]:
|
||||
"""Track progress by iterating over a sequence.
|
||||
|
||||
|
||||
Args:
|
||||
sequence (Sequence[ProgressType]): A sequence of values you want to iterate over and track progress.
|
||||
total: (int, optional): Total number of steps. Default is len(sequence).
|
||||
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.
|
||||
|
||||
|
||||
Returns:
|
||||
Iterable[ProgressType]: An iterable of values taken from the provided sequence.
|
||||
"""
|
||||
|
@ -682,7 +682,7 @@ class Progress(JupyterMixin, RenderHook):
|
|||
|
||||
Starts a task (used when calculating elapsed time). You may need to call this manually,
|
||||
if you called ``add_task`` with ``start=False``.
|
||||
|
||||
|
||||
Args:
|
||||
task_id (TaskID): ID of task.
|
||||
"""
|
||||
|
@ -695,7 +695,7 @@ class Progress(JupyterMixin, RenderHook):
|
|||
"""Stop a task.
|
||||
|
||||
This will freeze the elapsed time on the task.
|
||||
|
||||
|
||||
Args:
|
||||
task_id (TaskID): ID of task.
|
||||
"""
|
||||
|
@ -719,9 +719,9 @@ class Progress(JupyterMixin, RenderHook):
|
|||
**fields: Any,
|
||||
) -> None:
|
||||
"""Update information associated with a task.
|
||||
|
||||
|
||||
Args:
|
||||
task_id (TaskID): Task id (returned by add_task).
|
||||
task_id (TaskID): Task id (returned by add_task).
|
||||
total (float, optional): Updates task.total if not None.
|
||||
completed (float, optional): Updates task.completed if not None.
|
||||
advance (float, optional): Add a value to task.completed if not None.
|
||||
|
@ -763,7 +763,7 @@ class Progress(JupyterMixin, RenderHook):
|
|||
|
||||
def advance(self, task_id: TaskID, advance: float = 1) -> None:
|
||||
"""Advance task by a number of steps.
|
||||
|
||||
|
||||
Args:
|
||||
task_id (TaskID): ID of task.
|
||||
advance (float): Number of steps to advance. Default is 1.
|
||||
|
@ -859,7 +859,7 @@ class Progress(JupyterMixin, RenderHook):
|
|||
**fields: Any,
|
||||
) -> TaskID:
|
||||
"""Add a new 'task' to the Progress display.
|
||||
|
||||
|
||||
Args:
|
||||
description (str): A description of the task.
|
||||
start (bool, optional): Start the task immediately (to calculate elapsed time). If set to False,
|
||||
|
@ -868,7 +868,7 @@ class Progress(JupyterMixin, RenderHook):
|
|||
completed (int, optional): Number of steps completed so far.. Defaults to 0.
|
||||
visible (bool, optional): Enable display of the task. Defaults to True.
|
||||
**fields (str): Additional data fields required for rendering.
|
||||
|
||||
|
||||
Returns:
|
||||
TaskID: An ID you can use when calling `update`.
|
||||
"""
|
||||
|
@ -893,10 +893,10 @@ class Progress(JupyterMixin, RenderHook):
|
|||
|
||||
def remove_task(self, task_id: TaskID) -> None:
|
||||
"""Delete a task if it exists.
|
||||
|
||||
|
||||
Args:
|
||||
task_id (TaskID): A task ID.
|
||||
|
||||
|
||||
"""
|
||||
with self._lock:
|
||||
del self._tasks[task_id]
|
||||
|
|
|
@ -29,7 +29,7 @@ class InvalidResponse(PromptError):
|
|||
|
||||
class PromptBase(Generic[PromptType]):
|
||||
"""Ask the user for input until a valid response is received. This is the base class, see one of
|
||||
the concrete classes for examples.
|
||||
the concrete classes for examples.
|
||||
|
||||
Args:
|
||||
prompt (TextType, optional): Prompt text. Defaults to "".
|
||||
|
@ -184,7 +184,11 @@ class PromptBase(Generic[PromptType]):
|
|||
|
||||
@classmethod
|
||||
def get_input(
|
||||
cls, console: Console, prompt: TextType, password: bool, stream: TextIO = None,
|
||||
cls,
|
||||
console: Console,
|
||||
prompt: TextType,
|
||||
password: bool,
|
||||
stream: TextIO = None,
|
||||
) -> str:
|
||||
"""Get input from user.
|
||||
|
||||
|
@ -281,10 +285,10 @@ class PromptBase(Generic[PromptType]):
|
|||
|
||||
class Prompt(PromptBase[str]):
|
||||
"""A prompt that returns a str.
|
||||
|
||||
|
||||
Example:
|
||||
>>> name = Prompt.ask("Enter your name")
|
||||
|
||||
|
||||
|
||||
"""
|
||||
|
||||
|
@ -293,10 +297,10 @@ class Prompt(PromptBase[str]):
|
|||
|
||||
class IntPrompt(PromptBase[int]):
|
||||
"""A prompt that returns an integer.
|
||||
|
||||
|
||||
Example:
|
||||
>>> burrito_count = IntPrompt.ask("How many burritos do you want to order", prompt_suffix="? ")
|
||||
|
||||
|
||||
"""
|
||||
|
||||
response_type = int
|
||||
|
@ -305,10 +309,10 @@ class IntPrompt(PromptBase[int]):
|
|||
|
||||
class FloatPrompt(PromptBase[int]):
|
||||
"""A prompt that returns a float.
|
||||
|
||||
|
||||
Example:
|
||||
>>> temperature = FloatPrompt.ask("Enter desired temperature")
|
||||
|
||||
|
||||
"""
|
||||
|
||||
response_type = float
|
||||
|
@ -317,11 +321,11 @@ class FloatPrompt(PromptBase[int]):
|
|||
|
||||
class Confirm(PromptBase[bool]):
|
||||
"""A yes / no confirmation prompt.
|
||||
|
||||
|
||||
Example:
|
||||
>>> if Confirm.ask("Continue"):
|
||||
run_job()
|
||||
|
||||
|
||||
"""
|
||||
|
||||
response_type = bool
|
||||
|
|
|
@ -9,9 +9,9 @@ from .text import Text
|
|||
|
||||
class Rule(JupyterMixin):
|
||||
"""A console renderable to draw a horizontal rule (line).
|
||||
|
||||
|
||||
Args:
|
||||
title (Union[str, Text], optional): Text to render in the rule. Defaults to "".
|
||||
title (Union[str, Text], optional): Text to render in the rule. Defaults to "".
|
||||
characters (str, optional): Character(s) used to draw the line. Defaults to "─".
|
||||
style (StyleType, optional): Style of Rule. Defaults to "rule.line".
|
||||
end (str, optional): Character at end of Rule. defaults to "\\n"
|
||||
|
|
|
@ -10,7 +10,7 @@ from typing import Iterable, List, Tuple
|
|||
|
||||
class Segment(NamedTuple):
|
||||
"""A piece of text with associated style.
|
||||
|
||||
|
||||
Args:
|
||||
text (str): A piece of text.
|
||||
style (:class:`~rich.style.Style`, optional): An optional style to apply to the text.
|
||||
|
@ -90,7 +90,7 @@ class Segment(NamedTuple):
|
|||
|
||||
Returns:
|
||||
Iterable[Segment]: And iterable of Segment instances.
|
||||
|
||||
|
||||
"""
|
||||
if is_control:
|
||||
return filter(attrgetter("is_control"), segments)
|
||||
|
@ -183,7 +183,7 @@ class Segment(NamedTuple):
|
|||
segments (Iterable[Segment]): A list of segments in a single line.
|
||||
length (int): The desired width of the line.
|
||||
style (Style, optional): The style of padding if used (space on the end). Defaults to None.
|
||||
pad (bool, optional): Pad lines with spaces if they are shorter than `length`. Defaults to True.
|
||||
pad (bool, optional): Pad lines with spaces if they are shorter than `length`. Defaults to True.
|
||||
|
||||
Returns:
|
||||
List[Segment]: A line of segments with the desired length.
|
||||
|
|
|
@ -32,7 +32,7 @@ class Style:
|
|||
A terminal style consists of a color (`color`), a backround color (`bgcolor`), and a number of attributes, such
|
||||
as bold, italic etc. The attributes have 3 states: they can either be on
|
||||
(``True``), off (``False``), or not set (``None``).
|
||||
|
||||
|
||||
Args:
|
||||
color (Union[Color, str], optional): Color of terminal text. Defaults to None.
|
||||
bgcolor (Union[Color, str], optional): Color of terminal background. Defaults to None.
|
||||
|
@ -50,7 +50,7 @@ class Style:
|
|||
encircle (bool, optional): Enable encircled text. Defaults to None.
|
||||
overline (bool, optional): Enable overlined text. Defaults to None.
|
||||
link (str, link): Link URL. Defaults to None.
|
||||
|
||||
|
||||
"""
|
||||
|
||||
_color: Optional[Color]
|
||||
|
@ -267,10 +267,10 @@ class Style:
|
|||
def normalize(cls, style: str) -> str:
|
||||
"""Normalize a style definition so that styles with the same effect have the same string
|
||||
representation.
|
||||
|
||||
|
||||
Args:
|
||||
style (str): A style definition.
|
||||
|
||||
|
||||
Returns:
|
||||
str: Normal form of style definition.
|
||||
"""
|
||||
|
@ -335,10 +335,10 @@ class Style:
|
|||
|
||||
Args:
|
||||
style_definition (str): A string containing a style.
|
||||
|
||||
|
||||
Raises:
|
||||
errors.StyleSyntaxError: If the style definition syntax is invalid.
|
||||
|
||||
errors.StyleSyntaxError: If the style definition syntax is invalid.
|
||||
|
||||
Returns:
|
||||
`Style`: A Style instance.
|
||||
"""
|
||||
|
@ -457,10 +457,10 @@ class Style:
|
|||
@classmethod
|
||||
def combine(cls, styles: Iterable["Style"]) -> "Style":
|
||||
"""Combine styles and get result.
|
||||
|
||||
|
||||
Args:
|
||||
styles (Iterable[Style]): Styles to combine.
|
||||
|
||||
|
||||
Returns:
|
||||
Style: A new style instance.
|
||||
"""
|
||||
|
@ -470,10 +470,10 @@ class Style:
|
|||
@classmethod
|
||||
def chain(cls, *styles: "Style") -> "Style":
|
||||
"""Combine styles from positional argument in to a single style.
|
||||
|
||||
|
||||
Args:
|
||||
*styles (Iterable[Style]): Styles to combine.
|
||||
|
||||
|
||||
Returns:
|
||||
Style: A new style instance.
|
||||
"""
|
||||
|
@ -481,7 +481,7 @@ class Style:
|
|||
|
||||
def copy(self) -> "Style":
|
||||
"""Get a copy of this style.
|
||||
|
||||
|
||||
Returns:
|
||||
Style: A new Style instance with identical attributes.
|
||||
"""
|
||||
|
@ -504,11 +504,11 @@ class Style:
|
|||
legacy_windows: bool = False,
|
||||
) -> str:
|
||||
"""Render the ANSI codes for the style.
|
||||
|
||||
|
||||
Args:
|
||||
text (str, optional): A string to style. Defaults to "".
|
||||
color_system (Optional[ColorSystem], optional): Color system to render to. Defaults to ColorSystem.TRUECOLOR.
|
||||
|
||||
|
||||
Returns:
|
||||
str: A string containing ANSI style codes.
|
||||
"""
|
||||
|
@ -527,10 +527,10 @@ class Style:
|
|||
"""Write text with style directly to terminal.
|
||||
|
||||
This method is for testing purposes only.
|
||||
|
||||
|
||||
Args:
|
||||
text (Optional[str], optional): Text to style or None for style name.
|
||||
|
||||
|
||||
Returns:
|
||||
None:
|
||||
"""
|
||||
|
@ -574,7 +574,7 @@ class StyleStack:
|
|||
|
||||
def push(self, style: Style) -> None:
|
||||
"""Push a new style on to the stack.
|
||||
|
||||
|
||||
Args:
|
||||
style (Style): New style to combine with current style.
|
||||
"""
|
||||
|
@ -582,7 +582,7 @@ class StyleStack:
|
|||
|
||||
def pop(self) -> Style:
|
||||
"""Pop last style and discard.
|
||||
|
||||
|
||||
Returns:
|
||||
Style: New current style (also available as stack.current)
|
||||
"""
|
||||
|
|
|
@ -23,7 +23,7 @@ DEFAULT_THEME = "monokai"
|
|||
|
||||
class Syntax(JupyterMixin):
|
||||
"""Construct a Syntax object to render syntax highlighted code.
|
||||
|
||||
|
||||
Args:
|
||||
code (str): Code to highlight.
|
||||
lexer_name (str): Lexer to use (see https://pygments.org/docs/lexers/)
|
||||
|
@ -93,7 +93,7 @@ class Syntax(JupyterMixin):
|
|||
word_wrap: bool = False,
|
||||
) -> "Syntax":
|
||||
"""Construct a Syntax object from a file.
|
||||
|
||||
|
||||
Args:
|
||||
path (str): Path to file to highlight.
|
||||
encoding (str): Encoding of file.
|
||||
|
@ -298,12 +298,14 @@ class Syntax(JupyterMixin):
|
|||
if highlight_line(line_no):
|
||||
yield _Segment(line_pointer, number_style)
|
||||
yield _Segment(
|
||||
line_column, highlight_number_style,
|
||||
line_column,
|
||||
highlight_number_style,
|
||||
)
|
||||
else:
|
||||
yield _Segment(" ", highlight_number_style)
|
||||
yield _Segment(
|
||||
line_column, number_style,
|
||||
line_column,
|
||||
number_style,
|
||||
)
|
||||
else:
|
||||
yield padding
|
||||
|
|
|
@ -84,7 +84,7 @@ class _Cell(NamedTuple):
|
|||
|
||||
class Table(JupyterMixin):
|
||||
"""A console renderable to draw a table.
|
||||
|
||||
|
||||
Args:
|
||||
*headers (Union[Column, str]): Column headers, either as a string, or :class:`~rich.table.Column` instance.
|
||||
title (Union[str, Text], optional): The title of the table rendered at the top. Defaults to None.
|
||||
|
@ -180,7 +180,7 @@ class Table(JupyterMixin):
|
|||
collapse_padding (bool, optional): Enable collapsing of padding around cells. Defaults to True.
|
||||
pad_edge (bool, optional): Enable padding around edges of table. Defaults to False.
|
||||
expand (bool, optional): Expand the table to fit the available space if ``True``, otherwise the table width will be auto-calculated. Defaults to False.
|
||||
|
||||
|
||||
Returns:
|
||||
Table: A table instance.
|
||||
"""
|
||||
|
@ -277,7 +277,7 @@ class Table(JupyterMixin):
|
|||
no_wrap: bool = False,
|
||||
) -> None:
|
||||
"""Add a column to the table.
|
||||
|
||||
|
||||
Args:
|
||||
header (RenderableType, optional): Text or renderable for the header.
|
||||
Defaults to "".
|
||||
|
@ -315,7 +315,7 @@ class Table(JupyterMixin):
|
|||
self, *renderables: Optional["RenderableType"], style: StyleType = None
|
||||
) -> None:
|
||||
"""Add a row of renderables.
|
||||
|
||||
|
||||
Args:
|
||||
*renderables (None or renderable): Each cell in a row must be a renderable object (including str),
|
||||
or ``None`` for a blank cell.
|
||||
|
|
|
@ -9,11 +9,11 @@ from .table import Table
|
|||
|
||||
def tabulate_mapping(mapping: Mapping, title: str = None) -> Table:
|
||||
"""Generate a simple table from a mapping.
|
||||
|
||||
|
||||
Args:
|
||||
mapping (Mapping): A mapping object (e.g. a dict);
|
||||
title (str, optional): Optional title to be displayed over the table.
|
||||
|
||||
|
||||
Returns:
|
||||
Table: A table instance which may be rendered by the Console.
|
||||
"""
|
||||
|
|
90
rich/text.py
90
rich/text.py
|
@ -76,10 +76,10 @@ class Span(NamedTuple):
|
|||
|
||||
def move(self, offset: int) -> "Span":
|
||||
"""Move start and end by a given offset.
|
||||
|
||||
|
||||
Args:
|
||||
offset (int): Number of characters to add to start and end.
|
||||
|
||||
|
||||
Returns:
|
||||
TextSpan: A new TextSpan with adjusted position.
|
||||
"""
|
||||
|
@ -88,10 +88,10 @@ class Span(NamedTuple):
|
|||
|
||||
def right_crop(self, offset: int) -> "Span":
|
||||
"""Crop the span at the given offset.
|
||||
|
||||
|
||||
Args:
|
||||
offset (int): A value between start and end.
|
||||
|
||||
|
||||
Returns:
|
||||
Span: A new (possibly smaller) span.
|
||||
"""
|
||||
|
@ -103,16 +103,16 @@ class Span(NamedTuple):
|
|||
|
||||
class Text(JupyterMixin):
|
||||
"""Text with color / style.
|
||||
|
||||
Args:
|
||||
text (str, optional): Default unstyled text. Defaults to "".
|
||||
style (Union[str, Style], optional): Base style for text. Defaults to "".
|
||||
justify (str, optional): Justify method: "left", "center", "full", "right". Defaults to None.
|
||||
overflow (str, optional): Overflow method: "crop", "fold", "ellipsis". Defaults to None.
|
||||
no_wrap (bool, optional): Disable text wrapping, or None for default. Defaults to None.
|
||||
end (str, optional): Character to end text with. Defaults to "\\n".
|
||||
tab_size (int): Number of spaces per tab, or ``None`` to use ``console.tab_size``. Defaults to 8.
|
||||
spans (List[Span], optional). A list of predefined style spans. Defaults to None.
|
||||
|
||||
Args:
|
||||
text (str, optional): Default unstyled text. Defaults to "".
|
||||
style (Union[str, Style], optional): Base style for text. Defaults to "".
|
||||
justify (str, optional): Justify method: "left", "center", "full", "right". Defaults to None.
|
||||
overflow (str, optional): Overflow method: "crop", "fold", "ellipsis". Defaults to None.
|
||||
no_wrap (bool, optional): Disable text wrapping, or None for default. Defaults to None.
|
||||
end (str, optional): Character to end text with. Defaults to "\\n".
|
||||
tab_size (int): Number of spaces per tab, or ``None`` to use ``console.tab_size``. Defaults to 8.
|
||||
spans (List[Span], optional). A list of predefined style spans. Defaults to None.
|
||||
"""
|
||||
|
||||
__slots__ = [
|
||||
|
@ -196,13 +196,13 @@ class Text(JupyterMixin):
|
|||
overflow: "OverflowMethod" = None,
|
||||
) -> "Text":
|
||||
"""Create Text instance from markup.
|
||||
|
||||
|
||||
Args:
|
||||
text (str): A string containing console markup.
|
||||
emoji (bool, optional): Also render emoji code. Defaults to True.
|
||||
justify (str, optional): Justify method: "left", "center", "full", "right". Defaults to None.
|
||||
overflow (str, optional): Overflow method: "crop", "fold", "ellipsis". Defaults to None.
|
||||
|
||||
overflow (str, optional): Overflow method: "crop", "fold", "ellipsis". Defaults to None.
|
||||
|
||||
Returns:
|
||||
Text: A Text instance with markup rendered.
|
||||
"""
|
||||
|
@ -229,8 +229,8 @@ class Text(JupyterMixin):
|
|||
text (str): A string containing console markup.
|
||||
style (Union[str, Style]): Style to apply to the text. Defaults to "".
|
||||
justify (str, optional): Justify method: "left", "center", "full", "right". Defaults to None.
|
||||
overflow (str, optional): Overflow method: "crop", "fold", "ellipsis". Defaults to None.
|
||||
|
||||
overflow (str, optional): Overflow method: "crop", "fold", "ellipsis". Defaults to None.
|
||||
|
||||
Returns:
|
||||
Text: A text instance with a style applied to the entire string.
|
||||
"""
|
||||
|
@ -249,12 +249,12 @@ class Text(JupyterMixin):
|
|||
tab_size: int = 8,
|
||||
) -> "Text":
|
||||
"""Construct a text instance by combining a sequence of strings with optional styles.
|
||||
The positional arguments should be either strings, or a tuple of string + style.
|
||||
The positional arguments should be either strings, or a tuple of string + style.
|
||||
|
||||
Args:
|
||||
Args:
|
||||
style (Union[str, Style], optional): Base style for text. Defaults to "".
|
||||
justify (str, optional): Justify method: "left", "center", "full", "right". Defaults to None.
|
||||
overflow (str, optional): Overflow method: "crop", "fold", "ellipsis". Defaults to None.
|
||||
overflow (str, optional): Overflow method: "crop", "fold", "ellipsis". Defaults to None.
|
||||
end (str, optional): Character to end text with. Defaults to "\\n".
|
||||
tab_size (int): Number of spaces per tab, or ``None`` to use ``console.tab_size``. Defaults to 8.
|
||||
|
||||
|
@ -329,9 +329,9 @@ class Text(JupyterMixin):
|
|||
def stylize(
|
||||
self, style: Union[str, Style], start: int = 0, end: Optional[int] = None
|
||||
) -> None:
|
||||
"""Apply a style to the text, or a portion of the text.
|
||||
"""Apply a style to the text, or a portion of the text.
|
||||
|
||||
Args:
|
||||
Args:
|
||||
style (Union[str, Style]): Style instance or style definition to apply.
|
||||
start (int): Start offset (negative indexing is supported). Defaults to 0.
|
||||
end (Optional[int], optional): End offset (negative indexing is supported), or None for end of text. Defaults to None.
|
||||
|
@ -383,7 +383,7 @@ class Text(JupyterMixin):
|
|||
re_highlight (str): A regular expression.
|
||||
style (Union[GetStyleCallable, StyleType]): Optional style to apply to whole match, or a callable
|
||||
which accepts the matched text and returns a style. Defaults to None.
|
||||
style_prefix (str, optional): Optional prefix to add to style group names.
|
||||
style_prefix (str, optional): Optional prefix to add to style group names.
|
||||
|
||||
Returns:
|
||||
int: Number of regex matches
|
||||
|
@ -415,12 +415,12 @@ class Text(JupyterMixin):
|
|||
case_sensitive: bool = True,
|
||||
) -> int:
|
||||
"""Highlight words with a style.
|
||||
|
||||
|
||||
Args:
|
||||
words (Iterable[str]): Worlds to highlight.
|
||||
style (Union[str, Style]): Style to apply.
|
||||
case_sensitive (bool, optional): Enable case sensitive matchings. Defaults to True.
|
||||
|
||||
|
||||
Returns:
|
||||
int: Number of words highlighted.
|
||||
"""
|
||||
|
@ -496,11 +496,11 @@ class Text(JupyterMixin):
|
|||
|
||||
def render(self, console: "Console", end: str = "") -> Iterable["Segment"]:
|
||||
"""Render the text as Segments.
|
||||
|
||||
|
||||
Args:
|
||||
console (Console): Console instance.
|
||||
end (Optional[str], optional): Optional end character.
|
||||
|
||||
console (Console): Console instance.
|
||||
end (Optional[str], optional): Optional end character.
|
||||
|
||||
Returns:
|
||||
Iterable[Segment]: Result of render that may be written to the console.
|
||||
"""
|
||||
|
@ -556,10 +556,10 @@ class Text(JupyterMixin):
|
|||
|
||||
def join(self, lines: Iterable["Text"]) -> "Text":
|
||||
"""Join text together with this instance as the separator.
|
||||
|
||||
|
||||
Args:
|
||||
lines (Iterable[Text]): An iterable of Text instances to join.
|
||||
|
||||
|
||||
Returns:
|
||||
Text: A new text instance containing join text.
|
||||
"""
|
||||
|
@ -595,7 +595,7 @@ class Text(JupyterMixin):
|
|||
|
||||
def tabs_to_spaces(self, tab_size: int = None) -> "Text":
|
||||
"""Get a new string with tabs converted to spaces.
|
||||
|
||||
|
||||
Args:
|
||||
tab_size (int, optional): Size of tabs. Defaults to 8.
|
||||
|
||||
|
@ -688,7 +688,7 @@ class Text(JupyterMixin):
|
|||
|
||||
def pad_left(self, count: int, character: str = " ") -> None:
|
||||
"""Pad the left with a given character.
|
||||
|
||||
|
||||
Args:
|
||||
count (int): Number of characters to pad.
|
||||
character (str, optional): Character to pad with. Defaults to " ".
|
||||
|
@ -704,7 +704,7 @@ class Text(JupyterMixin):
|
|||
|
||||
def pad_right(self, count: int, character: str = " ") -> None:
|
||||
"""Pad the right with a given character.
|
||||
|
||||
|
||||
Args:
|
||||
count (int): Number of characters to pad.
|
||||
character (str, optional): Character to pad with. Defaults to " ".
|
||||
|
@ -737,11 +737,11 @@ class Text(JupyterMixin):
|
|||
self, text: Union["Text", str], style: Union[str, "Style"] = None
|
||||
) -> "Text":
|
||||
"""Add text with an optional style.
|
||||
|
||||
|
||||
Args:
|
||||
text (Union[Text, str]): A str or Text to append.
|
||||
style (str, optional): A style name. Defaults to None.
|
||||
|
||||
|
||||
Returns:
|
||||
Text: Returns self for chaining.
|
||||
"""
|
||||
|
@ -813,12 +813,12 @@ class Text(JupyterMixin):
|
|||
allow_blank: bool = False,
|
||||
) -> Lines:
|
||||
"""Split rich text in to lines, preserving styles.
|
||||
|
||||
|
||||
Args:
|
||||
separator (str, optional): String to split on. Defaults to "\\n".
|
||||
include_separator (bool, optional): Include the separator in the lines. Defaults to False.
|
||||
allow_blank (bool, optional): Return a blank line if the text ends with a separator. Defaults to False.
|
||||
|
||||
|
||||
Returns:
|
||||
List[RichText]: A list of rich text, one per line of the original.
|
||||
"""
|
||||
|
@ -851,7 +851,7 @@ class Text(JupyterMixin):
|
|||
|
||||
Args:
|
||||
offsets (Iterable[int]): Offsets used to divide text.
|
||||
|
||||
|
||||
Returns:
|
||||
Lines: New RichText instances between offsets.
|
||||
"""
|
||||
|
@ -923,7 +923,7 @@ class Text(JupyterMixin):
|
|||
no_wrap: bool = None,
|
||||
) -> Lines:
|
||||
"""Word wrap the text.
|
||||
|
||||
|
||||
Args:
|
||||
console (Console): Console instance.
|
||||
width (int): Number of characters per line.
|
||||
|
@ -932,7 +932,7 @@ class Text(JupyterMixin):
|
|||
overflow (str, optional): Overflow method: "crop", "fold", or "ellipsis". Defaults to None.
|
||||
tab_size (int, optional): Default tab size. Defaults to 8.
|
||||
no_wrap (bool, optional): Disable wrapping, Defaults to False.
|
||||
|
||||
|
||||
Returns:
|
||||
Lines: Number of lines.
|
||||
"""
|
||||
|
@ -964,10 +964,10 @@ class Text(JupyterMixin):
|
|||
|
||||
def fit(self, width: int) -> Lines:
|
||||
"""Fit the text in to given width by chopping in to lines.
|
||||
|
||||
|
||||
Args:
|
||||
width (int): Maximum characters in a line.
|
||||
|
||||
|
||||
Returns:
|
||||
Lines: List of lines.
|
||||
"""
|
||||
|
|
|
@ -7,7 +7,7 @@ from .style import Style, StyleType
|
|||
|
||||
class Theme:
|
||||
"""A container for style information, used by :class:`~rich.console.Console`.
|
||||
|
||||
|
||||
Args:
|
||||
styles (Dict[str, Style], optional): A mapping of style names on to styles. Defaults to None for empty styles.
|
||||
inherit (bool, optional): Inherit default styles. Defaults to True.
|
||||
|
@ -40,8 +40,8 @@ class Theme:
|
|||
Args:
|
||||
config_file (IO[str]): An open conf file.
|
||||
source (str, optional): The filename of the open file. Defaults to None.
|
||||
inherit (bool, optional): Inherit default styles. Defaults to True.
|
||||
|
||||
inherit (bool, optional): Inherit default styles. Defaults to True.
|
||||
|
||||
Returns:
|
||||
Theme: A New theme instance.
|
||||
"""
|
||||
|
@ -56,9 +56,9 @@ class Theme:
|
|||
"""Read a theme from a path.
|
||||
|
||||
Args:
|
||||
path (str): Path to a config file readable by Python configparser module.
|
||||
inherit (bool, optional): Inherit default styles. Defaults to True.
|
||||
|
||||
path (str): Path to a config file readable by Python configparser module.
|
||||
inherit (bool, optional): Inherit default styles. Defaults to True.
|
||||
|
||||
Returns:
|
||||
Theme: A new theme instance.
|
||||
"""
|
||||
|
|
|
@ -37,15 +37,15 @@ def install(
|
|||
"""Install a rich traceback handler.
|
||||
|
||||
Once installed, any tracebacks will be printed with syntax highlighting and rich formatting.
|
||||
|
||||
|
||||
|
||||
|
||||
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.
|
||||
line_numbers (bool, optional): Enable line numbers.
|
||||
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.
|
||||
a theme appropriate for the platform.
|
||||
word_wrap(bool, optional): Enable word wrapping of long lines. Defaults to False.
|
||||
|
||||
Returns:
|
||||
|
@ -55,7 +55,9 @@ def install(
|
|||
traceback_console = Console(file=sys.stderr) if console is None else console
|
||||
|
||||
def excepthook(
|
||||
type_: Type[BaseException], value: BaseException, traceback: TracebackType,
|
||||
type_: Type[BaseException],
|
||||
value: BaseException,
|
||||
traceback: TracebackType,
|
||||
) -> None:
|
||||
traceback_console.print(
|
||||
Traceback.from_exception(
|
||||
|
@ -110,7 +112,7 @@ class PathHighlighter(RegexHighlighter):
|
|||
|
||||
class Traceback:
|
||||
"""A Console renderable that renders a traceback.
|
||||
|
||||
|
||||
Args:
|
||||
trace (Trace, optional): A `Trace` object produced from `extract`. Defaults to None, which uses
|
||||
the last exception.
|
||||
|
@ -169,12 +171,12 @@ class Traceback:
|
|||
traceback: TracebackType,
|
||||
) -> Trace:
|
||||
"""Extrace traceback information.
|
||||
|
||||
|
||||
Args:
|
||||
exc_type (Type[BaseException]): Exception type.
|
||||
exc_value (BaseException): Exception value.
|
||||
traceback (TracebackType): Python Traceback object.
|
||||
|
||||
|
||||
Returns:
|
||||
Trace: A Trace instance which you can use to construct a `Traceback`.
|
||||
"""
|
||||
|
|
|
@ -10,7 +10,7 @@ re_link_ids = re.compile(r"id=[\d\.\-]*?;.*?\x1b")
|
|||
def replace_link_ids(render: str) -> str:
|
||||
"""Link IDs have a random ID and system path which is a problem for
|
||||
reproducible tests.
|
||||
|
||||
|
||||
"""
|
||||
return re_link_ids.sub("id=0;foo\x1b", render)
|
||||
|
||||
|
|
|
@ -12,7 +12,7 @@ re_link_ids = re.compile(r"id=[\d\.\-]*?;.*?\x1b")
|
|||
def replace_link_ids(render: str) -> str:
|
||||
"""Link IDs have a random ID and system path which is a problem for
|
||||
reproducible tests.
|
||||
|
||||
|
||||
"""
|
||||
return re_link_ids.sub("id=0;foo\x1b", render)
|
||||
|
||||
|
|
|
@ -76,7 +76,7 @@ re_link_ids = re.compile(r"id=[\d\.\-]*?;.*?\x1b")
|
|||
def replace_link_ids(render: str) -> str:
|
||||
"""Link IDs have a random ID and system path which is a problem for
|
||||
reproducible tests.
|
||||
|
||||
|
||||
"""
|
||||
return re_link_ids.sub("id=0;foo\x1b", render)
|
||||
|
||||
|
|
|
@ -76,7 +76,7 @@ re_link_ids = re.compile(r"id=[\d\.\-]*?;.*?\x1b")
|
|||
def replace_link_ids(render: str) -> str:
|
||||
"""Link IDs have a random ID and system path which is a problem for
|
||||
reproducible tests.
|
||||
|
||||
|
||||
"""
|
||||
return re_link_ids.sub("id=0;foo\x1b", render)
|
||||
|
||||
|
|
|
@ -25,7 +25,10 @@ def test_prompt_str_default():
|
|||
INPUT = ""
|
||||
console = Console(file=io.StringIO())
|
||||
name = Prompt.ask(
|
||||
"what is your name", console=console, default="Will", stream=io.StringIO(INPUT),
|
||||
"what is your name",
|
||||
console=console,
|
||||
default="Will",
|
||||
stream=io.StringIO(INPUT),
|
||||
)
|
||||
assert name == "Will"
|
||||
expected = "what is your name (Will): "
|
||||
|
@ -38,7 +41,9 @@ def test_prompt_int():
|
|||
INPUT = "foo\n100"
|
||||
console = Console(file=io.StringIO())
|
||||
number = IntPrompt.ask(
|
||||
"Enter a number", console=console, stream=io.StringIO(INPUT),
|
||||
"Enter a number",
|
||||
console=console,
|
||||
stream=io.StringIO(INPUT),
|
||||
)
|
||||
assert number == 100
|
||||
expected = "Enter a number: Please enter a valid integer number\nEnter a number: "
|
||||
|
@ -50,7 +55,11 @@ def test_prompt_int():
|
|||
def test_prompt_confirm_no():
|
||||
INPUT = "foo\nNO\nn"
|
||||
console = Console(file=io.StringIO())
|
||||
answer = Confirm.ask("continue", console=console, stream=io.StringIO(INPUT),)
|
||||
answer = Confirm.ask(
|
||||
"continue",
|
||||
console=console,
|
||||
stream=io.StringIO(INPUT),
|
||||
)
|
||||
assert answer is False
|
||||
expected = "continue [y/n]: Please enter Y or N\ncontinue [y/n]: Please enter Y or N\ncontinue [y/n]: "
|
||||
output = console.file.getvalue()
|
||||
|
@ -61,7 +70,11 @@ def test_prompt_confirm_no():
|
|||
def test_prompt_confirm_yes():
|
||||
INPUT = "foo\nNO\ny"
|
||||
console = Console(file=io.StringIO())
|
||||
answer = Confirm.ask("continue", console=console, stream=io.StringIO(INPUT),)
|
||||
answer = Confirm.ask(
|
||||
"continue",
|
||||
console=console,
|
||||
stream=io.StringIO(INPUT),
|
||||
)
|
||||
assert answer is True
|
||||
expected = "continue [y/n]: Please enter Y or N\ncontinue [y/n]: Please enter Y or N\ncontinue [y/n]: "
|
||||
output = console.file.getvalue()
|
||||
|
|
|
@ -467,7 +467,11 @@ def test_print(print_text, result):
|
|||
|
||||
@pytest.mark.parametrize(
|
||||
"print_text,result",
|
||||
[(("."), ".X"), ((".", "."), "..X"), (("Hello", "World", "!"), "HelloWorld!X"),],
|
||||
[
|
||||
(("."), ".X"),
|
||||
((".", "."), "..X"),
|
||||
(("Hello", "World", "!"), "HelloWorld!X"),
|
||||
],
|
||||
)
|
||||
def test_print_sep_end(print_text, result):
|
||||
console = Console(record=True, file=StringIO())
|
||||
|
@ -556,7 +560,11 @@ def test_truncate_ellipsis(input, count, expected):
|
|||
|
||||
@pytest.mark.parametrize(
|
||||
"input, count, expected",
|
||||
[("Hello", 5, "Hello"), ("Hello", 10, "Hello "), ("Hello", 3, "He…"),],
|
||||
[
|
||||
("Hello", 5, "Hello"),
|
||||
("Hello", 10, "Hello "),
|
||||
("Hello", 3, "He…"),
|
||||
],
|
||||
)
|
||||
def test_truncate_ellipsis_pad(input, count, expected):
|
||||
text = Text(input)
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue