Add ANSI escape sequences for inline styles
In this pull request, several changes were made to simple_term_menu 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.
Awesome, thanks for your contribution!
I think this PR is related to issue #14.
I have some questions regarding your code changes:
- Is there a reason not to use the color definitions in
_codename_to_terminal_code? This dictionary is generated with the terminal database. Thus, terminals can be supported which use color codes different from the standard ANSI escape codes (however, I don't know any recent terminal emulator which would use other escape codes...) - Do your changes work with search mode (activated by pressing
/)? I think, it could be quite difficult to get this right. This was also the reason, I didn't implement support for color codes yet.
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. :)
Edit: Yes, is related to issue #14 i needed inline colors too :)
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:
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: