Elisp: Define Face

By Xah Lee. Date: .

Define Face

💡 TIP: elisp manual says face name should not end in “-face” and reason being “redundant”.

;; examples of defining faces

(defface my-lang-phi-word
  '((t :foreground "black"
       :background "aquamarine"
       :weight bold
       :underline t
       ))
  "Face for function parameters."
  :group 'my-lang-mode )

(defface my-lang-gamma-word
  '((t :foreground "red"
       :background "#f5f5f5"
       ))
  "Face for global variables."
  :group 'my-lang-mode )

You can use the above code as a template to define your faces.

Alt+x list-colors-display to list named colors and their hexadecimal values.

Define Face for 8-Color Terminal

Emacs's face system supports terminal emulators that has limited colors. For example, you can define a face such that when user is in a terminal that only has 8 colors, the face will use a available color and still sensible.

For example, here's the definition of the standard face highlight:

(defface highlight
  '((((class color) (min-colors 88) (background light))
     :background "darkseagreen2")
    (((class color) (min-colors 88) (background dark))
     :background "darkolivegreen")
    (((class color) (min-colors 16) (background light))
     :background "darkseagreen2")
    (((class color) (min-colors 16) (background dark))
     :background "darkolivegreen")
    (((class color) (min-colors 8))
     :background "green" :foreground "black")
    (t :inverse-video t))
  "Basic face for highlighting."
  :group 'basic-faces)

Define a New Face by Inheritance

;; define a new face by inherit existing

(defface my-mode-property '((t :inherit font-lock-keyword-face))
  "font face for property keywords."
  :group 'my-mode
  )

Set a Face

face-spec-set → set a face spec regardless if it already has a face value. (this is useful when you are working on a major mode.)

(defface my-identifier-x
  '((t :foreground "red"
      :weight bold
      ))
  "face for user defined variables."
  :group 'my-mode )

(face-spec-set
 'my-identifier-x
 '((t :foreground "blue"
      :weight bold
      ))
 'face-defface-spec
 )

Face Attributes (styles)

You can specify font, weight, text color, background color, underline, overline, border, slant (italic), etc.

To see complete list of attributes, see:

Reference

Elisp, font face