-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathorg-node.el
More file actions
3651 lines (3217 loc) · 151 KB
/
org-node.el
File metadata and controls
3651 lines (3217 loc) · 151 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;;; org-node.el --- Fast org-roam replacement -*- lexical-binding: t; -*-
;; Copyright (C) 2024-2026 Martin Edström
;; SPDX-License-Identifier: GPL-3.0-or-later
;; Author: Martin Edström <meedstrom91@gmail.com>
;; URL: https://github.com/meedstrom/org-node
;; Created: 2024-04-13
;; Keywords: org, hypermedia
;; Package-Requires: ((emacs "29.1")
;; (cond-let "0.2")
;; (llama "1.0")
;; (magit-section "4.3.0")
;; (org-mem "0.34.0"))
;;; Commentary:
;; If you were the sort of person to prefer "id:" links,
;; over "file:" links, radio-targets or any other type of link,
;; you're in the right place!
;; Now you can worry less about mentally tracking subtree hierarchies
;; and directory structures. Once you've assigned an ID to something,
;; you can find it later.
;; The philosophy is the same as org-roam: if you assign an ID every
;; time you make an entry that you know you might want to link to from
;; elsewhere, then it tends to work out that the `org-node-find' command
;; can jump to more-or-less every entry you'd ever want to jump to.
;; That's just the core of it as described to someone not familiar with
;; zettelkasten-inspired software. In fact, out of the simplicity
;; arises something powerful, more to be experienced than explained.
;; "The fixed address of each note is the alpha and omega of the
;; world of Zettelkasten. Everything becomes possible because of it."
;; -- https://zettelkasten.de/introduction
;; Compared to Org-roam:
;; + Compatible (you can use both packages and compare)
;; + Fast
;; + No SQLite
;; + If you want, opt out of those file-level :PROPERTIES: drawers
;; + See user option `org-node-prefer-with-heading'
;; + Try to rely in a bare-metal way on upstream org-id and org-capture
;; + Extra utilities, notably to auto-rename files and links
;; + An alternative way to display backlinks
;; - No support for "roam:" links
;; - Smaller package ecosystem
;; + Packages based on org-roam can still work! Either by using
;; org-roam at the same time, or by configuring
;; `org-mem-roamy-do-overwrite-real-db' and enabling
;; `org-mem-roamy-db-mode'.
;; - Blind to TRAMP files (for now)
;; Compared to Denote:
;; + Compatible (you can use both packages and compare)
;; + No mandatory filename style (can match Denote format if you like)
;; + You can have as many "notes" as you want inside one file.
;; + You could possibly use Denote for coarse browsing,
;; and Org-node for more granular browsing.
;; - No support for "denote:" links
;; - No support for Markdown or other file types
;; - Blind to TRAMP files (for now)
;;; Code:
(declare-function consult--grep "ext:consult")
(declare-function consult--grep-make-builder "ext:consult")
(declare-function consult--ripgrep-make-builder "ext:consult")
(declare-function org-at-heading-p "org")
(declare-function org-back-to-heading "org")
(declare-function org-back-to-heading-or-point-min "org")
(declare-function org-before-first-heading-p "org")
(declare-function org-capture-get "org-capture")
(declare-function org-capture-put "org-capture")
(declare-function org-collect-keywords "org")
(declare-function org-cut-subtree "org")
(declare-function org-end-of-meta-data "org")
(declare-function org-entry-end-position "org")
(declare-function org-entry-get "org")
(declare-function org-entry-get-with-inheritance "org")
(declare-function org-entry-properties "org")
(declare-function org-entry-put "org")
(declare-function org-find-property "org")
(declare-function org-fold-show-children "org-fold")
(declare-function org-fold-show-context "org-fold")
(declare-function org-fold-show-entry "org-fold")
(declare-function org-get-buffer-tags "org")
(declare-function org-get-heading "org")
(declare-function org-get-tags "org")
(declare-function org-get-title "org")
(declare-function org-id-add-location "org-id")
(declare-function org-id-find "org-id")
(declare-function org-id-get-create "org-id")
(declare-function org-id-new "org-id")
(declare-function org-id-update-id-locations "org-id")
(declare-function org-in-block-p "org")
(declare-function org-in-regexp "org-macs")
(declare-function org-in-src-block-p "org")
(declare-function org-insert-drawer "org")
(declare-function org-insert-heading "org")
(declare-function org-insert-subheading "org")
(declare-function org-invisible-p "org-macs")
(declare-function org-link-display-format "ol")
(declare-function org-link-make-string "ol")
(declare-function org-lint "org-lint")
(declare-function org-map-region "org")
(declare-function org-mem-list--pop-to-tabulated-buffer "org-mem-list")
(declare-function org-mem-roamy-mk-backlinks "org-mem-roamy")
(declare-function org-mem-roamy-mk-reflinks "org-mem-roamy")
(declare-function org-paste-subtree "org")
(declare-function org-promote "org")
(declare-function org-remove-empty-drawer-at "org")
(declare-function org-roam-node-id "ext:org-roam-node")
(declare-function org-set-tags "org")
(declare-function org-time-stamp-format "org")
(declare-function org-up-heading-or-point-min "org")
(declare-function outline-next-heading "outline")
(defvar consult-ripgrep-args)
(defvar crm-separator)
(defvar org-attach-id-dir)
(defvar org-drawer-regexp)
(defvar org-element-citation-prefix-re)
(defvar org-link-plain-re)
(defvar org-roam-capture-templates)
(defvar org-roam-preview-function)
(defvar org-roam-preview-postprocess-functions)
(defvar zone-programs)
(require 'cl-lib)
(require 'fileloop)
(require 'org-faces)
(require 'repeat)
(require 'subr-x)
;; Externals
(require 'org-node-changes)
(require 'cond-let)
(require 'llama)
(require 'org-mem)
(require 'org-mem-updater)
(eval-when-compile
(require 'org)
(require 'org-id)
(require 'org-macs)
(require 'org-fold)
(require 'org-element))
(defconst org-node-internal-version 12)
;;;; Faces
(defgroup org-node-faces nil
"Faces used by Org-node."
:group 'faces
:group 'org-node)
(defface org-node-cite
'((t :inherit org-cite))
"Face for @citations in Org-node commands.")
(defface org-node-cite-type
'((t :inherit completions-annotations))
"Face for \"http:\" part of an URL citation in Org-node commands.")
(defface org-node-tag
'((t :inherit org-tag))
"Face for :tags: in Org-node commands.")
(defface org-node-parent
'((t :inherit completions-annotations))
"Face for parent headings in Org-node commands.")
(defface org-node-rewrite-link
'((t :inherit org-link
:inverse-video t))
"Face for use in `org-node-rewrite-links-ask'.")
(defface org-node-context-origin-title
'((((type nil)) ;; On a terminal.
:extend t
:inherit org-document-title)
(t ;; On GUI.
:extend t
:height 1.5
;; :inherit variable-pitch ;; Too controversial
:weight bold))
"Face for backlink node titles in the context buffer.")
;;;; Early defs
(defvar org-node--candidate<>entry (make-hash-table :test 'equal)
"1:1 table mapping minibuffer completion candidates to ID-nodes.
These candidates may or may not be pre-affixated, depending on
user option `org-node-alter-candidates'.")
(defvar org-node--title<>affixations (make-hash-table :test 'equal)
"1:1 table mapping titles or aliases to affixation triplets.
Even when the triplets are not used, this table serves double-duty such
that its keys constitute the subset of `org-mem--title<>id' that
passed `org-node-filter-fn'.")
;;;; Some options
(defgroup org-node nil
"Support a zettelkasten of org-id files and subtrees."
:group 'org
:link '(url-link :tag "GitHub source" "https://github.com/meedstrom/org-node")
:link '(info-link :tag "Info manual" "(org-node)"))
(defvar org-node-data-dir user-emacs-directory
"Directory in which to persist data between sessions.
As of 3.7.1, only used when `org-node-context-persist-on-disk' is t.")
(defun org-node--set-and-remind-reset (sym val)
"Set SYM to VAL.
Then remind the user to run \\[org-mem-reset]."
(let ((caller (cadr (backtrace-frame 5))))
(when (and (boundp 'org-node--first-init)
(not org-node--first-init)
;; TIL: loading a theme calls ALL custom-setters?!
(not (memq caller '(custom-theme-recalc-variable load-theme))))
(lwarn 'org-node :debug
"org-node--set-and-remind-reset called by %s" caller)
(run-with-timer
.1 nil #'message
"Remember to run M-x org-mem-reset after configuring %S" sym)))
(custom-set-default sym val))
(defcustom org-node-blank-input-hint
(propertize "(untitled node)" 'face 'completions-annotations)
"Whether to add an empty completion candidate to some commands.
It helps indicate that a blank input can be used there to
create an untitled node.
If non-nil, the value is actually the annotation added to it, a
propertized string."
:type '(choice string (const nil))
:package-version '(org-node . "3.3.0"))
;; Perhaps it would be handy if the blank input could do smart things like
;; create a daily-note, but it was not obvious how to shoehorn that into the
;; system we already have. This was what we could easily do.
(defcustom org-node-blank-input-title-generator #'org-node-titlegen-untitled
"Function to generate a title, given no user input.
Used in some commands when exiting minibuffer with a blank string."
:type '(radio (function-item org-node-titlegen-untitled)
(function-item org-node-titlegen-today)
(function-item org-node-titlegen-this-week)
(function :tag "Custom function" :value (lambda ())))
:package-version '(org-node . "3.3.12"))
;; TODO: If setting `org-node-creation-fn' to `org-capture', can we design a
;; capture template that makes new subtree in a pre-existing entry,
;; rather than always making a new file?
;; Would be handy for some kind of "inbox.org" datetree.
(defvar org-node-untitled-format "untitled-%d")
(defvar org-node--untitled-ctr 0)
(defun org-node-titlegen-untitled ()
"Combine `org-node-untitled-format' with a new integer on every call."
(cl-loop do (cl-incf org-node--untitled-ctr)
as title = (format org-node-untitled-format org-node--untitled-ctr)
while (or (gethash title org-node--title<>affixations)
(file-exists-p (org-node-title-to-filename-quiet title)))
finally return title))
(defun org-node-titlegen-today ()
"Make a node title for the day\\='s date."
(format-time-string "Assorted for %A, %d %b %Y"))
(defun org-node-titlegen-this-week ()
"Make a node title for the current ISO8601 week."
(format-time-string "Assorted for Week %V, %G"))
;;;; Time
;; Should have been TIME_CREATED but too late to change the default.
(defcustom org-node-property-crtime "CREATED"
"Name of a property for holding a creation-time timestamp.
Used by:
- `org-node-rename-file-by-title'
- `org-node-ensure-crtime-property'
- `org-node-sort-by-crtime-property'"
:type '(radio (const "CREATED")
(const :tag "TIME_CREATED (good for alphabetic sort near TIME_MODIFIED)"
"TIME_CREATED")
string)
:package-version '(org-node . "3.7.1"))
(defcustom org-node-property-mtime "TIME_MODIFIED"
"Name of a property for holding a last-modification-time timestamp.
Used by:
- `org-node-update-mtime-property'
- `org-node-sort-by-mtime-property'"
:type 'string
:package-version '(org-node . "3.10.0"))
(defun org-node-time-stamp (with-time inactive &optional time zone)
"Make a timestamp passing WITH-TIME, INACTIVE to `org-time-stamp-format'.
Pass TIME, ZONE to `format-time-string'."
(format-time-string (org-time-stamp-format with-time inactive)
time zone))
(defun org-node-update-mtime-property ()
"Update property `org-node-property-mtime' in entry at point.
Suitable on `org-node-modification-hook'."
(org-entry-put nil
org-node-property-mtime
(org-node-time-stamp t t)))
;;;; Filter
;; TODO: Compose a list of functions?
(defcustom org-node-filter-fn #'org-node-filter-no-roam-exclude-p
"Predicate returning non-nil to include a node, or nil to exclude it.
The filter affects two tables:
- `org-node--candidate<>entry', used by completions in the minibuffer
- `org-node--title<>affixations', used by `org-node-complete-at-point-mode'
In other words, returning nil means the user cannot autocomplete to the
node, but Lisp code can still find it in the output of
`org-mem-all-id-nodes', and backlinks are discovered normally.
This function is applied once for every ID-node found, and receives the
node data as a single argument: an `org-mem-entry' object. See examples
by typing \\[org-node-list-example]."
:type '(radio (function-item org-node-filter-no-roam-exclude-p)
(function-item org-node-filter-no-local-roam-exclude-p)
(function-item org-node-filter-watched-dir-p)
(function :tag "Custom function"
:value (lambda (node) t)))
:set #'org-node--set-and-remind-reset
:package-version '(org-node . "3.3.0"))
(defun org-node-filter-no-roam-exclude-p (node)
"Hide NODE if it has or inherits a :ROAM_EXCLUDE: property."
(not (org-mem-property-with-inheritance "ROAM_EXCLUDE" node)))
(defun org-node-filter-no-local-roam-exclude-p (node)
"Hide NODE if it has a :ROAM_EXCLUDE: property."
(not (org-mem-property "ROAM_EXCLUDE" node)))
(defun org-node-filter-watched-dir-p (node)
"Show NODE only if it is found inside `org-mem-watch-dirs'."
(let ((file (org-mem-file-truename node)))
(cl-some (lambda (dir) (string-prefix-p dir file))
(with-memoization (org-mem--table 0 'true-watch-dirs)
(with-temp-buffer ;; No buffer-env
(delete-dups (mapcar #'file-truename org-mem-watch-dirs)))))))
(defun org-node-all-filtered-nodes ()
"All currently cached ID-nodes that satisfied `org-node-filter-fn'."
(delete-dups (hash-table-values org-node--candidate<>entry)))
(defun org-node-all-filtered-files ()
"All files containing any of `org-node-all-filtered-nodes'."
(delete-dups (mapcar #'org-mem-entry-file (org-node-all-filtered-nodes))))
;;;; Sort
(defcustom org-node-display-sort-fn nil
"How to sort completions.
Used as `display-sort-function' in `completion-metadata'.
See Info node `(elisp) Completion Variables'."
:type '(radio
(const :tag "Do not override `completions-sort'" :value nil)
(function-item org-node-sort-by-file-mtime)
(function-item org-node-sort-by-crtime-property)
(function-item org-node-sort-by-mtime-property)
(function :tag "Custom function" :value (lambda (completions))))
:package-version '(org-node . "3.9.0"))
(defun org-node-sort-by-file-mtime (completions)
"Sort COMPLETIONS by file modification time."
(sort completions
(lambda (c1 c2)
(let* ((node1 (gethash c1 org-node--candidate<>entry))
(node2 (gethash c2 org-node--candidate<>entry))
;; mtime could be nil if the file does not exist yet
(mtime1 (and node1 (ignore-errors (org-mem-file-mtime node1))))
(mtime2 (and node2 (ignore-errors (org-mem-file-mtime node2)))))
;; REVIEW: Actually should all of these four cases return t?
(cond ((null node1) t)
((null node2) nil)
((null mtime1) t)
((null mtime2) nil)
(t (time-less-p mtime2 mtime1)))))))
(defun org-node-sort-by-crtime-property (completions)
"Sort COMPLETIONS by timestamp in `org-node-property-crtime'.
Nodes with no such property come after all the rest that do have the
property - in other words, nodes without may as well be dated to 1970."
(sort completions
(lambda (c1 c2)
(let* ((node1 (gethash c1 org-node--candidate<>entry))
(node2 (gethash c2 org-node--candidate<>entry))
(crtime1 (and node1 (org-mem-property org-node-property-crtime node1)))
(crtime2 (and node2 (org-mem-property org-node-property-crtime node2))))
(cond ((null node1) t)
((null node2) nil)
((null crtime1) nil)
((null crtime2) t)
(t (string< crtime2 crtime1)))))))
(defun org-node-sort-by-mtime-property (completions)
"Sort COMPLETIONS by timestamp in `org-node-property-mtime'."
(sort completions
(lambda (c1 c2)
(let* ((node1 (gethash c1 org-node--candidate<>entry))
(node2 (gethash c2 org-node--candidate<>entry))
(time1 (and node1 (org-mem-property org-node-property-mtime node1)))
(time2 (and node2 (org-mem-property org-node-property-mtime node2))))
(cond ((null node1) t)
((null node2) nil)
((null time1) nil)
((null time2) t)
(t (string< time2 time1)))))))
;;;; Pretty completion
(defcustom org-node-alter-candidates nil
"Whether to alter completion candidates instead of affixating.
This means that org-node will concatenate the results of
`org-node-affixation-fn' into a single string, so what the user types in
the minibuffer can match against the prefix and suffix as well as
against the node title.
In other words: you can match against the node's outline path, if
`org-node-affixation-fn' is set to `org-node-prepend-olp' \(default).
Another consequence: this setting can lift the uniqueness constraint on
note titles: you\\='ll be able to have two nodes with the same name, so
long as their prefix or suffix differ in some way."
:type 'boolean
:set #'org-node--set-and-remind-reset
:package-version '(org-node . "0.2"))
(defcustom org-node-affixation-fn #'org-node-prepend-olp
"Function to give prefix and suffix to minibuffer completions.
After changing this setting, run \\[org-mem-reset].
------
Info for writing a custom function
The function receives two arguments: NODE and TITLE, and it must return
a list of three strings: title, prefix and suffix. Of those three, the
title should be TITLE unmodified.
NODE is an `org-mem-entry' object. See examples
by typing \\[org-node-list-example].
If a node has aliases, the same node is passed to this function
again for every alias, in which case TITLE is actually one of the
aliases."
:type '(radio
(function-item org-node-affix-bare)
(function-item org-node-prepend-olp)
(function-item org-node-prepend-tags)
(function-item org-node-prepend-tags-and-olp)
(function-item org-node-prepend-olp-append-tags)
(function-item org-node-prepend-olp-append-tags-use-frame-width)
(function-item org-node-append-tags-use-frame-width)
(function :tag "Custom function"
:value (lambda (node title) (list title "" ""))))
:set #'org-node--set-and-remind-reset
:package-version '(org-node . "0.2"))
(defun org-node-affix-bare (_node title)
"Use TITLE as-is."
(list title "" ""))
(defun org-node-prepend-tags (node title)
"Prepend NODE\\='s tags to TITLE."
(list title
(let ((tags (org-mem-entry-tags node)))
(if tags
(propertize (concat "(" (string-join tags ", ") ") ")
'face 'org-node-tag)
""))
""))
(defun org-node-prepend-olp (node title)
"Prepend NODE\\='s outline path to TITLE."
(list title
(if-let ((fontified-ancestors
(cl-loop
for ancestor in (org-mem-olpath-with-file-title node)
collect
(propertize ancestor 'face 'org-node-parent))))
(concat (string-join fontified-ancestors " > ") " > ")
"")
""))
(defun org-node-prepend-tags-and-olp (node title)
"Prepend NODE's tags and outline path to TITLE."
(list title
(let ((tags (org-mem-entry-tags node))
(fontified-ancestors
(cl-loop
for ancestor in (org-mem-olpath-with-file-title node)
collect (propertize ancestor 'face 'org-node-parent))))
(concat
;; TODO: Fallback on other face before org init
(and tags (propertize (concat "(" (string-join tags ", ") ") ")
'face 'org-node-tag))
(and fontified-ancestors
(concat (and tags " ")
(string-join fontified-ancestors " > ") " > "))))
""))
(defun org-node-prepend-olp-append-tags (node title)
"Prepend NODE's outline path to TITLE, and append NODE\\='s tags."
(list title
(if (org-mem-entry-subtree-p node)
(let ((ancestors (org-mem-olpath-with-file-title node))
(result nil))
(dolist (anc ancestors)
(push (propertize anc 'face 'org-node-parent) result)
(push " > " result))
(setq result (apply #'concat (nreverse result)))
result)
"")
(let ((tags (org-mem-entry-tags node)))
(if tags (propertize (concat " :" (string-join tags ":") ":")
'face 'org-node-tag)
""))))
(defun org-node-append-tags-use-frame-width (node title)
"Append NODE tags after TITLE and justify them to `frame-width'.
Looks bad when you resize the frame, until you call `org-mem-reset'."
(list title
""
(concat
(let ((tags (org-mem-entry-tags node)))
(when tags
(setq tags (propertize (concat ":" (string-join tags ":") ":")
'face 'org-node-tag))
(concat (make-string (max 2 (- (frame-width)
(string-width title)
(string-width tags)
(fringe-columns 'right)
(fringe-columns 'left)))
?\s)
tags))))))
(defun org-node-prepend-olp-append-tags-use-frame-width (node title)
"Prepend NODE outline path to TITLE, and put NODE tags at frame edge.
Looks bad when you resize the frame, until you call `org-mem-reset'."
(let (olp)
(list title
(concat
(when (org-mem-entry-subtree-p node)
(let ((ancestors (org-mem-olpath-with-file-title node)))
(dolist (anc ancestors)
(push (propertize anc 'face 'org-node-parent) olp)
(push " > " olp))
(setq olp (apply #'concat (nreverse olp))))))
(concat
(let ((tags (org-mem-entry-tags node)))
(when tags
(setq tags (propertize (concat ":" (string-join tags ":") ":")
'face 'org-node-tag))
(concat (make-string (max 2 (- (frame-width)
(string-width title)
(if olp (string-width olp) 0)
(string-width tags)
(fringe-columns 'right)
(fringe-columns 'left)))
?\s)
tags)))))))
;; TODO: Bind a custom exporter to `embark-export'
;; TODO: Add user option to set 'group-function
;; TODO: Copy https://github.com/jgru/consult-org-roam
(defun org-node-collection (str pred action)
"Custom COLLECTION for `completing-read'.
Ahead of time, org-node takes titles and aliases from all nodes, runs
`org-node-affixation-fn' on each, and depending on the user option
`org-node-alter-candidates', it either saves the affixated thing
directly into `org-node--candidate<>entry', or into a secondary table
`org-node--title<>affixations'. Finally, this function then either
simply reads candidates off the former table, or attaches the
affixations in realtime.
Regardless of which, all completions are guaranteed to be keys of
`org-node--candidate<>entry' \(which is the main reason for this dual
code flow\), but remember that it is possible for `completing-read' to
exit with user-entered input that didn\\='t match anything.
Arguments STR, PRED and ACTION are handled behind the scenes,
see Info node `(elisp)Programmed Completion'."
(if (eq action 'metadata)
(cons 'metadata (append (and org-node-display-sort-fn
`((display-sort-function . ,org-node-display-sort-fn)))
`((category . org-node))
`((affixation-function . org-node--affixate))))
(complete-with-action action org-node--candidate<>entry str pred)))
(defun org-node--affixate (collection)
"From flat list COLLECTION, make alist ((TITLE PREFIX SUFFIX) ...).
Presumes that COLLECTION is the keys of `org-node--candidate<>entry'."
(and collection
;; REVIEW: We probably shouldn't assume it is always the `car'.
(if (string-blank-p (car collection))
(cons
(list (car collection) "" (or org-node-blank-input-hint ""))
(if org-node-alter-candidates
(cl-loop for altered-candidate in (cdr collection)
collect (list altered-candidate "" ""))
(cl-loop for title in (cdr collection)
collect (or (gethash title org-node--title<>affixations)
;; REVIEW: Sometimes above gethash returns
;; nil, don't remember why. That results in
;; odd glyphs in the completions, hence this
;; workaround. Can we guarantee it would
;; never return nil?
(list title "" "")))))
(if org-node-alter-candidates
(cl-loop for altered-candidate in collection
collect (list altered-candidate "" ""))
(cl-loop for title in collection
collect (or (gethash title org-node--title<>affixations)
(list title "" "")))))))
;; Finally, tying it all together
(defun org-node-read-candidate
(&optional prompt blank-ok predicate require-match initial-input hist def inherit-input-method)
"PROMPT for a known node and return the user input.
If the node exists, the user input is a key of table
`org-node--candidate<>entry', and the node is the value.
Otherwise, it does not exist and the user input can be taken as the
desired title for a new node.
BLANK-OK non-nil means to use `org-node-blank-input-hint' if non-nil.
This can affect PREDICATE and REQUIRE-MATCH, because a fake entry is
added to `org-node--candidate<>entry' during completion.
The rest of the arguments \(PREDICATE, REQUIRE-MATCH, INITIAL-INPUT,
HIST, DEF, INHERIT-INPUT-METHOD) same as in `completing-read'.
An obsolete calling convention allows the third argument to be a string,
used as INITIAL-INPUT in `completing-read'."
(when (stringp predicate)
;; Convert from obsolete calling convention.
(cl-assert (cl-every #'null (list require-match initial-input hist def inherit-input-method)))
(setq initial-input predicate)
(setq predicate nil))
(when (and (hash-table-empty-p org-node--candidate<>entry)
(not (featurep 'org)))
(when (y-or-n-p "No nodes found, load Org? ")
(require 'org)
(org-mem-reset t "Resetting org-mem...")
(org-mem-await "Resetting org-mem..." 60)))
(when (and blank-ok org-node-blank-input-hint)
(puthash (if (bound-and-true-p helm-mode) " " "")
(make-org-mem-entry)
org-node--candidate<>entry))
(unwind-protect (completing-read (or prompt "Node: ")
#'org-node-collection
predicate
require-match
initial-input
(or hist (if org-node-alter-candidates
'org-node-hist-altered
'org-node-hist))
def
inherit-input-method)
(remhash "" org-node--candidate<>entry)
(remhash " " org-node--candidate<>entry)))
(defvar org-node-hist nil
"Minibuffer history.")
(defvar org-node-hist-altered nil
"Minibuffer history while `org-node-alter-candidates' was t.")
;; Boost completion hist to at least 1000 elements, unless user has nerfed
;; the default `history-length'.
;; Because you often narrow down the completions majorly, and still want to
;; sort among what's left; perhaps it's a general topic you have not touched
;; since two months ago, but when you do, the recency order remains relevant.
(when (and (numberp history-length)
(not (get 'org-node-hist 'history-length))
(>= history-length (car (get 'history-length 'standard-value)))
(< history-length 1000))
(put 'org-node-hist 'history-length 1000)
(put 'org-node-hist-altered 'history-length 1000))
;;;; The cache mode
(defun org-node--let-refs-be-aliases (entry)
"Add ROAM_REFS of ENTRY as extra minibuffer completions."
(when (and (org-mem-entry-id entry)
(funcall org-node-filter-fn entry))
(dolist (ref (org-mem-entry-roam-refs entry))
(puthash (concat (when-let ((type (gethash ref org-mem--roam-ref<>type)))
(propertize (concat type ":") 'face 'org-node-cite-type))
(propertize ref 'face 'org-node-cite))
entry
org-node--candidate<>entry))))
(defun org-node--record-completion-candidates (entry)
"Cache completions for ENTRY and its aliases, if it is an ID-node."
(when (and (org-mem-entry-id entry)
(funcall org-node-filter-fn entry))
(dolist (title (cons (org-mem-entry-title entry)
(org-mem-entry-roam-aliases entry)))
(let ((affx (funcall org-node-affixation-fn entry title)))
(puthash title affx org-node--title<>affixations)
(if org-node-alter-candidates
;; Absorb the affixations into one candidate string
(puthash (concat (nth 1 affx) (nth 0 affx) (nth 2 affx))
entry
org-node--candidate<>entry)
;; Bare title, to be affixated later
(puthash title entry org-node--candidate<>entry))))))
(defun org-node--record-completion-candidates-all (parse-results)
"Cache completions for all entries in PARSE-RESULTS."
(cl-loop for (_ _ _ entries) in parse-results
do (dolist (entry entries)
(org-node--record-completion-candidates entry)
(org-node--let-refs-be-aliases entry))))
(defun org-node--wipe-completions (_parse-results)
"Clear completions tables."
(clrhash org-node--title<>affixations)
(clrhash org-node--candidate<>entry))
(defun org-node--forget-completions-in-results (parse-results)
"Remove old completions where PARSE-RESULTS indicates they are stale."
(org-node--forget-completions-in-files
(cl-loop for (bad-path _ file-data) in parse-results
collect bad-path
collect (car file-data))))
(defun org-node--forget-completions-in-files (files)
"Remove the minibuffer completions for all nodes in FILES."
(when files
(maphash (lambda (candidate entry)
(when (member (org-mem-file-truename entry) files)
(remhash candidate org-node--candidate<>entry)
(remhash (org-mem-title entry) org-node--title<>affixations)))
org-node--candidate<>entry)))
;; TODO: Submit patch upstream to print a message when `org-id-find'
;; fails to find ID and calls update-id-locations.
;; TODO: While we're at it... patch `org-id-find-id-in-file' so it allows the
;; file not to exist if a buffer exists with that file name.
;; TODO: While we're at it... patch `org-id-find-id-file' not to fallback on
;; the current buffer, that is so inviting to bugs! Probably it
;; shouldn't have been a separate function at all.
(defun org-node--ad-org-id-find (id &rest _)
"Print a message if ID is not in `org-id-locations'.
Designed as before-advice for `org-id-find'. This is merely an
informative helper, because often the attempt to open an unknown ID-link
results in Emacs appearing to freeze as org-id updates its database
without telling the user that it is doing so. With a lot of files, this
takes a long time."
(cond
((symbolp id) (setq id (symbol-name id)))
((numberp id) (setq id (number-to-string id))))
(when (and (hash-table-p org-id-locations)
(not (gethash id org-id-locations)))
(message "No cached location for ID \"%s\"..." id)))
(defcustom org-node-reset-on-org-load t
"Whether to allow resetting org-mem after Org loads.
This is the delay you can observe if `org-mem-do-look-everywhere' is t
and you jump into an Org file for the first time."
:type 'boolean)
;;;###autoload
(define-minor-mode org-node-cache-mode
"Cache completion candidates every time Org-mem updates its cache.
Enabling this mode asks org-mem to reset its cache.
You should enable `org-mem-updater-mode' at nearly the same time in your
init process, because then org-mem will tend to only scan files once
rather than twice."
:global t
(cond
(org-node-cache-mode
(advice-add #'org-id-find :before #'org-node--ad-org-id-find)
(add-hook 'org-mem-pre-full-scan-functions #'org-node--wipe-completions)
(add-hook 'org-mem-pre-targeted-scan-functions #'org-node--forget-completions-in-results)
(add-hook 'org-mem-post-full-scan-functions #'org-node--record-completion-candidates-all)
(add-hook 'org-mem-post-targeted-scan-functions #'org-node--record-completion-candidates-all)
(when (and org-mem-do-look-everywhere
(not (featurep 'org))
(not org-mem-watch-dirs)
(not (bound-and-true-p recentf-list)))
(eval-after-load 'org
(defun org-node--reset-once ()
(when org-node-cache-mode
(when org-node-reset-on-org-load
(org-mem-reset t "org-node: Re-caching to include org-id locations..."))
(fset 'org-node--reset-once #'ignore)))))
(org-mem-reset)
(org-mem-tip-if-empty)
(org-node-track-modifications-mode))
(t
(advice-remove #'org-id-find #'org-node--ad-org-id-find)
(remove-hook 'org-mem-pre-full-scan-functions #'org-node--wipe-completions)
(remove-hook 'org-mem-pre-targeted-scan-functions #'org-node--forget-completions-in-results)
(remove-hook 'org-mem-post-full-scan-functions #'org-node--record-completion-candidates-all)
(remove-hook 'org-mem-post-targeted-scan-functions #'org-node--record-completion-candidates-all)
(org-node-track-modifications-mode 0))))
;;;###autoload
(define-obsolete-function-alias 'org-node-reset #'org-mem-reset "3.0.0 (May 2025)")
;; TODO: Deprecate somehow
(defvar org-node--first-init t
"Non-nil until org-node has been initialized, then nil.")
(defun org-node-cache-ensure (&optional block force)
"Ensure that org-node is ready for use.
Ensure that modes `org-node-cache-mode' and `org-mem-updater-mode' are
enabled. If FORCE, trigger org-mem to rebuild cache. If BLOCK and a
cache build is underway \(perhaps started by FORCE), block Emacs until
it finishes \(or 60 seconds elapse\).
If cache has never been built, act as if both FORCE and BLOCK.
It is good to call this function at the start of autoloaded commands.
Most of the time, you can expect it to no-op.
These cache builds are normally async, so without BLOCK, this returns
immediately and can mean that the data you will next query from org-mem
is still out of date. That usually only matters if you had done
something to change the facts on the ground just prior."
(setq org-node--first-init nil)
(unless org-node-cache-mode
(when (y-or-n-p "Org-node needs `org-node-cache-mode', enable? ")
(org-node-cache-mode))
(setq force t))
(unless org-mem-updater-mode
(when (y-or-n-p "Org-node needs `org-mem-updater-mode', enable? ")
(org-mem-updater-mode))
(setq force t))
(when (hash-table-empty-p org-node--candidate<>entry)
(setq block t)
(setq force t))
(when force
(org-mem-reset nil "Org-node waiting for org-mem..."))
(when block
(org-mem-await "Org-node waiting for org-mem..." 60))
(org-mem-tip-if-empty))
;;;; Filename functions
(defcustom org-node-file-directory-ask nil
"Whether to ask the user where to save a new file.
- Value nil: Let `org-node-guess-dir' decide
- Value t: Ask every time
- String: A directory in which to put the file"
:type '(radio (const :tag "Let `org-node-guess-dir' decide" nil)
(const :tag "Ask every time" t)
directory)
:package-version '(org-node . "0.1"))
(defcustom org-node-file-timestamp-format ""
"Passed to `format-time-string' to prepend to filenames.
Beware that this setting is an \\+`attractive nuisance'.
Changing it leads to lots of possibly unwanted renames if you have
`org-node-rename-file-by-title' on a hook, and in any case requires
manual intervention for pre-existing files.
Example from Org-roam: %Y%m%d%H%M%S-
Example from Denote: %Y%m%dT%H%M%S--
For the rest of the filename, configure `org-node-file-slug-fn'."
:type '(radio
(const :tag "None" :value "")
(const :tag "Like Org-roam: %Y%m%d%H%M%S-" :value "%Y%m%d%H%M%S-")
(const :tag "Like Denote: %Y%m%dT%H%M%S--" :value "%Y%m%dT%H%M%S--")
(string :tag "Custom"))
:package-version '(org-node . "0.4"))
;; TODO: For Denote users, you get valid filename with just the default slug fn,
;; and a datestamp "%Y%m%dT%H%M%S--". However, Denote's full format
;; including optional parts looks like:
;;
;; DATE==SIGNATURE--TITLE__KEYWORDS.EXT
;;
;; So either the user adds SIGNATURE and KEYWORDS themselves, and never
;; uses `org-node-rename-file-by-title'. Or we could pass more arguments
;; into the slug fn, that it can use to systematically add these parts
;; based on some rule, like perhaps the content of an Org property.
(defcustom org-node-file-slug-fn #'org-node-slugify-for-web
"Function taking a node title and returning a filename component.
Receives one argument: the value of an Org #+TITLE keyword, or
the first heading in a file that has no #+TITLE.
It is popular to also prefix filenames with a datestamp. To do
that, configure `org-node-file-timestamp-format'."
:type '(radio
(function-item org-node-slugify-for-web)
(function-item org-node-slugify-like-roam-default)
(function :tag "Custom function" :value (lambda (title) title)))
:package-version '(org-node . "0.4"))
(defun org-node-slugify-like-roam-default (title)
"From TITLE, make a filename slug in default org-roam style.
Does not require org-roam installed.
A title like \"Löb\\='s Theorem\" becomes \"lob_s_theorem\".
Diacritical marks U+0300 to U+0331 are stripped \(mostly used with Latin
alphabets). Also stripped are all glyphs not categorized in Unicode as
\\+`alphanumeric', such as punctuation and emoji.
If you seek to emulate org-roam filenames, you may also want to
configure `org-node-file-timestamp-format'."
(require 'ol)
(thread-last title
(org-link-display-format)
(string-glyph-decompose)
(seq-remove (lambda (char) (<= #x300 char #x331)))
(concat)
(string-glyph-compose)
(downcase)
(string-trim)
(replace-regexp-in-string "[^[:alnum:]]" "_")
(replace-regexp-in-string "__*" "_")
(replace-regexp-in-string "^_" "")
(replace-regexp-in-string "_$" "")))
(defun org-node-slugify-for-web (title)
"From TITLE, make a filename slug meant to look nice as URL component.
A title like \"Löb\\='s Theorem\" becomes \"lobs-theorem\".
Diacritical marks U+0300 to U+0331 are stripped \(mostly used with Latin
alphabets). Also stripped are all glyphs not categorized in Unicode as
\\+`alphanumeric', such as punctuation and emoji."
(require 'ol)
(thread-last title
(org-link-display-format)
(string-glyph-decompose)
(seq-remove (lambda (char) (<= #x300 char #x331)))
(concat)
(string-glyph-compose)
(downcase)
(string-trim)
(replace-regexp-in-string "[[:space:]]+" "-")
(replace-regexp-in-string "[^[:alnum:]\\/-]" "")
(replace-regexp-in-string "\\/" "-")
(replace-regexp-in-string "--*" "-")
(replace-regexp-in-string "^-" "")
(replace-regexp-in-string "-$" "")))
;; Hacking on the above? Some useful test cases!
;; (org-node-slugify-for-web "A/B testing")
;; (org-node-slugify-for-web "\"But there's still a chance, right?\"")
;; (org-node-slugify-for-web "Löb's Theorem")
;; (org-node-slugify-for-web "Mañana Çedilla")
;; (org-node-slugify-for-web "How to convince me that 2 + 2 = 3")
;; (org-node-slugify-for-web "E. T. Jaynes")
;; (org-node-slugify-for-web "Amnesic recentf? Solution: Run kill-emacs-hook every 2 minutes.")
;; (org-node-slugify-for-web "Slimline/\"pizza box\" computer chassis")
;; (org-node-slugify-for-web "#emacs")
;; (org-node-slugify-for-web "칹え🐛")
(defun org-node--root-dirs (file-list)
"Infer root directories of FILE-LIST.
By root, we mean the longest directory path common to a set of files,
as long as that directory contains at least one member of
FILE-LIST itself. For example, if you have the 3 members
- \"/home/me/Syncthing/foo.org\"
- \"/home/kept/archive/bar.org\"
- \"/home/kept/baz.org\"