org-persist.el 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920
  1. ;;; org-persist.el --- Persist cached data across Emacs sessions -*- lexical-binding: t; -*-
  2. ;; Copyright (C) 2021-2022 Free Software Foundation, Inc.
  3. ;; Author: Ihor Radchenko <yantar92 at gmail dot com>
  4. ;; Keywords: cache, storage
  5. ;; This file is part of GNU Emacs.
  6. ;; GNU Emacs is free software: you can redistribute it and/or modify
  7. ;; it under the terms of the GNU General Public License as published by
  8. ;; the Free Software Foundation, either version 3 of the License, or
  9. ;; (at your option) any later version.
  10. ;; GNU Emacs is distributed in the hope that it will be useful,
  11. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. ;; GNU General Public License for more details.
  14. ;; You should have received a copy of the GNU General Public License
  15. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  16. ;;; Commentary:
  17. ;;
  18. ;; This file implements persistant cache storage across Emacs sessions.
  19. ;; Both global and buffer-local data can be stored. This
  20. ;; implementation is not meant to be used to store important data -
  21. ;; all the caches should be safe to remove at any time.
  22. ;;
  23. ;; Example usage:
  24. ;;
  25. ;; 1. Temporarily cache Elisp symbol value to disk. Remove upon
  26. ;; closing Emacs:
  27. ;; (org-persist-write 'variable-symbol)
  28. ;; (org-persist-read 'variable-symbol) ;; read the data later
  29. ;; 2. Temporarily cache a remote URL file to disk. Remove upon
  30. ;; closing Emacs:
  31. ;; (org-persist-write 'url "https://static.fsf.org/common/img/logo-new.png")
  32. ;; (org-persist-read 'url "https://static.fsf.org/common/img/logo-new.png")
  33. ;; `org-persist-read' will return the cached file location or nil if cached file
  34. ;; has been removed.
  35. ;; 3. Temporarily cache a file, including TRAMP path to disk:
  36. ;; (org-persist-write 'file "/path/to/file")
  37. ;; 4. Cache file or URL while some other file exists.
  38. ;; (org-persist-register '(url "https://static.fsf.org/common/img/logo-new.png") '(:file "/path to the other file") :expiry 'never :write-immediately t)
  39. ;; or, if the other file is current buffer file
  40. ;; (org-persist-register '(url "https://static.fsf.org/common/img/logo-new.png") (current-buffer) :expiry 'never :write-immediately t)
  41. ;; 5. Cache value of a Elisp variable to disk. The value will be
  42. ;; saved and restored automatically (except buffer-local
  43. ;; variables).
  44. ;; ;; Until `org-persist-default-expiry'
  45. ;; (org-persist-register 'variable-symbol)
  46. ;; ;; Specify expiry explicitly
  47. ;; (org-persist-register 'variable-symbol :expiry 'never)
  48. ;; ;; Save buffer-local variable (buffer-local will not be
  49. ;; ;; autoloaded!)
  50. ;; (org-persist-register 'org-element--cache (current-buffer))
  51. ;; ;; Save buffer-local variable preserving circular links:
  52. ;; (org-persist-register 'org-element--headline-cache (current-buffer)
  53. ;; :inherit 'org-element--cache)
  54. ;; 6. Load variable by side effects assigning variable symbol:
  55. ;; (org-persist-load 'variable-symbol (current-buffer))
  56. ;; 7. Version variable value:
  57. ;; (org-persist-register '((elisp variable-symbol) (version "2.0")))
  58. ;; 8. Cancel variable persistence:
  59. ;; (org-persist-unregister 'variable-symbol 'all) ; in all buffers
  60. ;; (org-persist-unregister 'variable-symbol) ;; global variable
  61. ;; (org-persist-unregister 'variable-symbol (current-buffer)) ;; buffer-local
  62. ;;
  63. ;; Most common data type is variable data. However, other data types
  64. ;; can also be stored.
  65. ;;
  66. ;; Persistent data is stored in individual files. Each of the files
  67. ;; can contain a collection of related data, which is particularly
  68. ;; useful when, say, several variables cross-reference each-other's
  69. ;; data-cells and we want to preserve their circular structure.
  70. ;;
  71. ;; Each data collection can be associated with a local or remote file,
  72. ;; its inode number, or contents hash. The persistent data collection
  73. ;; can later be accessed using either file bufer, file, inode, or
  74. ;; contents hash.
  75. ;;
  76. ;; The data collections can be versioned and removed upon expiry.
  77. ;;
  78. ;; In the code below I will use the following naming conventions:
  79. ;; 1. Container :: a type of data to be stored
  80. ;; Containers can store elisp variables, files, and version
  81. ;; numbers. Each container can be customized with container
  82. ;; options. For example, `elisp' container is customized with
  83. ;; variable symbol. (elisp variable) is a container storing
  84. ;; Lisp variable value. Similarly, (version "2.0") container
  85. ;; will store version number.
  86. ;; 2. Associated :: an object the container is associated with. The
  87. ;; object can be a buffer, file, inode number, file contents hash,
  88. ;; a generic key, or multiple of them. Associated can also be nil.
  89. ;; 3. Data collection :: a list of containers linked to an associated
  90. ;; object/objects. Each data collection can also have auxiliary
  91. ;; records. Their only purpose is readability of the collection
  92. ;; index.
  93. ;; 4. Index file :: a file listing all the stored data collections.
  94. ;; 5. Persist file :: a file holding data values or references to
  95. ;; actual data values for a single data collection. This file
  96. ;; contains an alist associating each data container in data
  97. ;; collection with its value or a reference to the actual value.
  98. ;;
  99. ;; All the persistent data is stored in `org-persist-directory'. The data
  100. ;; collections are listed in `org-persist-index-file' and the actual data is
  101. ;; stored in UID-style subfolders.
  102. ;;
  103. ;; The `org-persist-index-file' stores the value of `org-persist--index'.
  104. ;;
  105. ;; Each collection is represented as a plist containing the following
  106. ;; properties:
  107. ;; - `:container' : list of data continers to be stored in single
  108. ;; file;
  109. ;; - `:persist-file': data file name;
  110. ;; - `:associated' : list of associated objects;
  111. ;; - `:last-access' : last date when the container has been accessed;
  112. ;; - `:expiry' : list of expiry conditions.
  113. ;; - all other keywords are ignored
  114. ;;
  115. ;; The available types of data containers are:
  116. ;; 1. (file variable-symbol) or just variable-symbol :: Storing
  117. ;; elisp variable data.
  118. ;; 2. (file) :: Store a copy of the associated file preserving the
  119. ;; extension.
  120. ;; (file "/path/to/a/file") :: Store a copy of the file in path.
  121. ;; 3. (version "version number") :: Version the data collection.
  122. ;; If the stored collection has different version than "version
  123. ;; number", disregard it.
  124. ;; 4. (url) :: Store a downloaded copy of URL object.
  125. ;;
  126. ;; The data collections can expire, in which case they will be removed
  127. ;; from the persistent storage at the end of Emacs session. The
  128. ;; expiry condition can be set when saving/registering data
  129. ;; containers. The expirty condition can be `never' - data will never
  130. ;; expire; `nil' - data will expire at the end of current Emacs session;
  131. ;; a number - data will expire after the number days from last access;
  132. ;; a function - data will expire if the function, called with a single
  133. ;; argument - collection, returns non-nil.
  134. ;;
  135. ;;
  136. ;; Data collections associated with files will automatically expire
  137. ;; when the file is removed. If the associated file is remote, the
  138. ;; expiry is controlled by `org-persist-remote-files' instead.
  139. ;;
  140. ;; Data loading/writing can be more accurately controlled using
  141. ;; `org-persist-before-write-hook', `org-persist-before-read-hook', and `org-persist-after-read-hook'.
  142. ;;; Code:
  143. (require 'org-compat)
  144. (require 'org-id)
  145. (require 'xdg nil t)
  146. (declare-function org-back-to-heading "org" (&optional invisible-ok))
  147. (declare-function org-next-visible-heading "org" (arg))
  148. (declare-function org-at-heading-p "org" (&optional invisible-not-ok))
  149. (defconst org-persist--storage-version "2.4"
  150. "Persistent storage layout version.")
  151. (defgroup org-persist nil
  152. "Persistent cache for Org mode."
  153. :tag "Org persist"
  154. :group 'org)
  155. (defcustom org-persist-directory (expand-file-name
  156. (org-file-name-concat
  157. (let ((cache-dir (when (fboundp 'xdg-cache-home)
  158. (xdg-cache-home))))
  159. (if (or (seq-empty-p cache-dir)
  160. (not (file-exists-p cache-dir))
  161. (file-exists-p (org-file-name-concat
  162. user-emacs-directory
  163. "org-persist")))
  164. user-emacs-directory
  165. cache-dir))
  166. "org-persist/"))
  167. "Directory where the data is stored."
  168. :group 'org-persist
  169. :type 'directory)
  170. (defcustom org-persist-remote-files 100
  171. "Whether to keep persistent data for remote files.
  172. When this variable is nil, never save persitent data associated with
  173. remote files. When t, always keep the data. When
  174. `check-existence', contact remote server containing the file and only
  175. keep the data when the file exists on the server. When a number, keep
  176. up to that number persistent values for remote files.
  177. Note that the last option `check-existence' may cause Emacs to show
  178. password prompts to log in."
  179. :group 'org-persist
  180. :type '(choice (const :tag "Never" nil)
  181. (const :tag "Always" t)
  182. (number :tag "Keep not more than X files")
  183. (const :tag "Check if exist on remote" 'check-existence)))
  184. (defcustom org-persist-default-expiry 30
  185. "Default expiry condition for persistent data.
  186. When this variable is nil, all the data vanishes at the end of Emacs
  187. session. When `never', the data never vanishes. When a number, the
  188. data is deleted that number days after last access. When a function,
  189. it should be a function returning non-nil when the data is expired. The
  190. function will be called with a single argument - collection."
  191. :group 'org-persist
  192. :type '(choice (const :tag "Never" 'never)
  193. (const :tag "Always" nil)
  194. (number :tag "Keep N days")
  195. (function :tag "Function")))
  196. (defconst org-persist-index-file "index"
  197. "File name used to store the data index.")
  198. (defvar org-persist-before-write-hook nil
  199. "Abnormal hook ran before saving data.
  200. The hook must accept the same arguments as `org-persist-write'.
  201. The hooks will be evaluated until a hook returns non-nil.
  202. If any of the hooks return non-nil, do not save the data.")
  203. (defvar org-persist-before-read-hook nil
  204. "Abnormal hook ran before reading data.
  205. The hook must accept the same arguments as `org-persist-read'.
  206. The hooks will be evaluated until a hook returns non-nil.
  207. If any of the hooks return non-nil, do not read the data.")
  208. (defvar org-persist-after-read-hook nil
  209. "Abnormal hook ran after reading data.
  210. The hook must accept the same arguments as `org-persist-read'.")
  211. (defvar org-persist--index nil
  212. "Global index.
  213. The index is a list of plists. Each plist contains information about
  214. persistent data storage. Each plist contains the following
  215. properties:
  216. - `:container' : list of data continers to be stored in single file
  217. - `:persist-file': data file name
  218. - `:associated' : list of associated objects
  219. - `:last-access' : last date when the container has been read
  220. - `:expiry' : list of expiry conditions
  221. - all other keywords are ignored.")
  222. (defvar org-persist--index-hash nil
  223. "Hash table storing `org-persist--index'. Used for quick access.
  224. They keys are conses of (container . associated).")
  225. (defvar org-persist--report-time 0.5
  226. "Whether to report read/write time.
  227. When the value is a number, it is a threshold number of seconds. If
  228. the read/write time of a single variable exceeds the threashold, a
  229. message is displayed.
  230. When the value is a non-nil non-number, always display the message.
  231. When the value is nil, never diplay the message.")
  232. ;;;; Common functions
  233. (defun org-persist--display-time (duration format &rest args)
  234. "Report DURATION according to FORMAT + ARGS message.
  235. FORMAT and ARGS are passed to `message'."
  236. (when (or (and org-persist--report-time
  237. (numberp org-persist--report-time)
  238. (>= duration org-persist--report-time))
  239. (and org-persist--report-time
  240. (not (numberp org-persist--report-time))))
  241. (apply #'message
  242. (format "org-persist: %s took %%.2f sec" format)
  243. (append args (list duration)))))
  244. (defun org-persist--read-elisp-file (&optional buffer-or-file)
  245. "Read elisp data from BUFFER-OR-FILE or current buffer."
  246. (unless buffer-or-file (setq buffer-or-file (current-buffer)))
  247. (with-temp-buffer
  248. (if (bufferp buffer-or-file)
  249. (set-buffer buffer-or-file)
  250. (insert-file-contents buffer-or-file))
  251. (condition-case err
  252. (let ((coding-system-for-read 'utf-8)
  253. (read-circle t)
  254. (start-time (float-time)))
  255. ;; FIXME: Reading sometimes fails to read circular objects.
  256. ;; I suspect that it happens when we have object reference
  257. ;; #N# read before object definition #N=. If it is really
  258. ;; so, it should be Emacs bug - either in `read' or in
  259. ;; `prin1'. Meanwhile, just fail silently when `read'
  260. ;; fails to parse the saved cache object.
  261. (prog1
  262. (read (current-buffer))
  263. (org-persist--display-time
  264. (- (float-time) start-time)
  265. "Reading from %S" buffer-or-file)))
  266. ;; Recover gracefully if index file is corrupted.
  267. (error
  268. ;; Remove problematic file.
  269. (unless (bufferp buffer-or-file) (delete-file buffer-or-file))
  270. ;; Do not report the known error to user.
  271. (unless (string-match-p "Invalid read syntax" (error-message-string err))
  272. (warn "Emacs reader failed to read data in %S. The error was: %S"
  273. buffer-or-file (error-message-string err)))
  274. nil))))
  275. (defun org-persist--write-elisp-file (file data &optional no-circular pp)
  276. "Write elisp DATA to FILE."
  277. (let ((print-circle (not no-circular))
  278. print-level
  279. print-length
  280. print-quoted
  281. (print-escape-control-characters t)
  282. (print-escape-nonascii t)
  283. (print-continuous-numbering t)
  284. print-number-table
  285. (start-time (float-time)))
  286. (unless (file-exists-p (file-name-directory file))
  287. (make-directory (file-name-directory file) t))
  288. (with-temp-file file
  289. (if pp
  290. (pp data (current-buffer))
  291. (prin1 data (current-buffer))))
  292. (org-persist--display-time
  293. (- (float-time) start-time)
  294. "Writing to %S" file)))
  295. (defmacro org-persist-gc:generic (container collection)
  296. "Garbage collect CONTAINER data from COLLECTION."
  297. `(let* ((c (org-persist--normalize-container ,container))
  298. (gc-func-symbol (intern (format "org-persist-gc:%s" (car c)))))
  299. (unless (fboundp gc-func-symbol)
  300. (error "org-persist: GC function %s not defined"
  301. gc-func-symbol))
  302. (funcall gc-func-symbol c ,collection)))
  303. (defmacro org-persist--gc-expired-p (cnd collection)
  304. "Check if expiry condition CND triggers for COLLECTION."
  305. `(pcase ,cnd
  306. (`nil t)
  307. (`never nil)
  308. ((pred numberp)
  309. (when (plist-get ,collection :access-time)
  310. (<= (float-time) (+ (plist-get ,collection :access-time) (* ,cnd 24 60 60)))))
  311. ((pred functionp)
  312. (funcall ,cnd ,collection))
  313. (_ (error "org-persist: Unsupported expiry type %S" ,cnd))))
  314. ;;;; Working with index
  315. (defmacro org-persist-collection-let (collection &rest body)
  316. "Bind container and associated from COLLECTION and execute BODY."
  317. (declare (debug (form body)) (indent 1))
  318. `(with-no-warnings
  319. ;; FIXME: We only need to suppress warnings about unused
  320. ;; let-bindings. However, it is unclear how to achieve it with
  321. ;; `with-suppressed-warnings'.
  322. (let* ((container (plist-get ,collection :container))
  323. (associated (plist-get ,collection :associated))
  324. (path (plist-get associated :file))
  325. (inode (plist-get associated :inode))
  326. (hash (plist-get associated :hash))
  327. (key (plist-get associated :key)))
  328. ,@body)))
  329. (defun org-persist--find-index (collection)
  330. "Find COLLECTION in `org-persist--index'."
  331. (org-persist-collection-let collection
  332. (and org-persist--index-hash
  333. (catch :found
  334. (dolist (cont (cons container container))
  335. (let (r)
  336. (setq r (or (gethash (cons cont associated) org-persist--index-hash)
  337. (and path (gethash (cons cont (list :file path)) org-persist--index-hash))
  338. (and inode (gethash (cons cont (list :inode inode)) org-persist--index-hash))
  339. (and hash (gethash (cons cont (list :hash hash)) org-persist--index-hash))
  340. (and key (gethash (cons cont (list :key key)) org-persist--index-hash))))
  341. (when r (throw :found r))))))))
  342. (defun org-persist--add-to-index (collection &optional hash-only)
  343. "Add or update COLLECTION in `org-persist--index'.
  344. When optional HASH-ONLY is non-nil, only modify the hash table.
  345. Return PLIST."
  346. (org-persist-collection-let collection
  347. (let ((existing (org-persist--find-index collection)))
  348. (if existing
  349. (progn
  350. (plist-put existing :container container)
  351. (plist-put (plist-get existing :associated) :file path)
  352. (plist-put (plist-get existing :associated) :inode inode)
  353. (plist-put (plist-get existing :associated) :hash hash)
  354. (plist-put (plist-get existing :associated) :key key)
  355. existing)
  356. (unless hash-only (push collection org-persist--index))
  357. (unless org-persist--index-hash (setq org-persist--index-hash (make-hash-table :test 'equal)))
  358. (dolist (cont (cons container container))
  359. (puthash (cons cont associated) collection org-persist--index-hash)
  360. (when path (puthash (cons cont (list :file path)) collection org-persist--index-hash))
  361. (when inode (puthash (cons cont (list :inode inode)) collection org-persist--index-hash))
  362. (when hash (puthash (cons cont (list :hash inode)) collection org-persist--index-hash))
  363. (when key (puthash (cons cont (list :key inode)) collection org-persist--index-hash)))
  364. collection))))
  365. (defun org-persist--remove-from-index (collection)
  366. "Remove COLLECTION from `org-persist--index'."
  367. (let ((existing (org-persist--find-index collection)))
  368. (when existing
  369. (org-persist-collection-let collection
  370. (dolist (cont (cons container container))
  371. (unless (listp (car container))
  372. (org-persist-gc:generic cont collection))
  373. (remhash (cons cont associated) org-persist--index-hash)
  374. (when path (remhash (cons cont (list :file path)) org-persist--index-hash))
  375. (when inode (remhash (cons cont (list :inode inode)) org-persist--index-hash))
  376. (when hash (remhash (cons cont (list :hash hash)) org-persist--index-hash))
  377. (when key (remhash (cons cont (list :key key)) org-persist--index-hash))))
  378. (setq org-persist--index (delq existing org-persist--index)))))
  379. (defun org-persist--get-collection (container &optional associated &rest misc)
  380. "Return or create collection used to store CONTAINER for ASSOCIATED.
  381. When ASSOCIATED is nil, it is a global CONTAINER.
  382. ASSOCIATED can also be a (:buffer buffer) or buffer, (:file file-path)
  383. or file-path, (:inode inode), (:hash hash), or or (:key key).
  384. MISC, if non-nil will be appended to the collection."
  385. (unless (and (listp container) (listp (car container)))
  386. (setq container (list container)))
  387. (setq associated (org-persist--normalize-associated associated))
  388. (unless (equal misc '(nil))
  389. (setq associated (append associated misc)))
  390. (or (org-persist--find-index
  391. `( :container ,(org-persist--normalize-container container)
  392. :associated ,associated))
  393. (org-persist--add-to-index
  394. (list :container (org-persist--normalize-container container)
  395. :persist-file
  396. (replace-regexp-in-string "^.." "\\&/" (org-id-uuid))
  397. :associated associated))))
  398. ;;;; Reading container data.
  399. (defun org-persist--normalize-container (container)
  400. "Normalize CONTAINER representation into (type . settings)."
  401. (if (and (listp container) (listp (car container)))
  402. (mapcar #'org-persist--normalize-container container)
  403. (pcase container
  404. ((or `elisp `version `file `index `url)
  405. (list container nil))
  406. ((pred symbolp)
  407. (list `elisp container))
  408. (`(,(or `elisp `version `file `index `url) . ,_)
  409. container)
  410. (_ (error "org-persist: Unknown container type: %S" container)))))
  411. (defvar org-persist--associated-buffer-cache (make-hash-table :weakness 'key)
  412. "Buffer hash cache.")
  413. (defun org-persist--normalize-associated (associated)
  414. "Normalize ASSOCIATED representation into (:type value)."
  415. (pcase associated
  416. ((or (pred stringp) `(:file ,_))
  417. (unless (stringp associated)
  418. (setq associated (cadr associated)))
  419. (let* ((rtn `(:file ,associated))
  420. (inode (and (fboundp 'file-attribute-inode-number)
  421. (file-attribute-inode-number
  422. (file-attributes associated)))))
  423. (when inode (plist-put rtn :inode inode))
  424. rtn))
  425. ((or (pred bufferp) `(:buffer ,_))
  426. (unless (bufferp associated)
  427. (setq associated (cadr associated)))
  428. (let ((cached (gethash associated org-persist--associated-buffer-cache))
  429. file inode hash)
  430. (if (and cached (eq (buffer-modified-tick associated)
  431. (car cached)))
  432. (progn
  433. (setq file (nth 1 cached)
  434. inode (nth 2 cached)
  435. hash (nth 3 cached)))
  436. (setq file (buffer-file-name
  437. (or (buffer-base-buffer associated)
  438. associated)))
  439. (setq inode (when (and file
  440. (fboundp 'file-attribute-inode-number))
  441. (file-attribute-inode-number
  442. (file-attributes file))))
  443. (setq hash (secure-hash 'md5 associated))
  444. (puthash associated
  445. (list (buffer-modified-tick associated)
  446. file inode hash)
  447. org-persist--associated-buffer-cache))
  448. (let ((rtn `(:hash ,hash)))
  449. (when file (setq rtn (plist-put rtn :file file)))
  450. (when inode (setq rtn (plist-put rtn :inode inode)))
  451. rtn)))
  452. ((pred listp)
  453. associated)
  454. (_ (error "Unknown associated object %S" associated))))
  455. (defmacro org-persist-read:generic (container reference-data collection)
  456. "Read and return the data stored in CONTAINER.
  457. REFERENCE-DATA is associated with CONTAINER in the persist file.
  458. COLLECTION is the plist holding data collectin."
  459. `(let* ((c (org-persist--normalize-container ,container))
  460. (read-func-symbol (intern (format "org-persist-read:%s" (car c)))))
  461. (setf ,collection (plist-put ,collection :last-access (float-time)))
  462. (setf ,collection (plist-put ,collection :last-access-hr (format-time-string "%FT%T%z" (float-time))))
  463. (unless (fboundp read-func-symbol)
  464. (error "org-persist: Read function %s not defined"
  465. read-func-symbol))
  466. (funcall read-func-symbol c ,reference-data ,collection)))
  467. (defun org-persist-read:elisp (_ lisp-value __)
  468. "Read elisp container and return LISP-VALUE."
  469. lisp-value)
  470. (defun org-persist-read:version (container _ __)
  471. "Read version CONTAINER."
  472. (cadr container))
  473. (defun org-persist-read:file (_ path __)
  474. "Read file container from PATH."
  475. (when (and path (file-exists-p (concat org-persist-directory path)))
  476. (concat org-persist-directory path)))
  477. (defun org-persist-read:url (_ path __)
  478. "Read file container from PATH."
  479. (when (and path (file-exists-p (concat org-persist-directory path)))
  480. (concat org-persist-directory path)))
  481. (defun org-persist-read:index (cont index-file _)
  482. "Read index container CONT from INDEX-FILE."
  483. (when (file-exists-p index-file)
  484. (let ((index (org-persist--read-elisp-file index-file)))
  485. (when index
  486. (catch :found
  487. (dolist (collection index)
  488. (org-persist-collection-let collection
  489. (when (and (not associated)
  490. (pcase container
  491. (`((index ,version))
  492. (equal version (cadr cont)))
  493. (_ nil)))
  494. (throw :found index)))))))))
  495. ;;;; Applying container data for side effects.
  496. (defmacro org-persist-load:generic (container reference-data collection)
  497. "Load the data stored in CONTAINER for side effects.
  498. REFERENCE-DATA is associated with CONTAINER in the persist file.
  499. COLLECTION is the plist holding data collectin."
  500. `(let* ((container (org-persist--normalize-container ,container))
  501. (load-func-symbol (intern (format "org-persist-load:%s" (car container)))))
  502. (setf ,collection (plist-put ,collection :last-access (float-time)))
  503. (setf ,collection (plist-put ,collection :last-access-hr (format-time-string "%FT%T%z" (float-time))))
  504. (unless (fboundp load-func-symbol)
  505. (error "org-persist: Load function %s not defined"
  506. load-func-symbol))
  507. (funcall load-func-symbol container ,reference-data ,collection)))
  508. (defun org-persist-load:elisp (container lisp-value collection)
  509. "Assign elisp CONTAINER in COLLECTION LISP-VALUE."
  510. (let ((lisp-symbol (cadr container))
  511. (buffer (when (plist-get (plist-get collection :associated) :file)
  512. (get-file-buffer (plist-get (plist-get collection :associated) :file)))))
  513. (if buffer
  514. (with-current-buffer buffer
  515. (make-variable-buffer-local lisp-symbol)
  516. (set lisp-symbol lisp-value))
  517. (set lisp-symbol lisp-value))))
  518. (defalias 'org-persist-load:version #'org-persist-read:version)
  519. (defalias 'org-persist-load:file #'org-persist-read:file)
  520. (defun org-persist-load:index (container index-file _)
  521. "Load `org-persist--index' from INDEX-FILE according to CONTAINER."
  522. (unless org-persist--index
  523. (setq org-persist--index (org-persist-read:index container index-file nil))
  524. (setq org-persist--index-hash nil)
  525. (if org-persist--index
  526. (mapc (lambda (collection) (org-persist--add-to-index collection 'hash)) org-persist--index)
  527. (setq org-persist--index nil)
  528. (when (file-exists-p org-persist-directory)
  529. (dolist (file (directory-files org-persist-directory 'absolute "^[^.][^.]"))
  530. (if (file-directory-p file)
  531. (delete-directory file t)
  532. (delete-file file))))
  533. (plist-put (org-persist--get-collection container) :expiry 'never))))
  534. (defun org-persist--load-index ()
  535. "Load `org-persist--index."
  536. (org-persist-load:index
  537. `(index ,org-persist--storage-version)
  538. (org-file-name-concat org-persist-directory org-persist-index-file)
  539. nil))
  540. ;;;; Writing container data
  541. (defmacro org-persist-write:generic (container collection)
  542. "Write CONTAINER in COLLECTION."
  543. `(let* ((c (org-persist--normalize-container ,container))
  544. (write-func-symbol (intern (format "org-persist-write:%s" (car c)))))
  545. (setf ,collection (plist-put ,collection :last-access (float-time)))
  546. (setf ,collection (plist-put ,collection :last-access-hr (format-time-string "%FT%T%z" (float-time))))
  547. (unless (fboundp write-func-symbol)
  548. (error "org-persist: Write function %s not defined"
  549. write-func-symbol))
  550. (funcall write-func-symbol c ,collection)))
  551. (defun org-persist-write:elisp (container collection)
  552. "Write elisp CONTAINER according to COLLECTION."
  553. (if (and (plist-get (plist-get collection :associated) :file)
  554. (get-file-buffer (plist-get (plist-get collection :associated) :file)))
  555. (buffer-local-value
  556. (cadr container)
  557. (get-file-buffer (plist-get (plist-get collection :associated) :file)))
  558. (symbol-value (cadr container))))
  559. (defalias 'org-persist-write:version #'ignore)
  560. (defun org-persist-write:file (c collection)
  561. "Write file container C according to COLLECTION."
  562. (org-persist-collection-let collection
  563. (when (or (and path (file-exists-p path))
  564. (and (stringp (cadr c)) (file-exists-p (cadr c))))
  565. (when (and (stringp (cadr c)) (file-exists-p (cadr c)))
  566. (setq path (cadr c)))
  567. (let* ((persist-file (plist-get collection :persist-file))
  568. (ext (file-name-extension path))
  569. (file-copy (org-file-name-concat
  570. org-persist-directory
  571. (format "%s-%s.%s" persist-file (md5 path) ext))))
  572. (unless (file-exists-p (file-name-directory file-copy))
  573. (make-directory (file-name-directory file-copy) t))
  574. (copy-file path file-copy 'overwrite)
  575. (format "%s-%s.%s" persist-file (md5 path) ext)))))
  576. (defun org-persist-write:url (c collection)
  577. "Write url container C according to COLLECTION."
  578. (org-persist-collection-let collection
  579. (when (or path (cadr c))
  580. (when (cadr c) (setq path (cadr c)))
  581. (let* ((persist-file (plist-get collection :persist-file))
  582. (ext (file-name-extension path))
  583. (file-copy (org-file-name-concat
  584. org-persist-directory
  585. (format "%s-%s.%s" persist-file (md5 path) ext))))
  586. (unless (file-exists-p (file-name-directory file-copy))
  587. (make-directory (file-name-directory file-copy) t))
  588. (url-copy-file path file-copy 'overwrite)
  589. (format "%s-%s.%s" persist-file (md5 path) ext)))))
  590. (defun org-persist-write:index (container _)
  591. "Write index CONTAINER."
  592. (org-persist--get-collection container)
  593. (unless (file-exists-p org-persist-directory)
  594. (make-directory org-persist-directory))
  595. (unless (file-exists-p org-persist-directory)
  596. (warn "Failed to create org-persist storage in %s."
  597. org-persist-directory)
  598. (let ((dir (directory-file-name
  599. (file-name-as-directory org-persist-directory))))
  600. (while (and (not (file-exists-p dir))
  601. (not (equal dir (setq dir (directory-file-name
  602. (file-name-directory dir)))))))
  603. (unless (file-writable-p dir)
  604. (message "Missing write access rights to org-persist-directory: %S"
  605. org-persist-directory))))
  606. (when (file-exists-p org-persist-directory)
  607. (org-persist--write-elisp-file
  608. (org-file-name-concat org-persist-directory org-persist-index-file)
  609. org-persist--index
  610. t t)
  611. (org-file-name-concat org-persist-directory org-persist-index-file)))
  612. (defun org-persist--save-index ()
  613. "Save `org-persist--index."
  614. (org-persist-write:index
  615. `(index ,org-persist--storage-version) nil))
  616. ;;;; Public API
  617. (cl-defun org-persist-register (container &optional associated &rest misc
  618. &key inherit
  619. &key (expiry org-persist-default-expiry)
  620. &key (write-immediately nil)
  621. &allow-other-keys)
  622. "Register CONTAINER in ASSOCIATED to be persistent across Emacs sessions.
  623. Optional key INHERIT makes CONTAINER dependent on another container.
  624. Such dependency means that data shared between variables will be
  625. preserved (see elisp#Circular Objects).
  626. Optional key EXPIRY will set the expiry condition of the container.
  627. It can be `never', nil - until end of session, a number of days since
  628. last access, or a function accepting a single argument - collection.
  629. EXPIRY key has no effect when INHERIT is non-nil.
  630. Optional key WRITE-IMMEDIATELY controls whether to save the container
  631. data immediately.
  632. MISC will be appended to CONTAINER.
  633. When WRITE-IMMEDIATELY is non-nil, the return value will be the same
  634. with `org-persist-write'."
  635. (unless org-persist--index (org-persist--load-index))
  636. (setq container (org-persist--normalize-container container))
  637. (when inherit
  638. (setq inherit (org-persist--normalize-container inherit))
  639. (let ((inherited-collection (org-persist--get-collection inherit associated))
  640. new-collection)
  641. (unless (member container (plist-get inherited-collection :container))
  642. (setq new-collection
  643. (plist-put (copy-sequence inherited-collection) :container
  644. (cons container (plist-get inherited-collection :container))))
  645. (org-persist--remove-from-index inherited-collection)
  646. (org-persist--add-to-index new-collection))))
  647. (let ((collection (org-persist--get-collection container associated misc)))
  648. (when (and expiry (not inherit))
  649. (when expiry (plist-put collection :expiry expiry))))
  650. (when (or (bufferp associated) (bufferp (plist-get associated :buffer)))
  651. (with-current-buffer (if (bufferp associated)
  652. associated
  653. (plist-get associated :buffer))
  654. (add-hook 'kill-buffer-hook #'org-persist-write-all-buffer nil 'local)))
  655. (when write-immediately (org-persist-write container associated)))
  656. (defun org-persist-unregister (container &optional associated)
  657. "Unregister CONTAINER in ASSOCIATED to be persistent.
  658. When ASSOCIATED is `all', unregister CONTAINER everywhere."
  659. (unless org-persist--index (org-persist--load-index))
  660. (setq container (org-persist--normalize-container container))
  661. (setq associated (org-persist--normalize-associated associated))
  662. (if (eq associated 'all)
  663. (mapc (lambda (collection)
  664. (when (member container (plist-get collection :container))
  665. (org-persist-unregister container (plist-get collection :associated))))
  666. org-persist--index)
  667. (let ((collection (org-persist--find-index `(:container ,container :associated ,associated))))
  668. (when collection
  669. (if (= (length (plist-get collection :container)) 1)
  670. (org-persist--remove-from-index collection)
  671. (plist-put collection :container
  672. (remove container (plist-get collection :container)))
  673. (org-persist--add-to-index collection))))))
  674. (defun org-persist-read (container &optional associated hash-must-match load?)
  675. "Restore CONTAINER data for ASSOCIATED.
  676. When HASH-MUST-MATCH is non-nil, do not restore data if hash for
  677. ASSOCIATED file or buffer does not match.
  678. ASSOCIATED can be a plist, a buffer, or a string.
  679. A buffer is treated as (:buffer ASSOCIATED).
  680. A string is treated as (:file ASSOCIATED).
  681. When LOAD? is non-nil, load the data instead of reading."
  682. (setq associated (org-persist--normalize-associated associated))
  683. (setq container (org-persist--normalize-container container))
  684. (let* ((collection (org-persist--find-index `(:container ,container :associated ,associated)))
  685. (persist-file
  686. (when collection
  687. (org-file-name-concat
  688. org-persist-directory
  689. (plist-get collection :persist-file))))
  690. (data nil))
  691. (when (and collection
  692. (file-exists-p persist-file)
  693. (or (not (plist-get collection :expiry)) ; current session
  694. (not (org-persist--gc-expired-p
  695. (plist-get collection :expiry) collection)))
  696. (or (not hash-must-match)
  697. (and (plist-get associated :hash)
  698. (equal (plist-get associated :hash)
  699. (plist-get (plist-get collection :associated) :hash)))))
  700. (unless (seq-find (lambda (v)
  701. (run-hook-with-args-until-success 'org-persist-before-read-hook v associated))
  702. (plist-get collection :container))
  703. (setq data (org-persist--read-elisp-file persist-file))
  704. (cl-loop for container in (plist-get collection :container)
  705. with result = nil
  706. do
  707. (if load?
  708. (push (org-persist-load:generic container (alist-get container data nil nil #'equal) collection) result)
  709. (push (org-persist-read:generic container (alist-get container data nil nil #'equal) collection) result))
  710. (run-hook-with-args 'org-persist-after-read-hook container associated)
  711. finally return (if (= 1 (length result)) (car result) result))))))
  712. (defun org-persist-load (container &optional associated hash-must-match)
  713. "Load CONTAINER data for ASSOCIATED.
  714. The arguments have the same meaning as in `org-persist-read'."
  715. (org-persist-read container associated hash-must-match t))
  716. (defun org-persist-load-all (&optional associated)
  717. "Restore all the persistent data associated with ASSOCIATED."
  718. (unless org-persist--index (org-persist--load-index))
  719. (setq associated (org-persist--normalize-associated associated))
  720. (let (all-containers)
  721. (dolist (collection org-persist--index)
  722. (when collection
  723. (cl-pushnew (plist-get collection :container) all-containers :test #'equal)))
  724. (dolist (container all-containers)
  725. (org-persist-load container associated t))))
  726. (defun org-persist-load-all-buffer ()
  727. "Call `org-persist-load-all' in current buffer."
  728. (org-persist-load-all (current-buffer)))
  729. (defun org-persist-write (container &optional associated)
  730. "Save CONTAINER according to ASSOCIATED.
  731. ASSOCIATED can be a plist, a buffer, or a string.
  732. A buffer is treated as (:buffer ASSOCIATED).
  733. A string is treated as (:file ASSOCIATED).
  734. The return value is nil when writing fails and the written value (as
  735. returned by `org-persist-read') on success."
  736. (setq associated (org-persist--normalize-associated associated))
  737. ;; Update hash
  738. (when (and (plist-get associated :file)
  739. (plist-get associated :hash)
  740. (get-file-buffer (plist-get associated :file)))
  741. (setq associated (org-persist--normalize-associated (get-file-buffer (plist-get associated :file)))))
  742. (let ((collection (org-persist--get-collection container associated)))
  743. (setf collection (plist-put collection :associated associated))
  744. (unless (seq-find (lambda (v)
  745. (run-hook-with-args-until-success 'org-persist-before-write-hook v associated))
  746. (plist-get collection :container))
  747. (when (or (file-exists-p org-persist-directory) (org-persist--save-index))
  748. (let ((file (org-file-name-concat org-persist-directory (plist-get collection :persist-file)))
  749. (data (mapcar (lambda (c) (cons c (org-persist-write:generic c collection)))
  750. (plist-get collection :container))))
  751. (org-persist--write-elisp-file file data)
  752. (org-persist-read container associated))))))
  753. (defun org-persist-write-all (&optional associated)
  754. "Save all the persistent data.
  755. When ASSOCIATED is non-nil, only save the matching data."
  756. (unless org-persist--index (org-persist--load-index))
  757. (setq associated (org-persist--normalize-associated associated))
  758. (let (all-containers)
  759. (dolist (collection org-persist--index)
  760. (if associated
  761. (when collection
  762. (cl-pushnew (plist-get collection :container) all-containers :test #'equal))
  763. (org-persist-write (plist-get collection :container) (plist-get collection :associated))))
  764. (dolist (container all-containers)
  765. (when (org-persist--find-index `(:container ,container :associated ,associated))
  766. (org-persist-write container associated)))))
  767. (defun org-persist-write-all-buffer ()
  768. "Call `org-persist-write-all' in current buffer.
  769. Do nothing in an indirect buffer."
  770. (unless (buffer-base-buffer (current-buffer))
  771. (org-persist-write-all (current-buffer))))
  772. (defalias 'org-persist-gc:elisp #'ignore)
  773. (defalias 'org-persist-gc:index #'ignore)
  774. (defun org-persist-gc:file (container collection)
  775. "Garbage collect file CONTAINER in COLLECTION."
  776. (let ((file (org-persist-read container (plist-get collection :associated))))
  777. (when (file-exists-p file)
  778. (delete-file file))))
  779. (defun org-persist-gc:url (container collection)
  780. "Garbage collect url CONTAINER in COLLECTION."
  781. (let ((file (org-persist-read container (plist-get collection :associated))))
  782. (when (file-exists-p file)
  783. (delete-file file))))
  784. (defmacro org-persist--gc-persist-file (persist-file)
  785. "Garbage collect PERSIST-FILE."
  786. `(when (file-exists-p ,persist-file)
  787. (delete-file ,persist-file)
  788. (when (org-directory-empty-p (file-name-directory ,persist-file))
  789. (delete-directory (file-name-directory ,persist-file)))))
  790. (defun org-persist-gc ()
  791. "Remove expired or unregisted containers.
  792. Also, remove containers associated with non-existing files."
  793. (let (new-index (remote-files-num 0))
  794. (dolist (collection org-persist--index)
  795. (let* ((file (plist-get (plist-get collection :associated) :file))
  796. (file-remote (when file (file-remote-p file)))
  797. (persist-file (when (plist-get collection :persist-file)
  798. (org-file-name-concat
  799. org-persist-directory
  800. (plist-get collection :persist-file))))
  801. (expired? (org-persist--gc-expired-p
  802. (plist-get collection :expiry) collection)))
  803. (when persist-file
  804. (when file
  805. (when file-remote (cl-incf remote-files-num))
  806. (unless (if (not file-remote)
  807. (file-exists-p file)
  808. (pcase org-persist-remote-files
  809. ('t t)
  810. ('check-existence
  811. (file-exists-p file))
  812. ((pred #'numberp)
  813. (<= org-persist-remote-files remote-files-num))
  814. (_ nil)))
  815. (setq expired? t)))
  816. (if expired?
  817. (org-persist--gc-persist-file persist-file)
  818. (push collection new-index)))))
  819. (setq org-persist--index (nreverse new-index))))
  820. ;; Automatically write the data, but only when we have write access.
  821. (let ((dir (directory-file-name
  822. (file-name-as-directory org-persist-directory))))
  823. (while (and (not (file-exists-p dir))
  824. (not (equal dir (setq dir (directory-file-name
  825. (file-name-directory dir)))))))
  826. (if (not (file-writable-p dir))
  827. (message "Missing write access rights to org-persist-directory: %S"
  828. org-persist-directory)
  829. (add-hook 'kill-emacs-hook #'org-persist-write-all)
  830. ;; `org-persist-gc' should run before `org-persist-write-all'. So we are adding the
  831. ;; hook after `org-persist-write-all'.
  832. (add-hook 'kill-emacs-hook #'org-persist-gc)))
  833. (add-hook 'after-init-hook #'org-persist-load-all)
  834. (provide 'org-persist)
  835. ;;; org-persist.el ends here