1

Is it possible for a variable to be set to an expression that will be evaluated each time that variable is accessed? The idea would be that a user could then set the variable to be either a string or a function that returns a string. Perhaps something like this.

(setq test-variable (lambda () (if (string= (buffer-name) "*scratch*") "true" "false")))
(message "%s" test-variable) ;; prints true if in scratch buffer else print false

It would even be great if there were a way to evaluate something in the same way that the global-mode-line variable gets evaluated

(setq test-variable '(:eval (if (string= (buffer-name) "*scratch*") "true" "false")))
(message "%s" test-variable) ;; prints true if in scratch buffer else print false

It would also be work if all it took was some simple wrapper

(setq test-variable '(:eval (if (string= (buffer-name) "*scratch*") "true" "false")))
(message "%s" (test-wrapper test-variable)) ;; prints true if in scratch buffer else print false

Thank you,

  • 2
    Sounds like what you want is a function: (fset 'test-variable (lambda () (if (string= (buffer-name) "*scratch*") "true" "false"))) (message "%s" (test-variable)). – JeanPierre May 17 '16 at 19:49
  • 1
    Emacs lisp does not have global symbol macros, unlike common lisp. – sds May 17 '16 at 19:57
  • The function solution should work, although it would be nice to have a bit more sugar to it, like Scheme parameters. – wasamasa May 17 '16 at 21:51
  • @sds That sounds like what I would want – Jules May 23 '16 at 13:46
1

It sounds like what you want is a function rather than a variable -- evaluating something every time it's accessed is exactly what a function is for.

You can pass around the symbol for a function, and then apply it later, which I think gets at using it like a variable too.

Does this do what you're asking?

(defun is-scratch ()
  (string= (buffer-name) "*scratch*"))

(setq message-generator 'is-scratch)

(message "%s" (apply message-generator nil))
  • If you don't have a variable number of args, you can use funcall, i.e. (funcall message-generator). – npostavs May 20 '16 at 20:43
  • The issue is that in somebody else's code they have a variable that I believe would make much more sense as a function that returns the variable. I cannot change their code to take a function instead because that would possibly work other peoples workflows. So I was hoping there would be some elegant solution such as the one available in the modeline. – Jules May 23 '16 at 13:45

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.