diff options
-rw-r--r-- | .github/CONTRIBUTING.md | 1 | ||||
-rw-r--r-- | CHANGELOG.md | 8 | ||||
-rw-r--r-- | Pipfile | 2 | ||||
-rwxr-xr-x | README.md | 2 | ||||
-rw-r--r-- | cmd2/__init__.py | 28 | ||||
-rw-r--r-- | cmd2/ansi.py | 1154 | ||||
-rw-r--r-- | cmd2/clipboard.py | 2 | ||||
-rw-r--r-- | cmd2/cmd2.py | 35 | ||||
-rw-r--r-- | cmd2/table_creator.py | 8 | ||||
-rw-r--r-- | cmd2/utils.py | 30 | ||||
-rw-r--r-- | docs/features/builtin_commands.rst | 2 | ||||
-rw-r--r-- | docs/features/generating_output.rst | 19 | ||||
-rw-r--r-- | docs/features/initialization.rst | 31 | ||||
-rw-r--r-- | examples/argparse_completion.py | 2 | ||||
-rwxr-xr-x | examples/async_printing.py | 14 | ||||
-rwxr-xr-x | examples/basic.py | 6 | ||||
-rwxr-xr-x | examples/colors.py | 46 | ||||
-rwxr-xr-x | examples/initialization.py | 14 | ||||
-rwxr-xr-x | examples/pirate.py | 10 | ||||
-rwxr-xr-x | examples/plumbum_colors.py | 123 | ||||
-rwxr-xr-x | examples/table_creation.py | 9 | ||||
-rwxr-xr-x | setup.py | 1 | ||||
-rw-r--r-- | tests/conftest.py | 2 | ||||
-rw-r--r-- | tests/test_ansi.py | 231 | ||||
-rwxr-xr-x | tests/test_cmd2.py | 89 | ||||
-rwxr-xr-x | tests/test_completion.py | 28 | ||||
-rw-r--r-- | tests/test_table_creator.py | 25 | ||||
-rw-r--r-- | tests/test_utils.py | 43 | ||||
-rw-r--r-- | tests/transcripts/regex_set.txt | 2 |
29 files changed, 1367 insertions, 600 deletions
diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index 56c53450..8e3596bc 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -49,7 +49,6 @@ The tables below list all prerequisites along with the minimum required version | --------------------------------------------------- | --------------- | | [python](https://www.python.org/downloads/) | `3.6` | | [attrs](https://github.com/python-attrs/attrs) | `16.3` | -| [colorama](https://github.com/tartley/colorama) | `0.3.7` | | [pyperclip](https://github.com/asweigart/pyperclip) | `1.6` | | [setuptools](https://pypi.org/project/setuptools/) | `34.4` | | [wcwidth](https://pypi.python.org/pypi/wcwidth) | `0.1.7` | diff --git a/CHANGELOG.md b/CHANGELOG.md index f57e2d2b..b87e9bc8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,12 +1,20 @@ ## 2.3.0 (TBD, 2021) * Bug Fixes * Fixed `AttributeError` in `rl_get_prompt()` when prompt is `None`. + * Fixed bug where using choices on a Settable didn't verify that a valid choice had been entered. * Enhancements * Added settings to Column class which prevent a table from overriding existing styles in header and/or data text. These were added to support nesting an AlternatingTable within an AlternatingTable, but other custom table classes can also use these settings. * AlternatingTable no longer applies background color to outer borders. This was done to improve appearance since the background color extended beyond the borders of the table. + * Added support for 8-bit/256-colors with the `cmd2.EightBitFg` and `cmd2.EightBitBg` classes. + * Added support for 24-bit/RGB colors with the `cmd2.RgbFg` and `cmd2.RgbBg` classes. + * Removed dependency on colorama. + * Changed type of `ansi.allow_style` from a string to an `ansi.AllowStyle` Enum class. +* Deprecations + * Deprecated `cmd2.fg`. Use `cmd2.StdFg` instead. + * Deprecated `cmd2.bg`. Use `cmd2.StdBg` instead. ## 2.2.0 (September 14, 2021) * Bug Fixes @@ -5,7 +5,6 @@ verify_ssl = true [packages] attrs = ">=16.3.0" -colorama = ">=0.3.7" pyperclip = ">=1.6" setuptools = ">=34.4" wcwidth = ">=0.1.7" @@ -23,7 +22,6 @@ ipython = "*" isort = "*" mock = {version = "*",markers = "python_version < '3.6'"} mypy = "*" -plumbum = "*" pyreadline = {version = "*",sys_platform = "== 'win32'",markers = "python_version < '3.8'"} pyreadline3 = {version = "*",sys_platform = "== 'win32'",markers = "python_version >= '3.8'"} pytest = "*" @@ -95,7 +95,7 @@ Instructions for implementing each feature follow. class MyApp(cmd2.Cmd): def do_foo(self, args): """This docstring is the built-in help for the foo command.""" - self.poutput(cmd2.style('foo bar baz', fg=cmd2.fg.red)) + self.poutput(cmd2.style('foo bar baz', fg=cmd2.StdFg.RED)) ``` - By default the docstring for your **do_foo** method is the help for the **foo** command - NOTE: This doesn't apply if you use one of the `argparse` decorators mentioned below diff --git a/cmd2/__init__.py b/cmd2/__init__.py index 16158900..aab68653 100644 --- a/cmd2/__init__.py +++ b/cmd2/__init__.py @@ -19,7 +19,19 @@ except importlib_metadata.PackageNotFoundError: # pragma: no cover from typing import List -from .ansi import style, fg, bg +from .ansi import ( + Cursor, + EightBitBg, + EightBitFg, + RgbBg, + RgbFg, + StdBg, + StdFg, + TextStyle, + bg, # DEPRECATED: Use StdBg + fg, # DEPRECATED: Use StdFg + style, +) from .argparse_custom import ( Cmd2ArgumentParser, Cmd2AttributeWrapper, @@ -54,9 +66,17 @@ from .utils import categorize, CompletionMode, CustomCompletionSettings, Settabl __all__: List[str] = [ 'COMMAND_NAME', 'DEFAULT_SHORTCUTS', - # ANSI Style exports - 'bg', - 'fg', + # ANSI Exports + 'Cursor', + 'EightBitBg', + 'EightBitFg', + 'RgbBg', + 'RgbFg', + 'StdBg', + 'StdFg', + 'TextStyle', + 'bg', # DEPRECATED: Use StdBg + 'fg', # DEPRECATED: Use StdFg 'style', # Argparse Exports 'Cmd2ArgumentParser', diff --git a/cmd2/ansi.py b/cmd2/ansi.py index 32b50697..b7f01f2f 100644 --- a/cmd2/ansi.py +++ b/cmd2/ansi.py @@ -12,165 +12,56 @@ from typing import ( IO, Any, List, - Union, + Optional, cast, ) -import colorama # type: ignore [import] -from colorama import ( - Back, - Fore, - Style, -) -from wcwidth import ( # type: ignore [import] +from wcwidth import ( # type: ignore[import] wcswidth, ) -# On Windows, filter ANSI escape codes out of text sent to stdout/stderr, and replace them with equivalent Win32 calls -colorama.init(strip=False) +####################################################### +# Common ANSI escape sequence constants +####################################################### +CSI = '\033[' +OSC = '\033]' +BEL = '\a' -# Values for allow_style setting -STYLE_NEVER = 'Never' -""" -Constant for ``cmd2.ansi.allow_style`` to indicate ANSI style sequences should -be removed from all output. -""" -STYLE_TERMINAL = 'Terminal' -""" -Constant for ``cmd2.ansi.allow_style`` to indicate ANSI style sequences -should be removed if the output is not going to the terminal. -""" -STYLE_ALWAYS = 'Always' -""" -Constant for ``cmd2.ansi.allow_style`` to indicate ANSI style sequences should -always be output. -""" -# Controls when ANSI style sequences are allowed in output -allow_style = STYLE_TERMINAL -"""When using outside of a cmd2 app, set this variable to one of: +class AllowStyle(Enum): + """Values for ``cmd2.ansi.allow_style``""" -- ``STYLE_NEVER`` - remove ANSI style sequences from all output -- ``STYLE_TERMINAL`` - remove ANSI style sequences if the output is not going to the terminal -- ``STYLE_ALWAYS`` - always output ANSI style sequences + ALWAYS = 'Always' # Always output ANSI style sequences + NEVER = 'Never' # Remove ANSI style sequences from all output + TERMINAL = 'Terminal' # Remove ANSI style sequences if the output is not going to the terminal -to control the output of ANSI style sequences by methods in this module. - -The default is ``STYLE_TERMINAL``. -""" - -# Regular expression to match ANSI style sequences (including 8-bit and 24-bit colors) -ANSI_STYLE_RE = re.compile(r'\x1b\[[^m]*m') - - -class ColorBase(Enum): - """ - Base class used for defining color enums. See fg and bg classes for examples. - - Child classes should define enums in the follow structure: + def __str__(self) -> str: + """Return value instead of enum name for printing in cmd2's set command""" + return str(self.value) - key: color name (e.g. black) + def __repr__(self) -> str: + """Return quoted value instead of enum description for printing in cmd2's set command""" + return repr(self.value) - value: anything that when cast to a string returns an ANSI sequence - """ - def __str__(self) -> str: - """ - Return ANSI color sequence instead of enum name - This is helpful when using a ColorBase in an f-string or format() call - e.g. my_str = f"{fg.blue}hello{fg.reset}" - """ - return str(self.value) +# Controls when ANSI style sequences are allowed in output +allow_style = AllowStyle.TERMINAL +"""When using outside of a cmd2 app, set this variable to one of: - def __add__(self, other: Any) -> str: - """ - Support building a color string when self is the left operand - e.g. fg.blue + "hello" - """ - return cast(str, str(self) + other) +- ``AllowStyle.ALWAYS`` - always output ANSI style sequences +- ``AllowStyle.NEVER`` - remove ANSI style sequences from all output +- ``AllowStyle.TERMINAL`` - remove ANSI style sequences if the output is not going to the terminal - def __radd__(self, other: Any) -> str: - """ - Support building a color string when self is the right operand - e.g. "hello" + fg.reset - """ - return cast(str, other + str(self)) +to control how ANSI style sequences are handled by ``style_aware_write()``. - @classmethod - def colors(cls) -> List[str]: - """Return a list of color names.""" - # Use __members__ to ensure we get all key names, including those which are aliased - return [color for color in cls.__members__] +``style_aware_write()`` is called by cmd2 methods like ``poutput()``, ``perror()``, +``pwarning()``, etc. +The default is ``AllowStyle.TERMINAL``. +""" -# Foreground colors -# noinspection PyPep8Naming -class fg(ColorBase): - """Enum class for foreground colors""" - - black = Fore.BLACK - red = Fore.RED - green = Fore.GREEN - yellow = Fore.YELLOW - blue = Fore.BLUE - magenta = Fore.MAGENTA - cyan = Fore.CYAN - white = Fore.WHITE - bright_black = Fore.LIGHTBLACK_EX - bright_red = Fore.LIGHTRED_EX - bright_green = Fore.LIGHTGREEN_EX - bright_yellow = Fore.LIGHTYELLOW_EX - bright_blue = Fore.LIGHTBLUE_EX - bright_magenta = Fore.LIGHTMAGENTA_EX - bright_cyan = Fore.LIGHTCYAN_EX - bright_white = Fore.LIGHTWHITE_EX - reset = Fore.RESET - - -# Background colors -# noinspection PyPep8Naming -class bg(ColorBase): - """Enum class for background colors""" - - black = Back.BLACK - red = Back.RED - green = Back.GREEN - yellow = Back.YELLOW - blue = Back.BLUE - magenta = Back.MAGENTA - cyan = Back.CYAN - white = Back.WHITE - bright_black = Back.LIGHTBLACK_EX - bright_red = Back.LIGHTRED_EX - bright_green = Back.LIGHTGREEN_EX - bright_yellow = Back.LIGHTYELLOW_EX - bright_blue = Back.LIGHTBLUE_EX - bright_magenta = Back.LIGHTMAGENTA_EX - bright_cyan = Back.LIGHTCYAN_EX - bright_white = Back.LIGHTWHITE_EX - reset = Back.RESET - - -FG_RESET = fg.reset.value -"""ANSI sequence to reset the foreground attributes""" -BG_RESET = bg.reset.value -"""ANSI sequence to reset the terminal background attributes""" -RESET_ALL = Style.RESET_ALL -"""ANSI sequence to reset all terminal attributes""" - -# Text intensities -INTENSITY_BRIGHT = Style.BRIGHT -"""ANSI sequence to make the text bright""" -INTENSITY_DIM = Style.DIM -"""ANSI sequence to make the text dim""" -INTENSITY_NORMAL = Style.NORMAL -"""ANSI sequence to make the text normal""" - -# ANSI style sequences not provided by colorama -UNDERLINE_ENABLE = colorama.ansi.code_to_chars(4) -"""ANSI sequence to turn on underline""" -UNDERLINE_DISABLE = colorama.ansi.code_to_chars(24) -"""ANSI sequence to turn off underline""" +# Regular expression to match ANSI style sequences (including 8-bit and 24-bit colors) +ANSI_STYLE_RE = re.compile(r'\x1b\[[^m]*m') def strip_style(text: str) -> str: @@ -225,56 +116,843 @@ def style_aware_write(fileobj: IO[str], msg: str) -> None: :param fileobj: the file object being written to :param msg: the string being written """ - if allow_style.lower() == STYLE_NEVER.lower() or (allow_style.lower() == STYLE_TERMINAL.lower() and not fileobj.isatty()): + if allow_style == AllowStyle.NEVER or (allow_style == AllowStyle.TERMINAL and not fileobj.isatty()): msg = strip_style(msg) fileobj.write(msg) -def fg_lookup(fg_name: Union[str, fg]) -> str: +#################################################################################### +# Utility functions which create various ANSI sequences +#################################################################################### +def set_title(title: str) -> str: """ - Look up ANSI escape codes based on foreground color name. + Generate a string that, when printed, sets a terminal's window title. - :param fg_name: foreground color name or enum to look up ANSI escape code(s) for - :return: ANSI escape code(s) associated with this color - :raises: ValueError: if the color cannot be found + :param title: new title for the window + :return: the set title string """ - if isinstance(fg_name, fg): - return str(fg_name.value) + return f"{OSC}2;{title}{BEL}" - try: - ansi_escape = fg[fg_name.lower()].value - except KeyError: - raise ValueError(f"Foreground color '{fg_name}' does not exist; must be one of: {fg.colors()}") - return str(ansi_escape) + +def clear_screen(clear_type: int = 2) -> str: + """ + Generate a string that, when printed, clears a terminal screen based on value of clear_type. + + :param clear_type: integer which specifies how to clear the screen (Defaults to 2) + Possible values: + 0 - clear from cursor to end of screen + 1 - clear from cursor to beginning of the screen + 2 - clear entire screen + 3 - clear entire screen and delete all lines saved in the scrollback buffer + :return: the clear screen string + :raises: ValueError if clear_type is not a valid value + """ + if 0 <= clear_type <= 3: + return f"{CSI}{clear_type}J" + raise ValueError("clear_type must in an integer from 0 to 3") -def bg_lookup(bg_name: Union[str, bg]) -> str: +def clear_line(clear_type: int = 2) -> str: + """ + Generate a string that, when printed, clears a line based on value of clear_type. + + :param clear_type: integer which specifies how to clear the line (Defaults to 2) + Possible values: + 0 - clear from cursor to the end of the line + 1 - clear from cursor to beginning of the line + 2 - clear entire line + :return: the clear line string + :raises: ValueError if clear_type is not a valid value """ - Look up ANSI escape codes based on background color name. + if 0 <= clear_type <= 2: + return f"{CSI}{clear_type}K" + raise ValueError("clear_type must in an integer from 0 to 2") - :param bg_name: background color name or enum to look up ANSI escape code(s) for - :return: ANSI escape code(s) associated with this color - :raises: ValueError: if the color cannot be found + +#################################################################################### +# Base classes which are not intended to be used directly +#################################################################################### +class AnsiSequence: + """Base class to create ANSI sequence strings""" + + def __add__(self, other: Any) -> str: + """ + Support building an ANSI sequence string when self is the left operand + e.g. StdFg.LIGHT_MAGENTA + "hello" + """ + return str(self) + str(other) + + def __radd__(self, other: Any) -> str: + """ + Support building an ANSI sequence string when self is the right operand + e.g. "hello" + StdFg.RESET + """ + return str(other) + str(self) + + +class FgColor(AnsiSequence): + """Base class for ANSI Sequences which set foreground text color""" + + pass + + +class BgColor(AnsiSequence): + """Base class for ANSI Sequences which set background text color""" + + pass + + +#################################################################################### +# Implementations intended for direct use +#################################################################################### +# noinspection PyPep8Naming +class Cursor: + """Create ANSI sequences to alter the cursor position""" + + @staticmethod + def UP(count: int = 1) -> str: + """Move the cursor up a specified amount of lines (Defaults to 1)""" + return f"{CSI}{count}A" + + @staticmethod + def DOWN(count: int = 1) -> str: + """Move the cursor down a specified amount of lines (Defaults to 1)""" + return f"{CSI}{count}B" + + @staticmethod + def FORWARD(count: int = 1) -> str: + """Move the cursor forward a specified amount of lines (Defaults to 1)""" + return f"{CSI}{count}C" + + @staticmethod + def BACK(count: int = 1) -> str: + """Move the cursor back a specified amount of lines (Defaults to 1)""" + return f"{CSI}{count}D" + + @staticmethod + def SET_POS(x: int, y: int) -> str: + """Set the cursor position to coordinates which are 1-based""" + return f"{CSI}{y};{x}H" + + +class TextStyle(AnsiSequence, Enum): + """Create text style ANSI sequences""" + + # Resets all styles and colors of text + RESET_ALL = 0 + + INTENSITY_BOLD = 1 + INTENSITY_DIM = 2 + INTENSITY_NORMAL = 22 + + ITALIC_ENABLE = 3 + ITALIC_DISABLE = 23 + + OVERLINE_ENABLE = 53 + OVERLINE_DISABLE = 55 + + STRIKETHROUGH_ENABLE = 9 + STRIKETHROUGH_DISABLE = 29 + + UNDERLINE_ENABLE = 4 + UNDERLINE_DISABLE = 24 + + def __str__(self) -> str: + """ + Return ANSI text style sequence instead of enum name + This is helpful when using a TextStyle in an f-string or format() call + e.g. my_str = f"{TextStyle.UNDERLINE_ENABLE}hello{TextStyle.UNDERLINE_DISABLE}" + """ + return f"{CSI}{self.value}m" + + +class StdFg(FgColor, Enum): + """ + Create ANSI sequences for the 16 standard terminal foreground text colors. + A terminal's color settings affect how these colors appear. + To reset any foreground color, use StdFg.RESET. """ - if isinstance(bg_name, bg): - return str(bg_name.value) - try: - ansi_escape = bg[bg_name.lower()].value - except KeyError: - raise ValueError(f"Background color '{bg_name}' does not exist; must be one of: {bg.colors()}") - return str(ansi_escape) + BLACK = 30 + RED = 31 + GREEN = 32 + YELLOW = 33 + BLUE = 34 + MAGENTA = 35 + CYAN = 36 + LIGHT_GRAY = 37 + DARK_GRAY = 90 + LIGHT_RED = 91 + LIGHT_GREEN = 92 + LIGHT_YELLOW = 93 + LIGHT_BLUE = 94 + LIGHT_MAGENTA = 95 + LIGHT_CYAN = 96 + WHITE = 97 + + RESET = 39 + def __str__(self) -> str: + """ + Return ANSI color sequence instead of enum name + This is helpful when using a StdFg in an f-string or format() call + e.g. my_str = f"{StdFg.BLUE}hello{StdFg.RESET}" + """ + return f"{CSI}{self.value}m" + + +class StdBg(BgColor, Enum): + """ + Create ANSI sequences for the 16 standard terminal background text colors. + A terminal's color settings affect how these colors appear. + To reset any background color, use StdBg.RESET. + """ + + BLACK = 40 + RED = 41 + GREEN = 42 + YELLOW = 44 + BLUE = 44 + MAGENTA = 45 + CYAN = 46 + LIGHT_GRAY = 47 + DARK_GRAY = 100 + LIGHT_RED = 101 + LIGHT_GREEN = 102 + LIGHT_YELLOW = 103 + LIGHT_BLUE = 104 + LIGHT_MAGENTA = 105 + LIGHT_CYAN = 106 + WHITE = 107 + + RESET = 49 + + def __str__(self) -> str: + """ + Return ANSI color sequence instead of enum name + This is helpful when using a StdBg in an f-string or format() call + e.g. my_str = f"{StdBg.BLACK}hello{StdBg.RESET}" + """ + return f"{CSI}{self.value}m" + + +class EightBitFg(FgColor, Enum): + """ + Create ANSI sequences for 8-bit terminal foreground text colors. Most terminals support 8-bit/256-color mode. + The first 16 colors correspond to the 16 colors from StdFg and behave the same way. + To reset any foreground color, including 8-bit, use StdFg.RESET. + """ + + BLACK = 0 + RED = 1 + GREEN = 2 + YELLOW = 3 + BLUE = 4 + MAGENTA = 5 + CYAN = 6 + LIGHT_GRAY = 7 + DARK_GRAY = 8 + LIGHT_RED = 9 + LIGHT_GREEN = 10 + LIGHT_YELLOW = 11 + LIGHT_BLUE = 12 + LIGHT_MAGENTA = 13 + LIGHT_CYAN = 14 + WHITE = 15 + GRAY_0 = 16 + NAVY_BLUE = 17 + DARK_BLUE = 18 + BLUE_3A = 19 + BLUE_3B = 20 + BLUE_1 = 21 + DARK_GREEN = 22 + DEEP_SKY_BLUE_4A = 23 + DEEP_SKY_BLUE_4B = 24 + DEEP_SKY_BLUE_4C = 25 + DODGER_BLUE_3 = 26 + DODGER_BLUE_2 = 27 + GREEN_4 = 28 + SPRING_GREEN_4 = 29 + TURQUOISE_4 = 30 + DEEP_SKY_BLUE_3A = 31 + DEEP_SKY_BLUE_3B = 32 + DODGER_BLUE_1 = 33 + GREEN_3A = 34 + SPRING_GREEN_3A = 35 + DARK_CYAN = 36 + LIGHT_SEA_GREEN = 37 + DEEP_SKY_BLUE_2 = 38 + DEEP_SKY_BLUE_1 = 39 + GREEN_3B = 40 + SPRING_GREEN_3B = 41 + SPRING_GREEN_2A = 42 + CYAN_3 = 43 + DARK_TURQUOISE = 44 + TURQUOISE_2 = 45 + GREEN_1 = 46 + SPRING_GREEN_2B = 47 + SPRING_GREEN_1 = 48 + MEDIUM_SPRING_GREEN = 49 + CYAN_2 = 50 + CYAN_1 = 51 + DARK_RED_1 = 52 + DEEP_PINK_4A = 53 + PURPLE_4A = 54 + PURPLE_4B = 55 + PURPLE_3 = 56 + BLUE_VIOLET = 57 + ORANGE_4A = 58 + GRAY_37 = 59 + MEDIUM_PURPLE_4 = 60 + SLATE_BLUE_3A = 61 + SLATE_BLUE_3B = 62 + ROYAL_BLUE_1 = 63 + CHARTREUSE_4 = 64 + DARK_SEA_GREEN_4A = 65 + PALE_TURQUOISE_4 = 66 + STEEL_BLUE = 67 + STEEL_BLUE_3 = 68 + CORNFLOWER_BLUE = 69 + CHARTREUSE_3A = 70 + DARK_SEA_GREEN_4B = 71 + CADET_BLUE_2 = 72 + CADET_BLUE_1 = 73 + SKY_BLUE_3 = 74 + STEEL_BLUE_1A = 75 + CHARTREUSE_3B = 76 + PALE_GREEN_3A = 77 + SEA_GREEN_3 = 78 + AQUAMARINE_3 = 79 + MEDIUM_TURQUOISE = 80 + STEEL_BLUE_1B = 81 + CHARTREUSE_2A = 82 + SEA_GREEN_2 = 83 + SEA_GREEN_1A = 84 + SEA_GREEN_1B = 85 + AQUAMARINE_1A = 86 + DARK_SLATE_GRAY_2 = 87 + DARK_RED_2 = 88 + DEEP_PINK_4B = 89 + DARK_MAGENTA_1 = 90 + DARK_MAGENTA_2 = 91 + DARK_VIOLET_1A = 92 + PURPLE_1A = 93 + ORANGE_4B = 94 + LIGHT_PINK_4 = 95 + PLUM_4 = 96 + MEDIUM_PURPLE_3A = 97 + MEDIUM_PURPLE_3B = 98 + SLATE_BLUE_1 = 99 + YELLOW_4A = 100 + WHEAT_4 = 101 + GRAY_53 = 102 + LIGHT_SLATE_GRAY = 103 + MEDIUM_PURPLE = 104 + LIGHT_SLATE_BLUE = 105 + YELLOW_4B = 106 + DARK_OLIVE_GREEN_3A = 107 + DARK_GREEN_SEA = 108 + LIGHT_SKY_BLUE_3A = 109 + LIGHT_SKY_BLUE_3B = 110 + SKY_BLUE_2 = 111 + CHARTREUSE_2B = 112 + DARK_OLIVE_GREEN_3B = 113 + PALE_GREEN_3B = 114 + DARK_SEA_GREEN_3A = 115 + DARK_SLATE_GRAY_3 = 116 + SKY_BLUE_1 = 117 + CHARTREUSE_1 = 118 + LIGHT_GREEN_2 = 119 + LIGHT_GREEN_3 = 120 + PALE_GREEN_1A = 121 + AQUAMARINE_1B = 122 + DARK_SLATE_GRAY_1 = 123 + RED_3A = 124 + DEEP_PINK_4C = 125 + MEDIUM_VIOLET_RED = 126 + MAGENTA_3A = 127 + DARK_VIOLET_1B = 128 + PURPLE_1B = 129 + DARK_ORANGE_3A = 130 + INDIAN_RED_1A = 131 + HOT_PINK_3A = 132 + MEDIUM_ORCHID_3 = 133 + MEDIUM_ORCHID = 134 + MEDIUM_PURPLE_2A = 135 + DARK_GOLDENROD = 136 + LIGHT_SALMON_3A = 137 + ROSY_BROWN = 138 + GRAY_63 = 139 + MEDIUM_PURPLE_2B = 140 + MEDIUM_PURPLE_1 = 141 + GOLD_3A = 142 + DARK_KHAKI = 143 + NAVAJO_WHITE_3 = 144 + GRAY_69 = 145 + LIGHT_STEEL_BLUE_3 = 146 + LIGHT_STEEL_BLUE = 147 + YELLOW_3A = 148 + DARK_OLIVE_GREEN_3 = 149 + DARK_SEA_GREEN_3B = 150 + DARK_SEA_GREEN_2 = 151 + LIGHT_CYAN_3 = 152 + LIGHT_SKY_BLUE_1 = 153 + GREEN_YELLOW = 154 + DARK_OLIVE_GREEN_2 = 155 + PALE_GREEN_1B = 156 + DARK_SEA_GREEN_5B = 157 + DARK_SEA_GREEN_5A = 158 + PALE_TURQUOISE_1 = 159 + RED_3B = 160 + DEEP_PINK_3A = 161 + DEEP_PINK_3B = 162 + MAGENTA_3B = 163 + MAGENTA_3C = 164 + MAGENTA_2A = 165 + DARK_ORANGE_3B = 166 + INDIAN_RED_1B = 167 + HOT_PINK_3B = 168 + HOT_PINK_2 = 169 + ORCHID = 170 + MEDIUM_ORCHID_1A = 171 + ORANGE_3 = 172 + LIGHT_SALMON_3B = 173 + LIGHT_PINK_3 = 174 + PINK_3 = 175 + PLUM_3 = 176 + VIOLET = 177 + GOLD_3B = 178 + LIGHT_GOLDENROD_3 = 179 + TAN = 180 + MISTY_ROSE_3 = 181 + THISTLE_3 = 182 + PLUM_2 = 183 + YELLOW_3B = 184 + KHAKI_3 = 185 + LIGHT_GOLDENROD_2A = 186 + LIGHT_YELLOW_3 = 187 + GRAY_84 = 188 + LIGHT_STEEL_BLUE_1 = 189 + YELLOW_2 = 190 + DARK_OLIVE_GREEN_1A = 191 + DARK_OLIVE_GREEN_1B = 192 + DARK_SEA_GREEN_1 = 193 + HONEYDEW_2 = 194 + LIGHT_CYAN_1 = 195 + RED_1 = 196 + DEEP_PINK_2 = 197 + DEEP_PINK_1A = 198 + DEEP_PINK_1B = 199 + MAGENTA_2B = 200 + MAGENTA_1 = 201 + ORANGE_RED_1 = 202 + INDIAN_RED_1C = 203 + INDIAN_RED_1D = 204 + HOT_PINK_1A = 205 + HOT_PINK_1B = 206 + MEDIUM_ORCHID_1B = 207 + DARK_ORANGE = 208 + SALMON_1 = 209 + LIGHT_CORAL = 210 + PALE_VIOLET_RED_1 = 211 + ORCHID_2 = 212 + ORCHID_1 = 213 + ORANGE_1 = 214 + SANDY_BROWN = 215 + LIGHT_SALMON_1 = 216 + LIGHT_PINK_1 = 217 + PINK_1 = 218 + PLUM_1 = 219 + GOLD_1 = 220 + LIGHT_GOLDENROD_2B = 221 + LIGHT_GOLDENROD_2C = 222 + NAVAJO_WHITE_1 = 223 + MISTY_ROSE1 = 224 + THISTLE_1 = 225 + YELLOW_1 = 226 + LIGHT_GOLDENROD_1 = 227 + KHAKI_1 = 228 + WHEAT_1 = 229 + CORNSILK_1 = 230 + GRAY_100 = 231 + GRAY_3 = 232 + GRAY_7 = 233 + GRAY_11 = 234 + GRAY_15 = 235 + GRAY_19 = 236 + GRAY_23 = 237 + GRAY_27 = 238 + GRAY_30 = 239 + GRAY_35 = 240 + GRAY_39 = 241 + GRAY_42 = 242 + GRAY_46 = 243 + GRAY_50 = 244 + GRAY_54 = 245 + GRAY_58 = 246 + GRAY_62 = 247 + GRAY_66 = 248 + GRAY_70 = 249 + GRAY_74 = 250 + GRAY_78 = 251 + GRAY_82 = 252 + GRAY_85 = 253 + GRAY_89 = 254 + GRAY_93 = 255 + + def __str__(self) -> str: + """ + Return ANSI color sequence instead of enum name + This is helpful when using a EightBitFg in an f-string or format() call + e.g. my_str = f"{EightBitFg.SLATE_BLUE_1}hello{StdFg.RESET}" + """ + return f"{CSI}{38};5;{self.value}m" + + +class EightBitBg(BgColor, Enum): + """ + Create ANSI sequences for 8-bit terminal background text colors. Most terminals support 8-bit/256-color mode. + The first 16 colors correspond to the 16 colors from StdBg and behave the same way. + To reset any background color, including 8-bit, use StdBg.RESET. + """ + + BLACK = 0 + RED = 1 + GREEN = 2 + YELLOW = 3 + BLUE = 4 + MAGENTA = 5 + CYAN = 6 + LIGHT_GRAY = 7 + DARK_GRAY = 8 + LIGHT_RED = 9 + LIGHT_GREEN = 10 + LIGHT_YELLOW = 11 + LIGHT_BLUE = 12 + LIGHT_MAGENTA = 13 + LIGHT_CYAN = 14 + WHITE = 15 + GRAY_0 = 16 + NAVY_BLUE = 17 + DARK_BLUE = 18 + BLUE_3A = 19 + BLUE_3B = 20 + BLUE_1 = 21 + DARK_GREEN = 22 + DEEP_SKY_BLUE_4A = 23 + DEEP_SKY_BLUE_4B = 24 + DEEP_SKY_BLUE_4C = 25 + DODGER_BLUE_3 = 26 + DODGER_BLUE_2 = 27 + GREEN_4 = 28 + SPRING_GREEN_4 = 29 + TURQUOISE_4 = 30 + DEEP_SKY_BLUE_3A = 31 + DEEP_SKY_BLUE_3B = 32 + DODGER_BLUE_1 = 33 + GREEN_3A = 34 + SPRING_GREEN_3A = 35 + DARK_CYAN = 36 + LIGHT_SEA_GREEN = 37 + DEEP_SKY_BLUE_2 = 38 + DEEP_SKY_BLUE_1 = 39 + GREEN_3B = 40 + SPRING_GREEN_3B = 41 + SPRING_GREEN_2A = 42 + CYAN_3 = 43 + DARK_TURQUOISE = 44 + TURQUOISE_2 = 45 + GREEN_1 = 46 + SPRING_GREEN_2B = 47 + SPRING_GREEN_1 = 48 + MEDIUM_SPRING_GREEN = 49 + CYAN_2 = 50 + CYAN_1 = 51 + DARK_RED_1 = 52 + DEEP_PINK_4A = 53 + PURPLE_4A = 54 + PURPLE_4B = 55 + PURPLE_3 = 56 + BLUE_VIOLET = 57 + ORANGE_4A = 58 + GRAY_37 = 59 + MEDIUM_PURPLE_4 = 60 + SLATE_BLUE_3A = 61 + SLATE_BLUE_3B = 62 + ROYAL_BLUE_1 = 63 + CHARTREUSE_4 = 64 + DARK_SEA_GREEN_4A = 65 + PALE_TURQUOISE_4 = 66 + STEEL_BLUE = 67 + STEEL_BLUE_3 = 68 + CORNFLOWER_BLUE = 69 + CHARTREUSE_3A = 70 + DARK_SEA_GREEN_4B = 71 + CADET_BLUE_2 = 72 + CADET_BLUE_1 = 73 + SKY_BLUE_3 = 74 + STEEL_BLUE_1A = 75 + CHARTREUSE_3B = 76 + PALE_GREEN_3A = 77 + SEA_GREEN_3 = 78 + AQUAMARINE_3 = 79 + MEDIUM_TURQUOISE = 80 + STEEL_BLUE_1B = 81 + CHARTREUSE_2A = 82 + SEA_GREEN_2 = 83 + SEA_GREEN_1A = 84 + SEA_GREEN_1B = 85 + AQUAMARINE_1A = 86 + DARK_SLATE_GRAY_2 = 87 + DARK_RED_2 = 88 + DEEP_PINK_4B = 89 + DARK_MAGENTA_1 = 90 + DARK_MAGENTA_2 = 91 + DARK_VIOLET_1A = 92 + PURPLE_1A = 93 + ORANGE_4B = 94 + LIGHT_PINK_4 = 95 + PLUM_4 = 96 + MEDIUM_PURPLE_3A = 97 + MEDIUM_PURPLE_3B = 98 + SLATE_BLUE_1 = 99 + YELLOW_4A = 100 + WHEAT_4 = 101 + GRAY_53 = 102 + LIGHT_SLATE_GRAY = 103 + MEDIUM_PURPLE = 104 + LIGHT_SLATE_BLUE = 105 + YELLOW_4B = 106 + DARK_OLIVE_GREEN_3A = 107 + DARK_GREEN_SEA = 108 + LIGHT_SKY_BLUE_3A = 109 + LIGHT_SKY_BLUE_3B = 110 + SKY_BLUE_2 = 111 + CHARTREUSE_2B = 112 + DARK_OLIVE_GREEN_3B = 113 + PALE_GREEN_3B = 114 + DARK_SEA_GREEN_3A = 115 + DARK_SLATE_GRAY_3 = 116 + SKY_BLUE_1 = 117 + CHARTREUSE_1 = 118 + LIGHT_GREEN_2 = 119 + LIGHT_GREEN_3 = 120 + PALE_GREEN_1A = 121 + AQUAMARINE_1B = 122 + DARK_SLATE_GRAY_1 = 123 + RED_3A = 124 + DEEP_PINK_4C = 125 + MEDIUM_VIOLET_RED = 126 + MAGENTA_3A = 127 + DARK_VIOLET_1B = 128 + PURPLE_1B = 129 + DARK_ORANGE_3A = 130 + INDIAN_RED_1A = 131 + HOT_PINK_3A = 132 + MEDIUM_ORCHID_3 = 133 + MEDIUM_ORCHID = 134 + MEDIUM_PURPLE_2A = 135 + DARK_GOLDENROD = 136 + LIGHT_SALMON_3A = 137 + ROSY_BROWN = 138 + GRAY_63 = 139 + MEDIUM_PURPLE_2B = 140 + MEDIUM_PURPLE_1 = 141 + GOLD_3A = 142 + DARK_KHAKI = 143 + NAVAJO_WHITE_3 = 144 + GRAY_69 = 145 + LIGHT_STEEL_BLUE_3 = 146 + LIGHT_STEEL_BLUE = 147 + YELLOW_3A = 148 + DARK_OLIVE_GREEN_3 = 149 + DARK_SEA_GREEN_3B = 150 + DARK_SEA_GREEN_2 = 151 + LIGHT_CYAN_3 = 152 + LIGHT_SKY_BLUE_1 = 153 + GREEN_YELLOW = 154 + DARK_OLIVE_GREEN_2 = 155 + PALE_GREEN_1B = 156 + DARK_SEA_GREEN_5B = 157 + DARK_SEA_GREEN_5A = 158 + PALE_TURQUOISE_1 = 159 + RED_3B = 160 + DEEP_PINK_3A = 161 + DEEP_PINK_3B = 162 + MAGENTA_3B = 163 + MAGENTA_3C = 164 + MAGENTA_2A = 165 + DARK_ORANGE_3B = 166 + INDIAN_RED_1B = 167 + HOT_PINK_3B = 168 + HOT_PINK_2 = 169 + ORCHID = 170 + MEDIUM_ORCHID_1A = 171 + ORANGE_3 = 172 + LIGHT_SALMON_3B = 173 + LIGHT_PINK_3 = 174 + PINK_3 = 175 + PLUM_3 = 176 + VIOLET = 177 + GOLD_3B = 178 + LIGHT_GOLDENROD_3 = 179 + TAN = 180 + MISTY_ROSE_3 = 181 + THISTLE_3 = 182 + PLUM_2 = 183 + YELLOW_3B = 184 + KHAKI_3 = 185 + LIGHT_GOLDENROD_2A = 186 + LIGHT_YELLOW_3 = 187 + GRAY_84 = 188 + LIGHT_STEEL_BLUE_1 = 189 + YELLOW_2 = 190 + DARK_OLIVE_GREEN_1A = 191 + DARK_OLIVE_GREEN_1B = 192 + DARK_SEA_GREEN_1 = 193 + HONEYDEW_2 = 194 + LIGHT_CYAN_1 = 195 + RED_1 = 196 + DEEP_PINK_2 = 197 + DEEP_PINK_1A = 198 + DEEP_PINK_1B = 199 + MAGENTA_2B = 200 + MAGENTA_1 = 201 + ORANGE_RED_1 = 202 + INDIAN_RED_1C = 203 + INDIAN_RED_1D = 204 + HOT_PINK_1A = 205 + HOT_PINK_1B = 206 + MEDIUM_ORCHID_1B = 207 + DARK_ORANGE = 208 + SALMON_1 = 209 + LIGHT_CORAL = 210 + PALE_VIOLET_RED_1 = 211 + ORCHID_2 = 212 + ORCHID_1 = 213 + ORANGE_1 = 214 + SANDY_BROWN = 215 + LIGHT_SALMON_1 = 216 + LIGHT_PINK_1 = 217 + PINK_1 = 218 + PLUM_1 = 219 + GOLD_1 = 220 + LIGHT_GOLDENROD_2B = 221 + LIGHT_GOLDENROD_2C = 222 + NAVAJO_WHITE_1 = 223 + MISTY_ROSE1 = 224 + THISTLE_1 = 225 + YELLOW_1 = 226 + LIGHT_GOLDENROD_1 = 227 + KHAKI_1 = 228 + WHEAT_1 = 229 + CORNSILK_1 = 230 + GRAY_100 = 231 + GRAY_3 = 232 + GRAY_7 = 233 + GRAY_11 = 234 + GRAY_15 = 235 + GRAY_19 = 236 + GRAY_23 = 237 + GRAY_27 = 238 + GRAY_30 = 239 + GRAY_35 = 240 + GRAY_39 = 241 + GRAY_42 = 242 + GRAY_46 = 243 + GRAY_50 = 244 + GRAY_54 = 245 + GRAY_58 = 246 + GRAY_62 = 247 + GRAY_66 = 248 + GRAY_70 = 249 + GRAY_74 = 250 + GRAY_78 = 251 + GRAY_82 = 252 + GRAY_85 = 253 + GRAY_89 = 254 + GRAY_93 = 255 + + def __str__(self) -> str: + """ + Return ANSI color sequence instead of enum name + This is helpful when using a EightBitBg in an f-string or format() call + e.g. my_str = f"{EightBitBg.KHAKI_3}hello{StdBg.RESET}" + """ + return f"{CSI}{48};5;{self.value}m" + + +class RgbFg(FgColor): + """ + Create ANSI sequences for 24-bit (RGB) terminal foreground text colors. The terminal must support 24-bit/true-color mode. + To reset any foreground color, including 24-bit, use StdFg.RESET. + """ + + def __init__(self, r: int, g: int, b: int) -> None: + """ + RgbFg initializer + + :param r: integer from 0-255 for the red component of the color + :param g: integer from 0-255 for the green component of the color + :param b: integer from 0-255 for the blue component of the color + :raises: ValueError if r, g, or b is not in the range 0-255 + """ + if any(c < 0 or c > 255 for c in [r, g, b]): + raise ValueError("RGB values must be integers in the range of 0 to 255") + + self._sequence = f"{CSI}{38};2;{r};{g};{b}m" + + def __str__(self) -> str: + """ + Return ANSI color sequence instead of enum name + This is helpful when using a RgbFg in an f-string or format() call + e.g. my_str = f"{RgbFg(0, 55, 100)}hello{StdFg.RESET}" + """ + return self._sequence + + +class RgbBg(BgColor): + """ + Create ANSI sequences for 24-bit (RGB) terminal background text colors. The terminal must support 24-bit/true-color mode. + To reset any background color, including 24-bit, use StdBg.RESET. + """ + + def __init__(self, r: int, g: int, b: int) -> None: + """ + RgbBg initializer + + :param r: integer from 0-255 for the red component of the color + :param g: integer from 0-255 for the green component of the color + :param b: integer from 0-255 for the blue component of the color + :raises: ValueError if r, g, or b is not in the range 0-255 + """ + if any(c < 0 or c > 255 for c in [r, g, b]): + raise ValueError("RGB values must be integers in the range of 0 to 255") + + self._sequence = f"{CSI}{48};2;{r};{g};{b}m" + + def __str__(self) -> str: + """ + Return ANSI color sequence instead of enum name + This is helpful when using a RgbBg in an f-string or format() call + e.g. my_str = f"{RgbBg(100, 255, 27)}hello{StdBg.RESET}" + """ + return self._sequence + +# TODO: Remove this PyShadowingNames usage when deprecated fg and bg classes are removed. # noinspection PyShadowingNames def style( text: Any, *, - fg: Union[str, fg] = '', - bg: Union[str, bg] = '', - bold: bool = False, - dim: bool = False, - underline: bool = False, + fg: Optional[FgColor] = None, + bg: Optional[BgColor] = None, + bold: Optional[bool] = None, + dim: Optional[bool] = None, + italic: Optional[bool] = None, + overline: Optional[bool] = None, + strikethrough: Optional[bool] = None, + underline: Optional[bool] = None, ) -> str: """ Apply ANSI colors and/or styles to a string and return it. @@ -282,59 +960,74 @@ def style( to undo whatever styling was done at the beginning. :param text: text to format (anything convertible to a str) - :param fg: foreground color. Relies on `fg_lookup()` to retrieve ANSI escape based on name or enum. + :param fg: foreground color provided as any subclass of FgColor (e.g. StgFg, EightBitFg, RgbFg) Defaults to no color. - :param bg: background color. Relies on `bg_lookup()` to retrieve ANSI escape based on name or enum. + :param bg: foreground color provided as any subclass of BgColor (e.g. StgBg, EightBitBg, RgbBg) Defaults to no color. - :param bold: apply the bold style if True. Can be combined with dim. Defaults to False. - :param dim: apply the dim style if True. Can be combined with bold. Defaults to False. + :param bold: apply the bold style if True. Defaults to False. + :param dim: apply the dim style if True. Defaults to False. + :param italic: apply the italic style if True. Defaults to False. + :param overline: apply the overline style if True. Defaults to False. + :param strikethrough: apply the strikethrough style if True. Defaults to False. :param underline: apply the underline style if True. Defaults to False. :return: the stylized string """ # List of strings that add style - additions: List[str] = [] + additions: List[AnsiSequence] = [] # List of strings that remove style - removals: List[str] = [] + removals: List[AnsiSequence] = [] # Convert the text object into a string if it isn't already one text_formatted = str(text) # Process the style settings - if fg: - additions.append(fg_lookup(fg)) - removals.append(FG_RESET) + if fg is not None: + additions.append(fg) + removals.append(StdFg.RESET) - if bg: - additions.append(bg_lookup(bg)) - removals.append(BG_RESET) + if bg is not None: + additions.append(bg) + removals.append(StdBg.RESET) if bold: - additions.append(INTENSITY_BRIGHT) - removals.append(INTENSITY_NORMAL) + additions.append(TextStyle.INTENSITY_BOLD) + removals.append(TextStyle.INTENSITY_NORMAL) if dim: - additions.append(INTENSITY_DIM) - removals.append(INTENSITY_NORMAL) + additions.append(TextStyle.INTENSITY_DIM) + removals.append(TextStyle.INTENSITY_NORMAL) + + if italic: + additions.append(TextStyle.ITALIC_ENABLE) + removals.append(TextStyle.ITALIC_DISABLE) + + if overline: + additions.append(TextStyle.OVERLINE_ENABLE) + removals.append(TextStyle.OVERLINE_DISABLE) + + if strikethrough: + additions.append(TextStyle.STRIKETHROUGH_ENABLE) + removals.append(TextStyle.STRIKETHROUGH_DISABLE) if underline: - additions.append(UNDERLINE_ENABLE) - removals.append(UNDERLINE_DISABLE) + additions.append(TextStyle.UNDERLINE_ENABLE) + removals.append(TextStyle.UNDERLINE_DISABLE) # Combine the ANSI style sequences with the text - return "".join(additions) + text_formatted + "".join(removals) + return "".join(map(str, additions)) + text_formatted + "".join(map(str, removals)) # Default styles for printing strings of various types. # These can be altered to suit an application's needs and only need to be a # function with the following structure: func(str) -> str -style_success = functools.partial(style, fg=fg.green) +style_success = functools.partial(style, fg=StdFg.GREEN) """Partial function supplying arguments to :meth:`cmd2.ansi.style()` which colors text to signify success""" -style_warning = functools.partial(style, fg=fg.bright_yellow) +style_warning = functools.partial(style, fg=StdFg.LIGHT_YELLOW) """Partial function supplying arguments to :meth:`cmd2.ansi.style()` which colors text to signify a warning""" -style_error = functools.partial(style, fg=fg.bright_red) +style_error = functools.partial(style, fg=StdFg.LIGHT_RED) """Partial function supplying arguments to :meth:`cmd2.ansi.style()` which colors text to signify an error""" @@ -348,9 +1041,6 @@ def async_alert_str(*, terminal_columns: int, prompt: str, line: str, cursor_off :param alert_msg: the message to display to the user :return: the correct string so that the alert message appears to the user to be printed above the current line. """ - from colorama import ( - Cursor, - ) # Split the prompt lines since it can contain newline characters. prompt_lines = prompt.splitlines() @@ -385,20 +1075,76 @@ def async_alert_str(*, terminal_columns: int, prompt: str, line: str, cursor_off # Clear each line from the bottom up so that the cursor ends up on the first prompt line total_lines = num_prompt_terminal_lines + num_input_terminal_lines - terminal_str += (colorama.ansi.clear_line() + Cursor.UP(1)) * (total_lines - 1) + terminal_str += (clear_line() + Cursor.UP(1)) * (total_lines - 1) # Clear the first prompt line - terminal_str += colorama.ansi.clear_line() + terminal_str += clear_line() # Move the cursor to the beginning of the first prompt line and print the alert terminal_str += '\r' + alert_msg return terminal_str -def set_title_str(title: str) -> str: - """Get the required string, including ANSI escape codes, for setting window title for the terminal. +#################################################################################### +# The following classes are deprecated. +#################################################################################### +# noinspection PyPep8Naming +class fg(FgColor, Enum): + """Deprecated Enum class for foreground colors. Use StdFg instead.""" + + black = 30 + red = 31 + green = 32 + yellow = 33 + blue = 34 + magenta = 35 + cyan = 36 + white = 37 + reset = 39 + bright_black = 90 + bright_red = 91 + bright_green = 92 + bright_yellow = 93 + bright_blue = 94 + bright_magenta = 95 + bright_cyan = 96 + bright_white = 97 - :param title: new title for the window - :return: string to write to sys.stderr in order to set the window title to the desired test - """ - return cast(str, colorama.ansi.set_title(title)) + def __str__(self) -> str: + """ + Return ANSI color sequence instead of enum name + This is helpful when using a fg in an f-string or format() call + e.g. my_str = f"{fg.blue}hello{fg.reset}" + """ + return f"{CSI}{self.value}m" + + +# noinspection PyPep8Naming +class bg(BgColor, Enum): + """Deprecated Enum class for background colors. Use StdBg instead.""" + + black = 40 + red = 41 + green = 42 + yellow = 43 + blue = 44 + magenta = 45 + cyan = 46 + white = 47 + reset = 49 + bright_black = 100 + bright_red = 101 + bright_green = 102 + bright_yellow = 103 + bright_blue = 104 + bright_magenta = 105 + bright_cyan = 106 + bright_white = 107 + + def __str__(self) -> str: + """ + Return ANSI color sequence instead of enum name + This is helpful when using a bg in an f-string or format() call + e.g. my_str = f"{bg.black}hello{bg.reset}" + """ + return f"{CSI}{self.value}m" diff --git a/cmd2/clipboard.py b/cmd2/clipboard.py index f31f5d5a..ec8e615d 100644 --- a/cmd2/clipboard.py +++ b/cmd2/clipboard.py @@ -6,7 +6,7 @@ from typing import ( cast, ) -import pyperclip # type: ignore [import] +import pyperclip # type: ignore[import] # noinspection PyProtectedMember from pyperclip import ( diff --git a/cmd2/cmd2.py b/cmd2/cmd2.py index 0f7e1055..b647c48a 100644 --- a/cmd2/cmd2.py +++ b/cmd2/cmd2.py @@ -984,14 +984,29 @@ class Cmd(cmd.Cmd): def build_settables(self) -> None: """Create the dictionary of user-settable parameters""" + + def get_allow_style_choices(cli_self: Cmd) -> List[str]: + """Used to tab complete allow_style values""" + return [val.name.lower() for val in ansi.AllowStyle] + + def allow_style_type(value: str) -> ansi.AllowStyle: + """Converts a string value into an ansi.AllowStyle""" + try: + return ansi.AllowStyle[value.upper()] + except KeyError: + raise ValueError( + f"must be {ansi.AllowStyle.ALWAYS}, {ansi.AllowStyle.NEVER}, or " + f"{ansi.AllowStyle.TERMINAL} (case-insensitive)" + ) + self.add_settable( Settable( 'allow_style', - str, + allow_style_type, 'Allow ANSI text style sequences in output (valid values: ' - f'{ansi.STYLE_TERMINAL}, {ansi.STYLE_ALWAYS}, {ansi.STYLE_NEVER})', + f'{ansi.AllowStyle.ALWAYS}, {ansi.AllowStyle.NEVER}, {ansi.AllowStyle.TERMINAL})', self, - choices=[ansi.STYLE_TERMINAL, ansi.STYLE_ALWAYS, ansi.STYLE_NEVER], + choices_provider=cast(ChoicesProviderFunc, get_allow_style_choices), ) ) @@ -1016,18 +1031,14 @@ class Cmd(cmd.Cmd): # ----- Methods related to presenting output to the user ----- @property - def allow_style(self) -> str: + def allow_style(self) -> ansi.AllowStyle: """Read-only property needed to support do_set when it reads allow_style""" return ansi.allow_style @allow_style.setter - def allow_style(self, new_val: str) -> None: + def allow_style(self, new_val: ansi.AllowStyle) -> None: """Setter property needed to support do_set when it updates allow_style""" - new_val = new_val.capitalize() - if new_val in [ansi.STYLE_TERMINAL, ansi.STYLE_ALWAYS, ansi.STYLE_NEVER]: - ansi.allow_style = new_val - else: - raise ValueError(f"must be {ansi.STYLE_TERMINAL}, {ansi.STYLE_ALWAYS}, or {ansi.STYLE_NEVER} (case-insensitive)") + ansi.allow_style = new_val def _completion_supported(self) -> bool: """Return whether tab completion is supported""" @@ -1169,7 +1180,7 @@ class Cmd(cmd.Cmd): # Don't attempt to use a pager that can block if redirecting or running a script (either text or Python) # Also only attempt to use a pager if actually running in a real fully functional terminal if functional_terminal and not self._redirecting and not self.in_pyscript() and not self.in_script(): - if ansi.allow_style.lower() == ansi.STYLE_NEVER.lower(): + if ansi.allow_style == ansi.AllowStyle.NEVER: msg_str = ansi.strip_style(msg_str) msg_str += end @@ -5108,7 +5119,7 @@ class Cmd(cmd.Cmd): return try: - sys.stderr.write(ansi.set_title_str(title)) + sys.stderr.write(ansi.set_title(title)) sys.stderr.flush() except AttributeError: # Debugging in Pycharm has issues with setting terminal title diff --git a/cmd2/table_creator.py b/cmd2/table_creator.py index d049fb54..37b7b4c1 100644 --- a/cmd2/table_creator.py +++ b/cmd2/table_creator.py @@ -885,12 +885,14 @@ class AlternatingTable(BorderedTable): tab_width: int = 4, column_borders: bool = True, padding: int = 1, - bg_odd: Optional[ansi.bg] = None, - bg_even: Optional[ansi.bg] = ansi.bg.bright_black, + bg_odd: Optional[ansi.BgColor] = None, + bg_even: Optional[ansi.BgColor] = ansi.StdBg.DARK_GRAY, ) -> None: """ AlternatingTable initializer + Note: Specify background colors using subclasses of BgColor (e.g. StgBg, EightBitBg, RgbBg) + :param cols: column definitions for this table :param tab_width: all tabs will be replaced with this many spaces. If a row's fill_char is a tab, then it will be converted to one space. @@ -899,7 +901,7 @@ class AlternatingTable(BorderedTable): a row's cells. (Defaults to True) :param padding: number of spaces between text and left/right borders of cell :param bg_odd: optional background color for odd numbered rows (defaults to None) - :param bg_even: optional background color for even numbered rows (defaults to gray) + :param bg_even: optional background color for even numbered rows (defaults to StdBg.DARK_GRAY) :raises: ValueError if padding is less than 0 """ super().__init__(cols, tab_width=tab_width, column_borders=column_borders, padding=padding) diff --git a/cmd2/utils.py b/cmd2/utils.py index d9066a97..aecab276 100644 --- a/cmd2/utils.py +++ b/cmd2/utils.py @@ -150,8 +150,13 @@ class Settable: :param completer: tab completion function that provides choices for this argument """ if val_type == bool: + + def get_bool_choices(_) -> List[str]: # type: ignore[no-untyped-def] + """Used to tab complete lowercase boolean values""" + return ['true', 'false'] + val_type = str_to_bool - choices = ['true', 'false'] + choices_provider = cast(ChoicesProviderFunc, get_bool_choices) self.name = name self.val_type = val_type @@ -176,10 +181,17 @@ class Settable: :param value: New value to set :return: New value that the attribute was set to """ + # Run the value through its type function to handle any conversion or validation + new_value = self.val_type(value) + + # Make sure new_value is a valid choice + if self.choices is not None and new_value not in self.choices: + choices_str = ', '.join(map(repr, self.choices)) + raise ValueError(f"invalid choice: {new_value!r} (choose from {choices_str})") + # Try to update the settable's value orig_value = self.get_value() - setattr(self.settable_obj, self.settable_attrib_name, self.val_type(value)) - new_value = getattr(self.settable_obj, self.settable_attrib_name) + setattr(self.settable_obj, self.settable_attrib_name, new_value) # Check if we need to call an onchange callback if orig_value != new_value and self.onchange_cb: @@ -859,12 +871,12 @@ def align_text( # Don't allow styles in fill_char and text to affect one another if fill_char_styles or aggregate_styles or line_styles: if left_fill: - left_fill = ansi.RESET_ALL + left_fill - left_fill += ansi.RESET_ALL + left_fill = ansi.TextStyle.RESET_ALL + left_fill + left_fill += ansi.TextStyle.RESET_ALL if right_fill: - right_fill = ansi.RESET_ALL + right_fill - right_fill += ansi.RESET_ALL + right_fill = ansi.TextStyle.RESET_ALL + right_fill + right_fill += ansi.TextStyle.RESET_ALL # Write the line and restore any styles from previous lines text_buf.write(left_fill + aggregate_styles + line + right_fill) @@ -953,8 +965,8 @@ def truncate_line(line: str, max_width: int, *, tab_width: int = 4) -> str: If there are ANSI style sequences in the string after where truncation occurs, this function will append them to the returned string. - This is done to prevent issues caused in cases like: truncate_line(fg.blue + hello + fg.reset, 3) - In this case, "hello" would be truncated before fg.reset resets the color from blue. Appending the remaining style + This is done to prevent issues caused in cases like: truncate_line(StdFg.BLUE + hello + StdFg.RESET, 3) + In this case, "hello" would be truncated before StdFg.RESET resets the color from blue. Appending the remaining style sequences makes sure the style is in the same state had the entire string been printed. align_text() relies on this behavior when preserving style over multiple lines. diff --git a/docs/features/builtin_commands.rst b/docs/features/builtin_commands.rst index 97b160b5..eb14e9ab 100644 --- a/docs/features/builtin_commands.rst +++ b/docs/features/builtin_commands.rst @@ -106,7 +106,7 @@ within a running application: Name Value Description ================================================================================================================== allow_style Terminal Allow ANSI text style sequences in output (valid values: - Terminal, Always, Never) + Always, Never, Terminal) always_show_hint False Display tab completion hint even when completion suggestions print debug True Show full traceback on exception diff --git a/docs/features/generating_output.rst b/docs/features/generating_output.rst index d6484c26..7a6f047d 100644 --- a/docs/features/generating_output.rst +++ b/docs/features/generating_output.rst @@ -106,21 +106,10 @@ Colored Output You can add your own `ANSI escape sequences <https://en.wikipedia.org/wiki/ANSI_escape_code#Colors>`_ to your output which -tell the terminal to change the foreground and background colors. If you want -to give yourself a headache, you can generate these by hand. You could also use -a Python color library like `plumbum.colors -<https://plumbum.readthedocs.io/en/latest/colors.html>`_, `colored -<https://gitlab.com/dslackw/colored>`_, or `colorama -<https://github.com/tartley/colorama>`_. Colorama is unique because when it's -running on Windows, it wraps ``stdout``, looks for ANSI escape sequences, and -converts them into the appropriate ``win32`` calls to modify the state of the -terminal. - -``cmd2`` imports and uses Colorama and provides a number of convenience methods -for generating colorized output, measuring the screen width of colorized -output, setting the window title in the terminal, and removing ANSI text style -escape codes from a string. These functions are all documentated in -:mod:`cmd2.ansi`. +tell the terminal to change the foreground and background colors. + +``cmd2`` provides a number of convenience functions and classes for adding +color and other styles to text. These are all documented in :mod:`cmd2.ansi`. After adding the desired escape sequences to your output, you should use one of these methods to present the output to the user: diff --git a/docs/features/initialization.rst b/docs/features/initialization.rst index e51f87b2..cc3b6d36 100644 --- a/docs/features/initialization.rst +++ b/docs/features/initialization.rst @@ -19,17 +19,26 @@ capabilities which you may wish to utilize while initializing the app:: 10) How to make custom attributes settable at runtime """ import cmd2 - from cmd2 import style, fg, bg + from cmd2 import ( + StdBg, + StdFg, + style, + ) + class BasicApp(cmd2.Cmd): CUSTOM_CATEGORY = 'My Custom Commands' def __init__(self): - super().__init__(multiline_commands=['echo'], persistent_history_file='cmd2_history.dat', - startup_script='scripts/startup.txt', include_ipy=True) + super().__init__( + multiline_commands=['echo'], + persistent_history_file='cmd2_history.dat', + startup_script='scripts/startup.txt', + include_ipy=True, + ) # Prints an intro banner once upon application startup - self.intro = style('Welcome to cmd2!', fg=fg.red, bg=bg.white, bold=True) + self.intro = style('Welcome to cmd2!', fg=StdFg.RED, bg=StdBg.WHITE, bold=True) # Show this as the prompt when asking for input self.prompt = 'myapp> ' @@ -44,14 +53,13 @@ capabilities which you may wish to utilize while initializing the app:: self.default_category = 'cmd2 Built-in Commands' # Color to output text in with echo command - self.foreground_color = 'cyan' + self.foreground_color = StdFg.CYAN.name.lower() # Make echo_fg settable at runtime - self.add_settable(cmd2.Settable('foreground_color', - str, - 'Foreground color to use with echo command', - self, - choices=fg.colors())) + fg_colors = [c.name.lower() for c in StdFg] + self.add_settable( + cmd2.Settable('foreground_color', str, 'Foreground color to use with echo command', self, choices=fg_colors) + ) @cmd2.with_category(CUSTOM_CATEGORY) def do_intro(self, _): @@ -61,7 +69,8 @@ capabilities which you may wish to utilize while initializing the app:: @cmd2.with_category(CUSTOM_CATEGORY) def do_echo(self, arg): """Example of a multiline command""" - self.poutput(style(arg, fg=self.foreground_color)) + fg_color = StdFg[self.foreground_color.upper()] + self.poutput(style(arg, fg=fg_color)) if __name__ == '__main__': diff --git a/examples/argparse_completion.py b/examples/argparse_completion.py index 7350f46c..f67b0b7b 100644 --- a/examples/argparse_completion.py +++ b/examples/argparse_completion.py @@ -47,7 +47,7 @@ class ArgparseCompletion(Cmd): def choices_completion_item(self) -> List[CompletionItem]: """Return CompletionItem instead of strings. These give more context to what's being tab completed.""" fancy_item = "These things can\ncontain newlines and\n" - fancy_item += ansi.style("styled text!!", fg=ansi.fg.bright_yellow, underline=True) + fancy_item += ansi.style("styled text!!", fg=ansi.StdFg.LIGHT_YELLOW, underline=True) items = {1: "My item", 2: "Another item", 3: "Yet another item", 4: fancy_item} return [CompletionItem(item_id, description) for item_id, description in items.items()] diff --git a/examples/async_printing.py b/examples/async_printing.py index 4832bf0a..fa6cad2a 100755 --- a/examples/async_printing.py +++ b/examples/async_printing.py @@ -13,7 +13,7 @@ from typing import ( import cmd2 from cmd2 import ( - fg, + StdFg, style, ) @@ -151,18 +151,18 @@ class AlerterApp(cmd2.Cmd): """ rand_num = random.randint(1, 20) - status_color = fg.reset + status_color = StdFg.RESET if rand_num == 1: - status_color = fg.bright_red + status_color = StdFg.LIGHT_RED elif rand_num == 2: - status_color = fg.bright_yellow + status_color = StdFg.LIGHT_YELLOW elif rand_num == 3: - status_color = fg.cyan + status_color = StdFg.CYAN elif rand_num == 4: - status_color = fg.bright_green + status_color = StdFg.LIGHT_GREEN elif rand_num == 5: - status_color = fg.bright_blue + status_color = StdFg.LIGHT_BLUE return style(self.visible_prompt, fg=status_color) diff --git a/examples/basic.py b/examples/basic.py index 8f507e03..167dee80 100755 --- a/examples/basic.py +++ b/examples/basic.py @@ -10,8 +10,8 @@ """ import cmd2 from cmd2 import ( - bg, - fg, + StdBg, + StdFg, style, ) @@ -27,7 +27,7 @@ class BasicApp(cmd2.Cmd): include_ipy=True, ) - self.intro = style('Welcome to PyOhio 2019 and cmd2!', fg=fg.red, bg=bg.white, bold=True) + ' 😀' + self.intro = style('Welcome to PyOhio 2019 and cmd2!', fg=StdFg.RED, bg=StdBg.WHITE, bold=True) + ' 😀' # Allow access to your application in py and ipy via self self.self_in_py = True diff --git a/examples/colors.py b/examples/colors.py index 24a5cf09..589cd607 100755 --- a/examples/colors.py +++ b/examples/colors.py @@ -16,28 +16,23 @@ Terminal (the default value) poutput(), pfeedback(), and ppaged() do not strip any ANSI style sequences when the output is a terminal, but if the output is a pipe or a file the style sequences are stripped. If you want colorized - output you must add ANSI style sequences using either cmd2's internal ansi - module or another color library such as `plumbum.colors` or `colorama`. + output, add ANSI style sequences using cmd2's internal ansi module. Always poutput(), pfeedback(), and ppaged() never strip ANSI style sequences, regardless of the output destination """ -from typing import ( - Any, -) - -from colorama import ( - Back, - Fore, - Style, -) import cmd2 from cmd2 import ( + StdBg, + StdFg, ansi, ) +fg_choices = [c.name.lower() for c in StdFg] +bg_choices = [c.name.lower() for c in StdBg] + class CmdLineApp(cmd2.Cmd): """Example cmd2 application demonstrating colorized output.""" @@ -51,14 +46,14 @@ class CmdLineApp(cmd2.Cmd): self.add_settable(cmd2.Settable('maxrepeats', int, 'max repetitions for speak command', self)) # Should ANSI color output be allowed - self.allow_style = ansi.STYLE_TERMINAL + self.allow_style = ansi.AllowStyle.TERMINAL speak_parser = cmd2.Cmd2ArgumentParser() speak_parser.add_argument('-p', '--piglatin', action='store_true', help='atinLay') speak_parser.add_argument('-s', '--shout', action='store_true', help='N00B EMULATION MODE') speak_parser.add_argument('-r', '--repeat', type=int, help='output [n] times') - speak_parser.add_argument('-f', '--fg', choices=ansi.fg.colors(), help='foreground color to apply to output') - speak_parser.add_argument('-b', '--bg', choices=ansi.bg.colors(), help='background color to apply to output') + speak_parser.add_argument('-f', '--fg', choices=fg_choices, help='foreground color to apply to output') + speak_parser.add_argument('-b', '--bg', choices=bg_choices, help='background color to apply to output') speak_parser.add_argument('-l', '--bold', action='store_true', help='bold the output') speak_parser.add_argument('-u', '--underline', action='store_true', help='underline the output') speak_parser.add_argument('words', nargs='+', help='words to say') @@ -75,29 +70,14 @@ class CmdLineApp(cmd2.Cmd): words.append(word) repetitions = args.repeat or 1 - output_str = ansi.style(' '.join(words), fg=args.fg, bg=args.bg, bold=args.bold, underline=args.underline) + + fg_color = StdFg[args.fg.upper()] if args.fg else None + bg_color = StdBg[args.bg.upper()] if args.bg else None + output_str = ansi.style(' '.join(words), fg=fg_color, bg=bg_color, bold=args.bold, underline=args.underline) for _ in range(min(repetitions, self.maxrepeats)): # .poutput handles newlines, and accommodates output redirection too self.poutput(output_str) - self.perror('error message at the end') - - # noinspection PyMethodMayBeStatic - def perror(self, msg: Any = '', *, end: str = '\n', apply_style: bool = True) -> None: - """Override perror() method from `cmd2.Cmd` - - Use colorama native approach for styling the text instead of `cmd2.ansi` methods - - :param msg: message to print (anything convertible to a str with '{}'.format() is OK) - :param end: string appended after the end of the message, default a newline - :param apply_style: If True, then ansi.style_error will be applied to the message text. Set to False in cases - where the message text already has the desired style. Defaults to True. - """ - if apply_style: - final_msg = "{}{}{}{}".format(Fore.RED, Back.YELLOW, msg, Style.RESET_ALL) - else: - final_msg = "{}".format(msg) - ansi.style_aware_write(sys.stderr, final_msg + end) def do_timetravel(self, _): """A command which always generates an error message, to demonstrate custom error colors""" diff --git a/examples/initialization.py b/examples/initialization.py index dfea2183..375711ff 100755 --- a/examples/initialization.py +++ b/examples/initialization.py @@ -14,8 +14,8 @@ """ import cmd2 from cmd2 import ( - bg, - fg, + StdBg, + StdFg, style, ) @@ -32,7 +32,7 @@ class BasicApp(cmd2.Cmd): ) # Prints an intro banner once upon application startup - self.intro = style('Welcome to cmd2!', fg=fg.red, bg=bg.white, bold=True) + self.intro = style('Welcome to cmd2!', fg=StdFg.RED, bg=StdBg.WHITE, bold=True) # Show this as the prompt when asking for input self.prompt = 'myapp> ' @@ -47,11 +47,12 @@ class BasicApp(cmd2.Cmd): self.default_category = 'cmd2 Built-in Commands' # Color to output text in with echo command - self.foreground_color = 'cyan' + self.foreground_color = StdFg.CYAN.name.lower() # Make echo_fg settable at runtime + fg_colors = [c.name.lower() for c in StdFg] self.add_settable( - cmd2.Settable('foreground_color', str, 'Foreground color to use with echo command', self, choices=fg.colors()) + cmd2.Settable('foreground_color', str, 'Foreground color to use with echo command', self, choices=fg_colors) ) @cmd2.with_category(CUSTOM_CATEGORY) @@ -62,7 +63,8 @@ class BasicApp(cmd2.Cmd): @cmd2.with_category(CUSTOM_CATEGORY) def do_echo(self, arg): """Example of a multiline command""" - self.poutput(style(arg, fg=self.foreground_color)) + fg_color = StdFg[self.foreground_color.upper()] + self.poutput(style(arg, fg=fg_color)) if __name__ == '__main__': diff --git a/examples/pirate.py b/examples/pirate.py index 2de832eb..437ee07b 100755 --- a/examples/pirate.py +++ b/examples/pirate.py @@ -8,11 +8,15 @@ It demonstrates many features of cmd2. """ import cmd2 -import cmd2.ansi +from cmd2 import ( + StdFg, +) from cmd2.constants import ( MULTILINE_TERMINATOR, ) +color_choices = [c.name.lower() for c in StdFg] + class Pirate(cmd2.Cmd): """A piratical example cmd2 application involving looting and drinking.""" @@ -27,7 +31,7 @@ class Pirate(cmd2.Cmd): self.songcolor = 'blue' # Make songcolor settable at runtime - self.add_settable(cmd2.Settable('songcolor', str, 'Color to ``sing``', self, choices=cmd2.ansi.fg.colors())) + self.add_settable(cmd2.Settable('songcolor', str, 'Color to ``sing``', self, choices=color_choices)) # prompts and defaults self.gold = 0 @@ -72,7 +76,7 @@ class Pirate(cmd2.Cmd): def do_sing(self, arg): """Sing a colorful song.""" - self.poutput(cmd2.ansi.style(arg, fg=self.songcolor)) + self.poutput(cmd2.ansi.style(arg, fg=StdFg[self.songcolor.upper()])) yo_parser = cmd2.Cmd2ArgumentParser() yo_parser.add_argument('--ho', type=int, default=2, help="How often to chant 'ho'") diff --git a/examples/plumbum_colors.py b/examples/plumbum_colors.py deleted file mode 100755 index 6b0625f7..00000000 --- a/examples/plumbum_colors.py +++ /dev/null @@ -1,123 +0,0 @@ -#!/usr/bin/env python -# coding=utf-8 -""" -A sample application for cmd2. Demonstrating colorized output using the plumbum package. - -Experiment with the command line options on the `speak` command to see how -different output colors ca - -The allow_style setting has three possible values: - -Never - poutput(), pfeedback(), and ppaged() strip all ANSI style sequences - which instruct the terminal to colorize output - -Terminal - (the default value) poutput(), pfeedback(), and ppaged() do not strip any - ANSI style sequences when the output is a terminal, but if the output is - a pipe or a file the style sequences are stripped. If you want colorized - output you must add ANSI style sequences using either cmd2's internal ansi - module or another color library such as `plumbum.colors` or `colorama`. - -Always - poutput(), pfeedback(), and ppaged() never strip ANSI style sequences, - regardless of the output destination - -WARNING: This example requires the plumbum package, which isn't normally required by cmd2. -""" - -from plumbum.colors import ( - bg, - fg, -) - -import cmd2 -from cmd2 import ( - ansi, -) - - -class FgColors(ansi.ColorBase): - black = fg.Black - red = fg.DarkRedA - green = fg.MediumSpringGreen - yellow = fg.LightYellow - blue = fg.RoyalBlue1 - magenta = fg.Purple - cyan = fg.SkyBlue1 - white = fg.White - purple = fg.Purple - - -class BgColors(ansi.ColorBase): - black = bg.BLACK - red = bg.DarkRedA - green = bg.MediumSpringGreen - yellow = bg.LightYellow - blue = bg.RoyalBlue1 - magenta = bg.Purple - cyan = bg.SkyBlue1 - white = bg.White - purple = bg.Purple - - -def get_fg(name: str) -> str: - return str(FgColors[name]) - - -def get_bg(name: str) -> str: - return str(BgColors[name]) - - -ansi.fg_lookup = get_fg -ansi.bg_lookup = get_bg - - -class CmdLineApp(cmd2.Cmd): - """Example cmd2 application demonstrating colorized output.""" - - def __init__(self): - # Set include_ipy to True to enable the "ipy" command which runs an interactive IPython shell - super().__init__(include_ipy=True) - - self.maxrepeats = 3 - # Make maxrepeats settable at runtime - self.add_settable(cmd2.Settable('maxrepeats', int, 'max repetitions for speak command', self)) - - # Should ANSI color output be allowed - self.allow_style = ansi.STYLE_TERMINAL - - speak_parser = cmd2.Cmd2ArgumentParser() - speak_parser.add_argument('-p', '--piglatin', action='store_true', help='atinLay') - speak_parser.add_argument('-s', '--shout', action='store_true', help='N00B EMULATION MODE') - speak_parser.add_argument('-r', '--repeat', type=int, help='output [n] times') - speak_parser.add_argument('-f', '--fg', choices=FgColors.colors(), help='foreground color to apply to output') - speak_parser.add_argument('-b', '--bg', choices=BgColors.colors(), help='background color to apply to output') - speak_parser.add_argument('-l', '--bold', action='store_true', help='bold the output') - speak_parser.add_argument('-u', '--underline', action='store_true', help='underline the output') - speak_parser.add_argument('words', nargs='+', help='words to say') - - @cmd2.with_argparser(speak_parser) - def do_speak(self, args): - """Repeats what you tell me to.""" - words = [] - for word in args.words: - if args.piglatin: - word = '%s%say' % (word[1:], word[0]) - if args.shout: - word = word.upper() - words.append(word) - - repetitions = args.repeat or 1 - output_str = ansi.style(' '.join(words), fg=args.fg, bg=args.bg, bold=args.bold, underline=args.underline) - - for _ in range(min(repetitions, self.maxrepeats)): - # .poutput handles newlines, and accommodates output redirection too - self.poutput(output_str) - - -if __name__ == '__main__': - import sys - - c = CmdLineApp() - sys.exit(c.cmdloop()) diff --git a/examples/table_creation.py b/examples/table_creation.py index ff72311a..27045525 100755 --- a/examples/table_creation.py +++ b/examples/table_creation.py @@ -9,6 +9,7 @@ from typing import ( ) from cmd2 import ( + StdFg, ansi, ) from cmd2.table_creator import ( @@ -32,9 +33,9 @@ class DollarFormatter: # Text styles used in the data -bold_yellow = functools.partial(ansi.style, fg=ansi.fg.bright_yellow, bold=True) -blue = functools.partial(ansi.style, fg=ansi.fg.bright_blue) -green = functools.partial(ansi.style, fg=ansi.fg.green) +bold_yellow = functools.partial(ansi.style, fg=StdFg.LIGHT_YELLOW, bold=True) +blue = functools.partial(ansi.style, fg=StdFg.LIGHT_BLUE) +green = functools.partial(ansi.style, fg=StdFg.GREEN) # Table Columns (width does not account for any borders or padding which may be added) columns: List[Column] = list() @@ -71,7 +72,7 @@ def ansi_print(text): def main(): # Default to terminal mode so redirecting to a file won't include the ANSI style sequences - ansi.allow_style = ansi.STYLE_TERMINAL + ansi.allow_style = ansi.AllowStyle.TERMINAL st = SimpleTable(columns) table = st.generate_table(data_list) @@ -44,7 +44,6 @@ SETUP_REQUIRES = ['setuptools >= 34.4', 'setuptools_scm >= 3.0'] INSTALL_REQUIRES = [ 'attrs >= 16.3.0', - 'colorama >= 0.3.7', 'importlib_metadata>=1.6.0;python_version<"3.8"', 'pyperclip >= 1.6', 'typing_extensions; python_version<"3.8"', diff --git a/tests/conftest.py b/tests/conftest.py index 0829da2f..de74de46 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -109,7 +109,7 @@ SET_TXT = ( "Name Value Description \n" "==================================================================================================================\n" "allow_style Terminal Allow ANSI text style sequences in output (valid values: \n" - " Terminal, Always, Never) \n" + " Always, Never, Terminal) \n" "always_show_hint False Display tab completion hint even when completion suggestions\n" " print \n" "debug False Show full traceback on exception \n" diff --git a/tests/test_ansi.py b/tests/test_ansi.py index 1797a047..307d9ad7 100644 --- a/tests/test_ansi.py +++ b/tests/test_ansi.py @@ -5,21 +5,23 @@ Unit testing for cmd2/ansi.py module """ import pytest -import cmd2.ansi as ansi +from cmd2 import ( + ansi, +) HELLO_WORLD = 'Hello, world!' def test_strip_style(): base_str = HELLO_WORLD - ansi_str = ansi.style(base_str, fg='green') + ansi_str = ansi.style(base_str, fg=ansi.StdFg.GREEN) assert base_str != ansi_str assert base_str == ansi.strip_style(ansi_str) def test_style_aware_wcswidth(): base_str = HELLO_WORLD - ansi_str = ansi.style(base_str, fg='green') + ansi_str = ansi.style(base_str, fg=ansi.StdFg.GREEN) assert ansi.style_aware_wcswidth(HELLO_WORLD) == ansi.style_aware_wcswidth(ansi_str) assert ansi.style_aware_wcswidth('i have a tab\t') == -1 @@ -27,7 +29,7 @@ def test_style_aware_wcswidth(): def test_widest_line(): - text = ansi.style('i have\n3 lines\nThis is the longest one', fg='green') + text = ansi.style('i have\n3 lines\nThis is the longest one', fg=ansi.StdFg.GREEN) assert ansi.widest_line(text) == ansi.style_aware_wcswidth("This is the longest one") text = "I'm just one line" @@ -42,99 +44,111 @@ def test_style_none(): assert ansi.style(base_str) == ansi_str -def test_style_fg(): +@pytest.mark.parametrize('fg_color', [ansi.StdFg.BLUE, ansi.EightBitFg.AQUAMARINE_1A, ansi.RgbFg(0, 2, 4)]) +def test_style_fg(fg_color): base_str = HELLO_WORLD - fg_color = 'blue' - ansi_str = ansi.fg[fg_color].value + base_str + ansi.FG_RESET + ansi_str = fg_color + base_str + ansi.StdFg.RESET assert ansi.style(base_str, fg=fg_color) == ansi_str -def test_style_bg(): +@pytest.mark.parametrize('bg_color', [ansi.StdBg.BLUE, ansi.EightBitBg.AQUAMARINE_1A, ansi.RgbBg(0, 2, 4)]) +def test_style_bg(bg_color): base_str = HELLO_WORLD - bg_color = 'green' - ansi_str = ansi.bg[bg_color].value + base_str + ansi.BG_RESET + ansi_str = bg_color + base_str + ansi.StdBg.RESET assert ansi.style(base_str, bg=bg_color) == ansi_str def test_style_bold(): base_str = HELLO_WORLD - ansi_str = ansi.INTENSITY_BRIGHT + base_str + ansi.INTENSITY_NORMAL + ansi_str = ansi.TextStyle.INTENSITY_BOLD + base_str + ansi.TextStyle.INTENSITY_NORMAL assert ansi.style(base_str, bold=True) == ansi_str def test_style_dim(): base_str = HELLO_WORLD - ansi_str = ansi.INTENSITY_DIM + base_str + ansi.INTENSITY_NORMAL + ansi_str = ansi.TextStyle.INTENSITY_DIM + base_str + ansi.TextStyle.INTENSITY_NORMAL assert ansi.style(base_str, dim=True) == ansi_str -def test_style_underline(): +def test_style_italic(): base_str = HELLO_WORLD - ansi_str = ansi.UNDERLINE_ENABLE + base_str + ansi.UNDERLINE_DISABLE - assert ansi.style(base_str, underline=True) == ansi_str + ansi_str = ansi.TextStyle.ITALIC_ENABLE + base_str + ansi.TextStyle.ITALIC_DISABLE + assert ansi.style(base_str, italic=True) == ansi_str -def test_style_multi(): +def test_style_overline(): base_str = HELLO_WORLD - fg_color = 'blue' - bg_color = 'green' - ansi_str = ( - ansi.fg[fg_color].value - + ansi.bg[bg_color].value - + ansi.INTENSITY_BRIGHT - + ansi.INTENSITY_DIM - + ansi.UNDERLINE_ENABLE - + base_str - + ansi.FG_RESET - + ansi.BG_RESET - + ansi.INTENSITY_NORMAL - + ansi.INTENSITY_NORMAL - + ansi.UNDERLINE_DISABLE - ) - assert ansi.style(base_str, fg=fg_color, bg=bg_color, bold=True, dim=True, underline=True) == ansi_str + ansi_str = ansi.TextStyle.OVERLINE_ENABLE + base_str + ansi.TextStyle.OVERLINE_DISABLE + assert ansi.style(base_str, overline=True) == ansi_str -def test_style_color_not_exist(): +def test_style_strikethrough(): base_str = HELLO_WORLD + ansi_str = ansi.TextStyle.STRIKETHROUGH_ENABLE + base_str + ansi.TextStyle.STRIKETHROUGH_DISABLE + assert ansi.style(base_str, strikethrough=True) == ansi_str - with pytest.raises(ValueError): - ansi.style(base_str, fg='fake', bg='green') - - with pytest.raises(ValueError): - ansi.style(base_str, fg='blue', bg='fake') - - -def test_fg_lookup_exist(): - fg_color = 'green' - assert ansi.fg_lookup(fg_color) == ansi.fg_lookup(ansi.fg.green) - -def test_fg_lookup_nonexist(): - with pytest.raises(ValueError): - ansi.fg_lookup('foo') - - -def test_bg_lookup_exist(): - bg_color = 'red' - assert ansi.bg_lookup(bg_color) == ansi.bg_lookup(ansi.bg.red) +def test_style_underline(): + base_str = HELLO_WORLD + ansi_str = ansi.TextStyle.UNDERLINE_ENABLE + base_str + ansi.TextStyle.UNDERLINE_DISABLE + assert ansi.style(base_str, underline=True) == ansi_str -def test_bg_lookup_nonexist(): - with pytest.raises(ValueError): - ansi.bg_lookup('bar') +def test_style_multi(): + base_str = HELLO_WORLD + fg_color = ansi.StdFg.LIGHT_BLUE + bg_color = ansi.StdBg.LIGHT_GRAY + ansi_str = ( + fg_color + + bg_color + + ansi.TextStyle.INTENSITY_BOLD + + ansi.TextStyle.INTENSITY_DIM + + ansi.TextStyle.ITALIC_ENABLE + + ansi.TextStyle.OVERLINE_ENABLE + + ansi.TextStyle.STRIKETHROUGH_ENABLE + + ansi.TextStyle.UNDERLINE_ENABLE + + base_str + + ansi.StdFg.RESET + + ansi.StdBg.RESET + + ansi.TextStyle.INTENSITY_NORMAL + + ansi.TextStyle.INTENSITY_NORMAL + + ansi.TextStyle.ITALIC_DISABLE + + ansi.TextStyle.OVERLINE_DISABLE + + ansi.TextStyle.STRIKETHROUGH_DISABLE + + ansi.TextStyle.UNDERLINE_DISABLE + ) + assert ( + ansi.style( + base_str, + fg=fg_color, + bg=bg_color, + bold=True, + dim=True, + italic=True, + overline=True, + strikethrough=True, + underline=True, + ) + == ansi_str + ) -def test_set_title_str(): - OSC = '\033]' - BEL = '\007' +def test_set_title(): title = HELLO_WORLD - assert ansi.set_title_str(title) == OSC + '2;' + title + BEL + assert ansi.set_title(title) == ansi.OSC + '2;' + title + ansi.BEL @pytest.mark.parametrize( 'cols, prompt, line, cursor, msg, expected', [ - (127, '(Cmd) ', 'help his', 12, ansi.style('Hello World!', fg='magenta'), '\x1b[2K\r\x1b[35mHello World!\x1b[39m'), + ( + 127, + '(Cmd) ', + 'help his', + 12, + ansi.style('Hello World!', fg=ansi.StdFg.MAGENTA), + '\x1b[2K\r\x1b[35mHello World!\x1b[39m', + ), (127, '\n(Cmd) ', 'help ', 5, 'foo', '\x1b[2K\x1b[1A\x1b[2K\rfoo'), ( 10, @@ -151,40 +165,83 @@ def test_async_alert_str(cols, prompt, line, cursor, msg, expected): assert alert_str == expected -def test_cast_color_as_str(): - assert str(ansi.fg.blue) == ansi.fg.blue.value - assert str(ansi.bg.blue) == ansi.bg.blue.value +def test_clear_screen(): + clear_type = 2 + assert ansi.clear_screen(clear_type) == f"{ansi.CSI}{clear_type}J" + clear_type = -1 + with pytest.raises(ValueError): + ansi.clear_screen(clear_type) -def test_color_str_building(): - from cmd2.ansi import ( - bg, - fg, - ) + clear_type = 4 + with pytest.raises(ValueError): + ansi.clear_screen(clear_type) - assert fg.blue + "hello" == fg.blue.value + "hello" - assert bg.blue + "hello" == bg.blue.value + "hello" - assert fg.blue + "hello" + fg.reset == fg.blue.value + "hello" + fg.reset.value - assert bg.blue + "hello" + bg.reset == bg.blue.value + "hello" + bg.reset.value - assert ( - fg.blue + bg.white + "hello" + fg.reset + bg.reset - == fg.blue.value + bg.white.value + "hello" + fg.reset.value + bg.reset.value - ) +def test_clear_line(): + clear_type = 2 + assert ansi.clear_line(clear_type) == f"{ansi.CSI}{clear_type}K" + + clear_type = -1 + with pytest.raises(ValueError): + ansi.clear_line(clear_type) + + clear_type = 3 + with pytest.raises(ValueError): + ansi.clear_line(clear_type) -def test_color_nonunique_values(): - class Matching(ansi.ColorBase): - magenta = ansi.fg_lookup('magenta') - purple = ansi.fg_lookup('magenta') - assert sorted(Matching.colors()) == ['magenta', 'purple'] +def test_cursor(): + count = 1 + assert ansi.Cursor.UP(count) == f"{ansi.CSI}{count}A" + assert ansi.Cursor.DOWN(count) == f"{ansi.CSI}{count}B" + assert ansi.Cursor.FORWARD(count) == f"{ansi.CSI}{count}C" + assert ansi.Cursor.BACK(count) == f"{ansi.CSI}{count}D" + x = 4 + y = 5 + assert ansi.Cursor.SET_POS(x, y) == f"{ansi.CSI}{y};{x}H" -def test_color_enum(): - assert ansi.fg_lookup('bright_red') == ansi.fg_lookup(ansi.fg.bright_red) - assert ansi.bg_lookup('green') == ansi.bg_lookup(ansi.bg.green) + +@pytest.mark.parametrize( + 'ansi_sequence', + [ + ansi.fg.green, + ansi.bg.blue, + ansi.StdFg.MAGENTA, + ansi.StdBg.LIGHT_GRAY, + ansi.EightBitBg.CHARTREUSE_2A, + ansi.EightBitBg.MEDIUM_PURPLE, + ansi.RgbFg(0, 5, 22), + ansi.RgbBg(100, 150, 222), + ansi.TextStyle.OVERLINE_ENABLE, + ], +) +def test_sequence_str_building(ansi_sequence): + """This tests __add__(), __radd__(), and __str__() methods for AnsiSequences""" + assert ansi_sequence + ansi_sequence == str(ansi_sequence) + str(ansi_sequence) -def test_colors_list(): - assert list(ansi.fg.__members__.keys()) == ansi.fg.colors() - assert list(ansi.bg.__members__.keys()) == ansi.bg.colors() +@pytest.mark.parametrize( + 'r, g, b, valid', + [ + (0, 0, 0, True), + (255, 255, 255, True), + (-1, 0, 0, False), + (256, 255, 255, False), + (0, -1, 0, False), + (255, 256, 255, False), + (0, 0, -1, False), + (255, 255, 256, False), + ], +) +def test_rgb_bounds(r, g, b, valid): + + if valid: + ansi.RgbFg(r, g, b) + ansi.RgbBg(r, g, b) + else: + with pytest.raises(ValueError): + ansi.RgbFg(r, g, b) + with pytest.raises(ValueError): + ansi.RgbBg(r, g, b) diff --git a/tests/test_cmd2.py b/tests/test_cmd2.py index 0f022849..45e07603 100755 --- a/tests/test_cmd2.py +++ b/tests/test_cmd2.py @@ -198,18 +198,18 @@ def test_set_no_settables(base_app): @pytest.mark.parametrize( 'new_val, is_valid, expected', [ - (ansi.STYLE_NEVER, True, ansi.STYLE_NEVER), - ('neVeR', True, ansi.STYLE_NEVER), - (ansi.STYLE_TERMINAL, True, ansi.STYLE_TERMINAL), - ('TeRMInal', True, ansi.STYLE_TERMINAL), - (ansi.STYLE_ALWAYS, True, ansi.STYLE_ALWAYS), - ('AlWaYs', True, ansi.STYLE_ALWAYS), - ('invalid', False, ansi.STYLE_TERMINAL), + (ansi.AllowStyle.NEVER, True, ansi.AllowStyle.NEVER), + ('neVeR', True, ansi.AllowStyle.NEVER), + (ansi.AllowStyle.TERMINAL, True, ansi.AllowStyle.TERMINAL), + ('TeRMInal', True, ansi.AllowStyle.TERMINAL), + (ansi.AllowStyle.ALWAYS, True, ansi.AllowStyle.ALWAYS), + ('AlWaYs', True, ansi.AllowStyle.ALWAYS), + ('invalid', False, ansi.AllowStyle.TERMINAL), ], ) def test_set_allow_style(base_app, new_val, is_valid, expected): # Initialize allow_style for this test - ansi.allow_style = ansi.STYLE_TERMINAL + ansi.allow_style = ansi.AllowStyle.TERMINAL # Use the set command to alter it out, err = run_cmd(base_app, 'set allow_style {}'.format(new_val)) @@ -219,10 +219,29 @@ def test_set_allow_style(base_app, new_val, is_valid, expected): assert ansi.allow_style == expected if is_valid: assert not err - assert "now: {!r}".format(new_val.capitalize()) in out[1] + assert out # Reset allow_style to its default since it's an application-wide setting that can affect other unit tests - ansi.allow_style = ansi.STYLE_TERMINAL + ansi.allow_style = ansi.AllowStyle.TERMINAL + + +def test_set_with_choices(base_app): + """Test choices validation of Settables""" + fake_choices = ['valid', 'choices'] + base_app.fake = fake_choices[0] + + fake_settable = cmd2.Settable('fake', type(base_app.fake), "fake description", base_app, choices=fake_choices) + base_app.add_settable(fake_settable) + + # Try a valid choice + out, err = run_cmd(base_app, f'set fake {fake_choices[1]}') + assert base_app.last_result is True + assert not err + + # Try an invalid choice + out, err = run_cmd(base_app, 'set fake bad_value') + assert base_app.last_result is False + assert err[0].startswith("Error setting fake: invalid choice") class OnChangeHookApp(cmd2.Cmd): @@ -1031,7 +1050,7 @@ def test_escaping_prompt(): assert rl_escape_prompt(prompt) == prompt # This prompt has color which needs to be escaped - color = 'cyan' + color = ansi.StdFg.CYAN prompt = ansi.style('InColor', fg=color) escape_start = "\x01" @@ -1042,8 +1061,8 @@ def test_escaping_prompt(): # PyReadline on Windows doesn't need to escape invisible characters assert escaped_prompt == prompt else: - assert escaped_prompt.startswith(escape_start + ansi.fg_lookup(color) + escape_end) - assert escaped_prompt.endswith(escape_start + ansi.FG_RESET + escape_end) + assert escaped_prompt.startswith(escape_start + color + escape_end) + assert escaped_prompt.endswith(escape_start + ansi.StdFg.RESET + escape_end) assert rl_unescape_prompt(escaped_prompt) == prompt @@ -1743,8 +1762,8 @@ def test_poutput_none(outsim_app): def test_poutput_ansi_always(outsim_app): msg = 'Hello World' - ansi.allow_style = ansi.STYLE_ALWAYS - colored_msg = ansi.style(msg, fg='cyan') + ansi.allow_style = ansi.AllowStyle.ALWAYS + colored_msg = ansi.style(msg, fg=ansi.StdFg.CYAN) outsim_app.poutput(colored_msg) out = outsim_app.stdout.getvalue() expected = colored_msg + '\n' @@ -1754,8 +1773,8 @@ def test_poutput_ansi_always(outsim_app): def test_poutput_ansi_never(outsim_app): msg = 'Hello World' - ansi.allow_style = ansi.STYLE_NEVER - colored_msg = ansi.style(msg, fg='cyan') + ansi.allow_style = ansi.AllowStyle.NEVER + colored_msg = ansi.style(msg, fg=ansi.StdFg.CYAN) outsim_app.poutput(colored_msg) out = outsim_app.stdout.getvalue() expected = msg + '\n' @@ -2182,7 +2201,7 @@ def test_nonexistent_macro(base_app): def test_perror_style(base_app, capsys): msg = 'testing...' end = '\n' - ansi.allow_style = ansi.STYLE_ALWAYS + ansi.allow_style = ansi.AllowStyle.ALWAYS base_app.perror(msg) out, err = capsys.readouterr() assert err == ansi.style_error(msg) + end @@ -2191,7 +2210,7 @@ def test_perror_style(base_app, capsys): def test_perror_no_style(base_app, capsys): msg = 'testing...' end = '\n' - ansi.allow_style = ansi.STYLE_ALWAYS + ansi.allow_style = ansi.AllowStyle.ALWAYS base_app.perror(msg, apply_style=False) out, err = capsys.readouterr() assert err == msg + end @@ -2200,7 +2219,7 @@ def test_perror_no_style(base_app, capsys): def test_pwarning_style(base_app, capsys): msg = 'testing...' end = '\n' - ansi.allow_style = ansi.STYLE_ALWAYS + ansi.allow_style = ansi.AllowStyle.ALWAYS base_app.pwarning(msg) out, err = capsys.readouterr() assert err == ansi.style_warning(msg) + end @@ -2209,7 +2228,7 @@ def test_pwarning_style(base_app, capsys): def test_pwarning_no_style(base_app, capsys): msg = 'testing...' end = '\n' - ansi.allow_style = ansi.STYLE_ALWAYS + ansi.allow_style = ansi.AllowStyle.ALWAYS base_app.pwarning(msg, apply_style=False) out, err = capsys.readouterr() assert err == msg + end @@ -2217,7 +2236,7 @@ def test_pwarning_no_style(base_app, capsys): def test_pexcept_style(base_app, capsys): msg = Exception('testing...') - ansi.allow_style = ansi.STYLE_ALWAYS + ansi.allow_style = ansi.AllowStyle.ALWAYS base_app.pexcept(msg) out, err = capsys.readouterr() @@ -2226,7 +2245,7 @@ def test_pexcept_style(base_app, capsys): def test_pexcept_no_style(base_app, capsys): msg = Exception('testing...') - ansi.allow_style = ansi.STYLE_ALWAYS + ansi.allow_style = ansi.AllowStyle.ALWAYS base_app.pexcept(msg, apply_style=False) out, err = capsys.readouterr() @@ -2236,7 +2255,7 @@ def test_pexcept_no_style(base_app, capsys): def test_pexcept_not_exception(base_app, capsys): # Pass in a msg that is not an Exception object msg = False - ansi.allow_style = ansi.STYLE_ALWAYS + ansi.allow_style = ansi.AllowStyle.ALWAYS base_app.pexcept(msg) out, err = capsys.readouterr() @@ -2268,9 +2287,9 @@ def test_ppaged_none(outsim_app): def test_ppaged_strips_ansi_when_redirecting(outsim_app): msg = 'testing...' end = '\n' - ansi.allow_style = ansi.STYLE_TERMINAL + ansi.allow_style = ansi.AllowStyle.TERMINAL outsim_app._redirecting = True - outsim_app.ppaged(ansi.style(msg, fg='red')) + outsim_app.ppaged(ansi.style(msg, fg=ansi.StdFg.RED)) out = outsim_app.stdout.getvalue() assert out == msg + end @@ -2278,9 +2297,9 @@ def test_ppaged_strips_ansi_when_redirecting(outsim_app): def test_ppaged_strips_ansi_when_redirecting_if_always(outsim_app): msg = 'testing...' end = '\n' - ansi.allow_style = ansi.STYLE_ALWAYS + ansi.allow_style = ansi.AllowStyle.ALWAYS outsim_app._redirecting = True - colored_msg = ansi.style(msg, fg='red') + colored_msg = ansi.style(msg, fg=ansi.StdFg.RED) outsim_app.ppaged(colored_msg) out = outsim_app.stdout.getvalue() assert out == colored_msg + end @@ -2464,14 +2483,14 @@ class AnsiApp(cmd2.Cmd): self.perror(args) def do_echo_error(self, args): - self.poutput(ansi.style(args, fg='red')) + self.poutput(ansi.style(args, fg=ansi.StdFg.RED)) # perror uses colors by default self.perror(args) def test_ansi_pouterr_always_tty(mocker, capsys): app = AnsiApp() - ansi.allow_style = ansi.STYLE_ALWAYS + ansi.allow_style = ansi.AllowStyle.ALWAYS mocker.patch.object(app.stdout, 'isatty', return_value=True) mocker.patch.object(sys.stderr, 'isatty', return_value=True) @@ -2494,7 +2513,7 @@ def test_ansi_pouterr_always_tty(mocker, capsys): def test_ansi_pouterr_always_notty(mocker, capsys): app = AnsiApp() - ansi.allow_style = ansi.STYLE_ALWAYS + ansi.allow_style = ansi.AllowStyle.ALWAYS mocker.patch.object(app.stdout, 'isatty', return_value=False) mocker.patch.object(sys.stderr, 'isatty', return_value=False) @@ -2517,7 +2536,7 @@ def test_ansi_pouterr_always_notty(mocker, capsys): def test_ansi_terminal_tty(mocker, capsys): app = AnsiApp() - ansi.allow_style = ansi.STYLE_TERMINAL + ansi.allow_style = ansi.AllowStyle.TERMINAL mocker.patch.object(app.stdout, 'isatty', return_value=True) mocker.patch.object(sys.stderr, 'isatty', return_value=True) @@ -2539,7 +2558,7 @@ def test_ansi_terminal_tty(mocker, capsys): def test_ansi_terminal_notty(mocker, capsys): app = AnsiApp() - ansi.allow_style = ansi.STYLE_TERMINAL + ansi.allow_style = ansi.AllowStyle.TERMINAL mocker.patch.object(app.stdout, 'isatty', return_value=False) mocker.patch.object(sys.stderr, 'isatty', return_value=False) @@ -2554,7 +2573,7 @@ def test_ansi_terminal_notty(mocker, capsys): def test_ansi_never_tty(mocker, capsys): app = AnsiApp() - ansi.allow_style = ansi.STYLE_NEVER + ansi.allow_style = ansi.AllowStyle.NEVER mocker.patch.object(app.stdout, 'isatty', return_value=True) mocker.patch.object(sys.stderr, 'isatty', return_value=True) @@ -2569,7 +2588,7 @@ def test_ansi_never_tty(mocker, capsys): def test_ansi_never_notty(mocker, capsys): app = AnsiApp() - ansi.allow_style = ansi.STYLE_NEVER + ansi.allow_style = ansi.AllowStyle.NEVER mocker.patch.object(app.stdout, 'isatty', return_value=False) mocker.patch.object(sys.stderr, 'isatty', return_value=False) diff --git a/tests/test_completion.py b/tests/test_completion.py index c61a0eec..2eebaaeb 100755 --- a/tests/test_completion.py +++ b/tests/test_completion.py @@ -271,6 +271,34 @@ def test_cmd2_help_completion_nomatch(cmd2_app): assert first_match is None +def test_set_allow_style_completion(cmd2_app): + """Confirm that completing allow_style presents AllowStyle strings""" + text = '' + line = 'set allow_style'.format(text) + endidx = len(line) + begidx = endidx - len(text) + + expected = [val.name.lower() for val in cmd2.ansi.AllowStyle] + + first_match = complete_tester(text, line, begidx, endidx, cmd2_app) + assert first_match + assert cmd2_app.completion_matches == sorted(expected, key=cmd2_app.default_sort_key) + + +def test_set_bool_completion(cmd2_app): + """Confirm that completing a boolean Settable presents true and false strings""" + text = '' + line = 'set debug'.format(text) + endidx = len(line) + begidx = endidx - len(text) + + expected = ['false', 'true'] + + first_match = complete_tester(text, line, begidx, endidx, cmd2_app) + assert first_match + assert cmd2_app.completion_matches == sorted(expected, key=cmd2_app.default_sort_key) + + def test_shell_command_completion_shortcut(cmd2_app): # Made sure ! runs a shell command and all matches start with ! since there # isn't a space between ! and the shell command. Display matches won't diff --git a/tests/test_table_creator.py b/tests/test_table_creator.py index 5d8fefe9..33f36984 100644 --- a/tests/test_table_creator.py +++ b/tests/test_table_creator.py @@ -6,6 +6,9 @@ Unit testing for cmd2/table_creator.py module import pytest from cmd2 import ( + StdBg, + StdFg, + TextStyle, ansi, ) from cmd2.table_creator import ( @@ -45,7 +48,7 @@ def test_column_creation(): assert tc.cols[0].width == 1 # No width specified, label isn't blank but has no width - c = Column(ansi.style('', fg=ansi.fg.green)) + c = Column(ansi.style('', fg=StdFg.GREEN)) assert c.width < 0 tc = TableCreator([c]) assert tc.cols[0].width == 1 @@ -229,25 +232,25 @@ def test_wrap_long_word(): row_data = list() # Long word should start on the first line (style should not affect width) - row_data.append(ansi.style("LongerThan10", fg=ansi.fg.green)) + row_data.append(ansi.style("LongerThan10", fg=StdFg.GREEN)) # Long word should start on the second line row_data.append("Word LongerThan10") row = tc.generate_row(row_data=row_data) expected = ( - ansi.RESET_ALL - + ansi.fg.green + TextStyle.RESET_ALL + + StdFg.GREEN + "LongerThan" - + ansi.RESET_ALL + + TextStyle.RESET_ALL + " Word \n" - + ansi.RESET_ALL - + ansi.fg.green + + TextStyle.RESET_ALL + + StdFg.GREEN + "10" - + ansi.fg.reset - + ansi.RESET_ALL + + StdFg.RESET + + TextStyle.RESET_ALL + ' ' - + ansi.RESET_ALL + + TextStyle.RESET_ALL + ' LongerThan\n' ' 10 ' ) @@ -598,7 +601,7 @@ def test_alternating_table_creation(): ) # Other bg colors - at = AlternatingTable([column_1, column_2], bg_odd=ansi.bg.bright_blue, bg_even=ansi.bg.green) + at = AlternatingTable([column_1, column_2], bg_odd=StdBg.LIGHT_BLUE, bg_even=StdBg.GREEN) table = at.generate_table(row_data) assert table == ( '╔═════════════════╤═════════════════╗\n' diff --git a/tests/test_utils.py b/tests/test_utils.py index c14c2f07..18be61c8 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -393,11 +393,12 @@ def test_truncate_line_tabs(): def test_truncate_with_style(): from cmd2 import ( - ansi, + StdFg, + TextStyle, ) - before_style = ansi.fg.blue + ansi.UNDERLINE_ENABLE - after_style = ansi.fg.reset + ansi.UNDERLINE_DISABLE + before_style = StdFg.BLUE + TextStyle.UNDERLINE_ENABLE + after_style = StdFg.RESET + TextStyle.UNDERLINE_DISABLE # Style only before truncated text line = before_style + 'long' @@ -428,46 +429,48 @@ def test_align_text_fill_char_is_tab(): def test_align_text_with_style(): from cmd2 import ( - ansi, + StdFg, + TextStyle, + style, ) # Single line with only left fill - text = ansi.style('line1', fg=ansi.fg.bright_blue) - fill_char = ansi.style('-', fg=ansi.fg.bright_yellow) + text = style('line1', fg=StdFg.LIGHT_BLUE) + fill_char = style('-', fg=StdFg.LIGHT_YELLOW) width = 6 aligned = cu.align_text(text, cu.TextAlignment.RIGHT, fill_char=fill_char, width=width) - left_fill = ansi.RESET_ALL + fill_char + ansi.RESET_ALL - right_fill = ansi.RESET_ALL - line_1_text = ansi.fg.bright_blue + 'line1' + ansi.FG_RESET + left_fill = TextStyle.RESET_ALL + fill_char + TextStyle.RESET_ALL + right_fill = TextStyle.RESET_ALL + line_1_text = StdFg.LIGHT_BLUE + 'line1' + StdFg.RESET assert aligned == (left_fill + line_1_text + right_fill) # Single line with only right fill - text = ansi.style('line1', fg=ansi.fg.bright_blue) - fill_char = ansi.style('-', fg=ansi.fg.bright_yellow) + text = style('line1', fg=StdFg.LIGHT_BLUE) + fill_char = style('-', fg=StdFg.LIGHT_YELLOW) width = 6 aligned = cu.align_text(text, cu.TextAlignment.LEFT, fill_char=fill_char, width=width) - left_fill = ansi.RESET_ALL - right_fill = ansi.RESET_ALL + fill_char + ansi.RESET_ALL - line_1_text = ansi.fg.bright_blue + 'line1' + ansi.FG_RESET + left_fill = TextStyle.RESET_ALL + right_fill = TextStyle.RESET_ALL + fill_char + TextStyle.RESET_ALL + line_1_text = StdFg.LIGHT_BLUE + 'line1' + StdFg.RESET assert aligned == (left_fill + line_1_text + right_fill) # Multiple lines to show that style is preserved across all lines. Also has left and right fill. - text = ansi.style('line1\nline2', fg=ansi.fg.bright_blue) - fill_char = ansi.style('-', fg=ansi.fg.bright_yellow) + text = style('line1\nline2', fg=StdFg.LIGHT_BLUE) + fill_char = style('-', fg=StdFg.LIGHT_YELLOW) width = 7 aligned = cu.align_text(text, cu.TextAlignment.CENTER, fill_char=fill_char, width=width) - left_fill = ansi.RESET_ALL + fill_char + ansi.RESET_ALL - right_fill = ansi.RESET_ALL + fill_char + ansi.RESET_ALL - line_1_text = ansi.fg.bright_blue + 'line1' - line_2_text = ansi.fg.bright_blue + 'line2' + ansi.FG_RESET + left_fill = TextStyle.RESET_ALL + fill_char + TextStyle.RESET_ALL + right_fill = TextStyle.RESET_ALL + fill_char + TextStyle.RESET_ALL + line_1_text = StdFg.LIGHT_BLUE + 'line1' + line_2_text = StdFg.LIGHT_BLUE + 'line2' + StdFg.RESET assert aligned == (left_fill + line_1_text + right_fill + '\n' + left_fill + line_2_text + right_fill) diff --git a/tests/transcripts/regex_set.txt b/tests/transcripts/regex_set.txt index 68e61e30..c2a0f091 100644 --- a/tests/transcripts/regex_set.txt +++ b/tests/transcripts/regex_set.txt @@ -13,7 +13,7 @@ now: 'vim' Name Value Description/ +/ ================================================================================================================== allow_style Terminal Allow ANSI text style sequences in output (valid values:/ +/ - Terminal, Always, Never)/ +/ + Always, Never, Terminal)/ +/ always_show_hint False Display tab completion hint even when completion suggestions print/ +/ debug False Show full traceback on exception/ +/ |