this post was submitted on 13 Nov 2023
2 points (100.0% liked)

Emacs

311 readers
1 users here now

A community for the timeless and infinitely powerful editor. Want to see what Emacs is capable of?!

Get Emacs

Rules

  1. Posts should be emacs related
  2. Be kind please
  3. Yes, we already know: Google results for "emacs" and "vi" link to each other. We good.

Emacs Resources

Emacs Tutorials

Useful Emacs configuration files and distributions

Quick pain-saver tip

founded 1 year ago
MODERATORS
 

I'm wondering if there's any way to make a variable automatically save its old value, so that I can, e.g., write a minor mode that will automatically restore the old values of variables when it's deactivated (without having to declare a bunch of -old-value variables).

top 7 comments
sorted by: hot top controversial new old
[–] 7890yuiop@alien.top 2 points 1 year ago

You don't have to declare a new variable each time you want to remember an old value. You could, e.g., put a custom symbol property on the variable symbol with the old value (or list of old values) you wanted to store. Or maintain a single variable mapping all your variable symbols to their old values.

[–] arthurno1@alien.top 1 points 1 year ago

There is no built-in automatic way; you will have to backup your old values any way you want; create a bunch of new symbols, put them into a hash table, a list, or whichever else strategy you prefer.

[–] SnooPets20@alien.top 1 points 1 year ago

I think themes could be used for this.

[–] JDRiverRun@alien.top 1 points 1 year ago

A variable watcher maybe.

    (add-variable-watcher
     'myvar
     (lambda (sym val op buf)
       (when (eq op 'set)
         (push val (get sym 'prior-values)))))
[–] Qudit314159@alien.top 1 points 1 year ago

The function add-variable-watcher registers a callback that is invoked whenever the variable's value changes. You could use it to save old values in a list or other data structure.

[–] fuzzbomb23@alien.top 1 points 11 months ago

Have a look at the approach taken by the logos.el package. There's a section in the manual called Leverage logos-focus-mode-hook.

The idea there is that when you enable the logos-focus-mode, you'll often want to change some other minor modes and variables too. But when you disable logos-focus-mode, you'll want those other minor modes to revert to their previous value. The Logos package provides a few convenience functions to remember the previous values, and they are automatically restored when logos-focus-mode is turned off.

Perhaps the code for that could be made generic, instead of being coupled to the logos-focus-mode?

[–] pwnedary@alien.top 1 points 1 year ago

There is buffer-local-set-state at least, not sure if it is any good.