IngoMeyer441 / simple-term-menu

A Python package which creates simple interactive menus on the command line.
MIT License
492 stars 43 forks source link

Add ANSI escape sequences for inline styles #84

Open onekintaro opened 9 months ago

onekintaro commented 9 months ago

_In this pull request, several changes were made to simple_termmenu to improve support for inline ANSI colour and style sequences and to fix display errors when ANSI codes are inline used:

New function remove_ansi_sequences: Function to recognise and remove different formats of ANSI escape sequences. This ensures that the width calculation of menu entries and title lines is carried out correctly without including the invisible ANSI characters.

New function check_ansi_reset: Checks whether a menu entry contains ANSI reset sequences and returns True or False accordingly.

New function apply_inline_style: Inserts highlight styles again after a detected ANSI reset. This allows specific parts of the menu to be coloured, while other parts are highlighted normally. For example, a menu entry such as "- (online) name" can be formatted so that "online" is highlighted in green and "name" is highlighted normally.

Added _codename_to_ansi for direct ANSI codes: This list contains direct ANSI codes to enable apply_inline_style to insert the correct style after a reset.

Adjustments in print_menu_entries: The function has been modified to support the new ANSI functions and to correctly perform the width calculations in the menu and title. Screenshot 2023-12-03 095638

IngoMeyer441 commented 9 months ago

Awesome, thanks for your contribution!

I think this PR is related to issue #14.

I have some questions regarding your code changes:

onekintaro commented 9 months ago

the reason why i did not use _codename_to_terminal_code was because i have never worked with these definitions before and have always used ANSI codes. But if you prefer to use _codename_to_terminal_code you are welcome to change it.

The search mode should still work according to my tests. :) Screenshot 2023-12-04 113434

Edit: Yes, is related to issue #14 i needed inline colors too :)

IngoMeyer441 commented 9 months ago

I run some tests with this code snippet:

#!/usr/bin/env python3

from simple_term_menu import TerminalMenu

def main():
    # menu = TerminalMenu(map(str, range(200)), title="page up/down test")
    menu = TerminalMenu(
        ["Co\x1b[31mntai\x1b[0mer 1", "Co\x1b[32mntai\x1b[0mer 2", "Co\x1b[33mntai\x1b[0mer 3"],
        title="\x1b[34mcolor\x1b[0m test",
    )
    menu.show()

if __name__ == "__main__":
    main()

and get this result:

image

The default standout style for menu entries seems to be broken with color codes.

When searching for texts, which span over color codes, menu entries disappear:

image