0

I defined these variables/functions:

(defvar FirstVar-p nil
  "DOCSTRING")

(defun toggle-first-var ()
  "DOCSTRING"
  (interactive)
  (setq FirstVar-p (not FirstVar-p)))


(defvar SecondVar-p nil
  "DOCSTRING")

(defun toggle-second-var ()
  "DOCSTRING"
  (interactive)
  (setq SecondVar-p (not SecondVar-p)))


(defvar ThirdVar-p nil
  "DOCSTRING")

(defun toggle-third-var ()
  "DOCSTRING"
  (interactive)
  (setq ThirdVar-p (not ThirdVar-p)))

Now I want to add a new feature to the functions. I want them to display a message like:

The value of VAR is setted to VALUE

I tried with:

(defun message-variable-t-nil-value (VAR) 
  (let* ((VAR_NAME (symbol-name VAR))
         (MESSAGE (concat "The value of " 
              VAR_NAME 
              " is setted to " 
              ;; ??? VALUE as a string ??? 
                          )))
    
    
         (if 'VAR (message (propertize MESSAGE
                                       'face '(:foreground "GreenYellow")))

           ;; *ELSE*
           (message (propertize MESSAGE
                                'face '(:foreground "OrangeRed"))))
         ))

The idea is to use it like:

(message-variable-t-nil-value FirstVar-p)

in the funcions. Eg.:

(defun toggle-first-var ()
  "DOCSTRING"
  (interactive)
  (setq FirstVar-p (not FirstVar-p))
  (message-variable-t-nil-value FirstVar))

Is there a built-in function to do it. How can I fix my function?

2 Answers 2

2

Yes, the function you're looking for is format:

(defun message-variable-t-nil-value (var) 
  (let* ((val  (and (boundp var)  (symbol-value var)))
         (msg  (format "The value of `%S' is now %S" var val)))
    (message (propertize msg 'face `(:foreground ,(if val
                                                      "GreenYellow"
                                                    "OrangeRed"))))))

The other functions you were looking for are boundp and symbol-value.

It does no good to test 'val for non-nil: it's only nil if val is nil. (Was that what you wanted? I'm assuming instead that you wanted to check whether the symbol is bound as a variable.)

1

Use format. It's the Lisp equivalent of C's printf. Unlike Common Lisp, Emacs Lisp's format specifications are similar to C's, with % as the special character.

(defun show-value-of-variable (symbol)
  (message (format "The value of %s is %S" symbol (symbol-value symbol))))

%s prints a somewhat human-friendly string, for example without quotes around a string. %S prints a string that can be read back to the same value (except for types that don't have a read syntax).

1
  • Your functions works but the Drew's one includes the color stuff. Thanks.
    – Gabriele
    Commented Apr 29, 2022 at 16:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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