Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 230
secondwtq Avatar asked May 12 '15 11:05

secondwtq


2 Answers

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.

like image 105
speller Avatar answered Oct 14 '22 19:10

speller


This has been asked several times, with the same answer: you could write a parser to do this. For related discussion:

  • How to use ANSI escape codes inside mvwprintw in ncurses?
  • Comment on Parsing ANSI color escape sequences
  • Handle escape sequences with ncurses? Does printf handle escape sequences?

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

  • curses produces escape sequences, but for a wide variety of devices (which may not be "ANSI color escapes").
  • ncurses (see the FAQ Why aren't my bugs being fixed?) does not provide it as an extension because a parser of this type would not rely upon any of ncurses' internals.
like image 2
Thomas Dickey Avatar answered Oct 14 '22 20:10

Thomas Dickey