org-persist.el 40 KB

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