org-persist.el 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973
  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 persistent 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 buffer, 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-macs)
  144. (org-assert-version)
  145. (require 'org-compat)
  146. (require 'org-id)
  147. (require 'xdg nil t)
  148. (declare-function org-back-to-heading "org" (&optional invisible-ok))
  149. (declare-function org-next-visible-heading "org" (arg))
  150. (declare-function org-at-heading-p "org" (&optional invisible-not-ok))
  151. (defconst org-persist--storage-version "2.5"
  152. "Persistent storage layout version.")
  153. (defgroup org-persist nil
  154. "Persistent cache for Org mode."
  155. :tag "Org persist"
  156. :group 'org)
  157. (defcustom org-persist-directory (expand-file-name
  158. (org-file-name-concat
  159. (let ((cache-dir (when (fboundp 'xdg-cache-home)
  160. (xdg-cache-home))))
  161. (if (or (seq-empty-p cache-dir)
  162. (not (file-exists-p cache-dir))
  163. (file-exists-p (org-file-name-concat
  164. user-emacs-directory
  165. "org-persist")))
  166. user-emacs-directory
  167. cache-dir))
  168. "org-persist/"))
  169. "Directory where the data is stored."
  170. :type 'directory)
  171. (defcustom org-persist-remote-files 100
  172. "Whether to keep persistent data for remote files.
  173. When this variable is nil, never save persitent data associated with
  174. remote files. When t, always keep the data. When
  175. `check-existence', contact remote server containing the file and only
  176. keep the data when the file exists on the server. When a number, keep
  177. up to that number persistent values for remote files.
  178. Note that the last option `check-existence' may cause Emacs to show
  179. password prompts to log in."
  180. :group 'org-persist
  181. :type '(choice (const :tag "Never" nil)
  182. (const :tag "Always" t)
  183. (number :tag "Keep not more than X files")
  184. (const :tag "Check if exist on remote" check-existence)))
  185. (defcustom org-persist-default-expiry 30
  186. "Default expiry condition for persistent data.
  187. When this variable is nil, all the data vanishes at the end of Emacs
  188. session. When `never', the data never vanishes. When a number, the
  189. data is deleted that number days after last access. When a function,
  190. it should be a function returning non-nil when the data is expired. The
  191. function will be called with a single argument - collection."
  192. :group 'org-persist
  193. :type '(choice (const :tag "Never" never)
  194. (const :tag "Always" nil)
  195. (number :tag "Keep N days")
  196. (function :tag "Function")))
  197. (defconst org-persist-index-file "index"
  198. "File name used to store the data index.")
  199. (defvar org-persist-disable-when-emacs-Q t
  200. "Disable persistence when Emacs is called with -Q command line arg.")
  201. (defvar org-persist-before-write-hook nil
  202. "Abnormal hook ran before saving data.
  203. The hook must accept the same arguments as `org-persist-write'.
  204. The hooks will be evaluated until a hook returns non-nil.
  205. If any of the hooks return non-nil, do not save the data.")
  206. (defvar org-persist-before-read-hook nil
  207. "Abnormal hook ran before reading data.
  208. The hook must accept the same arguments as `org-persist-read'.
  209. The hooks will be evaluated until a hook returns non-nil.
  210. If any of the hooks return non-nil, do not read the data.")
  211. (defvar org-persist-after-read-hook nil
  212. "Abnormal hook ran after reading data.
  213. The hook must accept the same arguments as `org-persist-read'.")
  214. (defvar org-persist--index nil
  215. "Global index.
  216. The index is a list of plists. Each plist contains information about
  217. persistent data storage. Each plist contains the following
  218. properties:
  219. - `:container' : list of data continers to be stored in single file
  220. - `:persist-file': data file name
  221. - `:associated' : list of associated objects
  222. - `:last-access' : last date when the container has been read
  223. - `:expiry' : list of expiry conditions
  224. - all other keywords are ignored.")
  225. (defvar org-persist--index-hash nil
  226. "Hash table storing `org-persist--index'. Used for quick access.
  227. They keys are conses of (container . associated).")
  228. (defvar org-persist--report-time 0.5
  229. "Whether to report read/write time.
  230. When the value is a number, it is a threshold number of seconds. If
  231. the read/write time of a single variable exceeds the threshold, a
  232. message is displayed.
  233. When the value is a non-nil non-number, always display the message.
  234. When the value is nil, never display the message.")
  235. ;;;; Common functions
  236. (defun org-persist--display-time (duration format &rest args)
  237. "Report DURATION according to FORMAT + ARGS message.
  238. FORMAT and ARGS are passed to `message'."
  239. (when (or (and org-persist--report-time
  240. (numberp org-persist--report-time)
  241. (>= duration org-persist--report-time))
  242. (and org-persist--report-time
  243. (not (numberp org-persist--report-time))))
  244. (apply #'message
  245. (format "org-persist: %s took %%.2f sec" format)
  246. (append args (list duration)))))
  247. (defun org-persist--read-elisp-file (&optional buffer-or-file)
  248. "Read elisp data from BUFFER-OR-FILE or current buffer."
  249. (unless buffer-or-file (setq buffer-or-file (current-buffer)))
  250. (with-temp-buffer
  251. (if (bufferp buffer-or-file)
  252. (set-buffer buffer-or-file)
  253. (insert-file-contents buffer-or-file))
  254. (condition-case err
  255. (let ((coding-system-for-read 'utf-8)
  256. (read-circle t)
  257. (start-time (float-time)))
  258. ;; FIXME: Reading sometimes fails to read circular objects.
  259. ;; I suspect that it happens when we have object reference
  260. ;; #N# read before object definition #N=. If it is really
  261. ;; so, it should be Emacs bug - either in `read' or in
  262. ;; `prin1'. Meanwhile, just fail silently when `read'
  263. ;; fails to parse the saved cache object.
  264. (prog1
  265. (read (current-buffer))
  266. (org-persist--display-time
  267. (- (float-time) start-time)
  268. "Reading from %S" buffer-or-file)))
  269. ;; Recover gracefully if index file is corrupted.
  270. (error
  271. ;; Remove problematic file.
  272. (unless (bufferp buffer-or-file) (delete-file buffer-or-file))
  273. ;; Do not report the known error to user.
  274. (if (string-match-p "Invalid read syntax" (error-message-string err))
  275. (message "Emacs reader failed to read data in %S. The error was: %S"
  276. buffer-or-file (error-message-string err))
  277. (warn "Emacs reader failed to read data in %S. The error was: %S"
  278. buffer-or-file (error-message-string err)))
  279. nil))))
  280. (defun org-persist--write-elisp-file (file data &optional no-circular pp)
  281. "Write elisp DATA to FILE."
  282. (let ((print-circle (not no-circular))
  283. print-level
  284. print-length
  285. print-quoted
  286. (print-escape-control-characters t)
  287. (print-escape-nonascii t)
  288. (print-continuous-numbering t)
  289. print-number-table
  290. (start-time (float-time)))
  291. (unless (file-exists-p (file-name-directory file))
  292. (make-directory (file-name-directory file) t))
  293. (with-temp-file file
  294. (if pp
  295. (pp data (current-buffer))
  296. (prin1 data (current-buffer))))
  297. (org-persist--display-time
  298. (- (float-time) start-time)
  299. "Writing to %S" file)))
  300. (defmacro org-persist-gc:generic (container collection)
  301. "Garbage collect CONTAINER data from COLLECTION."
  302. `(let* ((c (org-persist--normalize-container ,container))
  303. (gc-func-symbol (intern (format "org-persist-gc:%s" (car c)))))
  304. (unless (fboundp gc-func-symbol)
  305. (error "org-persist: GC function %s not defined"
  306. gc-func-symbol))
  307. (funcall gc-func-symbol c ,collection)))
  308. (defmacro org-persist--gc-expired-p (cnd collection)
  309. "Check if expiry condition CND triggers for COLLECTION."
  310. `(pcase ,cnd
  311. (`nil t)
  312. (`never nil)
  313. ((pred numberp)
  314. (when (plist-get ,collection :last-access)
  315. (> (float-time) (+ (plist-get ,collection :last-access) (* ,cnd 24 60 60)))))
  316. ((pred functionp)
  317. (funcall ,cnd ,collection))
  318. (_ (error "org-persist: Unsupported expiry type %S" ,cnd))))
  319. ;;;; Working with index
  320. (defmacro org-persist-collection-let (collection &rest body)
  321. "Bind container and associated from COLLECTION and execute BODY."
  322. (declare (debug (form body)) (indent 1))
  323. `(with-no-warnings
  324. (let* ((container (plist-get ,collection :container))
  325. (associated (plist-get ,collection :associated))
  326. (path (plist-get associated :file))
  327. (inode (plist-get associated :inode))
  328. (hash (plist-get associated :hash))
  329. (key (plist-get associated :key)))
  330. ;; Suppress "unused variable" warnings.
  331. (ignore container associated path inode hash key)
  332. ,@body)))
  333. (defun org-persist--find-index (collection)
  334. "Find COLLECTION in `org-persist--index'."
  335. (org-persist-collection-let collection
  336. (and org-persist--index-hash
  337. (catch :found
  338. (dolist (cont (cons container container))
  339. (let (r)
  340. (setq r (or (gethash (cons cont associated) org-persist--index-hash)
  341. (and path (gethash (cons cont (list :file path)) org-persist--index-hash))
  342. (and inode (gethash (cons cont (list :inode inode)) org-persist--index-hash))
  343. (and hash (gethash (cons cont (list :hash hash)) org-persist--index-hash))
  344. (and key (gethash (cons cont (list :key key)) org-persist--index-hash))))
  345. (when r (throw :found r))))))))
  346. (defun org-persist--add-to-index (collection &optional hash-only)
  347. "Add or update COLLECTION in `org-persist--index'.
  348. When optional HASH-ONLY is non-nil, only modify the hash table.
  349. Return PLIST."
  350. (org-persist-collection-let collection
  351. (let ((existing (org-persist--find-index collection)))
  352. (if existing
  353. (progn
  354. (plist-put existing :container container)
  355. (plist-put (plist-get existing :associated) :file path)
  356. (plist-put (plist-get existing :associated) :inode inode)
  357. (plist-put (plist-get existing :associated) :hash hash)
  358. (plist-put (plist-get existing :associated) :key key)
  359. existing)
  360. (unless hash-only (push collection org-persist--index))
  361. (unless org-persist--index-hash (setq org-persist--index-hash (make-hash-table :test 'equal)))
  362. (dolist (cont (cons container container))
  363. (puthash (cons cont associated) collection org-persist--index-hash)
  364. (when path (puthash (cons cont (list :file path)) collection org-persist--index-hash))
  365. (when inode (puthash (cons cont (list :inode inode)) collection org-persist--index-hash))
  366. (when hash (puthash (cons cont (list :hash inode)) collection org-persist--index-hash))
  367. (when key (puthash (cons cont (list :key inode)) collection org-persist--index-hash)))
  368. collection))))
  369. (defun org-persist--remove-from-index (collection)
  370. "Remove COLLECTION from `org-persist--index'."
  371. (let ((existing (org-persist--find-index collection)))
  372. (when existing
  373. (org-persist-collection-let collection
  374. (dolist (cont (cons container container))
  375. (unless (listp (car container))
  376. (org-persist-gc:generic cont collection))
  377. (remhash (cons cont associated) org-persist--index-hash)
  378. (when path (remhash (cons cont (list :file path)) org-persist--index-hash))
  379. (when inode (remhash (cons cont (list :inode inode)) org-persist--index-hash))
  380. (when hash (remhash (cons cont (list :hash hash)) org-persist--index-hash))
  381. (when key (remhash (cons cont (list :key key)) org-persist--index-hash))))
  382. (setq org-persist--index (delq existing org-persist--index)))))
  383. (defun org-persist--get-collection (container &optional associated &rest misc)
  384. "Return or create collection used to store CONTAINER for ASSOCIATED.
  385. When ASSOCIATED is nil, it is a global CONTAINER.
  386. ASSOCIATED can also be a (:buffer buffer) or buffer, (:file file-path)
  387. or file-path, (:inode inode), (:hash hash), or or (:key key).
  388. MISC, if non-nil will be appended to the collection."
  389. (unless (and (listp container) (listp (car container)))
  390. (setq container (list container)))
  391. (setq associated (org-persist--normalize-associated associated))
  392. (unless (equal misc '(nil))
  393. (setq associated (append associated misc)))
  394. (or (org-persist--find-index
  395. `( :container ,(org-persist--normalize-container container)
  396. :associated ,associated))
  397. (org-persist--add-to-index
  398. (list :container (org-persist--normalize-container container)
  399. :persist-file
  400. (replace-regexp-in-string "^.." "\\&/" (org-id-uuid))
  401. :associated associated))))
  402. ;;;; Reading container data.
  403. (defun org-persist--normalize-container (container)
  404. "Normalize CONTAINER representation into (type . settings)."
  405. (if (and (listp container) (listp (car container)))
  406. (mapcar #'org-persist--normalize-container container)
  407. (pcase container
  408. ((or `elisp `version `file `index `url)
  409. (list container nil))
  410. ((pred symbolp)
  411. (list `elisp container))
  412. (`(,(or `elisp `version `file `index `url) . ,_)
  413. container)
  414. (_ (error "org-persist: Unknown container type: %S" container)))))
  415. (defvar org-persist--associated-buffer-cache (make-hash-table :weakness 'key)
  416. "Buffer hash cache.")
  417. (defun org-persist--normalize-associated (associated)
  418. "Normalize ASSOCIATED representation into (:type value)."
  419. (pcase associated
  420. ((or (pred stringp) `(:file ,_))
  421. (unless (stringp associated)
  422. (setq associated (cadr associated)))
  423. (let* ((rtn `(:file ,associated))
  424. (inode (and (fboundp 'file-attribute-inode-number)
  425. (file-attribute-inode-number
  426. (file-attributes associated)))))
  427. (when inode (plist-put rtn :inode inode))
  428. rtn))
  429. ((or (pred bufferp) `(:buffer ,_))
  430. (unless (bufferp associated)
  431. (setq associated (cadr associated)))
  432. (let ((cached (gethash associated org-persist--associated-buffer-cache))
  433. file inode hash)
  434. (if (and cached (eq (buffer-modified-tick associated)
  435. (car cached)))
  436. (progn
  437. (setq file (nth 1 cached)
  438. inode (nth 2 cached)
  439. hash (nth 3 cached)))
  440. (setq file (buffer-file-name
  441. (or (buffer-base-buffer associated)
  442. associated)))
  443. (setq inode (when (and file
  444. (fboundp 'file-attribute-inode-number))
  445. (file-attribute-inode-number
  446. (file-attributes file))))
  447. (setq hash (secure-hash 'md5 associated))
  448. (puthash associated
  449. (list (buffer-modified-tick associated)
  450. file inode hash)
  451. org-persist--associated-buffer-cache))
  452. (let ((rtn `(:hash ,hash)))
  453. (when file (setq rtn (plist-put rtn :file file)))
  454. (when inode (setq rtn (plist-put rtn :inode inode)))
  455. rtn)))
  456. ((pred listp)
  457. associated)
  458. (_ (error "Unknown associated object %S" associated))))
  459. (defmacro org-persist-read:generic (container reference-data collection)
  460. "Read and return the data stored in CONTAINER.
  461. REFERENCE-DATA is associated with CONTAINER in the persist file.
  462. COLLECTION is the plist holding data collection."
  463. `(let* ((c (org-persist--normalize-container ,container))
  464. (read-func-symbol (intern (format "org-persist-read:%s" (car c)))))
  465. (setf ,collection (plist-put ,collection :last-access (float-time)))
  466. (setf ,collection (plist-put ,collection :last-access-hr (format-time-string "%FT%T%z" (float-time))))
  467. (unless (fboundp read-func-symbol)
  468. (error "org-persist: Read function %s not defined"
  469. read-func-symbol))
  470. (funcall read-func-symbol c ,reference-data ,collection)))
  471. (defun org-persist-read:elisp (_ lisp-value __)
  472. "Read elisp container and return LISP-VALUE."
  473. lisp-value)
  474. (defun org-persist-read:version (container _ __)
  475. "Read version CONTAINER."
  476. (cadr container))
  477. (defun org-persist-read:file (_ 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:url (_ path __)
  482. "Read file container from PATH."
  483. (when (and path (file-exists-p (concat org-persist-directory path)))
  484. (concat org-persist-directory path)))
  485. (defun org-persist-read:index (cont index-file _)
  486. "Read index container CONT from INDEX-FILE."
  487. (when (file-exists-p index-file)
  488. (let ((index (org-persist--read-elisp-file index-file)))
  489. (when index
  490. (catch :found
  491. (dolist (collection index)
  492. (org-persist-collection-let collection
  493. (when (and (not associated)
  494. (pcase container
  495. (`((index ,version))
  496. (equal version (cadr cont)))
  497. (_ nil)))
  498. (throw :found index)))))))))
  499. ;;;; Applying container data for side effects.
  500. (defmacro org-persist-load:generic (container reference-data collection)
  501. "Load the data stored in CONTAINER for side effects.
  502. REFERENCE-DATA is associated with CONTAINER in the persist file.
  503. COLLECTION is the plist holding data collection."
  504. `(let* ((container (org-persist--normalize-container ,container))
  505. (load-func-symbol (intern (format "org-persist-load:%s" (car container)))))
  506. (setf ,collection (plist-put ,collection :last-access (float-time)))
  507. (setf ,collection (plist-put ,collection :last-access-hr (format-time-string "%FT%T%z" (float-time))))
  508. (unless (fboundp load-func-symbol)
  509. (error "org-persist: Load function %s not defined"
  510. load-func-symbol))
  511. (funcall load-func-symbol container ,reference-data ,collection)))
  512. (defun org-persist-load:elisp (container lisp-value collection)
  513. "Assign elisp CONTAINER in COLLECTION LISP-VALUE."
  514. (let ((lisp-symbol (cadr container))
  515. (buffer (when (plist-get (plist-get collection :associated) :file)
  516. (get-file-buffer (plist-get (plist-get collection :associated) :file)))))
  517. (if buffer
  518. (with-current-buffer buffer
  519. (make-variable-buffer-local lisp-symbol)
  520. (set lisp-symbol lisp-value))
  521. (set lisp-symbol lisp-value))))
  522. (defalias 'org-persist-load:version #'org-persist-read:version)
  523. (defalias 'org-persist-load:file #'org-persist-read:file)
  524. (defun org-persist-load:index (container index-file _)
  525. "Load `org-persist--index' from INDEX-FILE according to CONTAINER."
  526. (unless org-persist--index
  527. (setq org-persist--index (org-persist-read:index container index-file nil))
  528. (setq org-persist--index-hash nil)
  529. (if org-persist--index
  530. (mapc (lambda (collection) (org-persist--add-to-index collection 'hash)) org-persist--index)
  531. (setq org-persist--index nil)
  532. (when (file-exists-p org-persist-directory)
  533. (dolist (file (directory-files org-persist-directory 'absolute "^[^.][^.]"))
  534. (if (file-directory-p file)
  535. (delete-directory file t)
  536. (delete-file file))))
  537. (plist-put (org-persist--get-collection container) :expiry 'never))))
  538. (defun org-persist--load-index ()
  539. "Load `org-persist--index."
  540. (org-persist-load:index
  541. `(index ,org-persist--storage-version)
  542. (org-file-name-concat org-persist-directory org-persist-index-file)
  543. nil))
  544. ;;;; Writing container data
  545. (defmacro org-persist-write:generic (container collection)
  546. "Write CONTAINER in COLLECTION."
  547. `(let* ((c (org-persist--normalize-container ,container))
  548. (write-func-symbol (intern (format "org-persist-write:%s" (car c)))))
  549. (setf ,collection (plist-put ,collection :last-access (float-time)))
  550. (setf ,collection (plist-put ,collection :last-access-hr (format-time-string "%FT%T%z" (float-time))))
  551. (unless (fboundp write-func-symbol)
  552. (error "org-persist: Write function %s not defined"
  553. write-func-symbol))
  554. (funcall write-func-symbol c ,collection)))
  555. (defun org-persist-write:elisp (container collection)
  556. "Write elisp CONTAINER according to COLLECTION."
  557. (if (and (plist-get (plist-get collection :associated) :file)
  558. (get-file-buffer (plist-get (plist-get collection :associated) :file)))
  559. (let ((buf (get-file-buffer (plist-get (plist-get collection :associated) :file))))
  560. ;; FIXME: There is `buffer-local-boundp' introduced in Emacs 28.
  561. ;; Not using it yet to keep backward compatibility.
  562. (condition-case nil
  563. (buffer-local-value (cadr container) buf)
  564. (void-variable nil)))
  565. (when (boundp (cadr container))
  566. (symbol-value (cadr container)))))
  567. (defalias 'org-persist-write:version #'ignore)
  568. (defun org-persist-write:file (c collection)
  569. "Write file container C according to COLLECTION."
  570. (org-persist-collection-let collection
  571. (when (or (and path (file-exists-p path))
  572. (and (stringp (cadr c)) (file-exists-p (cadr c))))
  573. (when (and (stringp (cadr c)) (file-exists-p (cadr c)))
  574. (setq path (cadr c)))
  575. (let* ((persist-file (plist-get collection :persist-file))
  576. (ext (file-name-extension path))
  577. (file-copy (org-file-name-concat
  578. org-persist-directory
  579. (format "%s-%s.%s" persist-file (md5 path) ext))))
  580. (unless (file-exists-p (file-name-directory file-copy))
  581. (make-directory (file-name-directory file-copy) t))
  582. (copy-file path file-copy 'overwrite)
  583. (format "%s-%s.%s" persist-file (md5 path) ext)))))
  584. (defun org-persist-write:url (c collection)
  585. "Write url container C according to COLLECTION."
  586. (org-persist-collection-let collection
  587. (when (or path (cadr c))
  588. (when (cadr c) (setq path (cadr c)))
  589. (let* ((persist-file (plist-get collection :persist-file))
  590. (ext (file-name-extension path))
  591. (file-copy (org-file-name-concat
  592. org-persist-directory
  593. (format "%s-%s.%s" persist-file (md5 path) ext))))
  594. (unless (file-exists-p (file-name-directory file-copy))
  595. (make-directory (file-name-directory file-copy) t))
  596. (if (org--should-fetch-remote-resource-p path)
  597. (url-copy-file path file-copy 'overwrite)
  598. (error "The remote resource %S is considered unsafe, and will not be downloaded."
  599. path))
  600. (format "%s-%s.%s" persist-file (md5 path) ext)))))
  601. (defun org-persist-write:index (container _)
  602. "Write index CONTAINER."
  603. (org-persist--get-collection container)
  604. (unless (file-exists-p org-persist-directory)
  605. (make-directory org-persist-directory))
  606. (unless (file-exists-p org-persist-directory)
  607. (warn "Failed to create org-persist storage in %s."
  608. org-persist-directory)
  609. (let ((dir (directory-file-name
  610. (file-name-as-directory org-persist-directory))))
  611. (while (and (not (file-exists-p dir))
  612. (not (equal dir (setq dir (directory-file-name
  613. (file-name-directory dir)))))))
  614. (unless (file-writable-p dir)
  615. (message "Missing write access rights to org-persist-directory: %S"
  616. org-persist-directory))))
  617. (when (file-exists-p org-persist-directory)
  618. (org-persist--write-elisp-file
  619. (org-file-name-concat org-persist-directory org-persist-index-file)
  620. org-persist--index
  621. t t)
  622. (org-file-name-concat org-persist-directory org-persist-index-file)))
  623. (defun org-persist--save-index ()
  624. "Save `org-persist--index."
  625. (org-persist-write:index
  626. `(index ,org-persist--storage-version) nil))
  627. ;;;; Public API
  628. (cl-defun org-persist-register (container &optional associated &rest misc
  629. &key inherit
  630. &key (expiry org-persist-default-expiry)
  631. &key (write-immediately nil)
  632. &allow-other-keys)
  633. "Register CONTAINER in ASSOCIATED to be persistent across Emacs sessions.
  634. Optional key INHERIT makes CONTAINER dependent on another container.
  635. Such dependency means that data shared between variables will be
  636. preserved (see elisp#Circular Objects).
  637. Optional key EXPIRY will set the expiry condition of the container.
  638. It can be `never', nil - until end of session, a number of days since
  639. last access, or a function accepting a single argument - collection.
  640. EXPIRY key has no effect when INHERIT is non-nil.
  641. Optional key WRITE-IMMEDIATELY controls whether to save the container
  642. data immediately.
  643. MISC will be appended to CONTAINER.
  644. When WRITE-IMMEDIATELY is non-nil, the return value will be the same
  645. with `org-persist-write'."
  646. (unless org-persist--index (org-persist--load-index))
  647. (setq container (org-persist--normalize-container container))
  648. (when inherit
  649. (setq inherit (org-persist--normalize-container inherit))
  650. (let ((inherited-collection (org-persist--get-collection inherit associated))
  651. new-collection)
  652. (unless (member container (plist-get inherited-collection :container))
  653. (setq new-collection
  654. (plist-put (copy-sequence inherited-collection) :container
  655. (cons container (plist-get inherited-collection :container))))
  656. (org-persist--remove-from-index inherited-collection)
  657. (org-persist--add-to-index new-collection))))
  658. (let ((collection (org-persist--get-collection container associated misc)))
  659. (when (and expiry (not inherit))
  660. (when expiry (plist-put collection :expiry expiry))))
  661. (when (or (bufferp associated) (bufferp (plist-get associated :buffer)))
  662. (with-current-buffer (if (bufferp associated)
  663. associated
  664. (plist-get associated :buffer))
  665. (add-hook 'kill-buffer-hook #'org-persist-write-all-buffer nil 'local)))
  666. (when write-immediately (org-persist-write container associated)))
  667. (defun org-persist-unregister (container &optional associated)
  668. "Unregister CONTAINER in ASSOCIATED to be persistent.
  669. When ASSOCIATED is `all', unregister CONTAINER everywhere."
  670. (unless org-persist--index (org-persist--load-index))
  671. (setq container (org-persist--normalize-container container))
  672. (setq associated (org-persist--normalize-associated associated))
  673. (if (eq associated 'all)
  674. (mapc (lambda (collection)
  675. (when (member container (plist-get collection :container))
  676. (org-persist-unregister container (plist-get collection :associated))))
  677. org-persist--index)
  678. (let ((collection (org-persist--find-index `(:container ,container :associated ,associated))))
  679. (when collection
  680. (if (= (length (plist-get collection :container)) 1)
  681. (org-persist--remove-from-index collection)
  682. (plist-put collection :container
  683. (remove container (plist-get collection :container)))
  684. (org-persist--add-to-index collection))))))
  685. (defvar org-persist--write-cache (make-hash-table :test #'equal)
  686. "Hash table storing as-written data objects.
  687. This data is used to avoid reading the data multiple times.")
  688. (defun org-persist-read (container &optional associated hash-must-match load?)
  689. "Restore CONTAINER data for ASSOCIATED.
  690. When HASH-MUST-MATCH is non-nil, do not restore data if hash for
  691. ASSOCIATED file or buffer does not match.
  692. ASSOCIATED can be a plist, a buffer, or a string.
  693. A buffer is treated as (:buffer ASSOCIATED).
  694. A string is treated as (:file ASSOCIATED).
  695. When LOAD? is non-nil, load the data instead of reading."
  696. (setq associated (org-persist--normalize-associated associated))
  697. (setq container (org-persist--normalize-container container))
  698. (unless (and org-persist-disable-when-emacs-Q
  699. ;; FIXME: This is relying on undocumented fact that
  700. ;; Emacs sets `user-init-file' to nil when loaded with
  701. ;; "-Q" argument.
  702. (not user-init-file))
  703. (let* ((collection (org-persist--find-index `(:container ,container :associated ,associated)))
  704. (persist-file
  705. (when collection
  706. (org-file-name-concat
  707. org-persist-directory
  708. (plist-get collection :persist-file))))
  709. (data nil))
  710. (when (and collection
  711. (file-exists-p persist-file)
  712. (or (not (plist-get collection :expiry)) ; current session
  713. (not (org-persist--gc-expired-p
  714. (plist-get collection :expiry) collection)))
  715. (or (not hash-must-match)
  716. (and (plist-get associated :hash)
  717. (equal (plist-get associated :hash)
  718. (plist-get (plist-get collection :associated) :hash)))))
  719. (unless (seq-find (lambda (v)
  720. (run-hook-with-args-until-success 'org-persist-before-read-hook v associated))
  721. (plist-get collection :container))
  722. (setq data (or (gethash persist-file org-persist--write-cache)
  723. (org-persist--read-elisp-file persist-file)))
  724. (when data
  725. (cl-loop for container in (plist-get collection :container)
  726. with result = nil
  727. do
  728. (if load?
  729. (push (org-persist-load:generic container (alist-get container data nil nil #'equal) collection) result)
  730. (push (org-persist-read:generic container (alist-get container data nil nil #'equal) collection) result))
  731. (run-hook-with-args 'org-persist-after-read-hook container associated)
  732. finally return (if (= 1 (length result)) (car result) result))))))))
  733. (defun org-persist-load (container &optional associated hash-must-match)
  734. "Load CONTAINER data for ASSOCIATED.
  735. The arguments have the same meaning as in `org-persist-read'."
  736. (org-persist-read container associated hash-must-match t))
  737. (defun org-persist-load-all (&optional associated)
  738. "Restore all the persistent data associated with ASSOCIATED."
  739. (unless org-persist--index (org-persist--load-index))
  740. (setq associated (org-persist--normalize-associated associated))
  741. (let (all-containers)
  742. (dolist (collection org-persist--index)
  743. (when collection
  744. (cl-pushnew (plist-get collection :container) all-containers :test #'equal)))
  745. (dolist (container all-containers)
  746. (condition-case err
  747. (org-persist-load container associated t)
  748. (error
  749. (message "%s. Deleting bad index entry." err)
  750. (org-persist--remove-from-index (org-persist--find-index `(:container ,container :associated ,associated)))
  751. nil)))))
  752. (defun org-persist-load-all-buffer ()
  753. "Call `org-persist-load-all' in current buffer."
  754. (org-persist-load-all (current-buffer)))
  755. (defun org-persist-write (container &optional associated ignore-return)
  756. "Save CONTAINER according to ASSOCIATED.
  757. ASSOCIATED can be a plist, a buffer, or a string.
  758. A buffer is treated as (:buffer ASSOCIATED).
  759. A string is treated as (:file ASSOCIATED).
  760. The return value is nil when writing fails and the written value (as
  761. returned by `org-persist-read') on success.
  762. When IGNORE-RETURN is non-nil, just return t on success without calling
  763. `org-persist-read'."
  764. (unless (and org-persist-disable-when-emacs-Q
  765. ;; FIXME: This is relying on undocumented fact that
  766. ;; Emacs sets `user-init-file' to nil when loaded with
  767. ;; "-Q" argument.
  768. (not user-init-file))
  769. (setq associated (org-persist--normalize-associated associated))
  770. ;; Update hash
  771. (when (and (plist-get associated :file)
  772. (plist-get associated :hash)
  773. (get-file-buffer (plist-get associated :file)))
  774. (setq associated (org-persist--normalize-associated (get-file-buffer (plist-get associated :file)))))
  775. (let ((collection (org-persist--get-collection container associated)))
  776. (setf collection (plist-put collection :associated associated))
  777. (unless (seq-find (lambda (v)
  778. (run-hook-with-args-until-success 'org-persist-before-write-hook v associated))
  779. (plist-get collection :container))
  780. (when (or (file-exists-p org-persist-directory) (org-persist--save-index))
  781. (let ((file (org-file-name-concat org-persist-directory (plist-get collection :persist-file)))
  782. (data (mapcar (lambda (c) (cons c (org-persist-write:generic c collection)))
  783. (plist-get collection :container))))
  784. (puthash file data org-persist--write-cache)
  785. (org-persist--write-elisp-file file data)
  786. (or ignore-return (org-persist-read container associated))))))))
  787. (defun org-persist-write-all (&optional associated)
  788. "Save all the persistent data.
  789. When ASSOCIATED is non-nil, only save the matching data."
  790. (unless org-persist--index (org-persist--load-index))
  791. (setq associated (org-persist--normalize-associated associated))
  792. (let (all-containers)
  793. (dolist (collection org-persist--index)
  794. (if associated
  795. (when collection
  796. (cl-pushnew (plist-get collection :container) all-containers :test #'equal))
  797. (condition-case err
  798. (org-persist-write (plist-get collection :container) (plist-get collection :associated) t)
  799. (error
  800. (message "%s. Deleting bad index entry." err)
  801. (org-persist--remove-from-index collection)
  802. nil))))
  803. (dolist (container all-containers)
  804. (let ((collection (org-persist--find-index `(:container ,container :associated ,associated))))
  805. (when collection
  806. (condition-case err
  807. (org-persist-write container associated t)
  808. (error
  809. (message "%s. Deleting bad index entry." err)
  810. (org-persist--remove-from-index collection)
  811. nil)))))))
  812. (defun org-persist-write-all-buffer ()
  813. "Call `org-persist-write-all' in current buffer.
  814. Do nothing in an indirect buffer."
  815. (unless (buffer-base-buffer (current-buffer))
  816. (org-persist-write-all (current-buffer))))
  817. (defalias 'org-persist-gc:elisp #'ignore)
  818. (defalias 'org-persist-gc:index #'ignore)
  819. (defun org-persist-gc:file (container collection)
  820. "Garbage collect file CONTAINER in COLLECTION."
  821. (let ((file (org-persist-read container (plist-get collection :associated))))
  822. (when (file-exists-p file)
  823. (delete-file file))))
  824. (defun org-persist-gc:url (container collection)
  825. "Garbage collect url CONTAINER in COLLECTION."
  826. (let ((file (org-persist-read container (plist-get collection :associated))))
  827. (when (file-exists-p file)
  828. (delete-file file))))
  829. (defmacro org-persist--gc-persist-file (persist-file)
  830. "Garbage collect PERSIST-FILE."
  831. `(when (file-exists-p ,persist-file)
  832. (delete-file ,persist-file)
  833. (when (org-directory-empty-p (file-name-directory ,persist-file))
  834. (delete-directory (file-name-directory ,persist-file)))))
  835. (defun org-persist-gc ()
  836. "Remove expired or unregistered containers.
  837. Also, remove containers associated with non-existing files."
  838. (unless (and org-persist-disable-when-emacs-Q
  839. ;; FIXME: This is relying on undocumented fact that
  840. ;; Emacs sets `user-init-file' to nil when loaded with
  841. ;; "-Q" argument.
  842. (not user-init-file))
  843. (let (new-index (remote-files-num 0))
  844. (dolist (collection org-persist--index)
  845. (let* ((file (plist-get (plist-get collection :associated) :file))
  846. (file-remote (when file (file-remote-p file)))
  847. (persist-file (when (plist-get collection :persist-file)
  848. (org-file-name-concat
  849. org-persist-directory
  850. (plist-get collection :persist-file))))
  851. (expired? (org-persist--gc-expired-p
  852. (plist-get collection :expiry) collection)))
  853. (when persist-file
  854. (when file
  855. (when file-remote (cl-incf remote-files-num))
  856. (unless (if (not file-remote)
  857. (file-exists-p file)
  858. (pcase org-persist-remote-files
  859. ('t t)
  860. ('check-existence
  861. (file-exists-p file))
  862. ((pred numberp)
  863. (<= org-persist-remote-files remote-files-num))
  864. (_ nil)))
  865. (setq expired? t)))
  866. (if expired?
  867. (org-persist--gc-persist-file persist-file)
  868. (push collection new-index)))))
  869. (setq org-persist--index (nreverse new-index)))))
  870. ;; Automatically write the data, but only when we have write access.
  871. (let ((dir (directory-file-name
  872. (file-name-as-directory org-persist-directory))))
  873. (while (and (not (file-exists-p dir))
  874. (not (equal dir (setq dir (directory-file-name
  875. (file-name-directory dir)))))))
  876. (if (not (file-writable-p dir))
  877. (message "Missing write access rights to org-persist-directory: %S"
  878. org-persist-directory)
  879. (add-hook 'kill-emacs-hook #'org-persist-write-all)
  880. ;; `org-persist-gc' should run before `org-persist-write-all'.
  881. ;; So we are adding the hook after `org-persist-write-all'.
  882. (add-hook 'kill-emacs-hook #'org-persist-gc)))
  883. (add-hook 'after-init-hook #'org-persist-load-all)
  884. (provide 'org-persist)
  885. ;;; org-persist.el ends here