forked from jkitchin/scimax
-
Notifications
You must be signed in to change notification settings - Fork 0
/
org-db.el
1921 lines (1617 loc) · 63.9 KB
/
org-db.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
;;; Commentary:
;; org-db is used to index org-files into a sqlite database to make searching
;; easier. It is complementary to things like `org-agenda-files'. I have found
;; that `org-agenda' is too slow to deal with large (thousands+) of org-files
;; that are spread all over your directories.
;;
;; It works with a `save-buffer-hook' that runs a function that adds an org-file
;; to a queue for indexing when you save it. The queue is processed whenever
;; Emacs is idle. This is done for performance reasons.
;; 1. org-db parses the org-file which can be slow for large files, and I don't want to wait while working.
;; 2. sqlite can only have one process working on it at a time, so async updates is not a good idea.
;;
;; org-db balances performance and accuracy in a way that works "well enough"
;; for me. There are a number of ways it can be out of sync and inaccurate
;; though. The main way is if files get changed outside of emacs, e.g. by git,
;; cloud drive sync programs, or other users in shared drives, files are moved
;; or renamed, etc. org-db doesn't have a good way to keep up with these kinds
;; of changes. You can use `M-x C-u org-db-refresh' to update all the files in
;; the database.
;;
;; Similarly, org-db will generally not know about files you have never opened.
;;
;; The main entry points for you are:
;; `org-db-headings' actions for headings in the database - default open
;; `org-db-contacts' actions for headings with an EMAIL property - default open
;; `org-db-locations' actions for headings with an ADDRESS property - default open
;; `org-db-files' open a file in the db
;; `org-db-recentf' open a recent file in the db
;; `org-db-links' actions for links in the db
;; `org-db-hashtags' actions for hashtags
;; `org-db-@' actions for @-labels
;; `org-db-properties' searches properties, although I don't find it that useful
;; `org-db-editmarks' searches your editmarks
;; `org-db-email-addresses' finds email addresses in your files.
;; `org-db-src-blocks' search src-blocks
;; `org-db-toggle-org-id' If you want to use org-db to jump to an org-id instead
;; of `org-id-goto'. I find the built-in function to slow for me.
;;
;; Utilities
;; `org-db-index' will prompt you for a directory and index the org-files in that directory. Use a prefix arg to make it recursive.
;; `org-db-clean-db' will prune entries where the file no longer exists.
;; `org-db-reset-db' will clear all the entries from org-db if you want to start over.
;;
;; Advanced usage
;; you can build emacsql queries on org-db to do lots of things.
;;; org-db.el --- An org database
;;; Code:
(require 'cl-lib)
(require 's) ; for s-trim
(require 'org)
(use-package emacsql-sqlite)
(require 'ivy)
(defcustom org-db-root "~/org-db/"
"Root directory for db files."
:type 'directory
:group 'org-db)
(defcustom org-db-name "org-db.sqlite"
"Name of the sqlite database file."
:type 'string
:group 'org-db)
(defcustom org-db-update-functions
'(org-db-update-headlines
org-db-update-links
org-db-update-keywords
org-db-update-src-blocks
org-db-update-hashtags
org-db-update-@-labels
org-db-update-email-addresses
org-db-update-editmarks
org-db-update-targets)
"List of functions to run when updating a file in `org-db'.
Each function takes arguments that are the filename-id, and the
parse tree from `org-element-parse-buffer'. Your function should
delete old data if needed, and insert or update data as needed."
:type '(list function)
:group 'org-db)
;; Make sure we have a directory to store the root in
(unless (file-directory-p org-db-root)
(make-directory org-db-root t))
(defvar org-db nil
"Variable to hold the sqlite connection.")
(defvar org-db-queue '()
"A list of files that need to be updated.")
(defvar org-db-log-file (expand-file-name "org-db.log" org-db-root)
"Path to the log file.")
(defvar org-db-ignore-file-regexps '(".*.gpg$" "\\.dropbox" "*~undo-tree~*")
"A list of regexps of files (including their path) to ignore.")
(defvar org-db-ignore-tags '()
"A list of tags to exclude from the database.")
(defvar org-db-ignore-properties '("RESULT")
"A list of properties to exclude from the database.")
(defvar org-db-ignore-keywords '( )
"A list of keywords to exclude from the database.")
(defvar org-db-debug t
"If non-nil log messages.")
(defvar hashtag-rx (rx (:
;; hashtags begin at beginning of line, a blank, or
;; after these punctuations. I am not sure what the
;; "punctuation" group contains, so I am explicit here
;; to also include the brackets.
(or bol blank (in ",.;:?!(){}[]<>")) (= 1 "#")
(group-n 1
;; hashtags do not start with numbers
;; or # + punctuation or a space
(not (in digit punctuation "#+' "))
;; The rest of the chars cannot be a space or punctuation
(one-or-more
(one-or-more (not (in space punctuation)))
;; the words can be joined by - or _
(zero-or-one (in "-_"))))
;; hashtags end at blanks, end of line or punctuation
(or blank eol punct)))
"Regular expression to match hashtags.")
(defvar @-rx (rx (:
;; @label begin at beginning of line, a blank, or
;; after these punctuations. I am not sure what the
;; "punctuation" group contains, so I am explicit here
;; to also include the brackets.
(or bol blank (in ",.;:?!(){}[]<>")) (= 1 "@")
(group-n 1
;; The rest of the chars cannot be a space or punctuation
(one-or-more
(one-or-more (not (in space punctuation)))
;; the words can be joined by - or _
(zero-or-one (in "-_"))))
;; @labels end at blanks, end of line or punctuation
(or blank eol punct)))
"Regular expression to match @labels.
Maybe not surprisingly, there are a lot of false positives.
Sometimes, this seems to match emails, it matches things like
decorators in Python, etc.")
(defvar email-rx "<?\\([-+_.~a-zA-Z][-+_.~:a-zA-Z0-9]*@[-.a-zA-Z0-9]+\\)>?"
"Regular expression for email addresses.
Adapted from `thing-at-point-email-regexp'.")
(defun org-db-log (format-string &rest args)
"Insert the FORMAT-STRING formatted with ARGS into log file."
(f-append-text
(apply 'format (append (list (concat "%s " format-string "\n\n"))
(list (current-time-string)) args))
'utf-8
org-db-log-file))
(defmacro with-org-db (&rest body)
"Run BODY commands in an org-db context.
Opens the database if needed. BODY should be regular commands.
They can use the variable `org-db' in them. Does not close the
database."
`(progn
(unless (and org-db (emacsql-live-p org-db))
(setq org-db (emacsql-sqlite (expand-file-name org-db-name org-db-root) :debug t)))
,@body))
(org-db-log "Starting org-db")
;; create the tables if we need to.
(with-org-db
(emacsql org-db [:PRAGMA (= foreign_keys 1)])
(emacsql org-db [:create-table :if :not :exists files
([(rowid integer :primary-key)
(filename text :unique)
(md5 text)
(last-updated text)])])
(emacsql org-db [:create-table :if :not :exists tags
([(rowid integer :primary-key)
(tag text :unique)])])
(emacsql org-db [:create-table :if :not :exists properties
([(rowid integer :primary-key)
(property text :unique)])])
(emacsql org-db [:create-table :if :not :exists keywords
([(rowid integer :primary-key)
(keyword text :unique)])])
(emacsql org-db [:create-table :if :not :exists headlines
([(rowid integer :primary-key)
(filename-id integer :not :null)
(title text :not :null)
(level integer :not :null)
(todo-keyword text)
(todo-type text)
archivedp
commentedp
footnote-section-p
(begin integer :not :null)
(tags text)
(priority text)
(scheduled real)
(deadline real)]
(:foreign-key [filename-id] :references files [rowid]
:on-delete :cascade))])
(emacsql org-db [:create-table :if :not :exists headline-tags
([(rowid integer :primary-key)
(headline-id integer)
(tag-id integer)]
(:foreign-key [headline-id] :references headlines [rowid]
:on-delete :cascade)
(:foreign-key [tag-id] :references tags [rowid] :on-delete :cascade))])
(emacsql org-db [:create-table :if :not :exists headline-properties
([(rowid integer :primary-key)
(headline-id integer)
(property-id integer)
(value text)]
(:foreign-key [headline-id] :references headlines [rowid]
:on-delete :cascade)
(:foreign-key [property-id] :references properties [rowid]
:on-delete :cascade))])
(emacsql org-db [:create-table :if :not :exists file-keywords
([(rowid integer :primary-key)
(filename-id integer)
(keyword-id integer)
(value text)
(begin integer)]
(:foreign-key [filename-id] :references files [rowid] :on-delete :cascade)
(:foreign-key [keyword-id] :references keywords [rowid]
:on-delete :cascade))])
(emacsql org-db [:create-table :if :not :exists links
([(rowid integer :primary-key)
(filename-id integer)
(type text)
(path text)
(raw-link text)
(description text)
(search-option text)
(begin integer)]
(:foreign-key [filename-id] :references files [rowid]
:on-delete :cascade))])
;; targets
(emacsql org-db [:create-table :if :not :exists targets
([(rowid integer :primary-key)
(target text :unique)])])
(emacsql org-db [:create-table :if :not :exists file-targets
([(rowid integer :primary-key)
(filename-id integer)
(target-id integer)
(begin integer)]
(:foreign-key [filename-id] :references files [rowid] :on-delete :cascade)
(:foreign-key [target-id] :references targets [rowid]
:on-delete :cascade))])
;; hashtags
(emacsql org-db [:create-table :if :not :exists hashtags
([(rowid integer :primary-key)
(hashtag text :unique)])])
(emacsql org-db [:create-table :if :not :exists file-hashtags
([(rowid integer :primary-key)
(filename-id integer)
(hashtag-id integer)
(begin integer)]
(:foreign-key [filename-id] :references files [rowid] :on-delete :cascade)
(:foreign-key [hashtag-id] :references hashtags [rowid]
:on-delete :cascade))])
;; @labels
(emacsql org-db [:create-table :if :not :exists atlabels
([(rowid integer :primary-key)
(atlabel text :unique)])])
(emacsql org-db [:create-table :if :not :exists file-atlabels
([(rowid integer :primary-key)
(filename-id integer)
(atlabel-id integer)
(begin integer)]
(:foreign-key [filename-id] :references files [rowid] :on-delete :cascade)
(:foreign-key [atlabel-id] :references atlabels [rowid]
:on-delete :cascade))])
;; emails
(emacsql org-db [:create-table :if :not :exists email-addresses
([(rowid integer :primary-key)
(email-address text :unique)])])
;; email-addresses
(emacsql org-db [:create-table :if :not :exists file-email-addresses
([(rowid integer :primary-key)
(filename-id integer)
(email-address-id integer)
(begin integer)]
(:foreign-key [filename-id] :references files [rowid] :on-delete :cascade)
(:foreign-key [email-address-id] :references email-addresses [rowid]
:on-delete :cascade))])
;; editmarks
(emacsql org-db [:create-table :if :not :exists file-editmarks
([(rowid integer :primary-key)
(filename-id integer)
(type text)
(content text)
(begin integer)]
(:foreign-key [filename-id] :references files [rowid] :on-delete :cascade))])
;; src-blocks
(emacsql org-db [:create-table :if :not :exists src-blocks
([(rowid integer :primary-key)
(filename-id integer)
(language text)
(contents text)
(begin integer)]
(:foreign-key [filename-id] :references files [rowid] :on-delete :cascade))]))
(defun org-db-get-filename-id (fname)
"Return the rowid corresponding to FNAME.
Adds FNAME to the database if it doesn't exist."
(with-org-db
(or
;; this is a file in the database
(caar (emacsql org-db [:select rowid :from files
:where (= filename $s1)]
fname))
;; no file found, we add one and get the id.
(prog2
(emacsql org-db [:insert :into files :values [nil $s1 $s2 $s3]]
(buffer-file-name)
(md5 (buffer-string))
nil)
(caar (emacsql org-db [:select (funcall last-insert-rowid)]))))))
(defun org-db-remove-buffer ()
"Remove the current buffer from the database."
(interactive)
(org-db-remove-file (buffer-file-name)))
(defun org-db-remove-file (fname)
"Remove FNAME from the database."
(let* ((filename-id (org-db-get-filename-id fname)))
(when filename-id
(with-org-db
;; delete links
(emacsql org-db [:delete :from links :where (= links:filename-id $s1)] filename-id)
;; keywords
(emacsql org-db [:delete :from file-keywords
:where (= file-keywords:filename-id $s1)]
filename-id)
;; headlines
(emacsql org-db [:delete :from headlines :where (= headlines:filename-id $s1)]
filename-id)
;; and the file
(emacsql org-db [:delete :from files :where (= rowid $s2)] filename-id)
(org-db-log "Removed %s from the database." (buffer-file-name))))))
;; * Update the database for a buffer
;;
;; [2021-09-14 Tue] I refactored this into a sequence of functions that are run
;; in each buffer.
(defun org-db-update-src-blocks (filename-id parse-tree)
"Update the src blocks in the buffer."
(org-db-log "Updating src blocks")
(with-org-db
;; delete old entries
(emacsql org-db [:delete :from src-blocks
:where (= src-blocks:filename-id $s1)]
filename-id)
(org-babel-map-src-blocks nil
(emacsql org-db [:insert :into src-blocks :values [nil $s1 $s2 $s3 $s4]]
filename-id lang body beg-block))))
(defun org-db-update-keywords (filename-id parse-tree)
"Updates the keyword table for the org-buffer.
FILENAME-ID is the rowid for the org-file.
PARSE-TREE is from `org-element-parse-buffer'."
(org-db-log "Updating keywords")
(let ((keywords (org-element-map parse-tree 'keyword
(lambda (kw) (list
(upcase (org-element-property :key kw))
(org-element-property :value kw)
(org-element-property :begin kw)))))
keyword-id)
(with-org-db
;; * File keywords.
(emacsql org-db [:delete :from file-keywords
:where (= file-keywords:filename-id $s1)]
filename-id)
;; For each keyword, get the id or add to the keywords table and get the id.
(cl-loop for (keyword value begin) in keywords
if (not (member keyword org-db-ignore-keywords))
do
(setq keyword-id (or (caar (emacsql org-db [:select rowid :from keywords
:where (= keyword $s1)]
keyword))
(emacsql org-db [:insert :into keywords :values [nil $s1]]
keyword)
(caar (emacsql org-db
[:select (funcall last-insert-rowid)]))))
;; Now add to the file-keywords
(emacsql org-db [:insert :into file-keywords :values [nil $s1 $s2 $s3 $s4]]
filename-id keyword-id value begin)))))
(defun org-db-update-hashtags (filename-id parse-tree)
"Update hashtags in the buffer.
FILENAME-ID is the rowid for the org-file.
PARSE-TREE is from `org-element-parse-buffer'."
(org-db-log "Updating hashtags")
;; "#\\([^0-9!$%^&*+.]\\(\\w+[-_]?\\)+\\)"
(let ((hashtags (save-excursion
(goto-char (point-min))
(let ((hashtags '()))
(while (re-search-forward hashtag-rx nil t)
;; there are many scenarios we do not want to count these.
;; no src-blocks as these are often false matches for comments
;; These are not always reliable as it relies on font-lock
(when (and (not (org-in-src-block-p))
;; these are formulas in org lines sometimes
(not (eq 'org-meta-line (face-at-point)))
(not (save-match-data (equal 'src-block (car (org-element-context))))))
(push (cons (match-string-no-properties 1) (match-beginning 0)) hashtags)))
hashtags)))
hashtag-id)
(with-org-db
;; hashtags
;; first delete existing data on hashtags because it has probably changed.
(emacsql org-db [:delete :from file-hashtags
:where (= file-hashtags:filename-id $s1)]
filename-id)
(cl-loop for (hashtag . pos) in hashtags do
;; get hashtag id
(setq hashtag-id (or (caar (emacsql org-db [:select rowid :from hashtags
:where (= hashtag $s1)]
hashtag))
(emacsql org-db [:insert :into hashtags :values [nil $s1]]
hashtag)
(caar (emacsql org-db
[:select (funcall last-insert-rowid)]))))
(emacsql org-db [:insert :into file-hashtags :values [nil $s1 $s2 $s3]]
filename-id hashtag-id pos)))))
(defun org-db-update-targets (filename-id parse-tree)
"Update the targets table."
(org-db-log "Updating targets")
(with-org-db
;; delete entries from the targets table
(emacsql org-db [:delete :from file-targets :where (= file-targets:filename-id $s1)] filename-id)
(org-element-map parse-tree 'target
(lambda (target)
(let ((target-id (or (caar (emacsql org-db [:select rowid :from targets
:where (= target $s1)]
(org-element-property :value target)))
(emacsql org-db [:insert :into targets :values [nil $s1]]
(org-element-property :value target))
(caar (emacsql org-db
[:select (funcall last-insert-rowid)])))))
(emacsql org-db [:insert :into file-targets :values [nil $s1 $s2 $s3]]
filename-id target-id (org-element-property :begin target)))))))
(defun org-db-update-editmarks (filename-id parse-tree)
"Update the editmarks table in a buffer.
FILENAME-ID is the rowid for the org-file.
PARSE-TREE is from `org-element-parse-buffer'."
(org-db-log "Updating editmarks")
(when (fboundp 'sem-get-editmarks)
(with-org-db
(emacsql org-db [:delete :from file-editmarks
:where (= file-editmarks:filename-id $s1)]
filename-id)
(cl-loop for (em-type buffer (start . end) em-content) in (sem-get-editmarks)
do
(emacsql org-db [:insert :into file-editmarks
:values [nil $s1 $s2 $s3 $s4]]
filename-id
em-type
em-content
start)))))
(defun org-db-update-email-addresses (filename-id parse-tree)
"Update emails table.
FILENAME-ID is the rowid for the org-file.
PARSE-TREE is from `org-element-parse-buffer'."
(org-db-log "Updating email addresses")
(let ((emailaddresses (save-excursion
(goto-char (point-min))
(let ((emailaddresses '()))
(while (re-search-forward email-rx nil t)
;; there are many scenarios we do not want to count these.
;; no src-blocks as these are often false matches for comments
;; These are not always reliable as it relies on font-lock
(when (and (not (org-in-src-block-p))
(not (save-match-data (equal 'src-block (car (org-element-context))))))
(push (cons (match-string-no-properties 1) (match-beginning 0)) emailaddresses)))
emailaddresses)))
email-address-id)
(with-org-db
(emacsql org-db [:delete :from file-email-addresses
:where (= file-email-addresses:filename-id $s1)]
filename-id)
(cl-loop for (email-address . pos) in emailaddresses do
;; get email-address-id
(setq email-address-id (or (caar (emacsql org-db [:select rowid :from email-addresses
:where (= email-address $s1)]
email-address))
(emacsql org-db [:insert :into email-addresses :values [nil $s1]]
email-address)
(caar (emacsql org-db
[:select (funcall last-insert-rowid)]))))
(emacsql org-db [:insert :into file-email-addresses :values [nil $s1 $s2 $s3]]
filename-id email-address-id pos)))))
(defun org-db-update-@-labels (filename-id parse-tree)
"Update @labels.
FILENAME-ID is the rowid for the org-file.
PARSE-TREE is from `org-element-parse-buffer'."
(org-db-log "Updating @-labels")
(let ((atlabels (save-excursion
(goto-char (point-min))
(let ((atlabels '()))
(while (re-search-forward @-rx nil t)
;; there are many scenarios we do not want to count these.
;; no src-blocks as these are often false matches for comments
;; These are not always reliable as it relies on font-lock
(when (and (not (org-in-src-block-p))
;; these are formulas in org lines sometimes
(not (eq 'org-meta-line (face-at-point)))
(not (save-match-data (equal 'src-block (car (org-element-context))))))
(push (cons (match-string-no-properties 1) (match-beginning 0)) atlabels)))
atlabels)))
atlabel-id)
(with-org-db
;; delete existing records
(emacsql org-db [:delete :from file-atlabels
:where (= file-atlabels:filename-id $s1)]
filename-id)
(cl-loop for (atlabel . pos) in atlabels do
;; get atlabel id
(setq atlabel-id (or (caar (emacsql org-db [:select rowid :from atlabels
:where (= atlabel $s1)]
atlabel))
(emacsql org-db [:insert :into atlabels :values [nil $s1]]
atlabel)
(caar (emacsql org-db
[:select (funcall last-insert-rowid)]))))
(emacsql org-db [:insert :into file-atlabels :values [nil $s1 $s2 $s3]]
filename-id atlabel-id pos)))))
(defun org-db-update-links (filename-id parse-tree)
"Update links table.
FILENAME-ID is the rowid for the org-file.
PARSE-TREE is from `org-element-parse-buffer'."
(org-db-log "Updating links")
(let* ((links (org-element-map parse-tree 'link
(lambda (link)
(vector
nil
filename-id
(org-element-property :type link)
(org-element-property :path link)
(org-element-property :raw-link link)
(if (org-element-property :contents-begin link)
(buffer-substring-no-properties
(org-element-property :contents-begin link)
(org-element-property :contents-end link))
"")
(org-element-property :search-option link)
(org-element-property :begin link)))))
;; WHAT IS THIS DOING????
(before-after (-split-at 400 links))
(handle (nth 0 before-after))
(next (nth 1 before-after)))
(with-org-db
;; * delete old links
(emacsql org-db [:delete :from links :where (= links:filename-id $s1)] filename-id)
;; ** add new links
(while handle
(emacsql org-db [:insert :into links :values $v1] handle)
(setq before-after (-split-at 400 next)
handle (nth 0 before-after)
next (nth 1 before-after))))))
(defun org-db-update-headlines (filename-id parse-tree)
"Update headlines table.
FILENAME-ID is the rowid for the org-file.
PARSE-TREE is from `org-element-parse-buffer'."
(org-db-log "Updating headlines")
(let* ((headlines (org-element-map parse-tree 'headline
'identity))
hlv headline-id
tags tag-id
properties property-id
scheduled
deadline)
;; delete old headline data
(with-org-db
(emacsql org-db [:delete :from headlines :where (= headlines:filename-id $s1)]
filename-id))
(cl-loop for hl in headlines do
(save-excursion
(goto-char (org-element-property :begin hl))
(setq tags (mapcar 'org-no-properties (org-get-tags))
properties (org-entry-properties (org-element-property :begin hl) 'all)))
(setq
scheduled (when-let (ts (org-element-property :scheduled hl))
(float-time (org-time-string-to-time
(org-element-property :raw-value ts))))
deadline (when-let (ts (org-element-property :deadline hl))
(float-time (org-time-string-to-time
(org-element-property :raw-value ts)))))
(setq hlv (vector
nil
filename-id
(org-element-property :raw-value hl)
(org-element-property :level hl)
(when (org-element-property :todo-keyword hl)
(substring-no-properties
(org-element-property :todo-keyword hl)))
(org-element-property :todo-type hl)
(org-element-property :archivedp hl)
(org-element-property :commentedp hl)
(org-element-property :footnote-section-p hl)
(org-element-property :begin hl)
;; this is really a tag string for easy searching in
;; ivy because it seems tricky to build this from a
;; query
(when tags
(concat ":" (mapconcat
'substring-no-properties
tags ":")
":"))
;; priority
(if (org-element-property :priority hl)
(char-to-string (org-element-property :priority hl))
nil)
;; scheduled and deadline
scheduled
deadline))
;; insert headline row and get headline-id
(org-db-log "Working on headline: %s" (org-element-property :raw-value hl))
(with-org-db
(emacsql org-db [:insert :into headlines :values $v1] hlv)
(setq headline-id (caar (emacsql org-db
[:select (funcall last-insert-rowid)])))
(org-db-log "Working on headline-id: %s" headline-id))
;; remove old tag data
(with-org-db
(emacsql org-db [:delete :from headline-tags
:where (= headline-tags:headline-id $s1)]
headline-id))
(cl-loop for tag in tags
if (not (member tag org-db-ignore-tags))
do
(setq tag-id
(or (caar (with-org-db (emacsql org-db [:select rowid :from tags
:where (= tag $s1)]
tag)))
(with-org-db
(emacsql org-db [:insert :into tags :values [nil $s1]]
tag)
(caar (emacsql org-db [:select (funcall last-insert-rowid)])))))
(with-org-db
(emacsql org-db [:insert :into headline-tags :values $v1]
(vector nil headline-id tag-id))))
;; properties
(with-org-db
(emacsql org-db [:delete :from headline-properties
:where (= headline-properties:headline-id $s1)]
headline-id))
(setq properties (save-excursion
(goto-char (org-element-property :begin hl))
(org-entry-properties)))
(cl-loop for (property . value) in properties
if (not (member property org-db-ignore-properties))
do
;; get the property-id
(setq property-id
(or
;; we have a property already
(caar
(with-org-db (emacsql org-db [:select rowid :from properties
:where (= property $s1)]
property)))
;; no property, so insert one, and get the rowid
(with-org-db
(emacsql org-db [:insert :into properties
:values [nil $s1]]
property)
(caar (emacsql org-db [:select (funcall last-insert-rowid)])))))
;; and the values
(with-org-db
(emacsql org-db [:insert :into headline-properties
:values [nil $s1 $s2 $s3]]
headline-id
property-id
(org-no-properties value)))))))
;; ** update a buffer
(defun org-db-update-buffer (&optional force)
"Update the entries in the database for the currently visited buffer.
Optional argument FORCE. if non-nil force the buffer to be added."
(interactive "P")
(save-buffer)
(org-with-wide-buffer
(if (or force
(and
;; file does not match an ignore pattern
(and org-db-ignore-file-regexps
(not (string-match (regexp-opt org-db-ignore-file-regexps)
(buffer-file-name))))
;; file is not in database
(null (caar (with-org-db (emacsql org-db [:select [md5] :from files
:where (= filename $s1)]
(buffer-file-name)))))
(org-db-log "update %s is a new file" (buffer-file-name)))
(and
;; file does not match an ignore pattern
(and org-db-ignore-file-regexps
(not (string-match (regexp-opt org-db-ignore-file-regexps)
(buffer-file-name))))
;; file is in database and it has changed, i.e. the md5 is not the same as on record
(not (string= (md5 (buffer-string))
(caar (with-org-db (emacsql org-db [:select [md5] :from files
:where (= filename $s1)]
(buffer-file-name))))))))
(progn
(org-db-log "%s has changed." (buffer-file-name))
(let* ((filename-id (org-db-get-filename-id (buffer-file-name)))
(parse-tree (org-element-parse-buffer)))
;; update the md5 for the file so we can tell later if it has changed.
(with-org-db
(emacsql org-db [:update files :set (= md5 $s1) :where (= rowid $s2)]
(md5 (buffer-string)) filename-id))
(cl-loop for update-func in org-db-update-functions do
(funcall update-func filename-id parse-tree))
(with-org-db
(emacsql org-db [:update files :set (= last-updated $s1) :where (= rowid $s2)]
(format-time-string "%Y-%m-%d %H:%M:%S") filename-id))))
(org-db-log "no change detected"))))
;; * the hooks
(use-package pcache)
(defun org-db-hook-function ()
"Function to run after starting ‘org-mode’."
;; Run when we open in case it changed from some external program. Only for
;; org and org_archive files, and not just when we enter org-mode for some
;; reason.
(when (and (buffer-file-name)
(or (f-ext? (buffer-file-name) "org")
(f-ext? (buffer-file-name) "org_archive")))
(add-to-list 'org-db-queue (buffer-file-name) t)
(org-db-log "added %s to the queue." (buffer-file-name))
;; persistent cache. [2022-12-22 Thu] I am not sure we use this.
(let ((repo (pcache-repository :file "org-db-queue")))
(pcache-put repo 'org-db-queue org-db-queue))
;; add local after save hook in case this is a new file.
(add-hook 'after-save-hook 'org-db-hook-function t t)))
(add-hook 'org-mode-hook 'org-db-hook-function)
(let ((repo (pcache-repository :file "org-db-queue")))
(pcache-get repo 'org-db-queue))
;; * Idle timer to update
(defun org-db-process-queue (&optional force)
"Update all the files in `org-db-queue'.
Use a prefix ARG to FORCE the process instead of waiting for idle time."
(interactive "P")
(with-org-db
(catch 'done
(while org-db-queue
(unless (or force (current-idle-time))
(throw 'done nil))
(org-db-log "Updating org-db for files %s." org-db-queue)
(let* ((filename (pop org-db-queue))
(org-mode-hook '())
(enable-local-variables nil)
(already-open (find-buffer-visiting filename))
(buf (find-file-noselect filename)))
(org-db-log "Updating %s" filename)
(with-current-buffer buf
(org-db-update-buffer force))
(unless already-open (kill-buffer buf)))))
(org-db-log "Done processing org-db queue.")
;; [2022-12-02 Fri] I still don't have a good solution for shutting this
;; down. it didn't seem reliable to open and close it all the time. I have a
;; residual issue on startup where it is not open for some reason.
;;
;; close the org-db. The idea here is to shut it down when idle, and after
;; updating. Usually this means I am not working on this machine, and may be
;; working on another machine. It isn't a big deal to open the connection,
;; and it stays open while working. This way if you switch machines, it
;; should shut down, so the other machine won't have a conflict. It won't be
;; perfect, but I think it will be better.
;; (emacsql-close org-db)
;; (emacsql-close org-db)
;; (setq org-db nil)
))
;; if we are idle for 5 minutes, process the queue.
(setq org-db-timer (run-with-idle-timer (* 60 5) t 'org-db-process-queue))
(defun org-db-status ()
"Print a message of files scheduled for update."
(interactive)
(org-db-log "Files in queue for update: %s" org-db-queue)
(switch-to-buffer "*org-db-log*"))
;; * Update the whole database
(defun swap (LIST el1 el2)
"in LIST swap indices EL1 and EL2 in place"
(cl-psetf (elt LIST el2) (elt LIST el1)
(elt LIST el1) (elt LIST el2)))
(defun shuffle (LIST)
"Shuffle the elements in LIST.
Used to randomize the order. Shuffling is done in place."
(cl-loop for i in (reverse (number-sequence 1 (1- (length LIST))))
do (let ((j (random (+ i 1))))
(swap LIST i j)))
LIST)
(defun org-db-refresh (&optional force)
"Update all the files in the database.
Updates are done by `org-db-update-buffer'.
Use a prefix arg to FORCE updates."
(interactive "P")
(let* ((files)
(N)
(enable-local-variables nil)
(org-mode-hook '())
buf already-open
md5)
(with-org-db
;; (setq files (emacsql org-db [:select [filename] :from files :order-by last-updated :desc])
;; N (length files))
(setq files (emacsql org-db [:select [filename] :from files])
N (length files)))
(org-db-log "refresh %s Refreshing %s files" (current-time-string) N)
;; Shuffle the files so they are randomly updated. In case an early file
;; fails a lot, this increases the likely hood of getting past it.
(cl-loop for (fname) in (shuffle files) for i from 0 to N
if (and fname (file-exists-p fname))
do
(org-db-log "refresh Refreshing %s of %s (%s)" i N fname)
(unless (string=
(setq md5 (s-trim (shell-command-to-string
(format "md5sum %s | cut -c -32" fname))))
(caar (with-org-db (emacsql org-db [:select [md5] :from files
:where (= filename $s1)]
fname))))
(with-timeout (60 (org-db-log "refresh ERROR: Timed out refreshing %s." fname))
(setq already-open (find-buffer-visiting fname))
(setq buf (find-file-noselect fname))
(with-current-buffer buf
(condition-case err
(org-db-update-buffer force)
(org-db-log "refresh ERROR updating %s: %s" fname err)))
(unless already-open (kill-buffer buf))))
else
do
(org-db-log "refresh %s not found. Deleting from the database." fname)
(with-org-db
(emacsql org-db [:delete :from files :where (= filename $s1)] fname)))))
(defun org-db-index (path &optional recursive)
"Index all the org-files in PATH.
Optional RECURSIVE is non-nil find files recursively."
(interactive (list (read-directory-name "Path: ")
current-prefix-arg))
(let* ((enable-local-variables nil)
(org-mode-hook '())
already-open buf
(files (f-files path (lambda (f)
(and (or (f-ext? f "org")
;; I am not sure we should index these.
;; (f-ext? f "org_archive")
)
(and org-db-ignore-file-regexps
(not (string-match (regexp-opt org-db-ignore-file-regexps)
f)))))
recursive))
(N (length files)))
(cl-loop for fname in files
for i from 1
do
(org-db-log "index %s of %s - %s" i N fname)
(setq already-open (find-buffer-visiting fname))
(with-current-buffer (or already-open (setq buf (find-file-noselect fname)))
(condition-case err
(org-db-update-buffer)
(org-db-log "index ERROR updating %s: %s" fname err)))
(unless already-open (kill-buffer buf)))))