-
Notifications
You must be signed in to change notification settings - Fork 42
/
zetteldeft.el
1283 lines (1142 loc) · 46.7 KB
/
zetteldeft.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
;;; zetteldeft.el --- Turn deft into a zettelkasten system -*- lexical-binding: t -*-
;; Copyright (C) 2018-2021 EFLS
;; Author: EFLS <Elias Storms>
;; URL: https://efls.github.io/zetteldeft/
;; Keywords: deft zettelkasten zetteldeft wp files
;; Version: 0.3
;; Package-Requires: ((emacs "25.1") (deft "0.8") (ace-window "0.7.0"))
;; This file is not part of Emacs
;; 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:
;; Zetteldeft is an extension of the deft package for Emacs.
;; It generates unique IDs to create stable links between notes, which
;; allows the user to make an interconnected system of notes.
;; Zetteldeft uses deft to find and follow links to notes.
;; For more information, see zetteldeft.org
;; or https://efls.github.io/zetteldeft
;; Note: this file is tangled from zetteldeft.org.
;; The .org contains documentation and notes on usage of the package.
;;; Code:
(require 'deft)
(unless (require 'avy nil 'no-error)
(user-error "Avy not installed, required for zetteldeft-avy-* functions"))
(require 'thingatpt)
(require 'ace-window)
(require 'seq)
(declare-function avy-jump "avy")
(unless (fboundp 'avy-jump)
(display-warning 'zetteldeft
"Function `avy-jump' not available. Please update `avy'"))
(defgroup zetteldeft nil
"A zettelkasten on top of deft."
:group 'deft
:link '(url-link "https://efls.github.io/zetteldeft"))
;;;###autoload
(defun zetteldeft-search-at-point ()
"Search via `deft' with `thing-at-point' as filter.
Thing can be a double-bracketed link, a hashtag, or a word."
(interactive)
(let ((string (zetteldeft--get-thing-at-point)))
(if string
(zetteldeft--search-global string t)
(user-error "No search term at point"))))
;;;###autoload
(defun zetteldeft-search-current-id ()
"Search deft with the id of the current file as filter.
Open if there is only one result."
(interactive)
(zetteldeft--search-global
(zetteldeft--current-id) t))
(defun zetteldeft--get-thing-at-point ()
"Return the thing at point.
This can be
- a link: a string between [[ brackets ]],
- a tag matching `zetteldeft-tag-regex',
- a link matching `zetteldeft-link-indicator',
`zetteldeft-id-regex' and `zetteldeft-link-suffix',
- or a word."
(let* ((link-brackets-re "\\[\\[\\([^]]+\\)\\]\\]")
(link-id-re (zetteldeft--link-regex))
(htag-re zetteldeft-tag-regex))
(cond
((thing-at-point-looking-at link-brackets-re)
(match-string-no-properties 1))
((thing-at-point-looking-at link-id-re)
(match-string-no-properties 0))
((thing-at-point-looking-at htag-re)
(match-string-no-properties 0))
(t (thing-at-point 'word t)))))
(defun zetteldeft--search-global (str &optional dntOpn)
"Search deft with STR as filter.
If there is only one result, open that file (unless DNTOPN is true)."
;; Sanitize the filter string
(setq str (replace-regexp-in-string "[[:space:]\n]+" " " str))
;; Switch to Deft window if buffer is currently visible
(when (deft-buffer-visible-p)
(select-window (deft-buffer-visible-p)))
;; Call deft search on the filter string
(let ((deft-incremental-search t))
(deft)
(deft-filter str t))
;; If there is a single match, open the file
(unless dntOpn
(when (eq (length deft-current-files) 1)
(deft-open-file (car deft-current-files)))))
(defun zetteldeft--search-filename (thisStr &optional otherWindow)
"Search for deft files with string THISSTR in filename.
Open if there is only one result (in another window if OTHERWINDOW is non-nil).
Return a message if no results are found."
;; Sanitize the filter string
(setq thisStr (replace-regexp-in-string "[[:space:]\n]+" " " thisStr))
;; Call deft search on the filter string
(let ((deft-filter-only-filenames t))
(deft-filter thisStr t))
;; If there is a single match, open the file
(cond
((eq (length deft-current-files) 1)
(deft-open-file (car deft-current-files) otherWindow))
((eq (length deft-current-files) 0)
(message "No notes found with %s in name." thisStr))))
(defun zetteldeft--get-file-list (srch)
"Return a list of files with the search item SRCH."
(let ((deft-current-sort-method 'title))
(deft-filter srch t)
deft-current-files))
;;;###autoload
(defun zetteldeft-search-tag ()
"Prompt interactively for Zetteldeft tag and launch Deft search"
(interactive)
(let* ((tags (zetteldeft--get-all-sorted-tags))
(search-term (completing-read "Tag to search for: " tags)))
(zetteldeft--search-global search-term t)))
(defun zetteldeft--id-font-lock-setup (var val)
"Add font-lock highlighting for zetteldeft links.
Called when `zetteldeft-link-indicator' or
`zetteldeft-id-regex' are customized."
(when (and (boundp 'zetteldeft-link-indicator)
(boundp 'zetteldeft-id-regex)
(boundp 'zetteldeft-link-suffix))
(font-lock-remove-keywords 'org-mode
`((,(concat zetteldeft-link-indicator
zetteldeft-id-regex
zetteldeft-link-suffix)
. font-lock-warning-face))))
(set-default var val)
(when (and (boundp 'zetteldeft-id-regex)
(boundp 'zetteldeft-link-indicator)
(boundp 'zetteldeft-link-suffix))
(font-lock-add-keywords 'org-mode
`((,(concat zetteldeft-link-indicator
zetteldeft-id-regex
zetteldeft-link-suffix)
. font-lock-warning-face)))))
(defcustom zetteldeft-id-format "%Y-%m-%d-%H%M"
"Format used when generating time-based zetteldeft IDs.
Be warned: the regexp to find IDs is set separately.
If you change this value, set `zetteldeft-id-regex' so that
the IDs can be found.
Check the documentation of the `format-time-string'
function to see which placeholders can be used."
:type 'string
:group 'zetteldeft)
(setq deft-new-file-format zetteldeft-id-format)
(defun zetteldeft-generate-id (title &optional filename)
"Generate and return a Zetteldeft ID.
The ID is created using `zetteldeft-id-format', unless
`zetteldeft-custom-id-function' is bound to a function, in which case
that function is used and TITLE and FILENAME are passed to it."
(let ((id
(if-let ((f zetteldeft-custom-id-function))
(funcall f title filename)
(format-time-string zetteldeft-id-format))))
(if (zetteldeft--id-available-p id)
id
(error "Generated ID %s is not unique." id))))
(defun zetteldeft--id-available-p (str)
"Return t only if provided string STR is unique among Zetteldeft filenames."
(let ((deft-filter-only-filenames t))
(deft-filter str t))
(eq 0 (length deft-current-files)))
(defcustom zetteldeft-custom-id-function nil
"User-defined function to generate an ID.
The specified function must accept arguments for note `TITLE'
and &optional `FILENAME'. The returned ID must be a string."
:type 'function
:group 'zetteldeft)
(defcustom zetteldeft-id-regex "[0-9]\\{4\\}\\(-[0-9]\\{2,\\}\\)\\{3\\}"
"The regular expression used to search for zetteldeft IDs.
Set it so that it matches strings generated with
`zetteldeft-id-format'."
:type 'string
:group 'zetteldeft
:set 'zetteldeft--id-font-lock-setup)
(defcustom zetteldeft-link-indicator "§"
"String to indicate zetteldeft links.
String prepended to IDs to easily identify them as links to zetteldeft notes.
This variable should be a string containing only one character."
:type 'string
:group 'zetteldeft
:set 'zetteldeft--id-font-lock-setup)
(defcustom zetteldeft-link-suffix ""
"String to append to zetteldeft links.
To disable, set to empty string rather than to nil."
:type 'string
:group 'zetteldeft
:set 'zetteldeft--id-font-lock-setup)
(defun zetteldeft--link-regex ()
"Return regex for a Zetteldeft link.
Concat link indicator, id-regex, and link suffix."
(concat zetteldeft-link-indicator
zetteldeft-id-regex
zetteldeft-link-suffix))
(defun zetteldeft--lift-id (str)
"Extract zetteldeft ID from STR.
This is done with the regular expression stored in
`zetteldeft-id-regex'."
(with-temp-buffer
(insert str)
(when (re-search-forward zetteldeft-id-regex nil t -1)
(match-string 0))))
(defun zetteldeft--insert-link (id &optional title)
"Insert a link to Zetteldeft note ID.
If TITLE is included, use it as link text. To customize how inserted
links are formatted, change the `zetteldeft-insert-link-function'
variable."
(interactive)
(funcall zetteldeft-insert-link-function id title))
(defcustom zetteldeft-insert-link-function
#'zetteldeft-insert-link-zd-style
"The function to use when inserting note links.
Use either
- `zetteldeft-insert-link-zd-style' for Zetteldeft type links
- `zetteldeft-insert-link-org-style' for Org-mode zdlink: links
- A custom function that takes two arguments: an ID and an optional title."
:type 'function
:options '(zetteldeft-insert-link-zd-style
zetteldeft-insert-link-org-style)
:group 'zetteldeft)
(defun zetteldeft-insert-link-zd-style (id &optional title)
"Insert a Zetteldeft link to note with provided ID."
(insert zetteldeft-link-indicator
id
zetteldeft-link-suffix)
(when title (insert " " title)))
(defun zetteldeft-insert-link-org-style (id &optional title)
"Insert a Zetteldeft link in Org-mode format as zdlink: type."
(if title
(insert "[[zdlink:" id "][" title "]]")
(insert "[[zdlink:" id "]]")))
;;;###autoload
(defun zetteldeft-find-file (file)
"Open deft file FILE.
When no completing match, prompt user to create a new deft file using
input as the title."
(interactive
(list (completing-read "Deft find file: "
(deft-find-all-files-no-prefix))))
(let* ((dir (expand-file-name deft-directory)))
(unless (string-match (concat "^" dir) file)
(setq file (concat dir "/" file)))
(if (file-exists-p file)
(deft-open-file file)
(when (y-or-n-p (format
"Create new note with title \"%s\"?"
(file-name-base file)))
(zetteldeft-new-file (file-name-base file))))))
(defvar zetteldeft-home-id nil
"String with ID of home note, used by `zetteldeft-go-home'.")
(defun zetteldeft-go-home ()
"Move to a designated home note.
Set `zetteldeft-home-id' to an ID string of your home note."
(interactive)
(if (stringp zetteldeft-home-id)
(zetteldeft-find-file
(zetteldeft--id-to-full-path zetteldeft-home-id))
(message "No home set. Provide a string to zetteldeft-home-id.")))
;;;###autoload
(defun zetteldeft-find-file-id-insert (file)
"Find deft file FILE and insert a link."
(interactive (list
(completing-read "File to insert id from: "
(deft-find-all-files-no-prefix))))
(zetteldeft--insert-link (zetteldeft--lift-id file)))
(defcustom zetteldeft-backlink-prefix "# Backlink: "
"Prefix string included before a back link.
Formatted as `org-mode' comment by default."
:type 'string
:group 'zetteldeft)
(defcustom zetteldeft-backlink-location-function
#'zetteldeft-backlink-get-location
"Function to get location for new backlinks.
The function should return a position in the current buffer.")
(defun zetteldeft-backlink-get-location ()
"Default function that returns where a backlink should be added.
This is the line below whichever is found first:
- existing backlink
- tag line
- title
- at top of file
"
(interactive)
(save-excursion
(goto-char (point-min))
(cond
((re-search-forward (regexp-quote zetteldeft-backlink-prefix) nil t)
(forward-line)
(point))
((re-search-forward (regexp-quote zetteldeft-tag-line-prefix) nil t)
(forward-line)
(newline)
(point))
((re-search-forward (regexp-quote zetteldeft-title-prefix) nil t)
(forward-line)
(newline)
(point))
(t (point-min)))))
;;;###autoload
(defun zetteldeft-backlink-add (file)
"Find deft file FILE and insert a backlink to it.
Finds the title line, and adds `backlink-prefix' with
ID and title on a new line."
(interactive (list
(completing-read "File to add backlink to: "
(deft-find-all-files-no-prefix))))
(save-excursion
(goto-char (funcall zetteldeft-backlink-location-function))
(insert zetteldeft-backlink-prefix)
(zetteldeft--insert-link
(zetteldeft--lift-id file)
(zetteldeft--lift-file-title (concat deft-directory file)))
(insert "\n"))
(message "Backlink added."))
;;;###autoload
(defun zetteldeft-find-file-full-title-insert (file)
"Find deft file FILE and insert a link with title."
(interactive (list
(completing-read "File to insert full title from: "
(deft-find-all-files-no-prefix))))
(let ((id (zetteldeft--lift-id file)))
(zetteldeft--insert-link
id
(zetteldeft--id-to-title id))))
(defun zetteldeft--full-search (string)
"Return list of deft files with STRING in full body of file."
(let ((dir (expand-file-name deft-directory))
(result-files (zetteldeft--get-file-list string))
(this-file (buffer-file-name)))
(when this-file
(setq result-files (delete this-file result-files)))
(setq result-files
(mapcar
(lambda (f) (replace-regexp-in-string dir "" f))
result-files))
(completing-read (format "Search files containing \"%s\": " string)
result-files)))
;;;###autoload
(defun zetteldeft-full-search-id-insert (string)
"Insert ID of file from list of files containing STRING."
(interactive (list (read-string "Search string: ")))
(zetteldeft-find-file-id-insert
(zetteldeft--full-search string)))
;;;###autoload
(defun zetteldeft-full-search-full-title-insert (string)
"Insert title and ID of file from list of files containing
STRING."
(interactive (list (read-string "Search string: ")))
(zetteldeft-find-file-full-title-insert
(zetteldeft--full-search string)))
;;;###autoload
(defun zetteldeft-full-search-find-file (string)
"Open file containing STRING."
(interactive (list (read-string "Search string: ")))
(zetteldeft-find-file (zetteldeft--full-search string)))
(defcustom zetteldeft-id-filename-separator " "
"String to separate zetteldeft ID from filename."
:type 'string
:group 'zetteldeft)
(declare-function evil-insert-state "evil")
(defcustom zetteldeft-new-filename-to-kill-ring nil
"Add new filename to kill ring?"
:type 'boolean
:group 'zetteldeft)
;;;###autoload
(defun zetteldeft-new-file (str &optional id)
"Create a new deft file.
The filename is a Zetteldeft ID, appended by STR. The ID will be
generated, unless ID is provided. A file title will be inserted in the
newly created file wrapped in `zetteldeft-title-prefix' and
`zetteldeft-title-suffix'. When `zetteldeft-new-filename-to-kill-ring'
is non-nil, the filename (without extension) is added to the kill
ring. When `evil' is loaded, change to insert state."
(interactive (list (read-string "Note title: ")))
(let* ((deft-use-filename-as-title t)
(zdId (or id
(zetteldeft-generate-id str)))
(zdName (concat zdId zetteldeft-id-filename-separator str)))
(deft-new-file-named zdName)
(when zetteldeft-new-filename-to-kill-ring
(kill-new zdName))
(zetteldeft--insert-title str)
(save-buffer)
(when (featurep 'evil) (evil-insert-state))))
;;;###autoload
(defun zetteldeft-new-file-and-link (str)
"Create a new note and insert a link to it.
Similar to `zetteldeft-new-file', but insert a link to the new file."
(interactive (list (read-string "Note title: ")))
(let ((zdId (zetteldeft-generate-id str)))
(zetteldeft--insert-link zdId str)
(zetteldeft-new-file str zdId)))
;;;###autoload
(defun zetteldeft-new-file-and-backlink (str)
"Create a new note and insert link and backlink."
(interactive (list (read-string "Note title: ")))
(let ((ogId (zetteldeft--current-id))
(zdId (zetteldeft-generate-id str)))
(zetteldeft--insert-link zdId str)
(zetteldeft-new-file str zdId)
(newline)
(zetteldeft--insert-link ogId (zetteldeft--id-to-title ogId))))
(defun zetteldeft-extract-region-to-note (title)
"Extract the marked region to a new note with TITLE."
(interactive (list (if (not (use-region-p))
(user-error "No region active.")
(read-string "Note title: "))))
(let* ((id (zetteldeft-generate-id title))
(text (kill-region (region-beginning) (region-end))))
(save-excursion
(zetteldeft-new-file title id)
(yank)
(save-buffer))
(zetteldeft--insert-link id title)))
;;;###autoload
(defun zetteldeft-follow-link ()
"Use Avy to follow a link.
Follows zetteldeft link to a file if point is on a link.
Uses Avy to prompt for a link to follow with `zetteldeft-avy-file-search'
if it isn't. Variable `zetteldeft-follow-at-point' controls this last
option: when nil, always use Avy."
(interactive)
(if (and zetteldeft-follow-at-point
(thing-at-point-looking-at (zetteldeft--link-regex)))
(zetteldeft--search-filename
(zetteldeft--lift-id (zetteldeft--get-thing-at-point)))
(zetteldeft-avy-file-search)))
(defcustom zetteldeft-follow-at-point t
"Should `zetteldeft-follow-link' open link at point?
When t, open note at point if point is on a link.
When nil, always use Avy."
:type 'boolean
:group 'zetteldeft)
;;;###autoload
(defun zetteldeft-browse ()
"Browse your notes with avy.
Keep calling `zetteldeft-avy-file-search' in a loop."
(interactive)
(let ((avy-single-candidate-jump nil)
(avy-handler-function 'zetteldeft--browse-avy-handler))
(while (zetteldeft-avy-file-search)
(message "Browsing in Zetteldeft! [.] home [<] prev [>] next"))))
(defun zetteldeft--browse-avy-handler (char)
"The default handler for a bad CHAR."
(let (dispatch)
(cond ((setq dispatch (assoc char avy-dispatch-alist))
(unless (eq avy-style 'words)
(setq avy-action (cdr dispatch)))
(throw 'done 'restart))
((memq char avy-escape-chars)
;; exit silently
(throw 'done 'abort))
;; Go to home note
((eq char ?.)
(zetteldeft-go-home)
(message "Brwosing to home note.")
(zetteldeft-browse)
(throw 'done 'abort))
;; Previous buffer
((eq char ?<)
(previous-buffer)
(message "Browsing to previous buffer.")
(zetteldeft-browse)
(throw 'done 'abort))
((eq char ?>)
(next-buffer)
(message "Browsing to next buffer.")
(zetteldeft-browse)
(throw 'done 'abort))
((eq char ??)
(avy-show-dispatch-help)
(throw 'done 'restart))
((mouse-event-p char)
(signal 'user-error (list "Mouse event not handled" char)))
(t
(message "No such candidate: %s, hit `C-g' to quit."
(if (characterp char) (string char) char))))))
;;;###autoload
(defun zetteldeft-avy-tag-search ()
"Call on avy to jump to a tag.
Tags are filtered with `zetteldeft-tag-regex'."
(interactive)
(save-excursion
(let ((avy-all-windows nil))
(when (consp (avy-jump zetteldeft-tag-regex))
(zetteldeft-search-at-point)))))
;;;###autoload
(defun zetteldeft-avy-file-search (&optional otherWindow)
"Use `avy' to follow a zetteldeft link.
Links are found via `zetteldeft-link-indicator' and `zetteldeft-id-regex'.
Open that file (in another window if OTHERWINDOW)."
(interactive)
(save-excursion
(when (consp (avy-jump (zetteldeft--link-regex)))
(zetteldeft--search-filename
(zetteldeft--lift-id (zetteldeft--get-thing-at-point)) otherWindow))))
(declare-function aw-select "ace-window")
;;;###autoload
(defun zetteldeft-avy-file-search-ace-window ()
"Use `avy' to follow a zetteldeft link in another window.
Similar to `zetteldeft-avy-file-search', but with window selection.
When only one window is active, split it first.
When more windows are active, select one via `ace-window'."
(interactive)
(save-excursion
(when (consp (avy-jump (zetteldeft--link-regex)))
(let ((ID (zetteldeft--lift-id (zetteldeft--get-thing-at-point))))
(when (eq 1 (length (window-list))) (split-window))
(select-window (aw-select "Select window..."))
(zetteldeft--search-filename ID)))))
;;;###autoload
(defun zetteldeft-avy-link-search ()
"Use `avy' to perform a deft search on a zetteldeft link.
Similar to `zetteldeft-avy-file-search' but performs a full
text search for the link ID instead of filenames only.
Opens immediately if there is only one result."
(interactive)
(save-excursion
(when (consp (avy-jump (zetteldeft--link-regex)))
(zetteldeft--search-global
(zetteldeft--lift-id (zetteldeft--get-thing-at-point))))))
(defun zetteldeft--list-dead-links ()
"Return a list with IDs in Zetteldeft notes that have no corresponding note."
(let ((dead-links '())
(deft-filter-only-filenames t))
(dolist (link (zetteldeft--list-all-links))
(deft-filter link t)
(when (eq 0 (length deft-current-files))
(unless (member link dead-links)
(push link dead-links))))
dead-links))
(defconst zetteldeft--dead-links-buffer-name "*zetteldeft-dead-links*")
(defun zetteldeft-dead-links-buffer ()
"Show a buffer with all dead links in Zetteldeft."
(interactive)
(switch-to-buffer zetteldeft--dead-links-buffer-name)
(erase-buffer)
(message "Finding all dead Zetteldeft links...")
(let ((dead-links (zetteldeft--list-dead-links)))
(insert (format "# Found %d dead links\n" (length dead-links)))
(dolist (link dead-links)
(insert (format " - %s in: " link))
(deft-filter link t)
(dolist (source (deft-current-files))
(zetteldeft--insert-link (zetteldeft--lift-id source)))
(insert "\n")))
(unless (eq major-mode 'org-mode) (org-mode)))
;;;###autoload
(defun zetteldeft-deft-new-search ()
"Launch deft, clear filter and enter insert state."
(interactive)
(deft)
(deft-filter-clear)
(when (featurep 'evil) (evil-insert-state)))
(defun zetteldeft--check ()
"Check if the currently visited file is in `zetteldeft' territory:
whether it has `deft-directory' somewhere in its path."
(unless (buffer-file-name)
(user-error "Buffer not visiting a file"))
(unless (string-match-p
(regexp-quote (file-truename deft-directory))
(file-truename (buffer-file-name)))
(user-error "Not in zetteldeft territory")))
(defun zetteldeft--current-id ()
"Retrieve ID from current file."
(zetteldeft--check)
(zetteldeft--lift-id
(file-name-base (buffer-file-name))))
(defcustom zetteldeft-title-prefix "#+TITLE: "
"Prefix string included when `zetteldeft--insert-title' is called.
Formatted for `org-mode' by default.
Don't forget to include a space."
:type 'string
:group 'zetteldeft)
(defcustom zetteldeft-title-suffix ""
"String inserted below title when `zetteldeft--insert-title' is called.
Empty by default.
Don't forget to add `\\n' at the beginning to start a new line."
:type 'string
:group 'zetteldeft)
(defun zetteldeft--insert-title (title)
"Insert TITLE as title in file.
Prepended by `zetteldeft-title-prefix' and appended by `zetteldeft-title-suffix'."
(zetteldeft--check)
(insert
zetteldeft-title-prefix
title
zetteldeft-title-suffix))
(defcustom zetteldeft-title-parsing-function #'deft-parse-title
"Function used to extract a title from a note; defaults to `deft-parse-title'.
The function you use here must be compatible with `deft-parse-title': the
first argument is the file's fully qualified path; the second is the contents
of said file."
:type 'function
:group 'zetteldeft)
(defun zetteldeft--lift-file-title (zdFile)
"Return the title of a zetteldeft note.
ZDFILE should be a full path to a note."
(let ((deft-use-filename-as-title nil))
(funcall zetteldeft-title-parsing-function
zdFile
(with-temp-buffer
(insert-file-contents zdFile)
(buffer-string)))))
;;;###autoload
(defun zetteldeft-file-rename ()
"Change current file's title, and use the new title to rename the file.
Use this on files in the `deft-directory'.
When the file has no Zetteldeft ID, one is generated and included in the new name."
(interactive)
(zetteldeft--check)
(let ((old-filename (buffer-file-name)))
(when old-filename
(let* ((old-title (zetteldeft--lift-file-title old-filename))
(prompt-text (concat "Change " old-title " to: "))
(new-title (read-string prompt-text old-title))
(id (or (zetteldeft--lift-id (file-name-base old-filename))
(zetteldeft-generate-id new-title old-filename)))
(new-filename
(deft-absolute-filename
(concat id zetteldeft-id-filename-separator new-title))))
(rename-file old-filename new-filename)
(deft-update-visiting-buffers old-filename new-filename)
(zetteldeft-update-title-in-file new-title)
(deft-refresh)))))
(defcustom zetteldeft-always-insert-title t
"When renaming a note, insert title if not already present."
:type 'boolean
:group 'zetteldeft)
(defun zetteldeft-update-title-in-file (title)
"Update the title in the current note buffer to TITLE.
This searches the buffer for `zetteldeft-title-prefix' and updates the current
title, if present. If not present and `zetteldeft-always-insert-title' is set,
this inserts a title line at the beginning of the buffer. Otherwise, no change
is made."
(save-excursion
(let ((zetteldeft-title-suffix ""))
(goto-char (point-min))
(if (re-search-forward (regexp-quote zetteldeft-title-prefix) nil t)
(progn (delete-region (line-beginning-position) (line-end-position))
(zetteldeft--insert-title title))
(when zetteldeft-always-insert-title
(zetteldeft--insert-title title)
(newline))))))
;;;###autoload
(defun zetteldeft-count-words ()
"Prints total number of words and notes in the minibuffer."
(interactive)
(let ((numWords 0))
(dolist (deftFile deft-all-files)
(with-temp-buffer
(insert-file-contents deftFile)
(setq numWords (+ numWords (count-words (point-min) (point-max))))))
(message
"Your zettelkasten contains %s notes with %s words in total."
(length deft-all-files) numWords)))
;;;###autoload
(defun zetteldeft-copy-id-current-file ()
"Copy current ID.
Add the id from the filename the buffer is currently visiting to the
kill ring."
(interactive)
(zetteldeft--check)
(let ((ID (concat zetteldeft-link-indicator
(zetteldeft--lift-id (file-name-base (buffer-file-name)))
zetteldeft-link-suffix)))
(kill-new ID)
(message "%s" ID)))
(defun zetteldeft--extract-links (deftFile)
"Find all links in DEFTFILE and return a list."
(let ((zdLinks (list)))
(with-temp-buffer
(insert-file-contents deftFile)
(while (re-search-forward zetteldeft-id-regex nil t)
(let ((foundTag (replace-regexp-in-string " " "" (match-string 0))))
;; Add found tag to zdLinks if it isn't there already
(unless (member foundTag zdLinks)
(push foundTag zdLinks)))
;; Remove found tag from buffer
(delete-region (point) (re-search-backward zetteldeft-id-regex))))
zdLinks))
(defun zetteldeft--list-all-links ()
"Return a list with all IDs that appear in notes."
(let ((all-links '()))
(dolist (file deft-all-files)
(dolist (link (zetteldeft--extract-links file))
(unless (member link all-links)
(push link all-links))))
all-links))
(defun zetteldeft--id-to-full-path (zdID)
"Return full path from given zetteldeft ID ZDID.
Returns nil when no files are found.
Throws an error when multiple files are found."
(let ((deft-filter-only-filenames t))
(deft-filter zdID t))
(when (> (length deft-current-files) 1)
(user-error "ID Error. Multiple zetteldeft files found with ID %s" zdID))
(car deft-current-files))
(defun zetteldeft--id-to-title (zdId)
"Turn a Zetteldeft ID into the title."
(zetteldeft--lift-file-title
(zetteldeft--id-to-full-path zdId)))
(defcustom zetteldeft-tag-regex "[#@][[:alnum:]_-]+"
"Regular expression for finding Zetteldeft tags."
:type 'string
:group 'zetteldeft)
(defcustom zetteldeft-tag-prefix "#"
"String prefix used when inserting new Zetteldeft tags."
:type 'string
:group 'zetteldeft)
(defcustom zetteldeft-tag-line-prefix "# Tags"
"String used to find the line where tags in Zetteldeft files should go."
:type 'string
:group 'zetteldeft)
;;;###autoload
(defun zetteldeft-tag-insert-at-point (tag)
"Insert TAG at point. Interactively, select an existing tag or provide new one."
(interactive (list (completing-read
"Tag to insert: "
(zetteldeft--get-all-sorted-tags))))
(unless (string-prefix-p zetteldeft-tag-prefix tag)
(insert zetteldeft-tag-prefix))
(insert tag))
;;;###autoload
(defun zetteldeft-tag-insert ()
"Select existing tag or enter new one to insert in current Zetteldeft note.
The tag is appended to the first line starting with `zetteldeft-tag-line-prefix'.
If this variable is nil, or tag line is not found, insert tag at point."
(interactive)
(zetteldeft--check)
(let ((dest (when zetteldeft-tag-line-prefix
(save-excursion
(goto-char (point-min))
(re-search-forward zetteldeft-tag-line-prefix nil t)))))
(if dest
(save-excursion
(goto-char dest)
(end-of-line)
(insert " ")
(call-interactively 'zetteldeft-tag-insert-at-point))
(call-interactively 'zetteldeft-tag-insert-at-point))))
(defun zetteldeft-tag-remove ()
"Prompt for a tag to remove from the current Zetteldeft note.
Only the first instance of the selected tag is removed."
(interactive)
(zetteldeft--check)
; Extract tags of current file into `zetteldeft--tag-list'
(setq zetteldeft--tag-list (list))
(save-buffer)
(zetteldeft--extract-tags (buffer-file-name))
; Select a tag from that list
(let* ((tag (completing-read
"Tag to remove: "
(seq-filter 'stringp zetteldeft--tag-list))))
; Find and remove first instance of that tag
(save-excursion
(goto-char (point-min))
(re-search-forward tag nil t)
(delete-region (point) (re-search-backward tag nil t))
; remove potential empty space before tag
(backward-char)
(when (looking-at " ") (delete-char 1)))))
(defconst zetteldeft--tag-buffer-name "*zetteldeft-tag-buffer*")
;;;###autoload
(defun zetteldeft-tag-buffer ()
"Switch to the `zetteldeft-tag-buffer' and list tags."
(interactive)
(switch-to-buffer zetteldeft--tag-buffer-name)
(erase-buffer)
(let ((tagList (zetteldeft--get-all-tags)))
(dolist (zdTag tagList)
(when (stringp zdTag)
(insert (format "%s (%d) \n"
zdTag
(lax-plist-get tagList zdTag)))))
(unless (eq major-mode 'org-mode) (org-mode))
(sort-lines nil (point-min) (point-max))
(goto-char (point-min))))
(defvar zetteldeft--tag-list nil
"A temporary property list to store all tags.")
(defun zetteldeft--get-all-tags ()
"Return a plist of all the tags found in zetteldeft files."
(setq zetteldeft--tag-list (list))
(dolist (deftFile deft-all-files)
(zetteldeft--extract-tags deftFile))
zetteldeft--tag-list)
(defun zetteldeft--get-all-sorted-tags ()
"Return a sorted plist of all the tags found in zetteldeft files."
(seq-sort 'string-lessp
(seq-filter 'stringp
(zetteldeft--get-all-tags))))
(defun zetteldeft--tag-format ()
"Adjust `zetteldeft-tag-regex' for more accurate results."
(concat "\\(^\\|\s\\)" zetteldeft-tag-regex))
(defun zetteldeft--extract-tags (deftFile)
"Find all tags in DEFTFILE and add them to `zetteldeft--tag-list'.
Increase counters as we go."
(with-temp-buffer
(insert-file-contents deftFile)
(while (re-search-forward (zetteldeft--tag-format) nil t)
(let ((foundTag (replace-regexp-in-string " " "" (match-string 0))))
;; Add found tag to zetteldeft--tag-list if it isn't there already
(zetteldeft--tag-count foundTag))
;; Remove found tag from buffer
(delete-region (point) (re-search-backward (zetteldeft--tag-format))))))
(defun zetteldeft--tag-count (zdTag)
(let ((tagCount (lax-plist-get zetteldeft--tag-list zdTag)))
(if tagCount
; if the tag was there already, inc by 1
(setq zetteldeft--tag-list
(lax-plist-put zetteldeft--tag-list zdTag (1+ tagCount)))
; if tag was not there yet, add & set to 1
(setq zetteldeft--tag-list
(lax-plist-put zetteldeft--tag-list zdTag 1)))))
;;;###autoload
(defun zetteldeft-insert-list-links (string)
"Search for SEARCH-STRING and insert list of links to results."
(interactive (list (read-string "search string: ")))
(let ((result-files (zetteldeft--get-file-list string))
(this-file (buffer-file-name)))
(when this-file
(setq result-files (delete this-file result-files)))
(dolist (file result-files)
(zetteldeft--list-entry-file-link file))))
(defcustom zetteldeft-list-links-missing-message
" No missing links with search term =%s= found\n"
"Message to insert when no missing links are found.
This is used by `zetteldeft-insert-list-links-missing'.
%s will be replaced by the search term provided to
this function."
:type 'string
:group 'zetteldeft)
;;;###autoload
(defun zetteldeft-insert-list-links-missing (string)
"Insert a list of links to all deft files with a search string ZDSRCH.
In contrast to `zetteldeft-insert-list-links' only include links not
yet present in the current file. Can only be called from a file in the
zetteldeft directory."
(interactive (list (read-string "Search string: ")))
(zetteldeft--check)
(let (this-id ; ID of current file
current-ids ; IDs present in current buffer
found-ids ; IDs of notes with search result
final-ids) ; Final list of IDs for the list
;; Gather list of IDs in current buffer
(setq current-ids (zetteldeft--extract-links (buffer-file-name)))
;; Execute search and push found IDs to temporary list
(dolist (file (zetteldeft--get-file-list string))
(push (zetteldeft--lift-id file) found-ids))
;; Keep only unique IDs on the final list
(dolist (id found-ids)
(unless (member id current-ids)
(push id final-ids)))
;; Remove the ID of the current buffer from the final list
(setq this-id (zetteldeft--lift-id (file-name-base (buffer-file-name))))
(setq final-ids (delete this-id final-ids))
;; Finally insert ID and title for each element on the list
(if final-ids
(dolist (id final-ids)
(zetteldeft--list-entry-file-link (zetteldeft--id-to-full-path id)))
;; Unless the list is empty, then insert a message
(insert (format zetteldeft-list-links-missing-message string)))))
(defcustom zetteldeft-list-prefix " - "
"Prefix for lists created with `zetteldeft-insert-list-links'
and `zetteldeft-insert-list-links-missing'."
:type 'string
:group 'zetteldeft)
(defun zetteldeft--list-entry-file-link (file)
"Insert ZDFILE as list entry."
(let ((id (zetteldeft--lift-id (file-name-base file))))
(insert zetteldeft-list-prefix)
(when id
(insert zetteldeft-link-indicator
id
zetteldeft-link-suffix
" "))
(insert (zetteldeft--lift-file-title file)
"\n")))
(defun zetteldeft-list-links (str &optional missing sort)