Emacs Lisp: Text Properties

By Xah Lee. Date: . Last updated: .

Text in a buffer can have “text properties”.

Text properties is used to color text, or add keybinding to that text (for example, pressing Enter on a link in HTML opens the link instead of insert newline.), and other purposes.

What is Text Property

Text Property is a Property List attached to text.

When a property list is attached to text, some keys have special meaning that are predefined by emacs.

Here are some of the most useful property keys for writing a major/minor mode.

'font-lock-face
For syntax coloring. Value is a face. [see Emacs Lisp: How to Define Face]
'face
For syntax coloring. Value is a face. It overrides the 'font-lock-face property. This property is automatically updated/managed by font-lock-mode. [see Emacs Lisp: Font Lock Mode Basics]
'syntax-table
Add syntax table to text. Value is a Syntax Table.

This is useful for example, in a major mode for programing language, you want to make regex delimiter character such as slash / to have string syntax, so regex string are colored as string.

'keymap
Add keybinding to text. Value is a keymap. When cursor is on the text, the keymap has priority in determining keystroke action. [see Emacs Lisp: Create Keymap for Major Mode]

For a complete list, see Special Properties (ELISP Manual)

Functions for Working with Text Property

There are many functions to get values of text properties, add/change/delete them, or find out where a property begins, etc. See

Text Properties (ELISP Manual)

Example: Text Properties, Make a Region Red

Here's a command that makes a region red, by adding a text property of 'font-lock-face to it.

(defun xx-make-word-red (begin end)
  "make current region colored red, using text properties"
  (interactive (list (region-beginning) (region-end)))
  (put-text-property begin end 'font-lock-face '(:foreground "red")))

Select a region, then Alt+x xx-make-word-red

Example: Text Properties, Clickable Filepath to Open It

Here's example of adding a keymap to text, so that when Enter is pressed, it tries to open the file, taking current line as file name/path.

(setq xx-keymap (make-sparse-keymap))

(define-key
 xx-keymap (kbd "RET")
 (lambda () (find-file (thing-at-point 'filename))))

(defun xx-add-prop (begin end)
  "add text properties to a region."
  (interactive "r")
    (put-text-property begin end 'font-lock-face '(:foreground "blue"))
    (put-text-property begin end 'keymap xx-keymap))

try it:

  1. Open a new file, insert some text that contains file path.
  2. Go to a line that's a file path, select it, then Alt+x xx-add-prop. The region will be colored blue, and pressing Enter key on it will call xx-open-me

Video Tutorial

Xah Talk Show 2020-08-21 emacs lisp, write command to highlight text