changelog shortlog graph tags branches changeset files revisions annotate raw help

Mercurial > core / emacs/lib/graph.el

changeset 666: f15e0f021a64
parent: c60decbaae3d
child: bb8aa1eda12b
author: Richard Westhaver <ellis@rwest.io>
date: Sun, 22 Sep 2024 22:13:44 -0400
permissions: -rw-r--r--
description: more elisp
1 ;;; graph.el --- Graph-oriented Extensions -*- lexical-binding: t; -*-
2 
3 ;; Copyright (C) 2024 The Compiler Company
4 ;; Version: "0.2.0"
5 ;; Author: Richard Westhaver <richard.westhaver@gmail.com>
6 ;; Keywords: docs, maint, outlines, extensions
7 
8 ;; This program is free software; you can redistribute it and/or modify
9 ;; it under the terms of the GNU General Public License as published by
10 ;; the Free Software Foundation, either version 3 of the License, or
11 ;; (at your option) any later version.
12 
13 ;; This program is distributed in the hope that it will be useful,
14 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
15 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 ;; GNU General Public License for more details.
17 
18 ;; You should have received a copy of the GNU General Public License
19 ;; along with this program. If not, see <https://www.gnu.org/licenses/>.
20 
21 ;;; Commentary:
22 
23 ;;
24 
25 ;;; Code:
26 (require 'org)
27 (require 'org-agenda)
28 (require 'default)
29 (require 'ulang)
30 
31 (defgroup graph nil
32  "CC Graph")
33 
34 (defcustom org-graph-db-directory (join-paths user-org-stash-directory "graph")
35  "graph database storage directory."
36  :type 'directory
37  :group 'graph)
38 
39 (defcustom org-graph-locations (list (join-paths company-org-directory "notes/"))
40  "List of directories to check for nodes."
41  :type '(list directory)
42  :group 'graph)
43 
44 (defcustom org-graph-include-agenda-files nil
45  "When non-nil, include `org-agenda-files' in the graph."
46  :type 'boolean
47  :group 'graph)
48 
49 (defcustom org-graph-include-archive nil
50  "When non-nil, include `org-arhive-location' in the graph."
51  :type 'boolean
52  :group 'graph)
53 
54 (defcustom org-graph-include-org-directory nil
55  "When non-nil, include `org-directory' files in the graph."
56  :type 'boolean
57  :group 'graph)
58 
59 (defcustom org-graph-compaction-hook nil
60  "Hook run when a graph is compacted to `org-graph-db'."
61  :type 'hook
62  :group 'graph)
63 
64 (defcustom org-graph-capture-hook nil
65  "Hook run when a node is added to the graph."
66  :type 'hook
67  :group 'graph)
68 
69 (defcustom org-graph-db-init-script (join-paths company-source-directory "infra/scripts/org-db-init.lisp")
70  "Path to a lisp script responsible for initializing the `org-graph-db-directory'.")
71 
72 (cl-defstruct org-graph-db-handle
73  (type :rocksdb)
74  (name "org-graph-db")
75  init
76  get
77  put
78  delete
79  merge
80  compact
81  shutdown)
82 
83 (defcustom org-graph-db (make-org-graph-db-handle)
84  "A handle to the database backend which stores nodes and edges."
85  :type 'org-graph-db-handle
86  :group 'graph)
87 
88 (defun org-graph-from-id-locations (&optional edges local)
89  "Populate the `org-graph' from `org-id-locations', filtering out any
90 entries not under a member of `org-graph-locations'. When EDGES is
91 non-nil visit each node and collect all edges found."
92  (interactive "P")
93  (save-excursion
94  (let* ((node-ids (copy-hash-table (org-id-locations-load))) ;; don't overwrite `org-id-locations'
95  (graph (make-org-graph :nodes node-ids)))
96  (maphash
97  (lambda (k v)
98  (if-let ((ok (cl-loop for l in org-graph-locations
99  when (string-prefix-p l (file-truename v))
100  return t)))
101  (let ((pos (cdr (org-id-find-id-in-file k v))))
102  (message "%s %s" k v)
103  (org-with-file-buffer v
104  (goto-char pos)
105  (org-graph-node-at-point graph)
106  (when edges (org-graph-edges-at-point graph))))
107  (remhash k (org-graph-nodes graph))))
108  (org-graph-nodes graph))
109  (if local
110  (setq-local org-graph graph)
111  (setq org-graph graph)))))
112 
113 (defun org-graph-files ()
114  (org-list-files org-graph-locations org-agenda-extensions))
115 
116 (cl-defstruct org-graph
117  ;; TODO 2024-09-17: use integers instead of string
118  (nodes (make-hash-table :test 'equal))
119  (edges (make-hash-table :test 'equal)))
120 
121 (defvar org-graph (make-org-graph)
122  "The Emacs-native org-graph. Should be assigned to an `org-graph' instance.")
123 
124 (cl-defstruct org-graph-node id name file point)
125 (cl-defstruct org-graph-edge (type 'link) in properties timestamp point out)
126 
127 (defun org-graph--file-hash (file)
128  "Compute the hash of FILE."
129  (with-temp-buffer
130  (set-buffer-multibyte nil)
131  (insert-file-contents-literally file)
132  (secure-hash 'md5 (current-buffer))))
133 
134 (defun org-graph-node-at-point (&optional update)
135  "Return the `org-graph-node' at point. When UPDATE is non-nil insert or
136 update the node into the org-graph object specified or when 't' use the
137 currently active org-graph."
138  (let* ((file (buffer-file-name))
139  (node (make-org-graph-node :point (point) :file file)))
140  (if (derived-mode-p 'org-mode)
141  (progn
142  (if (org-before-first-heading-p)
143  (setf (org-graph-node-name node) (org-get-title)
144  ;; use the filename, create a hash as id
145  (org-graph-node-id node) (org-graph--file-hash file))
146  (setf (org-graph-node-id node) (org-id-get)
147  (org-graph-node-name node) (elt (org-heading-components) 4))))
148  (setf (org-graph-node-id node) (org-graph--file-hash file)
149  (org-graph-node-name node) (file-name-nondirectory file)))
150  (when update
151  (puthash (org-graph-node-id node) node (org-graph-nodes (if (eql t update) org-graph update))))
152  node))
153 
154 ;; TODO 2024-09-22: properties
155 (defun org-graph-collect-edge ()
156  "Collect the edge at point which should be a line created with `org-graph-edge--insert'."
157  (org-with-point-at (beginning-of-line)
158  (when (org-at-timestamp-p 'lax)
159  (let ((ep (point))
160  (ts (match-string-no-properties 0))
161  (end (match-end 0)))
162  (goto-char (1+ end))
163  ;; next 2 chars are the arrow
164  (let ((arrow (org-graph-edge-arrow* (buffer-substring-no-properties (point) (+ 2 (point))))))
165  (goto-char (+ (point) 4))
166  (make-org-graph-edge :in (org-id-get)
167  :type arrow
168  :point ep
169  :timestamp (org-parse-time-string ts t)
170  :out (string-trim (org--link-at-point) "id:")))))))
171 
172 (defun org-graph-map-edges (function)
173  "Eval FUNCTION once for each edge in node at point with point at start of the edge."
174  (with-org-graph-edge-drawer (end)
175  (re-search-backward (rx bol ?: (literal (org-graph-edge-drawer)) ?: eol) nil t)
176  (goto-char (1+ (match-end 0)))
177  (cl-loop while (> (point-max) end (point))
178  collect (funcall function)
179  do (next-line))))
180 
181 (defun org-graph-reduce-edges (function)
182  "Same as `cl-reduce' where SEQ is the list of edges at point. FUNCTION
183 takes two `org-graph-edge' objects as input."
184  (let ((edges (org-graph-map-edges 'org-graph-collect-edge)))
185  (cl-reduce function edges)))
186 
187 (defun org-graph-collect-edges-at-point (&optional update)
188  "Collect the contents of the EDGES drawer from node at point. When UPDATE
189 is non-nil insert or update the node into the org-graph object specified
190 or when 't' use the currently active org-graph."
191  (let ((edges (org-graph-map-edges 'org-graph-collect-edge)))
192  (when update
193  (mapc (lambda (e)
194  (puthash
195  (org-graph-edge-in e)
196  e
197  (org-graph-edges (if (eql t update) org-graph update))))
198  edges))
199  edges))
200 
201 (defun org-graph-edge-equal (a b)
202  "Return non-nil if A and B are 'equal' org-graph-edge objects."
203  (equal (org-graph-edge-out a) (org-graph-edge-out b)))
204 
205 (defun org-graph-edge-remove-duplicates ()
206  "Remove duplicate edge entries from node at point."
207  (org-graph-reduce-edges
208  (lambda (a b)
209  (when (org-graph-edge-equal a b)
210  (let ((tsa (org-graph-edge-timestamp a))
211  (tsb (org-graph-edge-timestamp b)))
212  (goto-char (org-graph-edge-point (if (org-time> tsa tsb) b a)))
213  (delete-line))))))
214 
215 (defun org-graph-edges-at-point (&optional update)
216  "Return a list of `org-graph-edge' instances associated with the node at
217 point. When UPDATE is non-nil insert or update the edges into the
218 currently active org-graph."
219  (interactive)
220  (when (derived-mode-p 'org-mode)
221  (org-graph-collect-edges-at-point update)))
222 
223 (defun org-graph-buffer-update (&optional buffer)
224  "Map over an org buffer adding all nodes to the active org-graph."
225  (interactive)
226  (save-excursion
227  (with-current-buffer (or buffer (current-buffer))
228  ;; capture file node
229  (goto-char (point-min))
230  (org-graph-node-at-point t)
231  (when (derived-mode-p 'org-mode)
232  (org-map-entries (lambda () (org-graph-node-at-point t)))))))
233 
234 ;;; Edges
235 ;; See https://github.com/toshism/org-super-links/blob/develop/org-super-links.el
236 (declare-function org-make-link-description-function "ext:org-mode")
237 
238 (defvar org-graph-edge-drawer "EDGES"
239  "Controls how/where to insert edges. If nil edges will just be inserted
240 under the heading.")
241 
242 ;; TODO 2024-09-16: edge properties
243 (defvar org-graph-edge-prefix 'org-graph-edge-prefix-timestamp
244  "Prefix to insert before the edge.
245 This can be a string, nil, or a function that takes no arguments and
246 returns a string.
247 
248 Default is the function `org-graph-edge-prefix-timestamp'
249 which returns an inactive timestamp formatted according to the variable
250 `org-time-stamp-formats'.")
251 
252 ;; TODO 2024-09-16: do we need this? what sort of information for a
253 ;; given edge would go in the postfix? this may be better suited as a
254 ;; per-edge value rather than global - maybe use for comments.
255 (defvar org-graph-edge-postfix nil
256  "Postfix to insert after the edge.
257 This can be a string, nil, or a function that takes no arguments and
258 returns a string")
259 
260 (defvar org-graph-edge-link-prefix nil
261  "Prefix to insert before the link.
262 This can be a string, nil, or a function that takes no arguments and
263 returns a string")
264 
265 (defvar org-graph-edge-link-postfix nil
266  "Postfix to insert after the link.
267 This can be a string, nil, or a function that takes no arguments and
268 returns a string")
269 
270 (defvar org-graph-edge-default-description-formatter org-make-link-description-function
271  "What to use if no description is provided.
272 This can be a string, nil or a function that accepts two arguments
273 LINK and DESC and returns a string.
274 
275 nil will return the default desciption or the link.
276 string will be used only as a default fall back if set.
277 function will be called for every link.
278 
279 Default is the variable `org-make-link-desciption-function'.")
280 
281 (defvar org-graph-edge-search-function 'org-graph-edge-get-location
282  "The interface to use for finding target links. If you provide a custom
283 function it will be called with the `point` at the location the link
284 should be inserted. The only other requirement is that it should call
285 the function `org-graph-edge--insert-link' with a marker to the target
286 link. AKA the place you want the edge.
287 
288 `org-graph-edge-get-location' internally uses `org-refile-get-location'.")
289 
290 (defvar org-graph-edge-pre-link-hook nil
291  "Hook called before storing the link on the link side.
292 This is called with point at the location where it was called.")
293 
294 (defvar org-graph-edge-pre-backlink-hook nil
295  "Hook called before storing the link on the backlink side.
296 This is called with point in the heading of the backlink.")
297 
298 (defvar org-graph-edge-indicator-alist
299  '((link . "->")
300  (backlink . "<-")
301  (relation . "--")
302  (parent . ">>")
303  (child . "<<"))
304  "An alist of (EDGE-TYPE . INDICATOR) pairs. Each INDICATOR is a string
305 which will be printed between the properties and backlink of the
306 associated EDGE-TYPE.")
307 
308 (defun org-graph-edge-arrow (sym)
309  (cdr (assoc sym org-graph-edge-indicator-alist)))
310 
311 (defun org-graph-edge-arrow* (str)
312  "Reverse lookup of edge arrow symbol."
313  (car (rassoc str org-graph-edge-indicator-alist)))
314 
315 (defun org-graph-edge-get-location ()
316  "Default for function `org-graph-edge-search-function' that reuses the `org-refile' machinery."
317  (let ((target (org-refile-get-location "Node")))
318  (org-graph-edge--insert-link (set-marker (make-marker) (car (cdddr target))
319  (get-file-buffer (car (cdr target)))))))
320 
321 (cl-defmacro with-org-graph-edge-drawer ((start &optional create) &rest body)
322  "START is a symbol which is bound to the start of the edge drawer."
323  (declare (indent 1))
324  `(save-excursion
325  (org-with-wide-buffer
326  (let ((org-log-into-drawer (org-graph-edge-drawer)))
327  (org-graph-edge--org-narrow-to-here)
328  (let ((,start (org-log-beginning ,create)))
329  (when (re-search-forward (rx bol ?: "END" ?: eol) nil t)
330  (goto-char ,start)
331  ,@body))))))
332 
333 (defun org-graph-edge-search-function ()
334  "Call the search interface specified in variable `org-graph-edge-search-function'."
335  (funcall org-graph-edge-search-function))
336 
337 (defun org-graph-edge-prefix ()
338  "Return an appropriate string based on variable `org-graph-edge-prefix'."
339  (cond ((equal org-graph-edge-prefix nil) "")
340  ((stringp org-graph-edge-prefix) org-graph-edge-prefix)
341  (t (funcall org-graph-edge-prefix))))
342 
343 (defun org-graph-edge-postfix ()
344  "Return an appropriate string based on variable `org-graph-edge-postfix'."
345  (cond ((equal org-graph-edge-postfix nil) "\n")
346  ((stringp org-graph-edge-postfix) org-graph-edge-postfix)
347  (t (funcall org-graph-edge-postfix))))
348 
349 (defun org-graph-edge-link-prefix ()
350  "Return an appropriate string based on variable `org-graph-edge-link-prefix'."
351  (cond ((equal org-graph-edge-link-prefix nil) "")
352  ((stringp org-graph-edge-link-prefix) org-graph-edge-link-prefix)
353  (t (funcall org-graph-edge-link-prefix))))
354 
355 (defun org-graph-edge-link-postfix ()
356  "Return an appropriate string based on variable `org-graph-edge-link-postfix'."
357  (cond ((equal org-graph-edge-link-postfix nil) "")
358  ((stringp org-graph-edge-link-postfix) org-graph-edge-link-postfix)
359  (t (funcall org-graph-edge-link-postfix))))
360 
361 ;; TODO 2024-09-16: edge-properties
362 (defun org-graph-edge-prefix-timestamp ()
363  "Return the default prefix string for an edge.
364 Inactive timestamp formatted according to `org-time-stamp-formats'."
365  (format-time-string (org-time-stamp-format t t) (current-time)))
366 
367 (defun org-graph-edge-default-description-formatter (link desc)
368  "Return a string to use as the link desciption.
369 LINK is the link target. DESC is the provided desc."
370  (let ((p org-graph-edge-default-description-formatter))
371  (cond ((equal p nil) (or desc link))
372  ((stringp p) (or desc p))
373  ((fboundp p) (funcall p link desc))
374  (t desc))))
375 
376 (defun org-graph-edge-drawer ()
377  "Name of the edge drawer, as a string, or nil.
378 This is the value of variable
379 `org-graph-edge-drawer'. However, if the current
380 entry has or inherits a EDGE_DRAWER property, it will be
381 used instead of the default value."
382  (let ((p (org-entry-get nil "EDGE_DRAWER" 'inherit t)))
383  (cond ((equal p "nil") nil)
384  ((stringp p) p)
385  (t org-graph-edge-drawer))))
386 
387 (defun org-graph-edge--org-narrow-to-here ()
388  "Narrow to current heading, excluding subheadings."
389  (org-narrow-to-subtree)
390  (save-excursion
391  (org-next-visible-heading 1)
392  (narrow-to-region (point-min) (point))))
393 
394 ;; delete related functions
395 (defun org-graph-find-edges (id)
396  "Return link elements for ID."
397  (org-graph-edge--org-narrow-to-here)
398  (let ((links
399  (org-element-map (org-element-parse-buffer) 'link
400  (lambda (link)
401  (when (string= (org-element-property :path link) id)
402  link)))))
403  (widen)
404  links))
405 
406 (defun org-graph-edge--in-drawer-p ()
407  "Return non-nil if point is in drawer. Value is element at point."
408  (let ((element (org-element-at-point)))
409  (while (and element
410  (not (memq (org-element-type element) '(drawer property-drawer))))
411  (setq element (org-element-property :parent element)))
412  element))
413 
414 (defun org-graph-edge--delete-link (link)
415  "Delete the LINK. If point is in edges drawer, delete the entire line."
416  (save-excursion
417  (goto-char (org-element-property :begin link))
418  (if (org-graph-edge--in-drawer)
419  (progn
420  (kill-whole-line 1)
421  (org-remove-empty-drawer-at (point)))
422  (delete-region (org-element-property :begin link) (org-element-property :end link)))))
423 
424 (defun org-graph-edge--insert (link desc arrow &rest props)
425  "Insert an edge at point. ARROW is a symbol representing the type of
426 arrow to insert. The rest of the arguments are parsed as :KEY VAL pairs
427 which are inserted with the edge."
428  (insert (format "%s %s " (org-graph-edge-prefix)
429  (org-graph-edge-arrow arrow)))
430  (org-insert-link nil link desc)
431  (insert (org-graph-edge-link-postfix))
432  (newline))
433 
434 (defun org-graph-edge-insert-related (link desc)
435  "Insert a relation edge."
436  (with-org-graph-edge-drawer (beg t)
437  (org-graph-edge--insert link desc 'relation)
438  (org-indent-region beg (point))))
439 
440 (defun org-graph-edge-insert-backlink (link desc)
441  "Insert edge to LINK with DESC.
442 Where the edge is placed is determined by the variable `org-graph-edge-drawer'."
443  (with-org-graph-edge-drawer (beg t)
444  (let ((description (org-graph-edge-default-description-formatter link desc)))
445  (org-graph-edge--insert link description 'backlink)
446  (org-indent-region beg (point)))))
447 
448 (defun org-graph-edge-insert-link (link desc)
449  "insert a forward link edge."
450  (with-org-graph-edge-drawer (beg t)
451  (org-graph-edge--insert link desc 'link)
452  (org-indent-region beg (point))))
453 
454 (defun org-graph-edge-links-action (marker hooks)
455  "Go to MARKER, run HOOKS and store a link."
456  (with-current-buffer (marker-buffer marker)
457  (save-excursion
458  (save-restriction
459  (widen) ;; buffer could be narrowed
460  (goto-char (marker-position marker))
461  (run-hooks hooks)
462  (call-interactively #'org-store-link)
463  (pop org-stored-links)))))
464 
465 (defun org-graph-edge-link-builder (link)
466  "Format link description for LINK."
467  (let* ((link-ref (car link))
468  (pre-desc (cadr link))
469  (description (org-graph-edge-default-description-formatter link-ref pre-desc)))
470  (cons link-ref description)))
471 
472 (defun org-graph-edge--insert-link (target &optional no-forward)
473  "Insert link to marker TARGET and create an edge.
474 Only create edges in files in `org-mode' or a derived mode, otherwise just
475 act like a normal link.
476 
477 If NO-FORWARD is non-nil skip creating the forward link. Currently
478 only used when converting a link."
479  (let* ((source (point-marker))
480  (source-link (org-graph-edge-links-action source 'org-graph-edge-pre-link-hook))
481  (target-link (org-graph-edge-links-action target 'org-graph-edge-pre-backlink-hook))
482  (source-formatted-link (org-graph-edge-link-builder source-link))
483  (target-formatted-link (org-graph-edge-link-builder target-link)))
484  (with-current-buffer (marker-buffer target)
485  (save-excursion
486  (save-restriction
487  (widen) ;; buffer could be narrowed
488  (goto-char (marker-position target))
489  (when (derived-mode-p 'org-mode)
490  (org-graph-edge-insert-backlink (car source-formatted-link) (cdr source-formatted-link))))))
491  (unless no-forward
492  (with-current-buffer (marker-buffer source)
493  (save-excursion
494  (goto-char (marker-position source))
495  (org-graph-edge-insert-link (car target-formatted-link) (cdr target-formatted-link)))))))
496 
497 ;;;###autoload
498 (defun org-graph-edge-convert-link (arg)
499  "Convert a normal `org-mode' link at `point' to a graph link, ARG prefix.
500 When called interactively with a `C-u' prefix argument do not modify existing link."
501  (interactive "P")
502  (let ((from-m (point-marker))
503  (target (save-window-excursion
504  (with-current-buffer (current-buffer)
505  (save-excursion
506  (org-open-at-point)
507  (point-marker))))))
508  (org-graph-edge--insert-link target arg)
509  (goto-char (marker-position from-m)))
510  (when (not arg)
511  (let ((begin (org-element-property :begin (org-element-context)))
512  (end (org-element-property :end (org-element-context))))
513  (delete-region begin end))))
514 
515 ;;;###autoload
516 (defun org-graph-edge-delete ()
517  "Delete the link at point, and the corresponding reverse link.
518 If no reverse link exists, just delete link at point.
519 This works from either side, and deletes both sides of a link."
520  (interactive)
521  (save-window-excursion
522  (with-current-buffer (current-buffer)
523  (save-excursion
524  (let ((id (org-id-get (point))))
525  (org-open-at-point)
526  (let ((link-elements (org-graph-find-edges id)))
527  (if link-elements
528  (if (> (length link-elements) 1)
529  (error "Multiple links found.")
530  (org-graph-edge--delete-link (car link-elements)))
531  (message "No edge found. Deleting active only.")))))))
532  (org-graph-edge--delete-link (org-element-context)))
533 
534 ;;;###autoload
535 (defun org-graph-edge-insert ()
536  "Insert an edge from `org-stored-links')"
537  (interactive)
538  (if org-stored-links
539  (progn
540  (org-link-open (pop org-stored-links))
541  (org-graph-edge--insert-link (set-marker (make-marker) (point))))
542  (org-graph-edge-link)))
543 
544 ;;;###autoload
545 (defun org-graph-edge-link ()
546  "Insert a link edge and add a backlink edge to the target heading."
547  (interactive)
548  (org-graph-edge-search-function))
549 
550 (defun org-dblock-write:links ()
551  "Generate a 'links' block for the designated node.")
552 
553 (defun org-dblock-write:graph ()
554  "Generate a 'graph' block for the designated set of nodes.")
555 
556 (provide 'graph)
557 ;; graph.el ends here