experiments, projects, miscellany

Saturday, January 22, 2011

Setting multiple text properties in elisp

Recently I was creating some simple elisp functions to make journal entries, and wanted to be able to define a keybinding that would set some combination of text properties on the selected text, or on text subsequently entered.

For some reason, this didn't seem to work in any obvious (at least to me) manner, but eventually with help from gnu.emacs.help I found a method that works. The function to be used is (put-text-property start end prop value).

The name of this function implies that it sets only a single text property. This is more or less correct, as the property I want to set is the "face" property. This property controls many aspects of the appearance of thetext, but the ones I was interested in were bold, italic, and foreground color, and it is not at all clear from the emacs documentation how to set more than one of these.

The answer is that if the property you are setting is the "face" property, you can supply as list as the value, and the face will be set to a combination of the values in the list.

Here are some examples of how to do this (tested on Emacs 23). These calls set properties on the entire line containing point.

;; Italic only 
(put-text-property (line-beginning-position) (line-end-position) 
  'face 'italic) 

;; Blue only: 
(put-text-property (line-beginning-position) (line-end-position) 
  'face '(:foreground "blue")) 

;; Blue and bold: 
(put-text-property (line-beginning-position) (line-end-position) 
  'face '((:foreground "blue") bold)) 

;; Blue and italic: 
(put-text-property (line-beginning-position) (line-end-position) 
  'face '((:foreground "blue") italic)) 

;; Bold, italic, and red: 
(put-text-property (line-beginning-position) (line-end-position) 
  'face '(bold italic (:foreground "red"))) 

No comments: