pythonncursescursespython-curses

How to display pre-colored string with curses?


I'm writing a curses program in Python. I'm a beginner of curses but I've used terminal control sequences for colored output.

Now there's some code snippets to print inside the window, I'd like them be syntax highlighted, and it's better done with libraries like pygments, which outputs highlighted code with control sequences.

Initially I feed pygments output directly to window.addstr(), but it is turned out that the control sequences is escaped and the whole highlighted string is printed on the screen (just like this: https://too-young.me/web/repos/curses-highlight.png). How can I display it directly with curses, just like cat?


Solution

  • This has been asked several times, with the same answer: you could write a parser to do this. curses (Python or not) is a high-level interface, with some low-level functions for special tweaking. The high-level interface assumes that strings are all data to be displayed. The addch manpage goes into some detail explaining that. If you use the low-level functions (such as putp), the high-level curses calls do not know what has been displayed.

    For related discussion:

    It is not suitable as an extension to ncurses for example because: