org-persist.el 44 KB

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