Elisp: Property List
What's Property List
Property list (in short, plist) is a list, but to be interpreted as list of pairs, like this:
'(key1 val1 key2 val2 …)
Property list is not supposed to have duplicate keys, and should always have even length.
Key should be lisp symbols, value can be any lisp object.
(info "(elisp) Property Lists")
Use of Property List
Property List is used as a simplest form of key/value pairs. For example, for less than 50 items.
Property list is just a normal list. There's no dedicated function to lookup by value as alist can.
[see Elisp: Association List]
Property list is used extensively in emacs.
The 2 major use of property list are:
- Symbol's property list. Each symbol, is associated with a property list. Used primarily to store info related to the symbol, such as compiler info, but can be anything.
- Text Properties. Any character or string in a buffer, can have a property list, used to store color, special keyboard shortcut, etc. [see Elisp: Text Properties]
Property list isn't a generic data structure. If you have for example more than 100 items, you probably should use alist instead.
[see Elisp: Association List]
For over 1k items, use hash table [see Elisp: Hash Table]
Access Property List
When accessing property list, existence of key is checked with eq
.
Here are generic functions for plist.
Get key value:
;; get a value of a key in property list (plist-get '(x 1 y 2) 'y) ; 2 ;; non existent key returns nil (plist-get '(x 1 y 2) 'b) ; nil
Set a key's value:
(setq xx '(a 1 b 2)) ;; set value to a existing key (setq xx (plist-put xx 'b 3)) ;; must use setq, because plist-put works by return value (plist-get xx 'b) ; 3 ;; set value to new key (setq xx (plist-put xx 'd 3)) (plist-get xx 'd) ; 3
check if a key exist:
(setq xx '(a 1 b 2)) ;; check if a key exist (plist-member xx 'b)
lax-plist-get
→ similar to plist-get
, but compare key using equal
.
lax-plist-put
→ similar to plist-put
, but compare key using equal
.
Symbol's Property List
Each elisp symbol, can be attached a property list. Such is called “symbol plist”.
Text Properties
Text in a buffer region can be attached a property list. Such is called “Text Properties”.
Data Structure Topic
Patreon me $5. Ask me question on patreon