eeeeeeeeengo
eeeeeeeeengo

Reputation: 143

Is ncurses possible to change only foreground color?

Below code can change only attribute with leaving colors.

init_color(1, 255);
init_color(2, 1);
init_pair(1, 1, 2);

attron(COLOR_PAIR(1)); // only change the pair of foreground and background color
addstr("aaa");

attron(A_BOLD); // only change the attribute
addstr("aaa");

attrset(COLOR_PAIR(1)|A_BOLD); // change both

I want to know if we can change only foreground color, but leave background color.

attron_fg(BACKGROUND_YELLOW); // only change the foreground color
addstr("aaa");

Upvotes: 0

Views: 884

Answers (2)

scodog
scodog

Reputation: 21

You can't do it directly but it can be done with some effort. Ultimately, you always need a color-pair to specify colors. You can get the current pair (either getbkgd() for the background pair, or { attr_get(..., &attr); p=PAIR_INDEX(attr); } for the window attribute pair).

Then you use pair_content(p, &f, &b) to get the individual f/g and b/g colors of that existing pair and create a new pair with init_pair(p, f, b) using your new f/g and your existing b/g.

With some coding and caching, you can do a lookup based on f/g, b/g colors and determine if a pair already exists or needs to be created.

Upvotes: 2

rici
rici

Reputation: 241671

No, you can't.

Ncurses is based on a model where each screen position has a colour pair. The possible colour pairs are in an indexed array, and it's the array index which ncurses stores in its screen representation. So you can only specify a colour pair.

Furthermore, since everything is based on indexed arrays, changing the definition of a colour or a colour pair will probably change the displayed colour of previously painted characters.

That model can be a bit annoying but its fundamental to the design of ncurses, so if you want to use ncurses, you need to adapt to the model.

Historically, there were hardware terminals based on the same model for essentially the same reason (limited memory). These days, such terminals are mostly confined to museums, but ncurses and the rest of the unix terminal handling infrastructure continues to cater to a world in which a diversity of external terminals each presented their own unique facilities and limitations.

These days, the same model is used to compensate for the differing implementations of terminal control sequences by a variety of different terminal emulators. But it also still works (or could work) with consoles connected to embedded devices.

That's an explanation, neither an excuse nor a justification.

Upvotes: 5

Related Questions