1

I have a list of key-value pairs that is assigned to a variable.

(setq m-point '(:beg 2811 :end 3018 :op "(" :cl ")" :prefix "" :suffix ""))

How do I access the values of :beg and :end within it?


Context

I wrote a function that makes use of sp-forward-sexp and sp-backward-sexp of smartparens-mode to get the positions of a pair of custom parenthesis.

   (defun paren-position ()
      "Returns a list of positions where parenthesis has been sitting."
      (interactive)
      (let ((m-point ;; find point with matching parenthesis with `(scan-sexps)`. 
         (list
          (ignore-errors (sp-backward-sexp)
          (ignore-errors (sp-forward-sexp))))))
    (flatten (remove nil m-point))))

(:beg 2811 :end 3018 :op "(" :cl ")" :prefix "" :suffix "")) is the value returned when the function is called.

This is the first time I am working with such a list with only key-value pairs (somewhat like a Python dictionary), and I don't quite know how to go about it.

7

I have a list of key-value pairs that is assigned to a variable.

(setq m-point '(:beg 2811 :end 3018 :op "(" :cl ")" :prefix "" :suffix ""))

This is known as a property list or plist.

How do I access the values of :beg and :end within it?

(plist-get m-point :beg)
=> 2811

See C-hig (elisp)Property Lists for more information.

  • For any future readers, the original title of the question did not use the term "plist" -- hence my identifying it as such here in the answer :) – phils Feb 11 at 9:11
1

Besides using the built-in plist-get function, you can also do this Common Lisp style using the getf function from the built-in cl package.

(require 'cl)
(getf '(:a 1 :b 2) :a)
;; => 1

One benefit is that you can then change the value associated with a key using setf:

(defvar l (list :a 1))
(setf (getf l :a) 2)
l
;; => (:a 2)

Something similar can be achieved in vanilla Elisp using plist-put:

(setq l (plist-put l :a 3))
l
;; => (:a 3)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.