Elisp: How to save data in a file?

后端 未结 2 726
时光取名叫无心
时光取名叫无心 2021-02-04 07:43

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

相关标签:
2条回答
  • 2021-02-04 08:21

    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

    0 讨论(0)
  • 2021-02-04 08:26

    Another proposal. Instead of serialising setq calls, this one basically lets you use the file as a variable.

    (defun print-to-file (filename data)
      (with-temp-file filename
        (prin1 data (current-buffer))))
    
    (defun read-from-file (filename)
      (with-temp-buffer
        (insert-file-contents filename)
        (cl-assert (eq (point) (point-min)))
        (read (current-buffer))))
    

    Usage:

    (print-to-file "bla.el" '(1 2 "foo" 'bar))
    (1 2 "foo" (quote bar))
    
    (read-from-file "bla.el")
    (1 2 "foo" (quote bar))
    
    0 讨论(0)
提交回复
热议问题