{"id":19880586,"url":"https://github.com/gabrielscabrera/termighty","last_synced_at":"2026-03-09T10:33:51.657Z","repository":{"id":57474237,"uuid":"198509318","full_name":"GabrielSCabrera/Termighty","owner":"GabrielSCabrera","description":"High-level utilities for cross-platform terminal interaction.","archived":false,"fork":false,"pushed_at":"2024-04-23T20:22:41.000Z","size":494,"stargazers_count":6,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-04-07T02:35:15.516Z","etag":null,"topics":["cross-platform","terminal","terminal-colors","terminal-graphics","terminal-ui"],"latest_commit_sha":null,"homepage":"https://pypi.org/project/Termighty/","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"gpl-3.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/GabrielSCabrera.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2019-07-23T21:15:50.000Z","updated_at":"2024-07-18T12:52:36.000Z","dependencies_parsed_at":"2024-04-23T21:41:33.108Z","dependency_job_id":"41c652dd-ea90-42ea-bc9e-b5f6b34712f0","html_url":"https://github.com/GabrielSCabrera/Termighty","commit_stats":{"total_commits":184,"total_committers":3,"mean_commits":"61.333333333333336","dds":"0.18478260869565222","last_synced_commit":"4d53714bb789e6a35a589051a0ad551ce2a0763e"},"previous_names":[],"tags_count":12,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/GabrielSCabrera%2FTermighty","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/GabrielSCabrera%2FTermighty/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/GabrielSCabrera%2FTermighty/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/GabrielSCabrera%2FTermighty/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/GabrielSCabrera","download_url":"https://codeload.github.com/GabrielSCabrera/Termighty/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":252046269,"owners_count":21685983,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cross-platform","terminal","terminal-colors","terminal-graphics","terminal-ui"],"created_at":"2024-11-12T17:11:51.275Z","updated_at":"2026-03-09T10:33:51.605Z","avatar_url":"https://github.com/GabrielSCabrera.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Termighty\n### High-level utilities for cross-platform terminal interaction.\n\nTermighty is a Python package that provides a comprehensive set of tools for managing and customizing the terminal environment, as well as handling user inputs and creating dynamic text displays. It consists of several classes, each serving specific purposes.\n\nThe Term class offers commands for modifying the terminal state, managing multiple buffers, and controlling terminal output. It includes methods for initializing the class, playing the terminal bell sound, clearing the terminal screen, hiding and showing the cursor, moving and saving the cursor position, and writing to the terminal.\n\nThe String class is an advanced version of Python's built-in str class, designed to handle ANSI Escape Sequences for custom text and background colors, as well as text styles. It provides methods for listing available styles, creating instances with specific colors and styles, and implementing magic methods to use the String class like a built-in string.\n\nThe Color class manages colors in RGB format and can be used in conjunction with the String class or for modifying terminal background and foreground colors directly. It supports many operations between colors, unary operations on colors, and color instantiation from a comprehensive catalog of colors.\n\nThe GetchIterator class is designed to iterate over a Listener's history, yielding all new additions to the history until the Listener is stopped. The Listener class, a superclass that must be inherited before instantiation, allows users to display live, dynamic text on the terminal while simultaneously accepting user inputs.\n\nThe TextBox class provides a base for rectangular shapes (with or without text) that display on the terminal. It simplifies and standardizes the creation of more complex objects. The TextEditor class, a subclass of TextBox, emulates a fully-functional word processor with advanced features such as cursor positioning, and text selection.\n\nIn summary, Termighty is a powerful package that enables developers to create customized terminal experiences with enhanced text manipulation, user input handling, and dynamic displays.\n\n# Class Documentation: System\n\nThe `System` class is used to keep track of the terminal dimensions and detect the current OS. It also contains the `kill_all` class attribute, which is by default set to `False`. If it is set to `True`, all active Termighty threads will be killed.\n\n## Attributes\n\n### terminal_size: tuple[int, int]\nStores the terminal dimensions (width and height) as a tuple.\n\n### os\nStores the name of the current operating system.\n\n### escape_code_encoding\nStores the encoding type of escape codes, based on the operating system.\n\n### kill_all\nA boolean attribute that, if set to `True`, stops all processes.\n\n## Methods\n\n### track_terminal_shape(cls)\n\nA class method that tracks the terminal size in a loop, updating the `terminal_size` attribute whenever the terminal dimensions change. The loop will run until `kill_all` is set to `True`. The method has a sleep time of `0.05` seconds to prevent excessive CPU usage.\n\n## Threading\n### track_terminal_shape_thread\n\nA daemon thread created to run the `track_terminal_shape` method in the background. The thread will start automatically when the module is imported.\n\n# Class Documentation: Term\n\nThe `Term` class is a collection of commands that can be used to make modifications to the terminal state. It allows for the existence of multiple buffers that each can be flushed and appended independently of others. By default, methods that write to the terminal are not set to flush the buffer when called, which improves performance. However, if the flush parameter is set to True, then the buffer is bypassed and the command outputs immediately to the terminal.\n\n## Methods\n\n### __init__(self, flush: bool = False) -\u003e None\nThe constructor method initializes the instance variables needed for the class.\n\n### bell(self, flush: bool = False) -\u003e None\nPlay the terminal bell sound.\n\n### clear(self, flush: bool = False) -\u003e None\nClears the terminal screen.\n\n### cursor_hide(self, flush: bool = False) -\u003e None\nMake the cursor invisible.\n\n### cursor_load(self, flush: bool = False) -\u003e None\nLoad the cursor position.\n\n### cursor_move(self, line: int, column: int, flush: bool = False) -\u003e None\nMove the cursor to the given line and column.\n\n### cursor_save(self, flush: bool = False) -\u003e None\nSave the cursor position.\n\n### cursor_show(self, flush: bool = False) -\u003e None\nMake the cursor visible.\n\n### flush(self) -\u003e None\nFlush the entire buffer to the terminal.\n\n### flush_string(self, string: str) -\u003e None\nWrite and flush the given string to the terminal.\n\n### write(self, line: int, column: int, string: str, flush: bool = False) -\u003e None\nWrite the given string starting at the designated line and column coordinates to the buffer.\n\n# Class Documentation: String\n\nThe String class is a more advanced version of the built-in `str` class, which can handle ANSI Escape Sequences indirectly through calling various methods. These methods allow for custom text and background colors, as well as text styles. Most methods for `str` class function, such as `string.partition()`, `string.strip()`, etc.\n\n## Class Methods\n\n### list_styles() -\u003e str\n\nReturn a list of all available styles (as viewable ANSI escape sequences) and their names. Remember to print the outputted string if you want to view the list in the terminal.\n\n## Constructor\n\n### __init__(string: str, foreground: Optional[Union[str, Color, tuple[int, int, int]]] = None, background: Optional[Union[str, Color, tuple[int, int, int]]] = None, style: Optional[str] = None) -\u003e None\n\nCreate an instance of class String. Arguments foreground and background should be the names of known colors, or instances of Color. Argument style should be the name of a known style in /data/styles.json.\n\n## Magic Methods\n\nSeveral magic methods are implemented for the String class, allowing it to be used in a similar way to a built-in string. Magic methods include: `__add__`, `__format__`, `__getitem__`, `__iter__`, `__mul__`, `__next__`, `__radd__`, `__repr__`, `__rmul__`, `__set__`, and `__str__`.\n\n## Properties\n\n### background -\u003e Color\nReturn a copy of the Color instance assigned to the current background.\n\n### foreground -\u003e Color\nReturn a copy of the Color instance assigned to the current foreground.\n\n### string -\u003e str\nReturn the uncolored and unformatted text currently assigned to this `String` instance.\n\n### style -\u003e str\nReturn the name of the text style associated with the current instance.\n\n## Setter Methods\n\n### background.setter(color: Optional[Union[str, Color, tuple[int, int, int]]] = None) -\u003e None\nSet the background color to a new value. Accepts the name of a color as a string, or an instance of `Color`, or a tuple containing three integers in the range [0, 255] representing RGB color channels.\n\n### foreground.setter(color: Optional[Union[str, Color, tuple[int, int, int]]] = None) -\u003e None\nSet the foreground color to a new value. Accepts the name of a color as a string, or an instance of `Color`, or a tuple containing three integers in the range [0, 255] representing RGB color channels.\n\n### string.setter(data: str) -\u003e None\nOverwrite the uncolored and unformatted text currently assigned to this `String` instance.\n\n### style.setter(style: Optional[str] = None) -\u003e None\nSet the style to a new value.\n\n# Class: Color\n\nThe Color class manages colors in RGB format for use in instances of the `String` class, or for modifying terminal background and foreground colors directly. It supports many operations between colors, as well as unary operations like adding and subtracting colors (by RGB value) or taking a color's negative.\n\nColors can be instantiated directly by inputting an RGB value (and optional color name), or they may be generated from a comprehensive catalog of colors using the classmethod `Color.palette` (the full catalog can be printed as a guide by executing the class method `Color.list_colors`).\n\n## Class Methods:\n\n### chart(r: Optional[int], g: Optional[int], b: Optional[int], term_width: int) -\u003e str\nReturns a terminal-printable color chart. Set exactly ONE of the parameters `r`, `g`, and `b` to a value in the range [0, 255], and the others must be set to None as they will be iterated over. Argument `term_width` should be a positive nonzero integer.\n\n### is_color(name: str) -\u003e bool\nReturns True if `/data/rgb.json` contains the given string. Can be used to check whether or not a color you want to instantiate is included in Termighty.\n\n### list_colors(sort_by=\"step\") -\u003e str\nReturns a string containing a list of all available colors (as viewable ANSI escape sequences) and their names. Remember to print the outputted string if you want to view the list in the terminal.\n\n### palette(name: str) -\u003e \"Color\"\nInitializes a `Color` instance using a color name; only succeeds if the name is found in `/data/rgb.json`.\n\n## Properties:\n\n### sample -\u003e str\nReturns a color sample in the form of a printable string, consisting of a single whitespace character with the background color set to that of the current instance of class Color.\n\n## Constructor:\n\n### init(self, rgb: Sequence[int], name: str = \"Unnamed Color\") -\u003e None\nInitializes a new instance of the `Color` class. Argument `rgb` should be a sequence containing three integers in the range [0, 255].\n\n## Magic Methods:\n\n### add(self, color: \"Color\") -\u003e \"Color\"\nAdds colors together by summing their RGB values.\n\n### call(self, string: str) -\u003e str\nReturns the given string, but with the text colored using the current instance's RGB values.\n\n### hash(self) -\u003e int\nReturns a unique hash for the combination of `rgb` values of the current Color instance.\n\n### repr(self) -\u003e str\nReturns a color sample from the current instance that is machine-readable.\n\n### str(self) -\u003e str\nReturns the current instance's color name, RGB value, and a sample of the color as a formatted human-readable multiline string.\n\n### sub(self, color: \"Color\") -\u003e \"Color\"\nSubtracts colors from each other by subtracting their RGB values.\n\n## Properties (Getters/Setters):\n\n### b -\u003e int\nReturns the current instance's blue RGB value.\n\n### g -\u003e int\nReturns the current instance's green RGB value.\n\n### name -\u003e str\nReturns the current instance's color name.\n\n### r -\u003e int\nReturns the current instance's red RGB value.\n\n### rgb -\u003e tuple[int, int, int]\nReturns the current instance's RGB values as a tuple of integers.\n\n## Public Methods:\n\n### brightness(self) -\u003e int\nReturns the mean of the RGB values, which can be considered a measure of the color's brightness.\n\n### copy(self) -\u003e \"Color\"\nReturns a deep copy of the current instance.\n\n### hsv(self) -\u003e tuple[float, float, float]\nReturn the color of the current instance in HSV form, which converts the red, green, and blue color channels to their equivalent hue, saturation, and brightness.  HSV is a representation of color that attempts to more closely represent the way that human vision interprets color.\n\n### lightness(self, weighted: bool = True) -\u003e float\nReturn the norm of the RGB vector as fraction of 255.  Should return a float in the range 0 to 1.\nIf weighted, multiply the squares of the `R`, `G`, and `B` color channels by 0.299, 0.587, and 0.114, respectively.\nSource of weights: http://alienryderflex.com/hsp.html\n\n### negative(self) -\u003e \"Color\"\nReturn the color negative of the current instance, which is the element-wise difference (255-R, 255-G, 255-B), where `R`, `G`, and `B` are the current instance's color channels.\n\n# Class: GetchIterator\n\nThe `GetchIterator` class is designed to be used in a for-loop to iterate over the `Listener`'s history, starting at the provided index, and continuously yielding all new additions to the history until the `Listener` is stopped.\n\n## Methods\n\n### __init__(self, idx: Optional[int] = None)\nInitializes the GetchIterator object, preparing the indices for the iteration if they are given.\n\n### __iter__(self)\nSets the start index for the iterator based on the current length of the Listener history if the index is not provided. Otherwise, it uses the given index.\n\n### __next__(self)\nReturns the next input detected by the Listener and appended to its history.\n\n# Class: Listener\n\nThe `Listener` class is a superclass that allows users to display live, dynamic text on the terminal while simultaneously accepting user inputs. It must be inherited before instantiation, and the `_writer` attribute must be overwritten. The overwritten `_writer` should contain the main loop displayed to the terminal.\n\nOnly one instance of `Listener` may be active at once.\n\n## Class Attributes\n\n### _active\nA boolean indicating whether the `Listener` is active.\n\n### _escape_hits\nThe number of consecutive Esc key presses needed to stop the `Listener`.\n\n### _history\nA list of the user's input history.\n\n### _raw\nA boolean indicating whether the `Listener` should return raw escape codes or interpret them.\n\n### _sleep_time\nThe time in seconds the `Listener` should sleep between input checks.\n\n## Class Methods\n\n### _getch_linux()\nListens for keyboard input on Linux systems and returns a string with a key name.\n\n### _getch_windows()\nListens for keyboard input on Windows systems and returns a string with a key name.\n\n### _interpret_escape_code(escape_code: bytes) -\u003e str\nReturns a character or command from the given escape code.\n\n### _listener()\nA method for updating the global `input_state` variable by appending the latest keypress to it (interpreted by `data/keymaps`).\n\nExpects `_raw_mode` to be True, implying the terminal will read user inputs immediately without echoing to the\nterminal.\n\nTo kill all running threads, hold key `ESC` for a few seconds, or hit it as many times in a row as the value\ngiven in `cls._escape_hits` -- be sure not to press any other keys in between or the kill process is interrupted.\n\n### _listener_raw()\nA method for updating the global `input_state` variable by appending the latest keypress to it (as an ANSI escape sequence or character).\n\n### _raw_mode_linux(state: bool)\nSets the terminal to raw mode on Linux systems if state is True, or to echo mode if state is False.\n\n### _raw_mode_windows(state: bool)\nWindows placeholder for raw mode, which is only necessary on Linux systems.\n\n## Public Methods\n\n### getch_iterator(cls, idx: Optional[int] = None, keytest: bool = False) -\u003e GetchIterator\nReturns a `GetchIterator` object for the given index.\n\n### start(cls, raw: bool = False)\nActivates the `Listener` session. If raw is True, the listener will return raw escape codes instead of interpreting them.\n\n### stop(cls)\nDeactivates the `Listener` session.\n\n## OS-Specific Methods\n\n### _getch\nAlias for `_getch_linux` on Linux systems, and `_getch_windows` on Windows systems.\n\n### _raw_mode\nAlias for `_raw_mode_linux` on Linux systems, and `_raw_mode_windows` on Windows systems.\n\n### _fd\nFile descriptor for the terminal input on Linux systems.\n\n### _old_settings\nThe terminal's old settings on Linux systems.\n\n# Class: TextBox\n\nThe `TextBox` class provides a base for rectangular shapes (that may or may not contain text) that display on the terminal. It is used to simplify and standardize more complex objects.\nMagic Methods\n\n## Constructor\n\n### __init__(self, row_start: int, col_start: int, row_end: int, col_end: int, wrap_text: bool = False, wrap_subsequent_indent: str = \"\", wrap_text_break_on_hyphens: bool = True, wrap_text_break_long_words: bool = True, background: Optional[Union[str, Color]] = None, foreground: Optional[Union[str, Color]] = None, style: Optional[str] = None, alignment: Literal[\"left\", \"right\", \"center\"] = \"left\", view: tuple[int, int] = (0, 0),) -\u003e None\nReturn a new instance of class `TextBox` at the specified coordinates.  If negative coordinates are given, they will be set dynamically relative to the size of the terminal; a thread will loop in the background keeping track of the terminal dimensions and resizing the `TextBox` if its coordinates are dynamic.\n\n### __call__(self, text: Union[str, list[str, ...]]) -\u003e None\nThis method modifies the current state of the `TextBox` by replacing its contents with the given text. It accepts a single string or a list of strings. If a list is given, each element will be placed in its own row within the `TextBox`. However, it does not support the use of strings containing ANSI escape sequences.\n\n### _process_text(self) -\u003e None\nThis method justifies the raw text given to the __call__ method such that all lines of text are equally-sized and wide enough to allow for the view of the text to be moved left, right, up, and down until the text is just out of view. It takes the `_alignment` attribute into account, aligning the text either to the left, right, or center of the `TextBox`.\n\n### _init_color_attributes(self, background: Color, foreground: Color, style: str) -\u003e None\nThis method prepares all the required instance attributes, such as colors, style, and the resulting ANSI sequences that will be used to correctly display the text with these colors and styles.\n\n### _init_spacial_attributes(self, row_start: int, col_start: int, row_end: int, col_end: int, view: tuple[int, int]) -\u003e None\nThis method initializes attributes that are related to the `TextBox` shape, position within the terminal, and the position of its contents. This includes the coordinates of the `TextBox` corners (user-defined), the initial size of the terminal, as obtained by the `System` class, and the window view, set to (0,0) by default.\n\n### _process_text_wrapper(self) -\u003e None\nThis method sets up the text wrapper.\n\n### _init_arguments(self, background: Union[str, Color, tuple[int, int, int]], foreground: Union[str, Color, tuple[int, int, int]], style: str, defaults: tuple[Color, Color, str], argnames: tuple[str, str, str]) -\u003e tuple[Color, Color, str]\nThis method performs checks making sure that the initialization arguments are correctly set up. It confirms that the `TextBox` dimensions are correctly set up (`start` \u003c `end`), that the given background \u0026 foreground colors are valid, and that the given style is valid.\n\n### _run_thread(self, dt: float) -\u003e None\nThis method keeps updating the window every `dt` seconds and accounts for changes in the terminal size (useful when dealing with relative coordinates on initialization).\n\n### _set_shape(self) -\u003e None\nThis method sets the size of the `TextBox` to those given by the user at instantiation. If the terminal size is smaller than the `TextBox` size, it will decrease the `TextBox` size to make it fit in the terminal. It also accounts for negative size instantiation values; if a value is negative, it is subtracted from the terminal size (from the axis in question).\n\n### _set_view(self) -\u003e None\nThis method limits the view to prevent out of bounds errors by using commands min and max with the `TextBox` dimensions.\n\n## Public Methods\n\n### start(self, dt: float = 0.005) -\u003e None\nThis method activates a thread that runs the method `_run_thread`.\n\n### stop(self) -\u003e None\nThis method kills the active thread.\n\n### alignment(self, mode: str) -\u003e None\nThis method sets the `TextBox` text alignment mode.\n\n# TextEditor Class\n\n`TextEditor` is a subclass of `TextBox` that emulates a fully-functional word processor. It uses class Listener to detect keyboard inputs and supports the following advanced functions:\n\n* Cursor positioning with the arrow keys\n* Ctrl-arrow key to move the cursor to the beginning/end of words\n* Alt-arrow to select text\n* Deletion of selected text\n* Copying \u0026 pasting of selected text.\n\n## Constructor\n### __init__(self, row_start: int, col_start: int, row_end: int, col_end: int, wrap_text: bool = False, wrap_subsequent_indent: str = \"\", line_numbers: bool = False, background: Union[str, Color, tuple[int, int, int]] = None, foreground: Union[str, Color, tuple[int, int, int]] = None, style: Optional[str] = None, select_background: Union[str, Color, tuple[int, int, int]] = None, select_foreground: Union[str, Color, tuple[int, int, int]] = None, select_style: Optional[str] = None, line_number_background: Union[str, Color, tuple[int, int, int]] = None, line_number_foreground: Union[str, Color, tuple[int, int, int]] = None, line_number_style: Optional[str] = None, vertical_scroll_buffer: Optional[int] = None, horizontal_scroll_buffer: Optional[int] = None, cursor_position: tuple[int, int] = (0, 0), frozen: bool = False,)\nThe constructor in class TextEditor creates an instance of TextEditor and initializes its attributes and those of its inherited TextBox.\n\n## Methods\n### _init_editor_attributes(self, cursor_position, frozen, line_numbers, select_background, select_foreground, select_style, line_number_background, line_number_foreground, line_number_style, selected=None)\nPrepare all the instance attributes for selected text, such as colors, style, and the resulting ANSI sequences that will be used to correctly display the text with these colors and styles. Also initializes the coordinate list of selected text, set to an empty list by default.\n\n### _process_text_wrapper(self)\nPrepare the TextWrapper object that wraps text when it is too long to fit on one line. If line numbers are enabled, this method also determines the maximum width required for the line numbers.\n\n### _run_getch_thread(self) -\u003e None\nKeeps updating the window every set number of seconds (given by dt) and accounts for changes in the terminal size (useful when dealing with relative coordinates on initialization).\n\n### _set_scroll_buffer(self) -\u003e None\nIf the vertical and/or horizontal scroll buffers are dynamic, changes them based on the current terminal dimensions.\n\n### _set_view(self) -\u003e None\nUpdates the current view of the text based on the current cursor position and selected text.\n\n### start(self)\nMain loop which runs on one thread, while a listener runs on another and provides commands to be read by this method. These inputs are accessed via the superclass attribute LiveMenu._input_state and are processed in an infinite loop until broken.\n\n### freeze(self)\nFreeze the TextEditor -- the getch_iterator in method _run_getch_thread will continue to run, but it will not act on the inputs and leave the window unchanged.\n\n### unfreeze(self)\nUnfreeze the TextEditor and reopen it to getch inputs.\n\n### write(self) -\u003e None\nWrites the text to its designated coordinates with the view taken into account.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgabrielscabrera%2Ftermighty","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fgabrielscabrera%2Ftermighty","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgabrielscabrera%2Ftermighty/lists"}