cncursescurses

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");

Solution

  • 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.