Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - Obtain neutral background with ncurses

In this simple program (written in C)

#include <ncurses.h>
#include <string.h>

int main()
{
 initscr();
 printw("line 1\n");
 printw("line 2\n");
 start_color();
 init_pair(1, COLOR_RED, COLOR_BLACK);
 printw("line 3");
 getch();
 endwin();

 return 0;
}

a red text is printed on the screen over a black background. But when I run the program, the background is slightly brighter than the black background of the terminal, in Linux (Gnome terminal).

I don't want to set a background color over the default, black color of the terminal: I would like to keep the terminal background and to actually set the ncurses background as transparent.

Is there a way to do this?

Note: I tried to put the function use_default_colors(); after start_color(); as suggested in this question, but it was not useful.

like image 450
BowPark Avatar asked Aug 17 '15 20:08

BowPark


2 Answers

From man init_pair:

As an extension, ncurses allows you to set color pair 0 via the assume_default_colors routine, or to specify the use of default colors (color number -1) if you first invoke the use_default_colors routine.

So, generally, if you want to use "default" color, use -1 for color value, but make sure you've called use_default_colors() first.

#include <ncurses.h>
#include <string.h>

int main()
{
 initscr();
 use_default_colors();
 printw("line 1\n");
 printw("line 2\n");
 start_color();
 init_pair(1, COLOR_RED, -1);
 printw("line 3");
 getch();
 endwin();

 return 0;
}
like image 73
Pawel Veselov Avatar answered Nov 19 '22 00:11

Pawel Veselov


For what it's worth, here is a corrected example starting with @Pawel Veselov's suggestion:

#include <ncurses.h>
#include <string.h>

int main(void)
{
 initscr();
 if (has_colors()) {
  use_default_colors();
  start_color();
  init_pair(1, COLOR_RED, -1);
 }
 printw("line 1\n");
 printw("line 2\n");
 attrset(COLOR_PAIR(1));
 printw("line 3");
 getch();
 endwin();

 return 0;
}

The last line should appear (for cooperating terminals) with red text on the terminal's default background color. (To be pedantic, one could do the attrset only when has_colors is true...).

Running in white-on-black:

enter image description here

or in black-on-white:

enter image description here

uses the terminal's default background. Without use_default_colors, ncurses assumes the terminal displays white-on-black (but then you can change that assumption using assume_default_colors).

like image 23
Thomas Dickey Avatar answered Nov 18 '22 23:11

Thomas Dickey