org-persist.el 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917
  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. ("elisp" 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.3"
  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. ;;;; Working with index
  304. (defmacro org-persist-collection-let (collection &rest body)
  305. "Bind container and associated from COLLECTION and execute BODY."
  306. (declare (debug (form body)) (indent 1))
  307. `(with-no-warnings
  308. ;; FIXME: We only need to suppress warnings about unused
  309. ;; let-bindings. However, it is unclear how to achieve it with
  310. ;; `with-suppressed-warnings'.
  311. (let* ((container (plist-get ,collection :container))
  312. (associated (plist-get ,collection :associated))
  313. (path (plist-get associated :file))
  314. (inode (plist-get associated :inode))
  315. (hash (plist-get associated :hash))
  316. (key (plist-get associated :key)))
  317. ,@body)))
  318. (defun org-persist--find-index (collection)
  319. "Find COLLECTION in `org-persist--index'."
  320. (org-persist-collection-let collection
  321. (and org-persist--index-hash
  322. (catch :found
  323. (dolist (cont (cons container container))
  324. (let (r)
  325. (setq r (or (gethash (cons cont associated) org-persist--index-hash)
  326. (and path (gethash (cons cont (list :file path)) org-persist--index-hash))
  327. (and inode (gethash (cons cont (list :inode inode)) org-persist--index-hash))
  328. (and hash (gethash (cons cont (list :hash hash)) org-persist--index-hash))
  329. (and key (gethash (cons cont (list :key key)) org-persist--index-hash))))
  330. (when r (throw :found r))))))))
  331. (defun org-persist--add-to-index (collection &optional hash-only)
  332. "Add or update COLLECTION in `org-persist--index'.
  333. When optional HASH-ONLY is non-nil, only modify the hash table.
  334. Return PLIST."
  335. (org-persist-collection-let collection
  336. (let ((existing (org-persist--find-index collection)))
  337. (if existing
  338. (progn
  339. (plist-put existing :container container)
  340. (plist-put (plist-get existing :associated) :file path)
  341. (plist-put (plist-get existing :associated) :inode inode)
  342. (plist-put (plist-get existing :associated) :hash hash)
  343. (plist-put (plist-get existing :associated) :key key)
  344. existing)
  345. (unless hash-only (push collection org-persist--index))
  346. (unless org-persist--index-hash (setq org-persist--index-hash (make-hash-table :test 'equal)))
  347. (dolist (cont (cons container container))
  348. (puthash (cons cont associated) collection org-persist--index-hash)
  349. (when path (puthash (cons cont (list :file path)) collection org-persist--index-hash))
  350. (when inode (puthash (cons cont (list :inode inode)) collection org-persist--index-hash))
  351. (when hash (puthash (cons cont (list :hash inode)) collection org-persist--index-hash))
  352. (when key (puthash (cons cont (list :key inode)) collection org-persist--index-hash)))
  353. collection))))
  354. (defun org-persist--remove-from-index (collection)
  355. "Remove COLLECTION from `org-persist--index'."
  356. (let ((existing (org-persist--find-index collection)))
  357. (when existing
  358. (org-persist-collection-let collection
  359. (dolist (cont (cons container container))
  360. (unless (listp (car container))
  361. (org-persist-gc:generic cont collection))
  362. (remhash (cons cont associated) org-persist--index-hash)
  363. (when path (remhash (cons cont (list :file path)) org-persist--index-hash))
  364. (when inode (remhash (cons cont (list :inode inode)) org-persist--index-hash))
  365. (when hash (remhash (cons cont (list :hash hash)) org-persist--index-hash))
  366. (when key (remhash (cons cont (list :key key)) org-persist--index-hash))))
  367. (setq org-persist--index (delq existing org-persist--index)))))
  368. (defun org-persist--get-collection (container &optional associated &rest misc)
  369. "Return or create collection used to store CONTAINER for ASSOCIATED.
  370. When ASSOCIATED is nil, it is a global CONTAINER.
  371. ASSOCIATED can also be a (:buffer buffer) or buffer, (:file file-path)
  372. or file-path, (:inode inode), (:hash hash), or or (:key key).
  373. MISC, if non-nil will be appended to the collection."
  374. (unless (and (listp container) (listp (car container)))
  375. (setq container (list container)))
  376. (setq associated (org-persist--normalize-associated associated))
  377. (unless (equal misc '(nil))
  378. (setq associated (append associated misc)))
  379. (or (org-persist--find-index
  380. `( :container ,(org-persist--normalize-container container)
  381. :associated ,associated))
  382. (org-persist--add-to-index
  383. (list :container (org-persist--normalize-container container)
  384. :persist-file
  385. (replace-regexp-in-string "^.." "\\&/" (org-id-uuid))
  386. :associated associated))))
  387. ;;;; Reading container data.
  388. (defun org-persist--normalize-container (container)
  389. "Normalize CONTAINER representation into (type . settings)."
  390. (if (and (listp container) (listp (car container)))
  391. (mapcar #'org-persist--normalize-container container)
  392. (pcase container
  393. ((pred symbolp)
  394. (list "elisp" container))
  395. ((pred stringp)
  396. (list container nil))
  397. (`(,(or "elisp" "version" "file" "index" "url") . ,_)
  398. container)
  399. (_ (error "org-persist: Unknown container type: %S" container)))))
  400. (defvar org-persist--associated-buffer-cache (make-hash-table :weakness 'key)
  401. "Buffer hash cache.")
  402. (defun org-persist--normalize-associated (associated)
  403. "Normalize ASSOCIATED representation into (:type value)."
  404. (pcase associated
  405. ((or (pred stringp) `(:file ,_))
  406. (unless (stringp associated)
  407. (setq associated (cadr associated)))
  408. (let* ((rtn `(:file ,associated))
  409. (inode (and (fboundp 'file-attribute-inode-number)
  410. (file-attribute-inode-number
  411. (file-attributes associated)))))
  412. (when inode (plist-put rtn :inode inode))
  413. rtn))
  414. ((or (pred bufferp) `(:buffer ,_))
  415. (unless (bufferp associated)
  416. (setq associated (cadr associated)))
  417. (let ((cached (gethash associated org-persist--associated-buffer-cache))
  418. file inode hash)
  419. (if (and cached (eq (buffer-modified-tick associated)
  420. (car cached)))
  421. (progn
  422. (setq file (nth 1 cached)
  423. inode (nth 2 cached)
  424. hash (nth 3 cached)))
  425. (setq file (buffer-file-name
  426. (or (buffer-base-buffer associated)
  427. associated)))
  428. (setq inode (when (and file
  429. (fboundp 'file-attribute-inode-number))
  430. (file-attribute-inode-number
  431. (file-attributes file))))
  432. (setq hash (secure-hash 'md5 associated))
  433. (puthash associated
  434. (list (buffer-modified-tick associated)
  435. file inode hash)
  436. org-persist--associated-buffer-cache))
  437. (let ((rtn `(:hash ,hash)))
  438. (when file (setq rtn (plist-put rtn :file file)))
  439. (when inode (setq rtn (plist-put rtn :inode inode)))
  440. rtn)))
  441. ((pred listp)
  442. associated)
  443. (_ (error "Unknown associated object %S" associated))))
  444. (defmacro org-persist-read:generic (container reference-data collection)
  445. "Read and return the data stored in CONTAINER.
  446. REFERENCE-DATA is associated with CONTAINER in the persist file.
  447. COLLECTION is the plist holding data collectin."
  448. `(let* ((c (org-persist--normalize-container ,container))
  449. (read-func-symbol (intern (format "org-persist-read:%s" (car c)))))
  450. (setf ,collection (plist-put ,collection :last-access (float-time)))
  451. (setf ,collection (plist-put ,collection :last-access-hr (format-time-string "%FT%T%z" (float-time))))
  452. (unless (fboundp read-func-symbol)
  453. (error "org-persist: Read function %s not defined"
  454. read-func-symbol))
  455. (funcall read-func-symbol c ,reference-data ,collection)))
  456. (defun org-persist-read:elisp (_ lisp-value __)
  457. "Read elisp container and return LISP-VALUE."
  458. lisp-value)
  459. (defun org-persist-read:version (container _ __)
  460. "Read version CONTAINER."
  461. (cadr container))
  462. (defun org-persist-read:file (_ path __)
  463. "Read file container from PATH."
  464. (when (and path (file-exists-p (concat org-persist-directory path)))
  465. (concat org-persist-directory path)))
  466. (defun org-persist-read:url (_ path __)
  467. "Read file container from PATH."
  468. (when (and path (file-exists-p (concat org-persist-directory path)))
  469. (concat org-persist-directory path)))
  470. (defun org-persist-read:index (cont index-file _)
  471. "Read index container CONT from INDEX-FILE."
  472. (when (file-exists-p index-file)
  473. (let ((index (org-persist--read-elisp-file index-file)))
  474. (when index
  475. (catch :found
  476. (dolist (collection index)
  477. (org-persist-collection-let collection
  478. (when (and (not associated)
  479. (pcase container
  480. (`(("index" ,version))
  481. (equal version (cadr cont)))
  482. (_ nil)))
  483. (throw :found index)))))))))
  484. ;;;; Applying container data for side effects.
  485. (defmacro org-persist-load:generic (container reference-data collection)
  486. "Load the data stored in CONTAINER for side effects.
  487. REFERENCE-DATA is associated with CONTAINER in the persist file.
  488. COLLECTION is the plist holding data collectin."
  489. `(let* ((container (org-persist--normalize-container ,container))
  490. (load-func-symbol (intern (format "org-persist-load:%s" (car container)))))
  491. (setf ,collection (plist-put ,collection :last-access (float-time)))
  492. (setf ,collection (plist-put ,collection :last-access-hr (format-time-string "%FT%T%z" (float-time))))
  493. (unless (fboundp load-func-symbol)
  494. (error "org-persist: Load function %s not defined"
  495. load-func-symbol))
  496. (funcall load-func-symbol container ,reference-data ,collection)))
  497. (defun org-persist-load:elisp (container lisp-value collection)
  498. "Assign elisp CONTAINER in COLLECTION LISP-VALUE."
  499. (let ((lisp-symbol (cadr container))
  500. (buffer (when (plist-get (plist-get collection :associated) :file)
  501. (get-file-buffer (plist-get (plist-get collection :associated) :file)))))
  502. (if buffer
  503. (with-current-buffer buffer
  504. (make-variable-buffer-local lisp-symbol)
  505. (set lisp-symbol lisp-value))
  506. (set lisp-symbol lisp-value))))
  507. (defalias 'org-persist-load:version #'org-persist-read:version)
  508. (defalias 'org-persist-load:file #'org-persist-read:file)
  509. (defun org-persist-load:index (container index-file _)
  510. "Load `org-persist--index' from INDEX-FILE according to CONTAINER."
  511. (unless org-persist--index
  512. (setq org-persist--index (org-persist-read:index container index-file nil))
  513. (setq org-persist--index-hash nil)
  514. (if org-persist--index
  515. (mapc (lambda (collection) (org-persist--add-to-index collection 'hash)) org-persist--index)
  516. (setq org-persist--index nil)
  517. (when (file-exists-p org-persist-directory)
  518. (dolist (file (directory-files org-persist-directory 'absolute "^[^.][^.]"))
  519. (if (file-directory-p file)
  520. (delete-directory file t)
  521. (delete-file file))))
  522. (plist-put (org-persist--get-collection container) :expiry 'never))))
  523. (defun org-persist--load-index ()
  524. "Load `org-persist--index."
  525. (org-persist-load:index
  526. `("index" ,org-persist--storage-version)
  527. (org-file-name-concat org-persist-directory org-persist-index-file)
  528. nil))
  529. ;;;; Writing container data
  530. (defmacro org-persist-write:generic (container collection)
  531. "Write CONTAINER in COLLECTION."
  532. `(let* ((c (org-persist--normalize-container ,container))
  533. (write-func-symbol (intern (format "org-persist-write:%s" (car c)))))
  534. (setf ,collection (plist-put ,collection :last-access (float-time)))
  535. (setf ,collection (plist-put ,collection :last-access-hr (format-time-string "%FT%T%z" (float-time))))
  536. (unless (fboundp write-func-symbol)
  537. (error "org-persist: Write function %s not defined"
  538. write-func-symbol))
  539. (funcall write-func-symbol c ,collection)))
  540. (defun org-persist-write:elisp (container collection)
  541. "Write elisp CONTAINER according to COLLECTION."
  542. (if (and (plist-get (plist-get collection :associated) :file)
  543. (get-file-buffer (plist-get (plist-get collection :associated) :file)))
  544. (buffer-local-value
  545. (cadr container)
  546. (get-file-buffer (plist-get (plist-get collection :associated) :file)))
  547. (symbol-value (cadr container))))
  548. (defalias 'org-persist-write:version #'ignore)
  549. (defun org-persist-write:file (c collection)
  550. "Write file container C according to COLLECTION."
  551. (org-persist-collection-let collection
  552. (when (or (and path (file-exists-p path))
  553. (and (stringp (cadr c)) (file-exists-p (cadr c))))
  554. (when (and (stringp (cadr c)) (file-exists-p (cadr c)))
  555. (setq path (cadr c)))
  556. (let* ((persist-file (plist-get collection :persist-file))
  557. (ext (file-name-extension path))
  558. (file-copy (org-file-name-concat
  559. org-persist-directory
  560. (format "%s-%s.%s" persist-file (md5 path) ext))))
  561. (unless (file-exists-p (file-name-directory file-copy))
  562. (make-directory (file-name-directory file-copy) t))
  563. (unless (file-exists-p file-copy)
  564. (copy-file path file-copy 'overwrite))
  565. (format "%s-%s.%s" persist-file (md5 path) ext)))))
  566. (defun org-persist-write:url (c collection)
  567. "Write url container C according to COLLECTION."
  568. (org-persist-collection-let collection
  569. (when (or path (cadr c))
  570. (when (cadr c) (setq path (cadr c)))
  571. (let* ((persist-file (plist-get collection :persist-file))
  572. (ext (file-name-extension path))
  573. (file-copy (org-file-name-concat
  574. org-persist-directory
  575. (format "%s-%s.%s" persist-file (md5 path) ext))))
  576. (unless (file-exists-p (file-name-directory file-copy))
  577. (make-directory (file-name-directory file-copy) t))
  578. (unless (file-exists-p file-copy)
  579. (url-copy-file path file-copy 'overwrite))
  580. (format "%s-%s.%s" persist-file (md5 path) ext)))))
  581. (defun org-persist-write:index (container _)
  582. "Write index CONTAINER."
  583. (org-persist--get-collection container)
  584. (unless (file-exists-p org-persist-directory)
  585. (make-directory org-persist-directory))
  586. (unless (file-exists-p org-persist-directory)
  587. (warn "Failed to create org-persist storage in %s."
  588. org-persist-directory)
  589. (let ((dir (directory-file-name
  590. (file-name-as-directory org-persist-directory))))
  591. (while (and (not (file-exists-p dir))
  592. (not (equal dir (setq dir (directory-file-name
  593. (file-name-directory dir)))))))
  594. (unless (file-writable-p dir)
  595. (message "Missing write access rights to org-persist-directory: %S"
  596. org-persist-directory))))
  597. (when (file-exists-p org-persist-directory)
  598. (org-persist--write-elisp-file
  599. (org-file-name-concat org-persist-directory org-persist-index-file)
  600. org-persist--index
  601. t t)
  602. t))
  603. (defun org-persist--save-index ()
  604. "Save `org-persist--index."
  605. (org-persist-write:index
  606. `("index" ,org-persist--storage-version) nil))
  607. ;;;; Public API
  608. (cl-defun org-persist-register (container &optional associated &rest misc
  609. &key inherit
  610. &key (expiry org-persist-default-expiry)
  611. &key (write-immediately nil)
  612. &allow-other-keys)
  613. "Register CONTAINER in ASSOCIATED to be persistent across Emacs sessions.
  614. Optional key INHERIT makes CONTAINER dependent on another container.
  615. Such dependency means that data shared between variables will be
  616. preserved (see elisp#Circular Objects).
  617. Optional key EXPIRY will set the expiry condition of the container.
  618. It can be `never', nil - until end of session, a number of days since
  619. last access, or a function accepting a single argument - collection.
  620. EXPIRY key has no effect when INHERIT is non-nil.
  621. Optional key WRITE-IMMEDIATELY controls whether to save the container
  622. data immediately.
  623. MISC will be appended to CONTAINER."
  624. (unless org-persist--index (org-persist--load-index))
  625. (setq container (org-persist--normalize-container container))
  626. (when inherit
  627. (setq inherit (org-persist--normalize-container inherit))
  628. (let ((inherited-collection (org-persist--get-collection inherit associated))
  629. new-collection)
  630. (unless (member container (plist-get inherited-collection :container))
  631. (setq new-collection
  632. (plist-put (copy-sequence inherited-collection) :container
  633. (cons container (plist-get inherited-collection :container))))
  634. (org-persist--remove-from-index inherited-collection)
  635. (org-persist--add-to-index new-collection))))
  636. (let ((collection (org-persist--get-collection container associated misc)))
  637. (when (and expiry (not inherit))
  638. (when expiry (plist-put collection :expiry expiry))))
  639. (when write-immediately (org-persist-write container associated))
  640. (when (or (bufferp associated) (bufferp (plist-get associated :buffer)))
  641. (with-current-buffer (if (bufferp associated)
  642. associated
  643. (plist-get associated :buffer))
  644. (add-hook 'kill-buffer-hook #'org-persist-write-all-buffer nil 'local))))
  645. (defun org-persist-unregister (container &optional associated)
  646. "Unregister CONTAINER in ASSOCIATED to be persistent.
  647. When ASSOCIATED is `all', unregister CONTAINER everywhere."
  648. (unless org-persist--index (org-persist--load-index))
  649. (setq container (org-persist--normalize-container container))
  650. (setq associated (org-persist--normalize-associated associated))
  651. (if (eq associated 'all)
  652. (mapc (lambda (collection)
  653. (when (member container (plist-get collection :container))
  654. (org-persist-unregister container (plist-get collection :associated))))
  655. org-persist--index)
  656. (let ((collection (org-persist--find-index `(:container ,container :associated ,associated))))
  657. (when collection
  658. (if (= (length (plist-get collection :container)) 1)
  659. (org-persist--remove-from-index collection)
  660. (plist-put collection :container
  661. (remove container (plist-get collection :container)))
  662. (org-persist--add-to-index collection))))))
  663. (defun org-persist-read (container &optional associated hash-must-match load?)
  664. "Restore CONTAINER data for ASSOCIATED.
  665. When HASH-MUST-MATCH is non-nil, do not restore data if hash for
  666. ASSOCIATED file or buffer does not match.
  667. ASSOCIATED can be a plist, a buffer, or a string.
  668. A buffer is treated as (:buffer ASSOCIATED).
  669. A string is treated as (:file ASSOCIATED).
  670. When LOAD? is non-nil, load the data instead of reading."
  671. (setq associated (org-persist--normalize-associated associated))
  672. (setq container (org-persist--normalize-container container))
  673. (let* ((collection (org-persist--find-index `(:container ,container :associated ,associated)))
  674. (persist-file
  675. (when collection
  676. (org-file-name-concat
  677. org-persist-directory
  678. (plist-get collection :persist-file))))
  679. (data nil))
  680. (when (and collection
  681. (file-exists-p persist-file)
  682. (or (not (plist-get collection :expiry)) ; current session
  683. (not (org-persist--gc-expired-p
  684. (plist-get collection :expiry) collection)))
  685. (or (not hash-must-match)
  686. (and (plist-get associated :hash)
  687. (equal (plist-get associated :hash)
  688. (plist-get (plist-get collection :associated) :hash)))))
  689. (unless (seq-find (lambda (v)
  690. (run-hook-with-args-until-success 'org-persist-before-read-hook v associated))
  691. (plist-get collection :container))
  692. (setq data (org-persist--read-elisp-file persist-file))
  693. (cl-loop for container in (plist-get collection :container)
  694. with result = nil
  695. do
  696. (if load?
  697. (push (org-persist-load:generic container (alist-get container data nil nil #'equal) collection) result)
  698. (push (org-persist-read:generic container (alist-get container data nil nil #'equal) collection) result))
  699. (run-hook-with-args 'org-persist-after-read-hook container associated)
  700. finally return (if (= 1 (length result)) (car result) result))))))
  701. (defun org-persist-load (container &optional associated hash-must-match)
  702. "Load CONTAINER data for ASSOCIATED.
  703. The arguments have the same meaning as in `org-persist-read'."
  704. (org-persist-read container associated hash-must-match t))
  705. (defun org-persist-load-all (&optional associated)
  706. "Restore all the persistent data associated with ASSOCIATED."
  707. (unless org-persist--index (org-persist--load-index))
  708. (setq associated (org-persist--normalize-associated associated))
  709. (let (all-containers)
  710. (dolist (collection org-persist--index)
  711. (when collection
  712. (cl-pushnew (plist-get collection :container) all-containers :test #'equal)))
  713. (dolist (container all-containers)
  714. (org-persist-load container associated t))))
  715. (defun org-persist-load-all-buffer ()
  716. "Call `org-persist-load-all' in current buffer."
  717. (org-persist-load-all (current-buffer)))
  718. (defun org-persist-write (container &optional associated)
  719. "Save CONTAINER according to ASSOCIATED.
  720. ASSOCIATED can be a plist, a buffer, or a string.
  721. A buffer is treated as (:buffer ASSOCIATED).
  722. A string is treated as (:file ASSOCIATED)."
  723. (setq associated (org-persist--normalize-associated associated))
  724. ;; Update hash
  725. (when (and (plist-get associated :file)
  726. (plist-get associated :hash)
  727. (get-file-buffer (plist-get associated :file)))
  728. (setq associated (org-persist--normalize-associated (get-file-buffer (plist-get associated :file)))))
  729. (let ((collection (org-persist--get-collection container associated)))
  730. (setf collection (plist-put collection :associated associated))
  731. (unless (seq-find (lambda (v)
  732. (run-hook-with-args-until-success 'org-persist-before-write-hook v associated))
  733. (plist-get collection :container))
  734. (when (or (file-exists-p org-persist-directory) (org-persist--save-index))
  735. (let ((file (org-file-name-concat org-persist-directory (plist-get collection :persist-file)))
  736. (data (mapcar (lambda (c) (cons c (org-persist-write:generic c collection)))
  737. (plist-get collection :container))))
  738. (org-persist--write-elisp-file file data))))))
  739. (defun org-persist-write-all (&optional associated)
  740. "Save all the persistent data.
  741. When ASSOCIATED is non-nil, only save the matching data."
  742. (unless org-persist--index (org-persist--load-index))
  743. (setq associated (org-persist--normalize-associated associated))
  744. (let (all-containers)
  745. (dolist (collection org-persist--index)
  746. (if associated
  747. (when collection
  748. (cl-pushnew (plist-get collection :container) all-containers :test #'equal))
  749. (org-persist-write (plist-get collection :container) (plist-get collection :associated))))
  750. (dolist (container all-containers)
  751. (when (org-persist--find-index `(:container ,container :associated ,associated))
  752. (org-persist-write container associated)))))
  753. (defun org-persist-write-all-buffer ()
  754. "Call `org-persist-write-all' in current buffer.
  755. Do nothing in an indirect buffer."
  756. (unless (buffer-base-buffer (current-buffer))
  757. (org-persist-write-all (current-buffer))))
  758. (defalias 'org-persist-gc:elisp #'ignore)
  759. (defalias 'org-persist-gc:index #'ignore)
  760. (defun org-persist-gc:file (container collection)
  761. "Garbage collect file CONTAINER in COLLECTION."
  762. (let ((file (org-persist-read container (plist-get collection :associated))))
  763. (when (file-exists-p file)
  764. (delete-file file))))
  765. (defun org-persist-gc:url (container collection)
  766. "Garbage collect url CONTAINER in COLLECTION."
  767. (let ((file (org-persist-read container (plist-get collection :associated))))
  768. (when (file-exists-p file)
  769. (delete-file file))))
  770. (defmacro org-persist--gc-persist-file (persist-file)
  771. "Garbage collect PERSIST-FILE."
  772. `(when (file-exists-p ,persist-file)
  773. (delete-file ,persist-file)
  774. (when (org-directory-empty-p (file-name-directory ,persist-file))
  775. (delete-directory (file-name-directory ,persist-file)))))
  776. (defmacro org-persist--gc-expired-p (cnd collection)
  777. "Check if expiry condition CND triggers for COLLECTION."
  778. `(pcase ,cnd
  779. (`nil t)
  780. (`never nil)
  781. ((pred numberp)
  782. (when (plist-get ,collection :access-time)
  783. (<= (float-time) (+ (plist-get ,collection :access-time) (* ,cnd 24 60 60)))))
  784. ((pred functionp)
  785. (funcall ,cnd ,collection))
  786. (_ (error "org-persist: Unsupported expiry type %S" ,cnd))))
  787. (defun org-persist-gc ()
  788. "Remove expired or unregisted containers.
  789. Also, remove containers associated with non-existing files."
  790. (let (new-index (remote-files-num 0))
  791. (dolist (collection org-persist--index)
  792. (let* ((file (plist-get (plist-get collection :associated) :file))
  793. (file-remote (when file (file-remote-p file)))
  794. (persist-file (when (plist-get collection :persist-file)
  795. (org-file-name-concat
  796. org-persist-directory
  797. (plist-get collection :persist-file))))
  798. (expired? (org-persist--gc-expired-p
  799. (plist-get collection :expiry) collection)))
  800. (when persist-file
  801. (when file
  802. (when file-remote (cl-incf remote-files-num))
  803. (unless (if (not file-remote)
  804. (file-exists-p file)
  805. (pcase org-persist-remote-files
  806. ('t t)
  807. ('check-existence
  808. (file-exists-p file))
  809. ((pred #'numberp)
  810. (<= org-persist-remote-files remote-files-num))
  811. (_ nil)))
  812. (setq expired? t)))
  813. (if expired?
  814. (org-persist--gc-persist-file persist-file)
  815. (push collection new-index)))))
  816. (setq org-persist--index (nreverse new-index))))
  817. ;; Automatically write the data, but only when we have write access.
  818. (let ((dir (directory-file-name
  819. (file-name-as-directory org-persist-directory))))
  820. (while (and (not (file-exists-p dir))
  821. (not (equal dir (setq dir (directory-file-name
  822. (file-name-directory dir)))))))
  823. (if (not (file-writable-p dir))
  824. (message "Missing write access rights to org-persist-directory: %S"
  825. org-persist-directory)
  826. (add-hook 'kill-emacs-hook #'org-persist-write-all)
  827. ;; `org-persist-gc' should run before `org-persist-write-all'. So we are adding the
  828. ;; hook after `org-persist-write-all'.
  829. (add-hook 'kill-emacs-hook #'org-persist-gc)))
  830. (add-hook 'after-init-hook #'org-persist-load-all)
  831. (provide 'org-persist)
  832. ;;; org-persist.el ends here