-
-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathvulpea.el
More file actions
1968 lines (1744 loc) · 81.4 KB
/
Copy pathvulpea.el
File metadata and controls
1968 lines (1744 loc) · 81.4 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
;;; vulpea.el --- Note management library for Org mode -*- lexical-binding: t; -*-
;;
;; Copyright (c) 2015-2026 Boris Buliga <boris@d12frosted.io>
;;
;; Author: Boris Buliga <boris@d12frosted.io>
;; Maintainer: Boris Buliga <boris@d12frosted.io>
;; Version: 2.7.0
;; Package-Requires: ((emacs "29.1") (org "9.4.4") (emacsql "4.3.0") (s "1.12") (dash "2.19"))
;;
;; 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
;; <http://www.gnu.org/licenses/>.
;;
;; Created: 08 Jan 2021
;;
;; URL: https://github.com/d12frosted/vulpea
;;
;; License: GPLv3
;;
;; This file is not part of GNU Emacs.
;;
;;; Commentary:
;;
;; Vulpea is a note management library for Org mode that maintains its
;; own SQLite database for efficient querying and organization.
;;
;; Key features:
;; - Fast note lookup via SQLite database with automatic sync
;; - Rich note structure: titles, aliases, tags, links, properties, metadata
;; - Flexible querying by tags, links, properties, dates, and more
;; - Metadata system using Org description lists
;; - Note creation with customizable templates
;; - Selection interface with filtering and alias expansion
;;
;; Quick start:
;; (setq vulpea-directory "~/org/")
;; (vulpea-db-sync-start)
;;
;; Main entry points:
;; - `vulpea-find' - find and open a note
;; - `vulpea-insert' - insert a link to a note
;; - `vulpea-create' - create a new note
;; - `vulpea-db-query' - query notes with a predicate
;; - `vulpea-select' - select a note with completion
;;
;; See https://github.com/d12frosted/vulpea for documentation.
;;
;;; Code:
(require 'package)
(require 'org-capture)
(require 'org-id)
(require 'vulpea-buffer)
(require 'vulpea-db)
(require 'vulpea-db-extract)
(require 'vulpea-db-sync)
(require 'vulpea-db-schema-validation)
(require 'vulpea-mentions)
(require 'vulpea-meta)
(require 'vulpea-note)
(require 'vulpea-schema)
(require 'vulpea-select)
(require 'vulpea-tags)
(require 'vulpea-utils)
(require 's)
;;; Version
(declare-function elpaca-get "ext:elpaca" (id))
(declare-function elpaca-source-dir "ext:elpaca" (e))
(declare-function elpaca<-repo-dir "ext:elpaca" (e))
(declare-function straight--repos-dir "ext:straight" (&rest segments))
(defconst vulpea-version "2.7.0"
"Version of the vulpea package.
Keep in sync with the Version header in vulpea.el; releases bump
both. For precise version information including commits past a
release, use the function `vulpea-version' instead.")
(defun vulpea-version--git ()
"Return version from \"git describe\", or nil if unavailable.
Works when vulpea is loaded from a git checkout and git is
available. The result looks like \"v2.2.0\" exactly on a release
tag, \"v2.2.0-15-g2938416\" when 15 commits past it, with a
\"-dirty\" suffix when there are uncommitted changes.
The checkout is searched in several places, because package
managers separate the loaded build from the git source: the
resolved truename of the loaded library (plain checkouts, and
managers that symlink their build directory), then elpaca's and
straight's source directories when those managers are present
\(their builds are plain copies, revealing nothing about the
checkout)."
(when-let* ((dir (seq-some
(lambda (candidate)
(and candidate
(locate-dominating-file candidate ".git")))
(list
(when-let* ((file (locate-library "vulpea")))
(file-truename file))
(when (fboundp 'elpaca-get)
(when-let* ((e (elpaca-get 'vulpea)))
(cond
((fboundp 'elpaca-source-dir)
(elpaca-source-dir e))
((fboundp 'elpaca<-repo-dir)
(elpaca<-repo-dir e)))))
(when (fboundp 'straight--repos-dir)
(straight--repos-dir "vulpea")))))
((executable-find "git")))
(with-temp-buffer
(let ((default-directory dir))
(when (eql 0 (ignore-errors
(call-process "git" nil t nil "describe"
"--tags" "--dirty" "--always")))
(string-trim (buffer-string)))))))
(defun vulpea-version--package ()
"Return version of the installed vulpea package, or nil.
For MELPA snapshot installs the result looks like
\"20260610.1234 (commit 2938416)\"."
(when-let* ((desc (cadr (assq 'vulpea package-alist)))
(version (package-version-join
(package-desc-version desc))))
(if-let* ((commit (cdr (assq :commit (package-desc-extras desc)))))
(format "%s (commit %s)"
version (substring commit 0 (min 7 (length commit))))
version)))
(defun vulpea-version (&optional show)
"Return the vulpea version with as much precision as available.
The version is resolved in the following order:
1. \"git describe\" output when running from a git checkout,
e.g. \"v2.2.0\" or \"v2.2.0-15-g2938416\".
2. Installed package version, including the commit for MELPA
snapshot installs, e.g. \"20260610.1234 (commit 2938416)\".
3. The `vulpea-version' constant as a fallback.
When SHOW is non-nil (always when called interactively), also
display the version in the echo area. Please include this
version in bug reports."
(interactive (list t))
(let ((version (or (vulpea-version--git)
(vulpea-version--package)
vulpea-version)))
(when show
(message "vulpea %s" version))
version))
;;; Doctor
(defun vulpea-doctor--db-file-info ()
"Return a human-readable description of the database file."
(if (file-exists-p vulpea-db-location)
(format "exists (%s)"
(file-size-human-readable
(file-attribute-size
(file-attributes vulpea-db-location))))
"missing"))
(defun vulpea-doctor--note-count ()
"Return the number of indexed notes, or nil when unavailable.
Returns nil instead of creating the database file when it does
not exist - the doctor must not modify state."
(when (file-exists-p vulpea-db-location)
(ignore-errors (vulpea-db-count-notes))))
(defun vulpea-doctor--cached-file-stats ()
"Return (TOTAL . NOTE-LESS) file change-detection cache counts.
TOTAL is how many files are tracked in the `files' table; NOTE-LESS
is how many of them have no note in the `notes' table. A non-zero
NOTE-LESS is expected for genuinely note-less files (READMEs,
drafts), but a surprising count can indicate notes that failed to
index and are now skipped by change detection (see vulpea#277);
`vulpea-db-sync-full-scan' with a force argument re-extracts them.
Returns nil when the database file is absent; does not create it."
(when (file-exists-p vulpea-db-location)
(ignore-errors
(let ((db (vulpea-db)))
(cons
(caar (emacsql db [:select (funcall count *) :from files]))
(caar (emacsql db
[:select (funcall count *) :from files
:where (not (in path
[:select :distinct [path]
:from notes]))])))))))
(defun vulpea-doctor--monitoring-status ()
"Return a string describing the active external file monitoring."
(cond
((and vulpea-db-sync--fswatch-process
(process-live-p vulpea-db-sync--fswatch-process))
"fswatch (process running)")
(vulpea-db-sync--poll-timer
(format "polling (every %ss)" vulpea-db-sync-poll-interval))
(t "none")))
(defun vulpea-doctor--issues ()
"Return a list of detected setup issues as human-readable strings."
(let ((issues nil)
(fswatch (executable-find "fswatch"))
(fd (executable-find "fd"))
(notes (vulpea-doctor--note-count)))
;; Sync directories
(if (null vulpea-db-sync-directories)
(push (concat "`vulpea-db-sync-directories' is empty - nothing will"
" be indexed. Set it (or `org-directory') to where"
" your notes live.")
issues)
(dolist (dir vulpea-db-sync-directories)
(unless (file-directory-p dir)
(push (format "Sync directory %s does not exist." dir) issues))))
;; External tools. A missing executable on a GUI Emacs is often a
;; PATH problem rather than a missing install (Doom env file,
;; minimal GUI PATH), hence the exec-path hint.
(when (and (not fswatch)
(memq vulpea-db-sync-external-method '(auto fswatch)))
(push (concat "fswatch not found on `exec-path'"
(if (eq vulpea-db-sync-external-method 'fswatch)
(concat " but `vulpea-db-sync-external-method' is"
" 'fswatch - external monitoring will fail"
" to start.")
" - external changes are detected via slower polling.")
" Install fswatch, or fix Emacs's PATH if it is already"
" installed (Doom users: re-run 'doom env').")
issues))
(unless fd
(push (concat "fd not found on `exec-path' - directory scans fall"
" back to find, which is much slower on large"
" collections. Install fd, or fix Emacs's PATH if it"
" is already installed (Doom users: re-run 'doom env').")
issues))
;; Sync state
(unless vulpea-db-autosync-mode
(push (concat "`vulpea-db-autosync-mode' is disabled - the database"
" will not stay up to date as notes change. Enable it"
" with (vulpea-db-autosync-mode +1).")
issues))
(when (and vulpea-db-autosync-mode
(memq vulpea-db-sync-external-method '(auto fswatch poll))
(string= "none" (vulpea-doctor--monitoring-status)))
(push (concat "External monitoring is configured but not active -"
" changes made outside Emacs will not be picked up."
" Try toggling `vulpea-db-autosync-mode'.")
issues))
;; Database
(cond
((not (file-exists-p vulpea-db-location))
(push (concat "Database file does not exist yet. Run"
" M-x vulpea-db-sync-full-scan to build it.")
issues))
((and notes (zerop notes))
(push (concat "Database exists but contains no notes. Run"
" M-x vulpea-db-sync-full-scan; if it stays empty,"
" check that your notes have ID properties and live"
" under `vulpea-db-sync-directories'.")
issues)))
;; Extractor plugins
(when-let* ((undeclared
(seq-filter
(lambda (extractor)
(eq (vulpea-extractor-requires-ast extractor) 'unset))
vulpea-db--extractors)))
(push (format
(concat "Extractor%s %s do%s not declare :requires-ast."
" Undeclared extractors receive a parse context whose"
" AST slot is always nil. Add :requires-ast t to the"
" definition if its extract-fn reads"
" (vulpea-parse-ctx-ast ctx), or :requires-ast nil to"
" confirm it works purely from note data (and keep"
" extraction fast and worker-eligible).")
(if (cdr undeclared) "s" "")
(mapconcat (lambda (extractor)
(format "`%s'" (vulpea-extractor-name extractor)))
undeclared ", ")
(if (cdr undeclared) "" "es"))
issues))
;; Async extraction
(when vulpea-db-async-extraction
(when-let* ((reasons (vulpea-db-worker-rejection-reasons "probe.org")))
(push (format
(concat "`vulpea-db-async-extraction' is enabled but your"
" .org files will NOT use the worker (%s) - every"
" file takes the synchronous path. %s")
(mapconcat #'symbol-name reasons ", ")
(cond
((memq 'ast-extractors reasons)
(concat "An extractor plugin declares :requires-ast t;"
" the AST cannot cross the process boundary, so"
" AST-reading extractors and async extraction"
" do not combine."))
((memq 'broken reasons)
(concat "The worker crash-looped; see *Warnings*, then"
" M-x vulpea-db-worker-reset to retry."))
(t "Run M-x vulpea-db-worker-diagnose for details.")))
issues))
(when (and (eq vulpea-db-async-extraction 'full)
(bound-and-true-p vulpea-db-worker--wal-failed))
(push (concat "Full-write mode is configured but WAL journaling"
" could not be enabled on the database (filesystem"
" without shared-memory support?) - degraded to"
" extract-only. The database write runs on the main"
" thread.")
issues))
(when (and (eq vulpea-db-async-extraction 'full)
(not (vulpea-db-worker--filters-inert-p)))
(push (concat "Full-write mode is configured but note index"
" filters are active (schema validation with a"
" non-silent action, or a custom filter) - degraded"
" to extract-only so the filters keep running in"
" your session.")
issues)))
(nreverse issues)))
(defun vulpea-doctor--report ()
"Build the doctor report as a string."
(let* ((issues (vulpea-doctor--issues))
(notes (vulpea-doctor--note-count))
(stats (vulpea-doctor--cached-file-stats))
(line (lambda (label value) (format " %-32s %s" label value))))
(string-join
(append
(list
"Vulpea Doctor"
"============="
""
"Versions"
(funcall line "vulpea" (vulpea-version))
(funcall line "emacs" emacs-version)
(funcall line "org" (org-version))
(funcall line "system" (format "%s" system-type))
""
"Configuration"
(funcall line "vulpea-db-sync-directories"
(format "%S" vulpea-db-sync-directories))
(funcall line "vulpea-db-location" vulpea-db-location)
(funcall line "vulpea-db-parse-method"
(format "%s" vulpea-db-parse-method))
(funcall line "vulpea-db-index-heading-level"
(format "%s" vulpea-db-index-heading-level))
(funcall line "vulpea-db-sync-external-method"
(format "%s" vulpea-db-sync-external-method))
(funcall line "vulpea-db-sync-scan-on-enable"
(format "%s" vulpea-db-sync-scan-on-enable))
""
"Database"
(funcall line "file" (vulpea-doctor--db-file-info))
(funcall line "schema version" (format "%s" vulpea-db-version))
(funcall line "notes" (if notes (format "%d" notes) "n/a"))
(funcall line "cached files"
(if stats (format "%d" (car stats)) "n/a"))
(funcall line "files without notes"
(if stats (format "%d" (cdr stats)) "n/a"))
""
"Sync"
(funcall line "autosync"
(if vulpea-db-autosync-mode "enabled" "disabled"))
(funcall line "external monitoring" (vulpea-doctor--monitoring-status))
(funcall line "pending queue"
(format "%d" (length vulpea-db-sync--queue)))
""
"Async Extraction"
(funcall line "mode" (format "%s" vulpea-db-async-extraction))
(funcall line "worker"
(cond
((not vulpea-db-async-extraction) "n/a")
((bound-and-true-p vulpea-db-worker--broken)
"BROKEN (crash loop; M-x vulpea-db-worker-reset)")
((process-live-p
(bound-and-true-p vulpea-db-worker--process))
(format "running (%d in flight)"
(vulpea-db-worker-in-flight-count)))
(t "not running (spawns on first change)")))
(funcall line "handles .org files"
(if vulpea-db-async-extraction
(if-let* ((reasons (vulpea-db-worker-rejection-reasons
"probe.org")))
(format "NO: %s"
(mapconcat #'symbol-name reasons ", "))
"yes")
"n/a"))
""
"External Tools"
(funcall line "fd" (or (executable-find "fd") "not found"))
(funcall line "fswatch" (or (executable-find "fswatch") "not found"))
(funcall line "rg" (or (executable-find "rg") "not found"))
(funcall line "git" (or (executable-find "git") "not found"))
""
"Issues")
(if issues
(mapcar (lambda (issue) (concat " - " issue)) issues)
(list " No issues detected.")))
"\n")))
;;;###autoload
(defun vulpea-doctor (&optional show)
"Diagnose the Vulpea setup and return a report string.
The report covers versions, configuration, database state, sync
state, external tool availability, and a list of detected issues.
It is read-only: nothing is created or modified, even when the
database does not exist yet. Please include the report in bug
reports.
When SHOW is non-nil (always when called interactively), also
display the report in the *vulpea-doctor* buffer."
(interactive (list t))
(let ((report (vulpea-doctor--report)))
(when show
(with-current-buffer (get-buffer-create "*vulpea-doctor*")
(let ((inhibit-read-only t))
(erase-buffer)
(insert report)
(goto-char (point-min)))
(special-mode)
(display-buffer (current-buffer))))
report))
;;; Customization
(defgroup vulpea nil
"Vulpea note-taking system."
:group 'org)
(defcustom vulpea-default-notes-directory nil
"Default directory for creating new notes.
When nil (the default), dynamically resolves to the first entry in
`vulpea-db-sync-directories', which itself defaults to
`org-directory'.
Set this explicitly only if you want notes created in a different
directory than the first sync directory."
:type '(choice (const :tag "Use first sync directory" nil)
(directory :tag "Explicit directory"))
:group 'vulpea)
(defcustom vulpea-create-default-function nil
"Function to compute default parameters for note creation.
Called with (title) and should return a plist of default parameters.
When nil, uses `vulpea-create-default-template' instead.
The function allows dynamic parameter computation based on context:
(setq vulpea-create-default-function
(lambda (title)
(list :tags (if (string-match-p \"TODO\" title)
\\='(\"task\" \"inbox\")
\\='(\"note\" \"inbox\"))
:head (format \"#+created: %s\"
(format-time-string \"[%Y-%m-%d]\"))
:properties (list (cons \"SOURCE\"
(buffer-name))))))
Parameters explicitly passed to `vulpea-create' override these defaults,
except for the title. If the template returned by this function includes
`:title', it will take precedence over the title passed to
`vulpea-create' in order to allow for this function to modify the note
title.
These defaults seed file-level note creation only. When
`vulpea-create' is called with a non-nil `:parent' (a heading-level
note), this function is not called and no defaults are applied.
When `vulpea-create' is called with a nil TITLE (an untitled note,
see vulpea#399), this function receives nil - account for that if
you opt into untitled creation. A returned `:title' still wins and
turns the note into a regular titled one."
:type '(choice (const :tag "Use template instead" nil)
(function :tag "Function returning plist"))
:group 'vulpea)
(defcustom vulpea-create-default-template
'(:file-name "${timestamp}_${slug}.org")
"Default template (plist) for note creation.
Only used when `vulpea-create-default-function' is nil.
Parameters explicitly passed to `vulpea-create' override these defaults.
These defaults seed file-level note creation only. When
`vulpea-create' is called with a non-nil `:parent' (a heading-level
note), no defaults are consulted and the heading is built solely
from the explicitly passed arguments.
Supports all template expansion features:
${var} - Variable substitution
%(elisp) - Elisp evaluation
%<format> - Timestamp formatting
Default configuration:
\\='(:file-name \"${timestamp}_${slug}.org\")
Example customization:
(setq vulpea-create-default-template
\\='(:file-name \"inbox/${slug}.org\"
:tags (\"fleeting\")
:head \"#+created: %<[%Y-%m-%d]>\"
:properties ((\"CREATED\" . \"%<[%Y-%m-%d]>\")
(\"AUTHOR\" . \"%(user-full-name)\"))
:context (:source \"manual\")))
Note: %(elisp) and %<format> directives are honored only inside
the template fields themselves (e.g. :head, :properties values).
Context values are inserted literally and are not re-evaluated.
Available parameters:
:file-name - File name template (relative to default directory)
Can also be a function: (lambda (title) ...)
:tags - List of tag strings
:head - Header content after #+filetags
:body - Note body content
:properties - Alist of (key . value) for property drawer
:meta - Alist of (key . value) for metadata
:context - Plist of custom template variables
:title - Note title. Takes precedence over the title passed to
`vulpea-create'. Mainly used to allow
`vulpea-create-default-function' to modify the note
title.
Template variables for :file-name:
${title} - Note title
${slug} - URL-friendly version of title
${timestamp} - Current timestamp (%Y%m%d%H%M%S)
${id} - Note ID (UUID)"
:type 'plist
:group 'vulpea)
;;; Variables
(defvar vulpea-db-sync-directories) ; Defined in vulpea-db
(defvar vulpea-find-default-filter nil
"Default filter to use in `vulpea-find'.")
(defvar vulpea-find-default-candidates-source #'vulpea-db-query
"Default source to get the list of candidates in `vulpea-find'.
Must be a function that accepts one argument - optional note
filter function.")
(defvar vulpea-find-default-create-fn #'vulpea-find-create-note
"Default function to create a note in `vulpea-find'.
Called with two arguments - the title typed by the user and
capture properties (currently always nil, reserved for future
use) - mirroring the CREATE-FN argument of `vulpea-insert'. It
should create the note and return the resulting `vulpea-note' to
visit, or nil to skip visiting (e.g. when creation is interactive,
asynchronous, or was aborted).
This is the hook for \"capture on empty\" workflows: set it to a
function that routes to `org-capture' or your own command to turn
a fruitless search straight into note creation.")
;;; Helper Functions
(defun vulpea-title-to-slug (title)
"Convert TITLE to URL-friendly slug.
Uses Unicode normalization to properly handle international characters
and diacritical marks. Implementation adapted from org-roam.
Credits: USAMI Kenta (@zonuexe)
See: https://github.com/org-roam/org-roam/pull/1460"
(require 'ucs-normalize)
(let ((slug-trim-chars
;; Combining Diacritical Marks https://www.unicode.org/charts/PDF/U0300.pdf
;; For why these specific glyphs: https://github.com/org-roam/org-roam/pull/1460
'( #x300 #x301 #x302 #x303 #x304 #x306 #x307
#x308 #x309 #x30A #x30B #x30C #x31B #x323
#x324 #x325 #x327 #x32D #x32E #x330 #x331)))
(thread-last title
(ucs-normalize-NFD-string) ;; aka. `string-glyph-decompose' from Emacs 29
(seq-remove (lambda (char) (memq char slug-trim-chars)))
(apply #'string)
(ucs-normalize-NFC-string) ;; aka. `string-glyph-compose' from Emacs 29
(replace-regexp-in-string "[^[:alnum:]]" "_") ;; convert anything not alphanumeric
(replace-regexp-in-string "__*" "_") ;; remove sequential underscores
(replace-regexp-in-string "^_" "") ;; remove starting underscore
(replace-regexp-in-string "_$" "") ;; remove ending underscore
(downcase))))
(define-obsolete-function-alias 'vulpea--title-to-slug #'vulpea-title-to-slug "2.0.0")
;;; Link Categorization
(defun vulpea--get-incoming-links-with-descriptions (note-id)
"Get all links pointing to NOTE-ID with their descriptions.
Returns list of plists with :source-id :source-path :pos :description."
(let* ((links (vulpea-db-query-links-to note-id))
;; Collect unique source IDs and batch fetch for paths
(source-ids (delete-dups (mapcar (lambda (l) (plist-get l :source)) links)))
(source-notes (vulpea-db-query-by-ids source-ids))
;; Build id->path lookup table
(id-to-path (make-hash-table :test 'equal))
result)
(dolist (note source-notes)
(puthash (vulpea-note-id note) (vulpea-note-path note) id-to-path))
;; Process links - description comes from database now
(dolist (link links)
(let* ((source-id (plist-get link :source))
(source-path (gethash source-id id-to-path)))
(when source-path
(push (list :source-id source-id
:source-path source-path
:pos (plist-get link :pos)
:description (plist-get link :description))
result))))
(nreverse result)))
(defun vulpea--categorize-links (links old-title)
"Categorize LINKS into exact and partial matches.
Case-insensitive matching against OLD-TITLE.
Returns plist (:exact :partial).
Exact matches: description equals old title (case-insensitive).
Partial matches: description contains old title but isn't exact.
Links using aliases are left unchanged (alias is still valid).
Links with nil descriptions or custom descriptions are excluded."
(let ((exact '())
(partial '())
(title-down (downcase old-title)))
(dolist (link links)
(let ((desc (plist-get link :description)))
(when desc
(let ((desc-down (downcase desc)))
(cond
;; Exact match (case-insensitive)
((string= desc-down title-down)
(push link exact))
;; Partial match - contains but not exact
((string-match-p (regexp-quote title-down) desc-down)
(push link partial)))))))
(list :exact (nreverse exact)
:partial (nreverse partial))))
(defun vulpea--update-link-description (file pos new-description)
"Update link description at POS in FILE to NEW-DESCRIPTION.
Works for both bare links [[id:xxx]] and links with
descriptions [[id:xxx][old]]."
(with-current-buffer (find-file-noselect file)
(save-excursion
(goto-char pos)
(cond
;; Link with existing description: [[id:xxx][old]]
((looking-at "\\(\\[\\[id:[^]]+\\]\\)\\[\\([^]]*\\)\\]\\]")
(let ((link-part (match-string 1)))
;; LITERAL (3rd arg) so backslashes in NEW-DESCRIPTION are not
;; interpreted as match-group backreferences.
(replace-match (concat link-part "[" new-description "]]") t t)))
;; Bare link without description: [[id:xxx]]
((looking-at "\\(\\[\\[id:[^]]+\\)\\]\\]")
(let ((link-part (match-string 1)))
(replace-match (concat link-part "][" new-description "]]") t t)))))))
(defun vulpea--default-directory ()
"Return the default directory for creating new notes.
Resolution order:
1. `vulpea-default-notes-directory' if set
2. First directory from `vulpea-db-sync-directories' if set
3. `org-directory' as fallback"
(or vulpea-default-notes-directory
(car vulpea-db-sync-directories)
org-directory))
(defun vulpea--expand-template (template title &optional id context)
"Expand TEMPLATE with TITLE, optional ID, and CONTEXT.
TEMPLATE is a string with placeholders:
${var} - Variable substitution
%(elisp) - Elisp evaluation
%<format> - Timestamp formatting
CONTEXT is a plist of additional variables (e.g., :url \"...\").
Returns expanded string with placeholders replaced.
Built-in variables: ${title}, ${slug}, ${timestamp}, ${id}
Context variables: ${key} for each :key in CONTEXT.
Evaluation order matters for safety: the %(elisp) and %<format>
directives are expanded first, on the template itself, and only
then are ${var} and context values substituted in. Consequently
%(...) and %<...> are honored only when written by the template
author - they are NOT re-evaluated when they appear inside a
substituted value such as TITLE or a CONTEXT value. This keeps
untrusted data (e.g. a note title) from being executed as code.
Note: Does not support %a (annotation) or %i (initial content)
from org-capture as they don't make sense for programmatic creation.
TITLE may be nil (untitled notes, see vulpea#399); a template
referencing ${title} or ${slug} then signals `user-error', since
there is nothing to substitute."
(let* ((slug (when title (vulpea-title-to-slug title)))
(timestamp (format-time-string "%Y%m%d%H%M%S"))
(id (or id (org-id-new)))
(result template))
;; SECURITY: expand the active directives (%(elisp) and %<format>)
;; on the raw template FIRST, before substituting ${var} and context
;; values. The directives are written by the template author and are
;; trusted; the substituted values (note title, slug, id, context)
;; are data and may be untrusted. Substituting first and scanning
;; afterwards would let a value containing "%(...)" be evaluated as
;; code - an arbitrary code execution hazard. Expanding before
;; substitution keeps all substituted data strictly literal.
;; Expand %(elisp) - evaluate elisp expressions
;; Note: save-match-data is critical because eval'd expressions may
;; call functions that do string matching, corrupting our match data
(while (string-match "%\\((.+?)\\)" result)
(let* ((expr (match-string 1 result))
(match-beg (match-beginning 0))
(match-end (match-end 0))
(value (save-match-data
(condition-case err
(eval (car (read-from-string expr)))
(error (format "ERROR: %S" err))))))
(setq result (concat (substring result 0 match-beg)
(format "%s" value)
(substring result match-end)))))
;; Expand %<format> - format timestamps
(while (string-match "%<\\(.+?\\)>" result)
(let* ((format-str (match-string 1 result))
(value (format-time-string format-str)))
(setq result (replace-match value t t result))))
;; Expand ${var} placeholders. Done AFTER directive expansion so
;; substituted values are never re-scanned for %(...) or %<...>.
(if title
(setq result (thread-last result
(s-replace "${title}" title)
(s-replace "${slug}" slug)))
(when (or (s-contains-p "${title}" result)
(s-contains-p "${slug}" result))
(user-error
"Cannot expand %S: ${title} and ${slug} are unavailable for a note without a title; pass an explicit file name or use a title-free template"
template)))
(setq result (thread-last result
(s-replace "${timestamp}" timestamp)
(s-replace "${id}" id)))
;; Expand context variables (treated as literal data, like ${var})
(when context
(let ((ctx context))
(while ctx
(let* ((key (pop ctx))
(val (pop ctx))
(placeholder (format "${%s}" (substring (symbol-name key) 1))))
(setq result (s-replace placeholder (format "%s" val) result))))))
result))
(defun vulpea--expand-file-name-template (title &optional id template context)
"Expand file name template with TITLE, ID, TEMPLATE, and CONTEXT.
If TEMPLATE is nil, uses `:file-name' from `vulpea-create-default-template'.
CONTEXT is a plist of additional template variables.
Returns absolute file path."
(let* ((template (or template
(plist-get vulpea-create-default-template :file-name)
"${slug}.org")) ; Absolute fallback
(template-resolved (if (functionp template)
(funcall template title)
template))
(file-name (vulpea--expand-template template-resolved title id context))
(dir (vulpea--default-directory)))
(expand-file-name file-name dir)))
(defun vulpea--format-note-content (id title &optional head meta tags properties)
"Format note content for `org-capture' template.
ID is required. TITLE may be nil for an untitled note (see
vulpea#399): no `#+title' line is written at all, so extraction
falls back to the file base name with title-source `filename'.
Optional: HEAD, META (alist), TAGS (list), PROPERTIES (alist)."
(string-join
(append
(list
":PROPERTIES:"
(format org-property-format ":ID:" id))
(mapcar
(lambda (prop)
(format org-property-format
(concat ":" (car prop) ":")
(cdr prop)))
properties)
(list ":END:")
(when title
(list (format "#+title: %s" title)))
(when tags
(list (concat "#+filetags: :"
(string-join tags ":")
":")))
(when head (list head))
(when meta
(list "")) ; blank line before meta
(when meta
(mapcar
(lambda (kvp)
(if (listp (cdr kvp))
(mapconcat
(lambda (val)
(concat "- " (car kvp) " :: " (vulpea-buffer-meta-format val)))
(cdr kvp) "\n")
(concat "- " (car kvp) " :: " (vulpea-buffer-meta-format (cdr kvp)))))
meta)))
"\n"))
(defun vulpea-find-create-note (title &optional _props)
"Create a new note with TITLE selected in `vulpea-find'.
Creates a file-level note via `vulpea-create' and returns the
resulting `vulpea-note'. PROPS mirrors the capture properties
argument of `vulpea-insert' CREATE-FN and is currently unused.
This is the default value of `vulpea-find-default-create-fn'."
(vulpea-create title))
;;;###autoload
(cl-defun vulpea-find (&key other-window
filter-fn
candidates-fn
create-fn
require-match
(expand-aliases t))
"Select and find a note.
If OTHER-WINDOW, visit the NOTE in another window.
CANDIDATES-FN is the function to query candidates for selection,
which takes as its argument a filtering function (see FILTER-FN).
Unless specified, `vulpea-find-default-candidates-source' is
used.
FILTER-FN is the function to apply on the candidates, which takes
as its argument a `vulpea-note'. Unless specified,
`vulpea-find-default-filter' is used.
CREATE-FN controls how a new note is created when user selects a
non-existent note (only possible when REQUIRE-MATCH is nil). Like
the CREATE-FN of `vulpea-insert', it is called with two arguments
- the typed title and capture properties (currently always nil).
It should return the created `vulpea-note' to visit, or nil to
skip visiting. Unless specified, `vulpea-find-default-create-fn'
is used.
When REQUIRE-MATCH is nil user may select a non-existent note,
which is then created via CREATE-FN. When non-nil, only existing
notes may be selected.
A note can be selected by typing its id: ids are matchable in
completion (see `vulpea-select-match-ids'), which makes them handy
handles when titles are incidental or absent (vulpea#400).
When EXPAND-ALIASES is non-nil (the default), each note with
aliases will appear multiple times in the completion list - once
for the original title and once for each alias."
(interactive)
(let* ((region-text
(when (region-active-p)
(org-link-display-format
(buffer-substring-no-properties
(set-marker
(make-marker) (region-beginning))
(set-marker
(make-marker) (region-end))))))
(note (vulpea-select-from
"Note"
(funcall
(or
candidates-fn
vulpea-find-default-candidates-source)
(or
filter-fn
vulpea-find-default-filter))
:require-match require-match
:initial-prompt region-text
:expand-aliases expand-aliases)))
(if (vulpea-note-id note)
;; Existing note - visit it
(vulpea-visit note other-window)
;; New note - create it
(when (not require-match)
(let ((new-note (funcall (or create-fn
vulpea-find-default-create-fn)
(vulpea-note-title note)
nil)))
(when new-note
(vulpea-visit new-note other-window)))))))
;;;###autoload
(defun vulpea-find-backlink ()
"Select and find a note linked to current note.
Point lands on the first link pointing back to the current note,
so you see the mention itself instead of the beginning of the
selected note. When the link cannot be found in the buffer (e.g.
the file changed since the last sync), point stays at the note."
(interactive)
(let* ((id (or (org-entry-get nil "ID" t)
(user-error "Current location has no ID property")))
(_ (unless (vulpea-db-get-by-id id)
(user-error
"%s is not a known note" id)))
(backlinks (vulpea-db-query-by-links-some
(list (cons "id" id)))))
(unless backlinks
(user-error "There are no backlinks to the current note"))
(let ((note (vulpea-select-from "Note" backlinks
:require-match t
:expand-aliases t)))
(when (vulpea-note-id note)
(vulpea-visit note)
;; Land on the link itself rather than the beginning of the note
(when (re-search-forward
(format "\\[\\[id:%s[]\\[]" (regexp-quote id))
nil t)
(goto-char (match-beginning 0))
(vulpea--show-context))))))
(defun vulpea--show-context ()
"Reveal the org context around point."
(if (fboundp 'org-fold-show-context)
(org-fold-show-context)
;; Fallback for Org < 9.6; the function is obsolete there but
;; still the correct entry point, so silence the warning.
(with-suppressed-warnings ((obsolete org-show-context))
(org-show-context))))
;;;###autoload
(defun vulpea-visit (note-or-id &optional other-window)
"Visit NOTE-OR-ID.
If OTHER-WINDOW, visit the NOTE in another window."
(let* ((note (if (vulpea-note-p note-or-id)
note-or-id
(vulpea-db-get-by-id note-or-id))))
(unless note
(user-error "Cannot find note with ID: %s"
(if (vulpea-note-p note-or-id)
(vulpea-note-id note-or-id)
note-or-id)))
(let ((file (vulpea-note-path note))
(id (vulpea-note-id note)))
;; Visit the file
(if (or current-prefix-arg other-window)
(find-file-other-window file)
(find-file file))
;; Go to the note position
(if (= (vulpea-note-level note) 0)
;; File-level note: go to beginning
(goto-char (point-min))
;; Heading-level note: search for the ID property
(goto-char (point-min))
(unless (re-search-forward
(format "^[ \t]*:ID:[ \t]+%s[ \t]*$" (regexp-quote id))
nil t)
(user-error "Could not find heading with ID: %s" id))
;; Move to the heading
(org-back-to-heading t))
(vulpea--show-context))))
(defvar vulpea-insert-default-filter nil
"Default filter to use in `vulpea-insert'.")
(defvar vulpea-insert-default-candidates-source #'vulpea-db-query
"Default source to get the list of candidates in `vulpea-insert'.
Must be a function that accepts one argument - optional note
filter function.")
(defvar vulpea-insert-default-create-fn nil
"Default function to create a note in `vulpea-insert'.
When non-nil, used as the CREATE-FN of `vulpea-insert' for a note
that does not exist yet (see its CREATE-FN argument): it is called
with the typed title and capture properties and is responsible for