Skip to content

Commit

Permalink
Add darker colors for light terminal backgrounds (merbanan#2864)
Browse files Browse the repository at this point in the history
  • Loading branch information
zuckschwerdt authored Mar 26, 2024
1 parent c00aa10 commit 1116ce1
Showing 1 changed file with 55 additions and 3 deletions.
58 changes: 55 additions & 3 deletions src/term_ctl.c
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,38 @@ int term_get_columns(void *ctx)
#endif
}

/**
Returns wether the environment suggests a dark or light
terminal background.
Our default color theme is for dark backgrounds.
Check the COLORFGBG environment variable, which should
be 15;0 for a dark theme and 0;15 for a light theme.
If the last value is 7 or 9 to 15 then assume a light theme.
@return 1 if a light background was detected, 0 for a dark background otherwise
*/
static int term_get_bg(void)
{
char const *colorfgbg = getenv("COLORFGBG");
if (!colorfgbg) {
return 0; // default dark theme
}
char *p = strrchr(colorfgbg, ';');
if (!p) {
return 0; // default dark theme
}

// Check if the last value is 7 or 9 to 15.
if (p[1] == '7' || p[1] == '9'
|| (p[1] == '1' && p[2] != '\0')) {
return 1; // light theme
}
return 0; // dark theme
}

int term_has_color(void *ctx)
{
#ifdef _WIN32
Expand Down Expand Up @@ -281,6 +313,12 @@ void term_ring_bell(void *ctx)

void term_set_fg(void *ctx, term_color_t color)
{
// Cache the detected terminal background color
static int light_bg = -1;
if (light_bg == -1) {
light_bg = term_get_bg();
}

#ifdef _WIN32
console_t *console = (console_t *)ctx;
if (!console->ansi) {
Expand All @@ -291,14 +329,28 @@ void term_set_fg(void *ctx, term_color_t color)
#else
FILE *fp = (FILE *)ctx;
#endif
if (color == TERM_COLOR_RESET)
if (color == TERM_COLOR_RESET) {
fprintf(fp, "\033[0m");
else
fprintf(fp, "\033[%d;1m", color);
}
else if (light_bg) {
fprintf(fp, "\033[%dm", color); // normal colors on light backgrounds
}
else {
fprintf(fp, "\033[%d;1m", color); // bright/bold colors on dark backgrounds
}
}

void term_set_bg(void *ctx, term_color_t bg, term_color_t fg)
{
// Cache the detected terminal background color
static int light_bg = -1;
if (light_bg == -1) {
light_bg = term_get_bg();
}
if (light_bg && fg >= TERM_COLOR_BRIGHT_BLACK && fg <= TERM_COLOR_BRIGHT_WHITE) {
fg -= 60; // remove bright/bold foreground on light backgrounds
}

if (bg < TERM_COLOR_BLACK
|| (bg > TERM_COLOR_WHITE && bg < TERM_COLOR_BRIGHT_BLACK)
|| bg > TERM_COLOR_BRIGHT_WHITE) {
Expand Down

0 comments on commit 1116ce1

Please sign in to comment.