setting gtk textview selection color with css

2.8k Views Asked by At

I have the following code that works fine to set background and foreground colors for a GtkTextview:

static void
setColor(GtkWidget * widget) {
    auto style_context = gtk_widget_get_style_context (widget);
    gtk_style_context_add_class(style_context, GTK_STYLE_CLASS_VIEW );
    auto css_provider = gtk_css_provider_new();
    GError *error=NULL;
    auto data = g_strdup_printf("\
    * {\
      background-color: black;\
      color: white;\
    }\
    *:selected {\
      background-color: blue;\
      color: yellow;\
    }\
    ");
    gtk_css_provider_load_from_data (css_provider, data, -1, &error);
    g_free(data);
    if (error){
        ERROR("gtk_css_provider_load_from_data: %s\n", error->message);
        g_error_free(error);
        return;
    }
    gtk_style_context_add_provider (style_context, 
            GTK_STYLE_PROVIDER(css_provider),
            GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);

}

The result is that both normal and selected text color have black background and white foreground.

Why doesn't the selected text appear in yellow/blue?

Any pointer to an example file would be much appreciated.

1

There are 1 best solutions below

1
On

Figured it out. The lack of any tutorials or example led me search the gtk source code for answers. A very complete css file is in the Adwaita theme (gtk-contained.css). From looking through that and a bit of experimenting, the following code will set the foreground and background colors for normal and selected text as specified.

auto data = g_strdup_printf("\
  textview text {\
  background-color: black;\
  color: white;\
}\
  .view text selection {\
  background-color: blue;\
  color: yellow;\
}\
");

The main problem was using the "*". In that same file there is a comment which reads "Wildcards ar bad and troublesome, use them with car, or better, just don't. Everytime a wildcard is used a kitten dies, painfully."