"""A bunch of color names mapped into RGB tuples and some methods for
setting the text color, background, etc... using ANSI escape
-sequences.
+sequences. See: https://en.wikipedia.org/wiki/ANSI_escape_code.
"""
import contextlib
logger = logging.getLogger(__name__)
-# https://en.wikipedia.org/wiki/ANSI_escape_code
-
COLOR_NAMES_TO_RGB: Dict[str, Tuple[int, int, int]] = {
"abbey": (0x4C, 0x4F, 0x56),
def clear() -> str:
"""Clear screen ANSI escape sequence"""
- return "\e[H\e[2J"
+ return "\x1B[H\x1B[2J"
def clear_screen() -> str:
"""Clear screen ANSI escape sequence"""
- return "\e[H\e[2J"
+ return "\x1B[H\x1B[2J"
def clear_line() -> str:
"""Clear the current line ANSI escape sequence"""
- return "\e[2K\r"
+ return "\x1B[2K\r"
def reset() -> str:
"""Reset text attributes to 'normal'"""
- return "\e[m"
+ return "\x1B[m"
def normal() -> str:
"""Reset text attributes to 'normal'"""
- return "\e[m"
+ return "\x1B[m"
def bold() -> str:
"""Set text to bold"""
- return "\e[1m"
+ return "\x1B[1m"
def italic() -> str:
"""Set text to italic"""
- return "\e[3m"
+ return "\x1B[3m"
def italics() -> str:
def underline() -> str:
"""Set text to underline"""
- return "\e[4m"
+ return "\x1B[4m"
def strikethrough() -> str:
"""Set text to strikethrough"""
- return "\e[9m"
+ return "\x1B[9m"
def strike_through() -> str:
bright_count += 1
if bright_count > 1:
code += 60
- return f"\e[{code}m"
+ return f"\x1B[{code}m"
def bg_16color(red: int, green: int, blue: int) -> str:
bright_count += 1
if bright_count > 1:
code += 60
- return f"\e[{code}m"
+ return f"\x1B[{code}m"
def _pixel_to_216color(n: int) -> int:
g = _pixel_to_216color(green)
b = _pixel_to_216color(blue)
code = 16 + r * 36 + g * 6 + b
- return f"\e[38;5;{code}m"
+ return f"\x1B[38;5;{code}m"
def bg_216color(red: int, green: int, blue: int) -> str:
g = _pixel_to_216color(green)
b = _pixel_to_216color(blue)
code = 16 + r * 36 + g * 6 + b
- return f"\e[48;5;{code}m"
+ return f"\x1B[48;5;{code}m"
def fg_24bit(red: int, green: int, blue: int) -> str:
"""Set foreground using 24bit color mode"""
- return f"\e[38;2;{red};{green};{blue}m"
+ return f"\x1B[38;2;{red};{green};{blue}m"
def bg_24bit(red: int, green: int, blue: int) -> str:
"""Set background using 24bit color mode"""
- return f"\e[48;2;{red};{green};{blue}m"
+ return f"\x1B[48;2;{red};{green};{blue}m"
def _find_color_by_name(name: str) -> Tuple[int, int, int]:
def reset_fg():
+ """Returns: an ANSI escape code to reset just the foreground color while
+ preserving the background color and any other formatting (bold, italics, etc...)"""
return '\033[39m'
force_16color: force bg to use 16 color mode
force_216color: force bg to use 216 color mode
+ Returns:
+ A string containing the requested escape sequence
+
>>> import string_utils as su
>>> su.to_base64(bg("red")) # b'\x1b[48;5;196m'
b'G1s0ODs1OzE5Nm0=\\n'