org-persist.el 45 KB

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