This repository has been archived by the owner on Dec 25, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathdelve.el
2174 lines (1901 loc) · 89.3 KB
/
delve.el
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
;;; delve.el --- Delve into the depths of your Org Roam zettelkasten -*- lexical-binding: t; -*-
;; Copyright (C) 2020-2023
;; Author: <[email protected]>
;; This program is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <https://www.gnu.org/licenses/>.
;;; Commentary:
;; Delve into the depths of your zettelkasten.
;; Terminology:
;;
;; - A "collection" is a list of Zettels, which can be
;; stored in a file. A buffer thus 'visits' a collection (or creates
;; one without associated file.)
;;; Code:
;; * Dependencies
(require 'org-roam)
(require 'dash)
(require 'seq)
(require 'lister)
(require 'lister-mode)
(require 'button)
(require 'bookmark)
(require 'cursor-sensor) ;; see `delve--get-hl-line-range'
(require 'face-remap) ;; see `delve--prepare-preview'
(require 'delve-transient)
(require 'delve-data-types)
(require 'delve-query)
(require 'delve-pp)
(require 'delve-store)
(require 'delve-edit)
(require 'delve-export)
(require 'delve-crm)
;; * Silence Byte Compiler
(declare-function all-the-icons-faicon "all-the-icons" (string) t)
(declare-function consult-completing-read-multiple "consult")
(defvar org-roam-node-read--cached-display-format)
;;; * Customizable Variables
(defgroup delve nil
"A zettelkasten tool on top of Org Roam."
:group 'org-roam
:link '(url-link :tag "Github" "https://github.com/publicimageltd/delve"))
(defcustom delve-dashboard-tags '("Dashboard")
"Tags for which to insert query objects in the Dashboard.
Each element can be a tag or a list of tags."
:group 'delve
:type '(repeat (choice (string :tag "Tag")
(repeat (string :tag "Tags")))))
(defcustom delve-dashboard-queries (list #'delve--create-todo-query
#'delve--create-unlinked-query
#'delve--create-last-modified-query)
"Additional non-tag queries for the initial Dashboard.
A list of functions which each returns a `delve--query'
struct (which see). If nil, do not add any non-tag queries to the
Dashboard."
:group 'delve
:type '(choice
(const :tag "No additional queries" nil)
(repeat function)))
(defcustom delve-storage-paths (concat (file-name-directory user-emacs-directory)
"delve-store")
"Default paths to store Delve buffers in.
When the user is prompted for reading a storage, all Delve stores
found here will be offered as default choices. It is, however,
not obligatory to store files in these locations. Storages
located elsewhere just don't show up in the prompt.
When writing a Delve list to a new storage file, the first (or
only) value of this variable is used.
The value of this variable can be either a file path, a list of
file paths, or nil.
Use the file path \".\" to add the current directory to the list
of default storage paths."
:group 'delve
:type '(choice
(const :tag "No default" nil)
(directory :tag "Single path (use M-TAB for completion)")
(repeat :tag "List of paths (use M-TAB for completion)" directory)))
(defcustom delve-storage-suffix ".delve"
"Suffix for Delve storage files."
:group 'delve
:type 'string)
(defcustom delve-display-path t
"Add outline path to the node's title.
If non-nil, add the file title and the node's Org outline path in
front of the title. This can cause quite long entries."
:group 'delve
:type 'boolean)
(defcustom delve-last-modified-limit 20
"Number of items for the Dashboard query \\='last modified\\='."
:group 'delve
:type 'integer)
(defcustom delve-compact-view-shows-node-path t
"If set, show the complete node path in compact view."
:group 'delve
:type 'boolean)
;;; * Global Variables
(defvar delve-version "0.9.6"
"Current version of delve.")
(defvar delve--no-icons nil
"*INTERNAL* If bound, do not use any icons when creating output.")
(defvar delve-dashboard-name "Dashboard"
"Name of the dashboard buffer.")
(defvar delve--select-history nil
"History for `delve--select-collection-buffer'.")
(defvar delve--last-selected-buffer nil
"Last buffer selected with `delve--select-collection-buffer'.")
(defvar delve--last-storage-dir nil
"Directory from last used storage file.")
;; * Buffer Local Variables
(defvar-local delve-local-storage-file nil
"Local storage file for a Delve buffer.")
(defun delve-get-storage-file (buf)
"Get the buffer local storage file for BUF."
(buffer-local-value 'delve-local-storage-file buf))
(defvar-local delve-local-header-info "DELVE"
"First line of the local Lister header.")
(defvar-local delve-local-compact-view nil
"*INTENRAL* Display the nodes in a compact way.
Do not set this variable directly, use `delve-compact-view-mode'
instead.")
;; * Faces
(defgroup delve-faces nil
"Faces used by Delve."
:group 'Delve
:group 'faces)
(defface delve-mark-face
'((t (:inherit highlight)))
"Face for highlighting manually marked items."
:group 'delve-faces)
(defface delve-path-face
'((t (:inherit transient-inactive-value)))
"Face for displaying the node path."
:group 'delve-faces)
(defface delve-header-face
'((t (:inherit org-document-title)))
"Face for displaying the header of a Delve list."
:group 'delve-faces)
(defface delve-note-face
'((t (:inherit font-lock-comment-face)))
"Face for displaying note items in a Delve list."
:group 'delve-faces)
(defface delve-info-face
'((t (:inherit warning)))
"Face for displaying info items in a Delve list."
:group 'delve-faces)
(defface delve-tags-face
'((t (:inherit org-tag)))
"Face for displaying roam tags in a Delve list."
:group 'delve-faces)
(defface delve-title-face
'((t (:inherit org-roam-title)))
"Face for displaying Org Roam page titles in a Delve list."
:group 'delve-faces)
(defface delve-pile-name-face
'((t (:inherit org-document-title)))
"Face for displaying the name of a Zettel pile."
:group 'delve-faces)
(defface delve-subtype-face
'((t (:inherit font-lock-constant-face)))
"Face for displaying the subtype of a Delve item."
:group 'delve-faces)
(defface delve-mtime-face
'((t (:inherit org-document-info-keyword)))
"Face for displaying the mtime of a Delve item."
:group 'delve-faces)
(defface delve-atime-face
'((t (:inherit org-document-info-keyword)))
"Face for displaying the atime of a Delve item."
:group 'delve-faces)
(defface delve-ctime-face
'((t (:inherit org-document-info-keyword)))
"Face for displaying the ctime of a Delve item."
:group 'delve-faces)
(defface delve-nbacklinks-face
'((t (:weight bold)))
"Face for displaying the number of backlinks to a Delve zettel."
:group 'delve-faces)
(defface delve-ntolinks-face
'((t (:weight bold)))
"Face for displaying the number of tolinks to a Delve zettel."
:group 'delve-faces)
(defface delve-pile-face
'((t (:inherit org-level-1)))
"Face for displaying the title of a Delve pile."
:group 'delve-faces)
(defface delve-query-face
'((t (:inherit org-level-2)))
"Face for displaying the title of a Delve query."
:group 'delve-faces)
;;;; -----------------------------------------------------------
;; * Small utilities
(defun delve-reload ()
"*INTERNAL* Reload Delve for debugging.
Only use it if you know what you do."
(interactive)
(when (y-or-n-p "This will close all existing Delve buffers. Reload Delve? ")
(let ((kill-buffer-query-functions nil))
(-each (delve-buffer-list) #'kill-buffer))
(when (featurep 'delve-minor-mode)
(unload-feature 'delve-minor-mode t))
(unload-feature 'delve t)
(require 'delve)
(message "Loaded Delve version %s" delve-version)))
(defun delve--assert-buf (&optional buf-or-ewoc error-msg)
"Raise an error if BUF-OR-EWOC does not belong to a Delve buffer.
BUF-OR-EWOC can be nil, meaning to check the current buffer, or a
buffer or an Ewoc object.
In case of a negative result, raise an error with ERROR-MSG, if
passed, or use a standardized error message."
(let ((buf (if (not buf-or-ewoc)
(current-buffer)
(cl-etypecase buf-or-ewoc
(buffer buf-or-ewoc)
(ewoc (ewoc-buffer buf-or-ewoc))))))
(or (and (delve--buffer-p buf)
;; don't pass the ewoc object around too much
(not (null (buffer-local-value 'lister-local-ewoc buf))))
(error (or error-msg "Function has to be called in a Delve buffer")))))
;; TODO Move this to lister
(defun delve--ewoc-node-invalid-p (ewoc node)
"Return t if NODE is not a valid node in EWOC."
(or (null node)
(and (not (marker-buffer (ewoc-location node)))
(and (not (or (ewoc-next ewoc node)
(ewoc-prev ewoc node)))))))
;; TODO Move this to lister
(defmacro delve--save-outline (ewoc &rest body)
"In EWOC, unhide all items, execute BODY and restore visibility.
Return the value returned by BODY."
(declare (indent 1) (debug (sexp body)))
(let ((nodes-var (gensym))
(res-var (gensym)))
`(let ((,nodes-var (lister-collect-nodes ,ewoc nil nil
(-partial #'lister--outline-invisible-p ,ewoc))))
(lister-outline-show-all ,ewoc)
(let ((,res-var (progn ,@body)))
(--each (-remove (-partial #'delve--ewoc-node-invalid-p ,ewoc) ,nodes-var)
(lister--outline-hide-show ,ewoc it it t))
,res-var))))
;;; -----------------------------------------------------------
;;; * The Lister Mapper
;; Type icon
(defun delve--type-as-string (delve-item)
"Return a string or icon representing the type of DELVE-ITEM.
If the global variable `delve--no-icons' is bound, always return
strings."
(pcase-let ((`(,s ,icon-name)
(pcase (type-of delve-item)
('delve--query (list "QUERY" "search"))
('delve--pile (list "PILE" "list-ul"))
('delve--info (list "INFO" "info"))
('delve--heading (list "HEADING" "header"))
('delve--note (list "NOTE" "pencil"))
('delve--zettel
(if (eq 0 (delve--zettel-level delve-item))
(list "FILE" "file-text-o")
(list "NODE" "dot-circle-o")))
(_ (list "TYPE?" "question")))))
(if (and (featurep 'all-the-icons)
(not delve--no-icons))
(concat (all-the-icons-faicon icon-name) " ")
(delve-pp--set-width s 8))))
;; Printing Zettel
(defun delve--node-title (node)
"Return the title of NODE."
(or (org-roam-node-title node)
(org-roam-node-file node)
"No file or title"))
(defun delve--get-button (label &rest properties)
"Return a propertized string with the button labeled LABEL.
Pass PROPERTIES to `insert-text-button', which creates the
button.
Example:
\(delve--get-button tag
\\='action \(lambda \(_\) \(message \"Do something with %s\" tag\)\)\)\)"
(declare (indent 1))
(with-temp-buffer
(apply #'insert-text-button label properties)
(buffer-string)))
(defun delve--string-join (strings &optional separator prefix)
"Join all non-nil strings in STRINGS using SEPARATOR.
Optionally add string PREFIX to each non-nil item."
(let ((strings (flatten-tree strings)))
(when prefix
(setq strings (--map (concat prefix it) strings)))
(string-join strings separator)))
;; TODO Change that to buttons which open all links with that tag in a
;; new buffer?
(defun delve--tags-as-string (node)
"Return the NODE's tags as a list of strings."
(if-let ((tags (org-roam-node-tags node)))
(delve--string-join tags ", " "#")
"No tags."))
(defun delve--collect-link (link)
"In an Org mode buffer, collect data for buttonizing LINK.
LINK has to be a LINK element as returned by
`org-element-parse-buffer'"
(when (equal (org-element-property :type link) "id")
(list
:beg (copy-marker (org-element-property :begin link))
:end (copy-marker (org-element-property :end link))
:id (org-element-property :path link)
:blanks (org-element-property :post-blanks link)
:label (buffer-substring-no-properties
(org-element-property :contents-begin link)
(org-element-property :contents-end link))
:link link)))
(defun delve--buttonize-link (link-plist)
"In current buffer, replace link LINK-PLIST with a button.
For the format of LINK-PLIST, see `delve--collect-link'."
;; TODO Use -let with &plist destructuring
(let ((beg (plist-get link-plist :beg))
(end (plist-get link-plist :end))
(link (plist-get link-plist :link))
(label (plist-get link-plist :label))
(blanks (plist-get link-plist :blanks))
(id (plist-get link-plist :id)))
(delete-region beg (- end (or blanks 1)))
(goto-char beg)
(insert-text-button
label
'follow-link t
'action (lambda (_)
(org-link-open link))
'keymap (let ((map (make-sparse-keymap)))
(set-keymap-parent map button-map)
(define-key map (kbd "i")
(lambda ()
(interactive)
(delve-insert-nodes-by-id (current-buffer) id)
(message "Inserted node %s"
(replace-regexp-in-string "\n" " " label))))
map))))
(defun delve--prepare-preview (s)
"Prepare preview string S for insertion.
Return the prepared string."
(with-temp-buffer
(insert s)
(let ((org-inhibit-startup nil))
(org-mode)
(let* ((tree (org-element-parse-buffer))
(links (org-element-map tree 'link
#'delve--collect-link)))
(font-lock-ensure)
;; use org-mode's special face remapping, if it exists:
(when buffer-face-mode
(add-face-text-property (point-min) (point-max)
buffer-face-mode-face))
;; If buffer has too many lines, inhibit setting the
;; `intangible' property so that it can be read properly:
(when (> (count-lines (point-min) (point-max))
(/ (window-body-height) 3))
(add-text-properties (point-min) (point-max) '(field t)))
;; now buttonize the links:
(cl-dolist (link links)
(delve--buttonize-link link)))
(buffer-string))))
(defun delve--zettel-strings (zettel)
"Return a list of strings representing ZETTEL."
;; TODO Refactor: split in two subfunctions
(let ((main-item-list
;; Compact View - one line only::
(if delve-local-compact-view
(list
(delve-pp-fields zettel `(;; path:
((when (and delve-compact-view-shows-node-path
(> (delve--zettel-level it) 0))
(delve--zettel-file-title it))
:format "%s/"
:add-face delve-path-face)
;; NOTE Seems unnecessary.
;; ((when (and delve-compact-view-shows-node-path
;; (> (delve--zettel-level it) 0)
;; (delve--zettel-olp it))
;; (string-join (delve--zettel-olp it) "/"))
;; :format "%s/"
;; :add-face delve-path-face)
;; title:
((or (delve--zettel-title it) "<No title>")
:add-face delve-title-face)
;; tags:
((delve--tags-as-string (delve--zettel-node it))
:add-face delve-tags-face))))
;; Default view:
(list
;; -- first line:
(when (and delve-display-path
(not (eq 0 (delve--zettel-level zettel))))
(delve-pp-fields zettel `(;; path:
(,#'delve--zettel-file-title
:format "%s/"
:add-face delve-path-face)
((when (delve--zettel-olp it)
(string-join (delve--zettel-olp it) "/"))
:format "%s/"
:add-face delve-path-face))))
;; -- second line:
(delve-pp-fields zettel `(;; title
(,#'delve--zettel-title
:add-face delve-title-face))
" " "<No title>")
;; -- third line:
(delve-pp-fields zettel `(;; tags
((delve--tags-as-string (delve--zettel-node it))
:add-face delve-tags-face)
;; info
,#'delve--zettel-info)
" " nil)))))
;; add sync marker to front:
(when (and (setq main-item-list (cl-remove-if #'null main-item-list))
(delve--zettel-out-of-sync zettel))
(setq main-item-list (cons (concat (delve-pp--add-face "* " 'warning)
(car main-item-list))
(cdr main-item-list))))
;; Now add everything which is common both to compact and default
;; view:
(list
main-item-list
;; -- Preview:
(when-let ((preview (delve--zettel-preview zettel)))
(split-string (delve--prepare-preview preview) "\n")))))
;; Printing a pile item
(defun delve--pile-size (pile)
"Return information of the size of PILE."
(format "(%d)" (length (delve--pile-zettels pile))))
(defun delve--pile-strings (pile)
"Return a list of strings representing PILE."
(list
(delve-pp-fields pile '((delve--pile-size (:set-face delve-pile-face))
(delve--pile-name (:set-face delve-pile-face))))))
;; Printing Queries
(defun delve--query-strings (query)
"Return a list of strings representing QUERY."
(list (delve--query-info query)))
;; Printing Notes
(defun delve--note-s-to-list (string)
"Format STRING as a paragraph and return it as a list of strings."
(split-string
(with-temp-buffer
;; (let ((org-inhibit-startup nil))
;; (org-mode)
(insert " " string)
(goto-char (point-min))
(fill-paragraph)
;; (font-lock-ensure)
(buffer-string))
"\n"))
(defun delve--note-strings (note)
"Return a list of strings representing NOTE."
(delve--note-s-to-list
(delve-pp--add-face (delve--note-text note) 'delve-note-face)))
(defun delve--info-strings (info)
"Return a list of strings representing INFO."
(delve--note-s-to-list
(delve-pp--add-face (delve--note-text info) 'delve-info-face)))
(defun delve--heading-strings (heading)
"Return a list of strings representing HEADING."
(list (delve-pp--add-face
(delve--heading-text heading)
'outline-1)))
;; The actual mapper
(defun delve-mapper (item)
"Transform ITEM into a list of printable strings."
(let* ((typestring (delve--type-as-string item))
(datastrings (or (cl-typecase item
(delve--zettel (delve--zettel-strings item))
(delve--pile (delve--pile-strings item))
(delve--query (delve--query-strings item))
(delve--heading (delve--heading-strings item))
(delve--info (delve--info-strings item))
;; always check the basic type "delve--note" last!
(delve--note (delve--note-strings item))
(t (list "no printer available for that item type")))
(list (format "Error: Mapper for item type %s returned NIL" item)))))
;; hanging indent:
(let* ((datastrings (flatten-tree datastrings))
(pad (make-string (length typestring) ? ))
(first-line (concat typestring (car datastrings)))
(rest-lines (--map (concat pad it)
(cdr datastrings))))
(apply #'list first-line rest-lines))))
;; * Dynamic Header
(defun delve--db-info ()
"Return strings with some basic infos."
(let* ((nnodes (caar (delve-query [:select (funcall count *) :from nodes])))
(n0nodes (caar (delve-query [:select (funcall count *) :from nodes :where (= level 0)])))
(tags (caar (delve-query [:select :distinct tag :from tags :order :by asc]))))
(list
(propertize (format "Current db has %d nodes in %d files. %d tags are in use."
nnodes n0nodes (length tags))
'face 'font-lock-comment-face))))
(defun delve--header-function ()
"Generate a Lister header item from local buffer vars."
(flatten-tree
(list (propertize delve-local-header-info 'face 'delve-header-face)
(delve--db-info)
(if delve-local-storage-file
(concat (when lister-local-modified "* ")
(propertize delve-local-storage-file 'face 'font-lock-string-face))
(propertize "<Collection not saved>" 'face 'warning)))))
;; -----------------------------------------------------------
;; * Storage File Handling
(defun delve--file-as-dir (s)
"Return S as a directory file name iff it is a string.
Unlike `file-name-as-directory', this function returns nil if S
is nil."
(when s (file-name-as-directory s)))
(defun delve--set-storage-dir (&optional last-file-name)
"Make sure that `delve--last-storage-dir' has a value.
Optionally set the value to the directory part of LAST-FILE-NAME."
(setq delve--last-storage-dir (delve--file-as-dir
(if last-file-name
(delve--file-as-dir (file-name-directory last-file-name))
(or delve--last-storage-dir
(car (-list delve-storage-paths)))))))
(defun delve--fix-suffix (s suffix)
"Add file SUFFIX to S, maybe removing existing suffixes."
(let ((ext (file-name-extension s t)))
(if (eq "" ext)
(concat s suffix)
(concat (file-name-sans-extension s) suffix))))
(defun delve--all-files-in-paths (paths &optional suffix)
"Return all files ending in SUFFIX within list of PATHS.
Return the full paths (expanded file names)."
(let* ((the-suffix (or suffix ""))
(regexp (rx (and string-start (* (not "."))
(literal the-suffix) string-end))))
;; delete dups in case there's a "." in the list
(-uniq
(-flatten
(--map (directory-files it t regexp) paths)))))
(defun delve--all-file-extensions (files)
;; DONT TEST, will be removed in 1.0
"Return an aggregate list counting all extensions in FILES.
The result is an alist with the file extension (without period)
as its key and an integer count as value."
(--map (cons (car it) (length (cdr it)))
(-group-by #'file-name-extension files)))
(defun delve-convert-storage-directory (delve-store)
;; DONT TEST, will be removed in 1.0
"Change all files in DELVE-STORE to conform to `delve-storage-suffix'.
Prompt the user before doing any real changes. If DELVE-STORE is
not provided, also prompt the user for the directory to be
converted."
(interactive (list (read-directory-name " Convert all files in this directory:"
(concat (file-name-directory user-emacs-directory) "delve-store"))))
(let* ((files (delve--all-files-in-paths (list delve-store) ""))
(ext-list (delve--all-file-extensions files))
;; That's way too explicit for this one-time function, but
;; hey, it's so easy in lisp:
(ext-string (string-join (--map (let ((ext (car it))
(n (cdr it)))
(format "%d %s %s"
n
(if (eq 1 n) "file has" "files have")
(if ext (format "the extension .%s" ext)
"no extension")))
ext-list)
", and "))
(total (length files)))
(if (not (y-or-n-p (format "There are total %d files. %s. Convert them all to end in %s? "
total ext-string delve-storage-suffix)))
(user-error "Canceled")
(dolist-with-progress-reporter (file files)
"Renaming files..."
(rename-file file (concat (file-name-sans-extension file) delve-storage-suffix) t)))))
(defun delve--storage-files ()
"Return all available storage files as full path names.
If `delve-storage-paths' only contains one single directory which
does not yet exist, create it."
(when delve-storage-paths
;; If delve-storage-path is a single directory, maybe create it:
(when (and (eq 'string (type-of delve-storage-paths))
(not (file-exists-p delve-storage-paths)))
(if (y-or-n-p (format "Storage directory %s does not exist. Create it? " delve-storage-paths))
(make-directory delve-storage-paths t)
(user-error "Canceled. To skip this test, call (setq delve-storage-paths '(\"%s\")) in your config file. " delve-storage-paths)))
;; Now collect the files
(delve--all-files-in-paths (-list delve-storage-paths) delve-storage-suffix)))
(defun delve--storage-p (file-path)
"Check if FILE-PATH represents an existing Delve storage file.
Just check the existence of the file, don't look at the contents."
;; TODO this function might modify the file system by using
;; `delve--storage-files'; change it to a pure function
(-contains-p (delve--storage-files)
(expand-file-name file-path)))
(defun delve--storage-file-name-p (file-name)
"Check if FILE-NAME is a valid storage file name.
Do not check for existence; just validate the name."
(string-match-p (rx (literal delve-storage-suffix) string-end) file-name))
;; * Buffer and Dashboard
(defun delve--create-buffer-name (name)
"Create a name for a Delve buffer using NAME."
(concat "DELVE " name))
(defun delve--new-buffer (name &optional initial-list)
"Create a new delve buffer NAME with INITIAL-LIST.
Return the buffer object."
(let* ((name (generate-new-buffer-name (delve--create-buffer-name name))))
(with-current-buffer (get-buffer-create name)
(delve-mode)
(when initial-list
(lister-set-list lister-local-ewoc initial-list))
;; setting a major mode clears all buffer local variables
(setq delve-local-header-info name)
(lister-refresh-header-footer lister-local-ewoc)
(current-buffer))))
(defun delve--create-tag-query (tags)
"Create a Query list item searching for nodes matching TAGS."
(let* ((tags (-list tags)))
(delve--query-create :info (format "Query for nodes matching %s"
(delve--string-join tags " and " "#"))
:fn (lambda ()
(delve-query-nodes-by-tags tags)))))
(defun delve--create-unlinked-query ()
"Create a Query list item searching for unlinked nodes."
(delve--query-create :info "Unlinked nodes"
:fn #'delve-query-unlinked))
(defun delve--create-last-modified-query ()
"Create a Query list item searching for the 10 last modified nodes."
(delve--query-create :info "Last modified nodes"
:fn (apply-partially #'delve-query-last-modified
delve-last-modified-limit)))
(defun delve--create-todo-query ()
"Create a Query list item returning all nodes marked \"TODO\"."
(delve--query-create :info "Nodes marked 'TODO'"
:fn (lambda ()
(delve-query-nodes-by-todo "TODO"))))
(defun delve--dashboard-queries ()
"Return a list of all dashboard Query items."
(let* ((tag-queries (--map (delve--create-tag-query (-list it)) delve-dashboard-tags))
(non-tag-queries (-flatten (-map #'funcall delve-dashboard-queries))))
(append tag-queries non-tag-queries)))
(defun delve--new-dashboard ()
"Return a new Delve dashboard buffer."
(with-temp-message "Setting up dashboard..."
(let ((buf (delve--new-buffer delve-dashboard-name (delve--dashboard-queries))))
(lister-goto (lister-get-ewoc buf) :first)
buf)))
(defun delve--dashboard-p (&optional buf)
"Check if BUF is the Delve dashboard."
(string= (delve--create-buffer-name delve-dashboard-name)
(buffer-name buf)))
(defun delve--dashboard-buf ()
"Return the dashboard buffer, if existing."
(seq-find #'delve--dashboard-p (buffer-list)))
(defun delve--buffer-p (&optional buf)
"Check if BUF is a Delve buffer."
(and (eq (buffer-local-value 'major-mode (or buf (current-buffer)))
'delve-mode)))
(defun delve-buffer-list ()
"Return a list of all Delve buffers."
(seq-filter #'delve--buffer-p (buffer-list)))
(defun delve-unopened-storages ()
"Return all Delve storage files which are not visited yet."
;; TODO Use ->
;; TODO Write tests
(-map #'abbreviate-file-name
(-difference (delve--storage-files)
(-map #'expand-file-name
(-keep #'delve-get-storage-file
(delve-buffer-list))))))
(defun delve--prepare-candidates (cand key-fn suffix)
"Return list CAND as an alist with a string key.
Use KEY-FN to create the string key. It will have SUFFIX added
to the end, in parentheses. To remove SUFFIX, use
`delve--remove-candidate-suffix'."
(--group-by (format "%s (%s)" (funcall key-fn it) suffix)
cand))
(defun delve--remove-candidate-suffix (cand)
"Remove suffix in parentheses from CAND."
(replace-regexp-in-string (rx (one-or-more space)
"(" (+ (not ")")) ")"
string-end)
"\\1"
cand))
(defun delve--get-collection-buffer (buf-or-name)
"Get a Delve buffer containing the collection BUF-OR-NAME.
BUF-OR-NAME must be a string or a buffer object. If it is a
buffer object, return it unchanged. Else check if the string is
the path to a Delve storage file and load it, or create a new
Delve buffer using the string as its name. Always return the
newly created buffer object."
(if (bufferp buf-or-name)
buf-or-name
(or (get-buffer buf-or-name)
(if (delve--storage-p buf-or-name)
(let ((buf (delve--read-storage-file buf-or-name)))
(delve--set-storage-dir buf-or-name)
buf)
(when (file-name-extension buf-or-name)
(setq buf-or-name (file-name-sans-extension (file-name-base buf-or-name))))
(delve--new-buffer buf-or-name)))))
(defun delve--select-collection-buffer (prompt)
"Select Delve buffer, collection, or create a new buffer.
Use PROMPT as a prompt to prompt the user to choose promptly."
(let* ((alist (append
;; Existing buffers:
(delve--prepare-candidates (delve-buffer-list) #'buffer-name "Existing buffer")
;; Dashboard, if not yet open:
(unless (delve--dashboard-buf)
(delve--prepare-candidates '("Dashboard") #'identity "Create"))
;; Storage files:
(delve--prepare-candidates (delve-unopened-storages) #'identity "Open file")))
(new-name (delve--remove-candidate-suffix
(completing-read prompt alist nil nil nil 'delve--select-history))))
;;
(setq delve--last-selected-buffer
(if (string= new-name "Dashboard")
(delve--new-dashboard)
(delve--get-collection-buffer new-name)))))
(defun delve-kill-all-delve-buffers ()
"Kill all Delve buffers."
(interactive)
(seq-do #'kill-buffer (delve-buffer-list)))
;;; * Insert
(defun delve-insert-items (collection items)
"Insert ITEMS in COLLECTION after current item and move point.
ITEMS is a list of Delve objects. Move point to the last item
inserted. For possible values for COLLECTION, see
`delve--get-collection-buffer'. Return the collection buffer."
(let* ((buf (delve--get-collection-buffer collection))
(ewoc (lister-get-ewoc buf))
(was-empty-p (lister-empty-p ewoc))
(eolp (lister-eolp buf))
(next-node (lister-get-node-at ewoc :next))) ;; nil if no next
(lister-insert-list-at ewoc :point items nil t)
(unless was-empty-p
;; Switch to buffer for `lister-goto' to be effective. Simple
;; `with-current-buffer' does not work with underlying
;; `ewoc-next' (?!?!)
(save-window-excursion
(switch-to-buffer buf)
(if eolp
(goto-char (point-max))
(lister-goto ewoc (or (ewoc-prev ewoc next-node)
:last)))))
buf))
(defun delve-insert-nodes (collection nodes)
"Insert NODES in COLLECTION after current item and move point.
NODES is a list of Org Roam nodes or a single node. Move point
to the last item inserted. For possible values for COLLECTION,
see `delve--get-collection-buffer'. Return the collection
buffer."
(delve-insert-items collection (-map #'delve--zettel-create (-list nodes))))
(defun delve-insert-nodes-by-id (collection ids)
"Insert nodes with IDS in COLLECTION after current item and move point.
IDS can be either a single ID string or a list of IDs. For
possible values for COLLECTION, see
`delve--get-collection-buffer'. Return the collection buffer."
(delve-insert-nodes collection (delve-query-nodes-by-id (-list ids))))
(defun delve--add-to-buffer (items prompt)
"Add ITEMS to a Delve buffer and return that buffer object.
ITEMS is a list of Delve objects. Use PROMPT when asking the
user to select or create a buffer."
(delve-insert-items (delve--select-collection-buffer prompt) items))
;; * Sort
(defun delve--cmp-fn (sort-fn slot-fn &optional map-fn)
"Return a function for sorting Zettels by SLOT-FN.
SORT-FN must be a binary predicate. Access the value using
SLOT-FN. Optionally pass the slot value through MAP-FN before
using it for sorting."
(-on sort-fn (-compose (or map-fn #'identity) slot-fn)))
(cl-defstruct (delve-dual-cmp
(:constructor delve-dual-cmp--create))
"Structure holding two comparator functions for sorting in
ascending and descending order, and a description of the sorting
criterion for the user."
comp-asc comp-desc
criterion-name ascending-name descending-name)
;; FIXME Since the predicates for sorting are just the reverse from
;; each other, maybe just use one and construct the other on
;; on the fly (being nothing but '(not (fn ....)))
(defmacro delve--build-dual-cmp (name criterion-name
sort-fn-asc ascending-name
sort-fn-desc descending-name
slot-fn
&optional map-fn)
"Define a dual comperator object NAME.
A dual comperator object holds two comparator functions. NAME is
the name of the variable which holds the comperator object.
CRITERION-NAME is a description of the sorting criterion for the
user (e.g. \"title\"). It will be used for constructing a user
interface where the user can select this criterion.
SORT-FN-ASC and SORT-FN-DESC are predicates used for sorting in
ascending or in descending order, respectively. For ascending
order, the predicate should return non-nil if the first element
is \"less\" than the second, or nil if not; for descending order,
the reverse holds.
ASCENDING-NAME and DESCENDING-NAME give a user readable
description of the sorting result, e.g. \"from A to Z\".
SLOT-FN will be used to access the value, e.g.
`delve--zettel-tags'. Optionally pass the slot value through
MAP-FN before using it for sorting, e.g. `length'."
(declare (indent 1))
`(defvar ,name
(delve-dual-cmp--create :comp-asc (delve--cmp-fn ,sort-fn-asc ,slot-fn ,map-fn)
:comp-desc (delve--cmp-fn ,sort-fn-desc ,slot-fn ,map-fn)
:criterion-name ,criterion-name
:ascending-name ,ascending-name
:descending-name ,descending-name)
,(concat "Structure holding a dual comporator to sort Zettel structs by " (downcase criterion-name))))
;; * Define the comparators for sorting
(delve--build-dual-cmp delve-2cmp--title
"title"
#'string< "from A to Z"
#'string> "from Z to A"
#'delve--zettel-title)
(delve--build-dual-cmp delve-2cmp--tag-n
"number of tags"
#'< "most tags first"
#'> "no tags first"
#'delve--zettel-tags
#'length)
(delve--build-dual-cmp delve-2cmp--level
"nesting level"
#'< "deeply nested first"
#'> "top nodes first"
#'delve--zettel-level)
(delve--build-dual-cmp delve-2cmp--file-title
"file title"
#'string< "from A to Z"
#'string> "from Z to A"
#'delve--zettel-file-title)
(delve--build-dual-cmp delve-2cmp--file-mtime
"modification time"
(-compose #'not #'time-less-p) "last modified first"
#'time-less-p "last modified last"
#'delve--zettel-file-mtime)
;; * Utilities to use comparators in transients
(defvar delve--all-2cmps-symbols
'(delve-2cmp--title
delve-2cmp--file-title
delve-2cmp--level
delve-2cmp--tag-n
delve-2cmp--file-mtime)
"*Internal* All comperator names, as symbols.")
(defvar delve--all-2cmps
(-map #'eval delve--all-2cmps-symbols)
"*Internal* All comparators for sorting.")
(defun delve--cmp-info (dual-cmp slot-name)
"Return informative string about the comparator DUAL-CMP.
SLOT-NAME must be either \"comp-asc\" or \"comp-desc\",
designating the respective slot in the dual comperator
object. Return nil if one of the args is nil."
(when (and dual-cmp slot-name)
(format "by %s (%s)"
;; sorting criterion: by nesting level; by title; etc.
(delve-dual-cmp-criterion-name dual-cmp)
;; comparator description: