Customizing syntax highlighting colors in Emacs (Shallow Thoughts)

Akkana's Musings on Open Source Computing and Technology, Science, and Nature.

Sun, 23 Dec 2012

Customizing syntax highlighting colors in Emacs

Emacs has wonderful syntax highlighting. Words will be displayed in different colors depending on their syntax and the mode of the current file -- for instance, in C code, keywords of the language are highlighted in one color, comments in another, strings in a third.

The problem comes when the colors aren't right. Like that awful gold color that the flyspell spell checker uses for some words. Against a light background it makes the words almost impossible to read. I've struggled for years trying to set up custom color schemes to get around that problem, but I finally learned a simpler way to handle it when you see something in a color you want to change.

The trick is to find out what face you need to change. "Face" to emacs means more than a font face like Sans or Lucida; it means a collection of information about how characters are displayed, including font face, weight, slant, color and other attributes.

[Emacs' customize-face screen] When you see something displayed in a color you don't want, place the cursor somewhere in the word. type C-u C-x = will get you the face used, along with all sorts of information about it and a handy Customize what to show link. Or you can go straight to the Customize screen with M-x customize-face -- hit return to customize the face at point (the cursor location).

In the customize-face screen, there's no GUI to choose colors, but you can edit color names. Emacs lists "red" as the foreground color; if you change it to "blue" you'll see a preview of how it will look. Color names come from /etc/X11/rgb.txt, and there are various programs like xcolorsel that will show them -- or better yet, see Wikipedia's X11 color names chart.

Once you've chosen a color, the Save for future sessions button will add a section to your .emacs file with the appropriate elisp code. Of course, you can move this code elsewhere as well. I have a somewhat complex .emacs setup, so I've moved the code into another file. Strangely, I found that my .Xdefaults background color setting no longer worked once I started using custom-set-faces, so I added a line for that as well.

(set-background-color "grey90")
(custom-set-faces
 '(flyspell-duplicate ((((class color)) (:foreground "red" :underline t :weight bold))))
 '(font-lock-comment-face ((((class color) (min-colors 88) (background light)) (:foreground "blue"))))
 )

Tags: ,
[ 13:59 Dec 23, 2012    More linux/editors | permalink to this entry | ]

Comments via Disqus:

blog comments powered by Disqus