Reputation: 63
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
?
Upvotes: 6
Views: 4175
Reputation: 54505
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:
Upvotes: 3
Reputation: 1741
There's the "culour" python module which does exactly that.
Install it using pip install culour
, and then you can use it to print pre-colored strings:
import culour
culour.addstr(window, colored_string)
This will print the string colored in your window.
Upvotes: 6
Reputation: 11
On GitHub there is a free to use, study, modify and re-distribute High Level GUI library, at "https://github.com/rigordo959/tsWxGTUI_PyVx_Repository".
It is implemented in Python 2x & 3x using the "curses" Low Level GUI package. The Linux nCurses implementation has typically replaced the original Unix Curses implementation.
Your application programs can be programmed using a character-mode subset of the pixel-mode "wxPython" High Level GUI API. It supports displays with keyboard and mouse input and various terminal emulators including the color xterms (8-color with 64-color pairs and 16-color with 256-color pairs) and non-color vt100/vt220.
Curses enables you to colorize text strings by inserting an attribute (for color, underline, bold, reverse etc.) token before the text and one to restore the previous attribute after the text. For example:
sampleWindow.attron(curses.A_REVERSE |
curses.color_pair(color_pair_number))
sampleWindow.addstr(begin_y + 3,
begin_x + 48,
' ')
sampleWindow.attroff(curses.A_REVERSE |
curses.color_pair(color_pair_number))
Upvotes: 0