Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elisp: How to save data in a file?

I want to save data to a file in my elisp program. I have a multi-dimensional list that I want to save to a file, so I can restore it the next time my program runs. What's the easiest / best way to do this?

I realise, of course, that I can simply write my data to a buffer in a custom format and then save the buffer, but then I'd have to write a function to parse that data format when I want to restore it. I'd rather not have to do that.

In Python, there's the Pickle module that lets you "dump" objects to disk and restore them, very easily. Is there something similar for elisp?

like image 523
Enfors Avatar asked Feb 23 '10 21:02

Enfors


People also ask

How do I save a file in Emacs?

To save the file you are editing, type C-x C-s or select Save Buffer from the Files menu. Emacs writes the file. To let you know that the file was saved correctly, it puts the message Wrote filename in the minibuffer.

Can you only have one buffer open in Emacs at a time?

Each Emacs window displays one Emacs buffer at any time. A single buffer may appear in more than one window; if it does, any changes in its text are displayed in all the windows where it appears. But the windows showing the same buffer can show different parts of it, because each window has its own value of point.

How do I open a file in Emacs?

Use Ctrl-x f to open a file from within Emacs.


1 Answers

This 'dump-vars-to-file routine will create some expressions that can be read by simply evaluating the expressions later (via a 'load command or 'read):

(defun dump-vars-to-file (varlist filename)
  "simplistic dumping of variables in VARLIST to a file FILENAME"
  (save-excursion
    (let ((buf (find-file-noselect filename)))
      (set-buffer buf)
      (erase-buffer)
      (dump varlist buf)
      (save-buffer)
      (kill-buffer))))

(defun dump (varlist buffer)
  "insert into buffer the setq statement to recreate the variables in VARLIST"
  (loop for var in varlist do
        (print (list 'setq var (list 'quote (symbol-value var)))
               buffer)))

I'm sure I'm missing some built-in routine that does a nicer job or is more flexible.

I tested it with this little routine:

(defun checkit ()
  (let ((a '(1 2 3 (4 5)))
        (b '(a b c))
        (c (make-vector 3 'a)))
    (dump-vars-to-file '(a b c) "/some/path/to/file.el")))

Which produced the output:

(setq a (quote (1 2 3 (4 5))))
(setq b (quote (a b c)))
(setq c (quote [a a a]))

For more information, see the info page on reading and printing lisp objects

like image 200
Trey Jackson Avatar answered Oct 15 '22 22:10

Trey Jackson