org-persist.el 43 KB

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