2016-03-24 27 views
3

目前我正在研究一種elisp主要模式,它使跨會話使用哈希表。所以每次主模式被初始化時,表格都被加載到內存中。在會議期間和會議結束時,他們被寫入一個文件。通過讀emacs lisp中的習慣性方式序列化

(with-temp-buffer 
    (prin1 hash-table (current-buffer)) 
    (write-file ("path/to/file.el")))) 

加載在會議開始時,數據等做是這樣的:我的當前實現以下面的方式將數據寫入

(setq name-of-table (car 
     (read-from-string 
     (with-temp-buffer 
      (insert-file-contents path-of-file) 
      (buffer-substring-no-properties 
     (point-min) 
     (point-max)))))))) 

它的工作原理,但我有感覺這不是最好的方法。我的目標是:我希望這種主要模式變成一個很好的清潔包,它將自己的數據存儲在包中存儲其他數據的文件夾中。

+1

把初始化到你正在評估反正Lisp代碼?當你閱讀時,你可以省去任何複雜的東西 - 那麼你可以只用'eval-buffer',並且你在寫入時添加的代碼只需要'(setq變量)和最後的結束符。「 – tripleee

+0

看起來簡單而可行。 ^^我會看看它是如何工作的,如果順利的話我會將你的文章標記爲答案:) –

+0

不需要轉換爲字符串,只需在臨時緩衝區中執行'(read(current-buffer))'。 – Lindydancer

回答

2

我這是怎麼實現

寫入文件:

(defun my-write (file data) 
    (with-temp-file file 
    (prin1 data (current-buffer)))) 

從文件中讀取:

(defun my-read (file symbol) 
    (when (boundp symbol) 
    (with-temp-buffer 
     (insert-file-contents file) 
     (goto-char (point-min)) 
     (set symbol (read (current-buffer)))))) 

調用write:

(my-write "~/test.txt" emacs-version) 

調用read

(my-read "~/test.txt" 'my-emacs-version) 
+1

你可以使用'(goto-char(point-min))'後跟'(read(current-buffer))',這樣你就不必創建一個字符串。 – Lindydancer

+0

@Lindydancer編輯你的建議。 – tom

+0

太棒了!不過,我建議在'insert-file-content'之後放置'goto-char',這樣就會更容易閱讀。另外,是否有任何理由不直接返回讀取值而不是設置變量?該代碼將非常簡單:'(defun my-read-from-file(file)(with-temp-buffer(insert-file-content file)(goto-char(point-min))(read(current-緩衝區「)))' – Lindydancer

1

我想出了以下解決方案,通過第一個答案在這裏啓發:

(with-temp-buffer 
    (insert "(setq hash-table ") 
    (prin1 hash-table (current-buffer) 
    (insert ")") 
    (write-file (locate-library "my-data-lib")) 

而且主要模式的初始化過程中,我只是做:

(load "my-data-lib") 

無需for和read-operation,而且我也不需要提供任何文件路徑,只是在加載路徑上有這樣一個文件就足夠了。 Emacs會找到它。 elisp岩石。 :)

1

desktop能爲你做到這一點:

(require 'desktop) 
(unless (memq 'hash-table desktop-globals-to-save) 
    (nconc desktop-globals-to-save (list 'hash-table)))`