Determining If Emacs Is Running In Terminal Or Gui Mode

Even if, like me, you mostly run Emacs in GUI mode, it’s sometimes desirable to invoke a terminal instance. Mostly it doesn’t matter which mode you’re in but there are a few things—font colors, for example—that you may want to set depending on which mode you’re in.

That means you need a way of determining the mode you’re running in. As Bozhidar Batsov tells us, that’s not hard: simply test the variable display-graphic-p. The problem comes when you have both modes running in a single instance of Emacs. In that case, one of the color schemes, say, is going to be wrong.

Batsov has a solution. The answer is to make the mode test in a after-make-frame-functions hook function. That way you can make frame specific settings for the appropriate mode. Here’s the example Batsov gives for setting the font text:

(add-hook 'after-make-frame-functions
  (lambda ()
    ;; we want some font only in GUI Emacs
    (when (display-graphics-p)
      (set-frame-font "DejaVu Sans Mono 28")))

As you see in this example, the code runs in the proper frame environment and the resulting customization is set for this frame only. That allows fine grained configurations even when an Emacs instance has both types of frames. Problem solved.

This entry was posted in General and tagged . Bookmark the permalink.