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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
|
;;; elel.el --- Front end for the elel notes engine -*- lexical-binding: t; -*-
;; Copyright (C) 2026 Durand
;; Author: Durand
;; Keywords: outlines, files
;; Package-Requires: ((emacs "27.1"))
;; 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:
;; This is the Emacs side of elel. The engine (a Rust program in the
;; same directory) reads the note files and keeps an index; this file
;; only shows what the engine reports and helps to write notes.
;;
;; The interface follows Gnus:
;;
;; Group buffer -> the views buffer, M-x elel
;; Summary buffer -> the summary buffer, threaded by Parent
;; Article buffer -> the article buffer, the note as it is in its
;; file, in the major mode of its file, with the
;; minor mode `elel-article-mode' on top
;;
;; The summary and the article are shown together; close either.
;; The engine never writes to the note files. Creating notes and
;; adding missing IDs is done here.
;;; Code:
(require 'cl-lib)
(require 'subr-x)
(require 'button)
(require 'outline)
(require 'rx)
(require 'hl-line)
(declare-function org-link-set-parameters "ol" (type &rest parameters))
(declare-function org-entry-get "org" (epom property &optional inherit literal-nil))
(defvar elel-article-id)
(defvar elel-capture-id)
(declare-function org-next-link "org" (&optional search-backward))
(declare-function org-previous-link "org" ())
(declare-function org-fold-hide-drawer-all "org-fold" ())
(declare-function org-hide-drawer-all "org" ())
(declare-function org-open-at-point "org" (&optional arg))
(declare-function org-back-to-heading "org" (&optional invisible-ok))
(declare-function org-entry-get "org" (pom property &optional inherit literal-nil))
;;; Customization
(defgroup elel nil
"A notes system with full-text search and links."
:group 'applications
:prefix "elel-")
(defconst elel--directory
(file-name-directory (or load-file-name buffer-file-name default-directory))
"The directory of this file.")
(defcustom elel-root (expand-file-name "~/notes")
"The directory that holds the note files."
:type 'directory)
(defcustom elel-index-directory nil
"The directory of the derived index.
If nil, the engine chooses its own default."
:type '(choice (const :tag "Engine default" nil) directory))
(defcustom elel-program
(let ((release (expand-file-name "target/release/elel" elel--directory))
(debug (expand-file-name "target/debug/elel" elel--directory)))
(cond
((file-executable-p release) release)
((file-executable-p debug) debug)
((executable-find "elel"))
("elel")))
"The engine executable."
:type 'file)
(defcustom elel-capture-file "inbox.org"
"The file, relative to `elel-root', where new notes are written.
The extension decides the format: \".org\" or \".txt\"."
:type 'string)
(defcustom elel-auto-index t
"If non-nil, update the index after saving a file under `elel-root'."
:type 'boolean)
(defcustom elel-id-function #'elel-generate-id
"The function that makes the ID of a new note."
:type 'function)
(defcustom elel-views
(list
(list "Inbox" "is:inbox")
(list "Recent" "" :limit 30)
(list "All" ""))
"The views listed in the views buffer, like the groups of Gnus.
Each element is (NAME QUERY . PLIST). QUERY is a search query (see
the README), and PLIST may have these properties:
:limit N show at most N notes;
:hidden t list the view only after \\`L' (list all views).
Views for a tag or a file are just entries such as
(\"Math\" \"tag:math\") or (\"Journal\" \"file:journal\" :hidden t)."
:type '(repeat (cons string (cons string plist))))
(defcustom elel-major-mode-alist
(list (cons (rx-to-string (list 'seq ".org" 'eos) t) 'org-mode)
(cons (rx-to-string (list 'seq 'any) t) 'text-mode))
"Alist of (REGEXP . MODE): the major mode for showing a note.
The first REGEXP that matches the file name of the note decides."
:type '(alist :key-type regexp :value-type function))
(defcustom elel-summary-window-height 0.3
"The fraction of the height that the summary window keeps.
It applies when an article window is made below the summary."
:type 'number)
(defcustom elel-article-keep-summary t
"Non-nil to show the article below the summary.
If nil, the article replaces the summary window; press \\`h' in the
article to go back to the summary."
:type 'boolean)
(defcustom elel-thread-root ""
"What to draw before the title of a note without a parent."
:type 'string)
(defcustom elel-thread-false-root "─┬> "
"What to draw before a note whose parent is not in the summary."
:type 'string)
(defcustom elel-thread-indent " "
"What to draw under a note that has no younger siblings."
:type 'string)
(defcustom elel-thread-vertical "│"
"What to draw under a note that has younger siblings."
:type 'string)
(defcustom elel-thread-leaf-with-other "├─> "
"What to draw before a note that has younger siblings."
:type 'string)
(defcustom elel-thread-single-leaf "└─> "
"What to draw before a note that is the last child of its parent."
:type 'string)
;;; Faces
(defface elel-title
'((t :weight bold))
"Face of note titles.")
(defface elel-mark
'((t :inherit font-lock-warning-face :weight bold))
"Face of the mark column of the summary buffer."
:group 'elel)
(defcustom elel-suggest-after-capture t
"Non-nil means a new note is followed by suggestions of links and tags."
:type 'boolean
:group 'elel)
(defcustom elel-suggest-limit 15
"How many notes to suggest."
:type 'integer
:group 'elel)
(defface elel-date
'((t :inherit shadow))
"Face of dates.")
(defface elel-tag
'((t :inherit font-lock-type-face))
"Face of tags.")
(defface elel-hit
'((t :inherit highlight))
"Face of the words that matched a search.")
(defface elel-thread
'((t :inherit shadow))
"Face of the lines that draw the threads.")
(defface elel-heading
'((t :inherit font-lock-keyword-face :weight bold))
"Face of section headings.")
;;; Talking to the engine
(defun elel--environment ()
"The process environment for running the engine."
(append
(list (concat "ELEL_ROOT=" (expand-file-name elel-root)))
(cond
(elel-index-directory
(list (concat "ELEL_INDEX=" (expand-file-name elel-index-directory)))))
process-environment))
(defun elel--parse-lines ()
"Parse the JSON objects, one per line, in the current buffer."
(goto-char (point-min))
(let (objects)
(while (not (eobp))
(cond
((eq (char-after) ?{)
(push (json-parse-buffer :object-type 'alist
:array-type 'list
:null-object nil
:false-object nil)
objects))
((forward-line 1))))
(nreverse objects)))
(defun elel--call (&rest args)
"Run the engine with ARGS. Return the list of objects it prints."
(let ((process-environment (elel--environment))
(coding-system-for-read 'utf-8)
(coding-system-for-write 'utf-8))
(with-temp-buffer
(let ((status (apply #'call-process elel-program nil t nil args)))
(cond
((eq status 0) (elel--parse-lines))
((user-error "elel: %s" (string-trim (buffer-string)))))))))
(defvar elel--index-process nil
"The running asynchronous index process, if any.")
(defvar elel--index-pending nil
"Non-nil if another index was requested while one was running.")
(defun elel-index ()
"Update the index now, and wait for it."
(interactive)
(let ((r (car (elel--call "index"))))
(message "elel: %d files, %d notes (%d changed, %d removed)"
(alist-get 'files r) (alist-get 'notes r)
(alist-get 'changed r) (alist-get 'removed r))
r))
(defvar elel--index-callbacks nil
"Functions to call once the running index has finished.")
(defun elel-index-async ()
"Update the index in the background."
(interactive)
(cond
((process-live-p elel--index-process)
(setq elel--index-pending t))
(t
(let ((process-environment (elel--environment))
(buffer (generate-new-buffer " *elel-index*")))
(setq elel--index-pending nil)
(setq elel--index-process
(make-process
:name "elel-index"
:buffer buffer
:command (list elel-program "index")
:connection-type 'pipe
:noquery t
:sentinel
(lambda (process _event)
(cond
((not (process-live-p process))
(let ((ok (eq (process-exit-status process) 0))
(out (with-current-buffer (process-buffer process)
(string-trim (buffer-string)))))
(kill-buffer (process-buffer process))
(cond
((not ok)
(setq elel--index-callbacks nil)
(message "elel: indexing failed: %s" out))
(elel--index-pending (elel-index-async))
(t (elel--run-index-callbacks)))))))))))))
(defun elel--run-index-callbacks ()
"Call and forget the functions waiting for the index."
(let ((callbacks (nreverse elel--index-callbacks)))
(setq elel--index-callbacks nil)
(dolist (f callbacks)
(condition-case err
(funcall f)
(error (message "elel: %s" (error-message-string err)))))))
(defun elel--maybe-index ()
"Index after saving a file under `elel-root'."
(cond
((and elel-auto-index
buffer-file-name
(string-prefix-p
(file-name-as-directory (expand-file-name elel-root))
(expand-file-name buffer-file-name)))
(elel-index-async))))
(add-hook 'after-save-hook #'elel--maybe-index)
;;; Rendering helpers
(defun elel--field (note key)
"The value of KEY in NOTE."
(alist-get key note))
(defun elel--short-date (note)
"The date of NOTE, cut to ten characters."
(let ((d (elel--field note 'date)))
(cond
((stringp d) (substring d 0 (min 10 (length d))))
((make-string 10 ?\s)))))
(defun elel--tags (note)
"The tags of NOTE as a propertized string."
(let ((tags (elel--field note 'tags)))
(cond
(tags (propertize (concat ":" (mapconcat #'identity tags ":") ":")
'face 'elel-tag))
(""))))
(defun elel--fontify-snippet (string)
"Turn the highlight markers of the engine in STRING into faces."
(with-temp-buffer
(insert string)
(goto-char (point-min))
(while (search-forward (string #xe000) nil t)
(let ((beg (match-beginning 0)))
(delete-region beg (point))
(cond
((search-forward (string #xe001) nil t)
(let ((end (match-beginning 0)))
(delete-region end (point))
(put-text-property beg end 'face 'elel-hit))))))
(buffer-string)))
;;; Asking the engine for notes
(defun elel--get (id)
"The engine's answer for the note ID.
If the files moved since the last index, update the index and retry."
(condition-case err
(car (elel--call "get" id))
(user-error
(cond
((string-match-p "index out of date" (error-message-string err))
(elel-index)
(car (elel--call "get" id)))
((signal (car err) (cdr err)))))))
(defun elel--quote-id (id)
"ID, quoted if needed to be the value of a filter in a query."
(cond
((string-match-p "[ \t\"]" id) (concat "\"" id "\""))
(id)))
(defun elel--filter (key id)
"The query term that selects with KEY (such as \"thread\") the note ID."
(concat key ":" (elel--quote-id id)))
(defcustom elel-hybrid-search t
"Non-nil means a search also ranks by meaning.
The words of the query are embedded and the result is fused with the
text search. If Ollama is not running, only the text search is used."
:type 'boolean
:group 'elel)
(defun elel--search (query &optional limit)
"The notes matching QUERY, at most LIMIT (default: all)."
(apply #'elel--call "search" "-n" (number-to-string (or limit 1000000))
(append (and elel-hybrid-search
(not (string-empty-p (string-trim (or query ""))))
(list "--hybrid"))
(list "--" (or query "")))))
(defun elel--counts (queries)
"The number of notes matching each of QUERIES."
(mapcar (lambda (o) (alist-get 'count o))
(apply #'elel--call "count" "--" queries)))
;;; Threads
(defun elel--thread (notes)
"Order NOTES so that each child follows its parent.
Return a list of (NOTE PREFIX CONTINUATION), where PREFIX is the
drawing in front of the title (see `elel-thread-root' and friends) and
CONTINUATION is what to put in front of a further line of the note. A
note whose parent is not among NOTES is a root."
(let ((ids (mapcar (lambda (n) (elel--field n 'id)) notes))
(kids (make-hash-table :test 'equal))
(seen (make-hash-table :test 'equal))
roots out)
(dolist (n notes)
(let ((p (elel--field n 'parent)))
(cond
((and p (member p ids) (not (equal p (elel--field n 'id))))
(puthash p (cons n (gethash p kids)) kids))
((push n roots)))))
(cl-labels
((walk (n depth ancestors lastp)
(let ((id (elel--field n 'id)))
(cond
((gethash id seen))
(t
(puthash id t seen)
(let* ((leaf (cond
((= depth 0)
(cond
((elel--field n 'parent) elel-thread-false-root)
(elel-thread-root)))
(lastp elel-thread-single-leaf)
(elel-thread-leaf-with-other)))
(kids-of (cl-remove-if
(lambda (c) (gethash (elel--field c 'id) seen))
(reverse (gethash id kids))))
(below (cond
((= depth 0) "")
(t (concat ancestors
(cond
(lastp elel-thread-indent)
(elel-thread-vertical)))))))
(push (list n
(concat (cond ((= depth 0) "") (ancestors)) leaf)
(concat (cond ((= depth 0) "") (ancestors))
(make-string (string-width leaf) ?\s)))
out)
(let ((rest kids-of))
(while rest
(walk (car rest) (1+ depth) below (null (cdr rest)))
(setq rest (cdr rest))))))))))
(dolist (r (nreverse roots)) (walk r 0 "" t))
;; Notes caught in a cycle of parents have no root.
(dolist (n notes) (walk n 0 "" t)))
(nreverse out)))
;;; The summary buffer
(defconst elel--summary-buffer-name "*elel summary*")
(defconst elel--article-buffer-name "*elel article*")
(defvar-local elel-summary-title nil
"The title of this summary buffer.")
(defvar-local elel-summary-query nil
"The query of this summary buffer, or nil if it has a function.")
(defvar-local elel-summary-limit nil
"The maximum number of notes of the query, or nil.")
(defvar-local elel-summary-function nil
"A function that returns the notes of this summary, instead of a query.")
(defvar-local elel-summary-extra nil
"Queries whose notes are added to this summary (see `elel-summary-refer-thread').")
(defvar-local elel-summary-threaded t
"Non-nil if the notes are threaded by their parents.")
(defvar-local elel-summary-show-snippets nil
"Non-nil if snippets are shown below the notes.")
(defvar-local elel-summary-marks nil
"Alist of (ID . CHAR) for the marked notes: ?+ is liked, ?- is disliked.")
(defvar-local elel-summary-insert-marker nil
"Where `elel-summary-insert-link' puts the link, a marker, or nil.")
(defvar elel-search-history nil
"History of search queries.")
(defvar elel-summary-mode-map (make-sparse-keymap)
"Keymap of `elel-summary-mode'.")
;; Filled in separately, so that loading this file again updates the keys.
(let ((map elel-summary-mode-map))
(set-keymap-parent map special-mode-map)
(define-key map (vector ?\r) #'elel-summary-open)
(define-key map (vector ?\s) #'elel-summary-scroll-up)
(define-key map (vector ?\d) #'elel-summary-scroll-down)
(define-key map (vector ?n) #'elel-summary-next)
(define-key map (vector ?p) #'elel-summary-previous)
(define-key map (vector ?g) #'elel-summary-show-article)
(define-key map (vector ?s) #'elel-summary-toggle-snippets)
(define-key map (vector ?/) #'elel-summary-narrow)
(define-key map (vector ?G) #'elel-search)
(define-key map (vector ?a) #'elel-summary-refer-thread)
(define-key map (vector ?^) #'elel-summary-parent)
(define-key map (vector ?c) #'elel-summary-children)
(define-key map (vector ?o) #'elel-summary-outlinks)
(define-key map (vector ?b) #'elel-summary-backlinks)
(define-key map (vector ?H) #'elel-summary-hood)
(define-key map (vector ?e) #'elel-summary-edit)
(define-key map (vector ?r) #'elel-summary-new-child)
(define-key map (vector ?N) #'elel-new-note)
(define-key map (vector ?#) #'elel-summary-mark-like)
(define-key map (vector ?-) #'elel-summary-mark-unlike)
(define-key map (vector ?R) #'elel-summary-related)
(define-key map (vector ?S) #'elel-suggest)
(define-key map (vector ?i) #'elel-summary-insert-link)
(define-key map (vector ?=) #'elel-summary-expand-window)
(define-key map (vector ?A) #'elel-summary-select-article-buffer)
(define-key map (vector ?q) #'elel-summary-quit))
(define-derived-mode elel-summary-mode special-mode "elel-summary"
"Major mode for a list of notes, like a Gnus summary buffer.
\\{elel-summary-mode-map}"
(setq truncate-lines t)
(hl-line-mode 1)
(setq-local revert-buffer-function
(lambda (&rest _) (elel-summary-refresh))))
(defun elel--id-at-point ()
"The ID of the note at point, in a summary buffer."
(or (get-text-property (point) 'elel-id)
(user-error "No note here")))
(defun elel--note-at-point ()
"The note at point, in a summary buffer."
(or (get-text-property (point) 'elel-note)
(user-error "No note here")))
(defun elel--insert-note-line (entry show-snippets)
"Insert the lines of ENTRY, an element of the value of `elel--thread'."
(let* ((note (nth 0 entry))
(prefix (nth 1 entry))
(continuation (nth 2 entry))
(beg (point))
(rel (elel--field note 'rel))
(score (elel--field note 'score))
(back (elel--field note 'backlinks))
(snippet (elel--field note 'snippet)))
(insert
(propertize (string (or (alist-get (elel--field note 'id) elel-summary-marks
nil nil #'equal)
?\s))
'face 'elel-mark)
(propertize (elel--short-date note) 'face 'elel-date)
" "
(cond
(rel (propertize (format "%-8s " rel) 'face 'elel-date))
(""))
(propertize prefix 'face 'elel-thread)
(propertize (elel--field note 'title) 'face 'elel-title)
" " (elel--tags note)
(cond
((and (numberp back) (> back 0))
(propertize (format " ←%d" back) 'face 'elel-date))
(""))
(cond
(score (propertize (format " %.2f" score) 'face 'elel-date))
(""))
"\n")
(cond
((and show-snippets snippet)
(insert (make-string 13 ?\s)
(propertize continuation 'face 'elel-thread)
(elel--fontify-snippet snippet) "\n")))
(put-text-property beg (point) 'elel-id (elel--field note 'id))
(put-text-property beg (point) 'elel-note note)))
(defun elel--summary-notes ()
"The notes of the current summary buffer, asked of the engine."
(let ((notes (cond
(elel-summary-function (funcall elel-summary-function))
(t (elel--search elel-summary-query elel-summary-limit)))))
(dolist (q elel-summary-extra)
(dolist (n (elel--search q))
(unless (cl-find (elel--field n 'id) notes
:key (lambda (x) (elel--field x 'id))
:test #'equal)
(setq notes (append notes (list n))))))
notes))
(defun elel--render-summary (notes)
"Show NOTES in the current summary buffer."
(let ((inhibit-read-only t)
(id (get-text-property (point) 'elel-id))
(line (line-number-at-pos)))
(erase-buffer)
(insert (propertize (or elel-summary-title "Notes") 'face 'elel-heading)
(format " (%d)\n\n" (length notes)))
(dolist (entry (cond
(elel-summary-threaded (elel--thread notes))
((mapcar (lambda (n) (list n "" "")) notes))))
(elel--insert-note-line entry elel-summary-show-snippets))
(goto-char (point-min))
(cond
((and id (elel--goto-note id)))
((forward-line (max 2 (1- line)))))))
(defun elel--goto-note (id)
"Move to the line of the note ID in this summary buffer.
Return non-nil if it is there."
(let ((pos (point-min))
found)
(while (and (not found)
(setq pos (next-single-property-change pos 'elel-id)))
(cond
((equal (get-text-property pos 'elel-id) id)
(goto-char pos)
(setq found t))))
found))
(defun elel--summary-buffer ()
"The summary buffer, or nil."
(get-buffer elel--summary-buffer-name))
(cl-defun elel--show-summary (title &key query limit function (threaded t) quiet)
"Show a summary buffer named TITLE and select its window.
The notes are those of the QUERY (at most LIMIT of them), or the value
of FUNCTION. THREADED says whether to thread them. With QUIET, only
display the buffer, and leave the selection alone."
(let ((buffer (get-buffer-create elel--summary-buffer-name)))
(with-current-buffer buffer
(elel-summary-mode)
(let ((inhibit-read-only t)) (erase-buffer))
(setq elel-summary-title title)
(setq elel-summary-query query)
(setq elel-summary-limit limit)
(setq elel-summary-function function)
(setq elel-summary-threaded threaded)
(let ((notes (elel--summary-notes)))
(setq elel-summary-show-snippets
(and (seq-some (lambda (n) (elel--field n 'snippet)) notes) t))
(elel--render-summary notes)))
(let ((window (get-buffer-window buffer)))
(cond
(quiet (display-buffer buffer))
(window (select-window window))
(t (switch-to-buffer buffer))))
buffer))
(defun elel-summary-refresh ()
"Ask the engine again and redraw."
(interactive)
(elel--render-summary (elel--summary-notes)))
(defun elel-summary-toggle-snippets ()
"Show or hide the snippets."
(interactive)
(setq elel-summary-show-snippets (not elel-summary-show-snippets))
(elel-summary-refresh))
(defun elel-summary-show-article ()
"Show the note at point again, read fresh from its file, like Gnus's \`g'.
The summary stays as it is; search again (\`G') or use `revert-buffer' to
refresh it."
(interactive)
(elel--show-article (elel--id-at-point)))
(defun elel-summary-open ()
"Show the note at point in the article window."
(interactive)
(elel--show-article (elel--id-at-point)))
(defun elel-summary-expand-window (&optional arg)
"Make the summary window take up the whole frame, like Gnus's `='.
This works from the article window too: the summary is what expands.
With a prefix argument ARG, go back to the summary and article layout,
showing the note at point (or else the note last shown)."
(interactive "P")
(let* ((summary (or (elel--summary-buffer) (user-error "No summary")))
(article (get-buffer elel--article-buffer-name))
(id (or (cond
((eq (current-buffer) summary)
(get-text-property (point) 'elel-id))
((bound-and-true-p elel-article-mode) elel-article-id))
(and article (buffer-local-value 'elel-article-id article))))
(window (get-buffer-window summary)))
(cond
(window (select-window window))
((switch-to-buffer summary)))
(delete-other-windows)
(cond
((not arg))
(id (elel--show-article id))
((message "No note to show")))))
(defun elel-summary-select-article-buffer ()
"Select the article window, like `gnus-summary-select-article-buffer'.
If the article is not shown (say, after `elel-summary-expand-window'),
show it again first. If there is no article yet, show the note at point."
(interactive)
(let ((buffer (get-buffer elel--article-buffer-name))
(window (elel--article-visible-window)))
(cond
((null buffer) (elel--show-article (elel--id-at-point) nil t))
(window (select-window window))
(t
(let ((new (elel--article-window)))
(set-window-buffer new buffer)
(select-window new))))))
(defun elel--article-visible-window ()
"The window that shows the article buffer, or nil."
(get-buffer-window elel--article-buffer-name))
(defun elel-summary-scroll-up ()
"Scroll the article; at its end, show the next note."
(interactive)
(let ((window (elel--article-visible-window)))
(cond
((null window) (elel-summary-open))
(t
(condition-case nil
(with-selected-window window (scroll-up-command))
(end-of-buffer (elel-summary-next)))))))
(defun elel-summary-scroll-down ()
"Scroll the article backward."
(interactive)
(let ((window (elel--article-visible-window)))
(cond
((null window) (user-error "No article"))
((condition-case nil
(with-selected-window window (scroll-down-command))
(beginning-of-buffer (message "Beginning of the note")))))))
(defun elel--move-to-note (step)
"Move STEP (1 or -1) notes in this summary buffer. Return non-nil if moved."
(let ((start (point))
found)
(while (and (not found)
(zerop (forward-line step))
(not (eobp)))
(cond
((get-text-property (point) 'elel-id)
(let ((here (get-text-property (point) 'elel-id))
(there (get-text-property start 'elel-id)))
(cond
((not (equal here there)) (setq found t)))))))
(cond
(found
;; Land on the first line of the note.
(beginning-of-line)
(while (and (> (point) (point-min))
(equal (get-text-property (1- (point)) 'elel-id)
(get-text-property (point) 'elel-id)))
(forward-line -1)))
((goto-char start)))
found))
(defun elel-summary-next ()
"Show the next note."
(interactive)
(cond
((not (get-text-property (point) 'elel-id))
(goto-char (point-min))
(cond ((next-single-property-change (point) 'elel-id)
(goto-char (next-single-property-change (point) 'elel-id))
(elel-summary-open))))
((elel--move-to-note 1) (elel-summary-open))
((message "No more notes"))))
(defun elel-summary-previous ()
"Show the previous note."
(interactive)
(cond
((elel--move-to-note -1) (elel-summary-open))
((message "No previous note"))))
(defun elel-summary-narrow (query)
"Search again, with QUERY, which starts as the current query."
(interactive
(list (read-string "Limit to: "
(cond
(elel-summary-query (concat elel-summary-query " "))
(""))
'elel-search-history)))
(elel--show-summary (format "Search: %s" query) :query query :threaded nil))
;;; Related notes and suggestions (the semantic side)
(defun elel--set-mark (char)
"Toggle the mark CHAR on the note at point, then go to the next note."
(let* ((id (elel--id-at-point))
(note (get-text-property (point) 'elel-note))
(old (alist-get id elel-summary-marks nil nil #'equal)))
(setf (alist-get id elel-summary-marks nil t #'equal)
(cond ((eq old char) nil) (char)))
(let ((inhibit-read-only t))
(save-excursion
(goto-char (line-beginning-position))
(delete-char 1)
(insert (propertize (string (or (alist-get id elel-summary-marks
nil nil #'equal)
?\s))
'face 'elel-mark 'elel-id id 'elel-note note))))
(elel--move-to-note 1)))
(defun elel-summary-mark-like ()
"Mark the note at point as one that the wanted notes resemble."
(interactive)
(elel--set-mark ?+))
(defun elel-summary-mark-unlike ()
"Mark the note at point as one that the wanted notes should not resemble."
(interactive)
(elel--set-mark ?-))
(defun elel--related-query (positive negative)
"The query for the notes like those of IDs POSITIVE and unlike NEGATIVE."
(mapconcat #'identity
(append (mapcar (lambda (id) (format "like:\"%s\"" id)) positive)
(mapcar (lambda (id) (format "-like:\"%s\"" id)) negative))
" "))
(defun elel--related (positive negative)
"Show the notes like those of IDs POSITIVE and unlike NEGATIVE."
(elel--show-summary "Related"
:query (elel--related-query positive negative)
:limit 30 :threaded nil))
(defun elel-summary-related ()
"Show the notes closest in meaning to the marked notes.
Notes marked with \\`#' count for, notes marked with \\`-' count against.
If none is marked, use the note at point."
(interactive)
(let (positive negative)
(dolist (m elel-summary-marks)
(cond
((eq (cdr m) ?+) (push (car m) positive))
((eq (cdr m) ?-) (push (car m) negative))))
(cond
((null positive) (setq positive (list (elel--id-at-point)))))
(elel--related positive negative)))
(defun elel-article-related ()
"Show the notes closest in meaning to this note."
(interactive)
(elel--related (list elel-article-id) nil))
(defun elel--suggested-tags (id)
"The tags that fit the note ID best and that it does not have yet."
(let (tags)
(dolist (x (elel--call "tags" "--like" id))
(cond
((and (not (alist-get 'has x)) (< (length tags) 5))
(push (alist-get 'tag x) tags))))
(nreverse tags)))
;;;###autoload
(defun elel-suggest (&optional id marker quiet)
"Show the notes that a note ID could link to, and tags that fit it.
The notes it already has relations with are left out. If MARKER is a
marker, then \\`i' in the summary inserts a link at that place. With
QUIET, do not select the summary window."
(interactive)
(let* ((id (or id (elel--note-id-here) (user-error "No note here")))
(data (elel--get id))
(excluded (cons id
(mapcar (lambda (n) (elel--field n 'id))
(append (list (alist-get 'parent data))
(alist-get 'children data)
(alist-get 'links data)))))
(tags (elel--suggested-tags id))
(title (format "Suggestions for %s%s"
(elel--field (alist-get 'note data) 'title)
(cond (tags (concat " tags: " (string-join tags " ")))
(""))))
(buffer
(elel--show-summary
title
:function (lambda ()
(cl-remove-if
(lambda (n) (member (elel--field n 'id) excluded))
(elel--search (format "like:\"%s\"" id)
(+ elel-suggest-limit
(length excluded)))))
:threaded nil
:quiet quiet)))
(with-current-buffer buffer
(setq elel-summary-insert-marker (and (markerp marker) marker)))))
(defun elel-summary-insert-link ()
"Insert a link to the note at point where `elel-suggest' was asked for."
(interactive)
(let ((note (elel--note-at-point))
(marker elel-summary-insert-marker))
(cond
((not (and marker (marker-buffer marker)))
(user-error "No place to insert a link; use \\`S' from a capture"))
(t
(with-current-buffer (marker-buffer marker)
(save-excursion
(goto-char marker)
(cond
((and (not (bolp)) (not (memq (char-before) (list ?\s ?\t))))
(insert " ")))
(insert (elel--link-string (elel--field note 'id)
(elel--field note 'title))
" ")
(set-marker marker (point))))
(message "elel: linked %s" (elel--field note 'title))))))
(defun elel-summary-refer-thread (&optional id)
"Add the whole thread of the note ID (default: at point) to this summary."
(interactive)
(let ((id (or id (elel--id-at-point))))
(cl-pushnew (elel--filter "thread" id) elel-summary-extra :test #'equal)
(setq elel-summary-threaded t)
(let ((inhibit-read-only t))
(elel--render-summary (elel--summary-notes)))
(elel--goto-note id)))
(defun elel--summary-query (title query)
"Show a summary of the notes matching QUERY, named TITLE."
(elel--show-summary title :query query :threaded t))
(defun elel-summary-parent ()
"Show the parent of the note at point."
(interactive)
(elel--show-parent (elel--note-at-point)))
(defun elel-summary-children ()
"Summarize the children of the note at point."
(interactive)
(elel--children (elel--id-at-point)))
(defun elel-summary-outlinks ()
"Summarize the notes that the note at point links to."
(interactive)
(elel--outlinks (elel--id-at-point)))
(defun elel-summary-backlinks ()
"Summarize the notes that link to the note at point."
(interactive)
(elel--backlinks (elel--id-at-point)))
(defun elel-summary-hood ()
"Summarize the neighbourhood of the note at point."
(interactive)
(elel-hood (elel--id-at-point) (prefix-numeric-value current-prefix-arg)))
(defun elel-summary-edit ()
"Edit the file of the note at point."
(interactive)
(elel-edit-note (elel--id-at-point)))
(defun elel-summary-new-child ()
"Write a new note whose parent is the note at point."
(interactive)
(elel-new-note (read-string "Title: ") (elel--id-at-point)))
(defun elel-summary-quit ()
"Leave the summary, and close the article window.
The summary and article buffers are killed, as in Gnus, so that quitting
the views buffer afterwards does not bring the summary back."
(interactive)
(let ((window (elel--article-visible-window))
(summary (current-buffer))
(article (get-buffer elel--article-buffer-name))
(views (get-buffer "*elel*")))
(cond
((and window (cdr (window-list nil 'nomini))) (delete-window window)))
(cond
(views (switch-to-buffer views))
((quit-window)))
(cond ((buffer-live-p article) (kill-buffer article)))
(cond ((buffer-live-p summary) (kill-buffer summary)))))
;;; The same queries, from anywhere
(defun elel--children (id)
"Summarize the children of the note ID."
(elel--summary-query (format "Children of %s" id)
(elel--filter "parent" id)))
(defun elel--outlinks (id)
"Summarize the notes that the note ID links to."
(elel--summary-query (format "Links of %s" id) (elel--filter "from" id)))
(defun elel--backlinks (id)
"Summarize the notes that link to the note ID."
(elel--summary-query (format "Backlinks of %s" id) (elel--filter "to" id)))
(defun elel--show-parent (note)
"Show the parent of NOTE in the article window."
(let ((parent (elel--field note 'parent)))
(cond
(parent (elel--show-article parent t))
((user-error "This note has no parent")))))
;;;###autoload
(defun elel-search (query)
"Search the notes for QUERY and show the results.
QUERY may hold filters such as tag:X or date:2025..; see the README."
(interactive (list (read-string "Search: " nil 'elel-search-history)))
(elel--show-summary (format "Search: %s" query)
:query query :threaded nil))
(defun elel--hood-notes (id hops)
"The notes within HOPS steps of ID, with the center first."
(let* ((objects (elel--call "hood" id "--hops" (number-to-string hops)))
(center (alist-get 'center (car objects))))
(cons (cons (cons 'rel "this") center) (cdr objects))))
;;;###autoload
(defun elel-hood (id &optional hops)
"Show the notes around ID, within HOPS steps (default 1)."
(interactive (list (cond
((bound-and-true-p elel-article-mode) elel-article-id)
((elel--id-at-point)))
(prefix-numeric-value current-prefix-arg)))
(let ((hops (or hops 1)))
(elel--show-summary
(format "Neighbourhood of %s" id)
:function (lambda () (elel--hood-notes id hops))
:threaded nil)))
;;; The article buffer
(defvar-local elel-article-id nil
"The ID of the note shown in this article buffer.")
(defvar-local elel-article-note nil
"The note shown in this article buffer, as the engine reported it.")
(defvar elel--history nil
"The IDs of the notes visited before, newest first.")
(defvar elel-article-mode-map (make-sparse-keymap)
"Keymap of `elel-article-mode'.")
;; Filled in separately, so that loading this file again updates the keys.
(let ((map elel-article-mode-map))
(define-key map (vector ?\s) #'elel-article-scroll-up)
(define-key map (vector ?j) #'elel-article-scroll-up)
(define-key map (vector ?\d) #'elel-article-scroll-down)
(define-key map (vector ?k) #'elel-article-scroll-down)
(define-key map (vector ?n) #'elel-article-next)
(define-key map (vector ?p) #'elel-article-previous)
(define-key map (vector ?\t) #'elel-article-next-link)
(define-key map (vector 'backtab) #'elel-article-previous-link)
(define-key map (vector ?\r) #'elel-article-follow)
(define-key map (vector ?l) #'elel-article-back)
(define-key map (vector ?^) #'elel-article-parent)
(define-key map (vector ?c) #'elel-article-children)
(define-key map (vector ?o) #'elel-article-outlinks)
(define-key map (vector ?b) #'elel-article-backlinks)
(define-key map (vector ?H) #'elel-hood)
(define-key map (vector ?a) #'elel-article-refer-thread)
(define-key map (vector ?=) #'elel-summary-expand-window)
(define-key map (vector ?R) #'elel-article-related)
(define-key map (vector ?S) #'elel-suggest)
(define-key map (vector ?h) #'elel-article-goto-summary)
(define-key map (vector ?q) #'elel-article-quit)
(define-key map (vector ?e) #'elel-article-edit)
(define-key map (vector ?r) #'elel-article-new-child)
(define-key map (vector ?g) #'elel-article-refresh)
(define-key map (vector ?/) #'elel-search)
(define-key map (vector ?N) #'elel-new-note))
(define-minor-mode elel-article-mode
"Minor mode for reading a note, like `view-mode' but aware of the summary.
The major mode of the buffer is chosen by the file of the note, through
`elel-major-mode-alist'.
\\{elel-article-mode-map}"
:lighter " elel"
:keymap elel-article-mode-map
(setq truncate-lines nil)
(setq buffer-read-only elel-article-mode))
(defun elel--major-mode (path)
"The major mode in which to show a note of the file PATH."
(let ((mode (assoc-default path elel-major-mode-alist
#'string-match-p 'text-mode)))
(cond
((fboundp mode) mode)
('text-mode))))
(defun elel--article-window ()
"The window in which to show the article.
It is the window that shows the article already. Failing that, it is
a new window below the summary window if `elel-article-keep-summary';
failing that, the selected window."
(let ((summary (get-buffer-window elel--summary-buffer-name)))
(cond
((elel--article-visible-window))
((and elel-article-keep-summary summary
(ignore-errors
(let* ((total (window-total-height summary))
(new (split-window summary nil 'below))
(want (round (* elel-summary-window-height total))))
(ignore-errors
(window-resize summary (- want (window-total-height summary))))
new))))
((selected-window)))))
(defun elel--hide-drawers ()
"Fold the property drawers of the current org buffer."
(cond
((fboundp 'org-fold-hide-drawer-all) (org-fold-hide-drawer-all))
((fboundp 'org-hide-drawer-all) (org-hide-drawer-all))))
(defun elel--show-article (id &optional history select)
"Show the note ID in the article window.
With HISTORY, remember the note shown before. With SELECT, select
the article window. The note is shown as it is in its file, in the
major mode chosen by `elel-major-mode-alist'."
(let* ((data (elel--get id))
(note (alist-get 'note data))
(text (or (alist-get 'raw data) (alist-get 'body data) ""))
(mode (elel--major-mode (elel--field note 'path)))
(buffer (get-buffer-create elel--article-buffer-name))
(previous (buffer-local-value 'elel-article-id buffer)))
(cond
((and history previous (not (equal previous id)))
(push previous elel--history)))
(with-current-buffer buffer
(let ((inhibit-read-only t))
(kill-all-local-variables t)
(erase-buffer)
(insert text)
(cond
((not (bolp)) (insert "\n")))
(funcall mode)
(setq elel-article-id id)
(setq elel-article-note note)
(elel-article-mode 1)
(cond
((derived-mode-p 'org-mode) (elel--hide-drawers))
;; Without org, make the links buttons.
((elel--buttonize-body (point-min) (point-max))))
(goto-char (point-min))
(set-buffer-modified-p nil)))
(cond
((alist-get 'stale data)
(message "elel: the file changed since the last index; update the index")))
(let ((window (elel--article-window)))
(set-window-buffer window buffer)
(set-window-point window (point-min))
(set-window-start window (point-min))
(cond (select (select-window window))))
buffer))
;;;###autoload
(defun elel-open-note (id)
"Show the note with ID in the article window, and select that window."
(interactive "sNote ID: ")
(elel--show-article id (bound-and-true-p elel-article-mode) t))
(defun elel--with-summary (function)
"Call FUNCTION in the summary window, or else in the summary buffer."
(let ((buffer (elel--summary-buffer)))
(cond
((null buffer) (user-error "No summary; search first"))
((get-buffer-window buffer)
(with-selected-window (get-buffer-window buffer)
(funcall function)))
((with-current-buffer buffer (funcall function))))))
(defun elel-article-scroll-up ()
"Scroll forward; at the end of the note, go to the next note."
(interactive)
(condition-case nil
(scroll-up-command)
(end-of-buffer (elel-article-next))))
(defun elel-article-scroll-down ()
"Scroll backward."
(interactive)
(condition-case nil
(scroll-down-command)
(beginning-of-buffer (message "Beginning of the note"))))
(defun elel-article-next ()
"Show the next note of the summary."
(interactive)
(elel--with-summary #'elel-summary-next))
(defun elel-article-previous ()
"Show the previous note of the summary."
(interactive)
(elel--with-summary #'elel-summary-previous))
(defun elel-article-next-link ()
"Move to the next link."
(interactive)
(cond
((derived-mode-p 'org-mode) (org-next-link))
((forward-button 1))))
(defun elel-article-previous-link ()
"Move to the previous link."
(interactive)
(cond
((derived-mode-p 'org-mode) (org-previous-link))
((backward-button 1))))
(defun elel-article-follow ()
"Follow the link at point, in the article window."
(interactive)
(let ((id (elel--link-at-point)))
(cond
(id (elel--show-article id t))
((button-at (point)) (push-button))
((derived-mode-p 'org-mode) (call-interactively #'org-open-at-point))
((user-error "No link here")))))
(defun elel-article-back ()
"Go back to the note shown before."
(interactive)
(cond
(elel--history (elel--show-article (pop elel--history)))
((user-error "No previous note"))))
(defun elel-article-parent ()
"Show the parent of this note."
(interactive)
(elel--show-parent elel-article-note))
(defun elel-article-children ()
"Summarize the children of this note."
(interactive)
(elel--children elel-article-id))
(defun elel-article-outlinks ()
"Summarize the notes this note links to."
(interactive)
(elel--outlinks elel-article-id))
(defun elel-article-backlinks ()
"Summarize the notes that link to this note."
(interactive)
(elel--backlinks elel-article-id))
(defun elel-article-refer-thread ()
"Add the whole thread of this note to the summary."
(interactive)
(let ((id elel-article-id))
(cond
((elel--summary-buffer)
(elel--with-summary (lambda () (elel-summary-refer-thread id))))
((elel--summary-query (format "Thread of %s" id)
(elel--filter "thread" id))))))
(defun elel-article-goto-summary ()
"Select the summary window."
(interactive)
(let ((buffer (elel--summary-buffer)))
(cond
((null buffer) (user-error "No summary"))
((get-buffer-window buffer) (select-window (get-buffer-window buffer)))
((switch-to-buffer buffer)))))
(defun elel-article-quit ()
"Close the article window."
(interactive)
(let ((summary (elel--summary-buffer)))
(cond
((and summary (not (get-buffer-window summary)))
(switch-to-buffer summary))
((cdr (window-list nil 'nomini)) (delete-window))
((bury-buffer)))))
(defun elel-article-edit ()
"Edit the file of this note."
(interactive)
(elel-edit-note elel-article-id))
(defun elel-article-new-child ()
"Write a new note whose parent is this note."
(interactive)
(elel-new-note (read-string "Title: ") elel-article-id))
(defun elel-article-refresh ()
"Read the note again from its file, as if opening it anew.
Point goes back to the start, like `elel-summary-show-article'."
(interactive)
(elel--show-article elel-article-id))
(defconst elel--body-link-regexp
(concat "\\[\\[note:"
;; The kind, for typed links: [[note::KIND:ID]].
"\\(?::\\([[:alnum:]_-]+\\):\\)?"
;; The ID.
"\\([^] \t\n]+\\)\\]"
;; The description, which is for humans.
"\\(?:\\[\\([^]\n]*\\)\\]\\)?"
"\\]")
"Matches a link to a note: [[note:ID][DESCRIPTION]].
Group 1 is the kind (nil if untyped), group 2 the ID and group 3 the
description, if any. The typed form is [[note::KIND:ID][DESCRIPTION]].")
(defun elel--open-button (button)
"Open the note of BUTTON."
(elel--show-article (button-get button 'elel-id) t))
(defun elel--buttonize-body (beg end)
"Replace the links between BEG and END by buttons.
A button shows the description of the link, or the ID if there is none."
(save-excursion
(let ((end (copy-marker end)))
(goto-char beg)
(while (re-search-forward elel--body-link-regexp end t)
(let* ((id (match-string-no-properties 2))
(label (or (match-string-no-properties 3) id))
(start (match-beginning 0)))
(replace-match label t t)
(make-text-button start (+ start (length label))
'elel-id id
'action #'elel--open-button
'follow-link t
'face 'link))))))
(defun elel-edit-note (id)
"Visit the file of the note ID, at the note."
(interactive "sNote ID: ")
(let* ((data (elel--get id))
(note (alist-get 'note data)))
(find-file (elel--field note 'path))
(goto-char (point-min))
(forward-line (1- (elel--field note 'line)))
(cond
((derived-mode-p 'org-mode) (outline-show-entry)))))
;;; The views buffer
(defvar-local elel-views-show-hidden nil
"Non-nil if the views marked :hidden are listed.")
(defvar elel-views-mode-map (make-sparse-keymap)
"Keymap of `elel-views-mode'.")
;; Filled in separately, so that loading this file again updates the keys.
(let ((map elel-views-mode-map))
(set-keymap-parent map special-mode-map)
(define-key map (vector ?\r) #'elel-views-open)
(define-key map (vector ?\s) #'elel-views-open)
(define-key map (vector ?n) #'next-line)
(define-key map (vector ?p) #'previous-line)
(define-key map (vector ?g) #'elel-views-refresh)
(define-key map (vector ?u) #'elel-views-update)
(define-key map (vector ?L) #'elel-views-toggle-hidden)
(define-key map (vector ?/) #'elel-search)
(define-key map (vector ?G) #'elel-search)
(define-key map (vector ?N) #'elel-new-note)
(define-key map (vector ?C) #'elel-check)
(define-key map (vector ?q) #'quit-window))
(define-derived-mode elel-views-mode special-mode "elel-views"
"Major mode for the list of views, like a Gnus group buffer.
\\{elel-views-mode-map}"
(setq truncate-lines t)
(hl-line-mode 1))
(defun elel--view-plist (view)
"The property list of the view VIEW, which is (NAME QUERY . PLIST)."
(cddr view))
(defun elel-views-refresh ()
"Redraw the views buffer."
(interactive)
(let* ((inhibit-read-only t)
(line (line-number-at-pos))
(shown (cl-remove-if
(lambda (v)
(and (plist-get (elel--view-plist v) :hidden)
(not elel-views-show-hidden)))
elel-views))
(counts (and shown (elel--counts (mapcar #'cadr shown)))))
(erase-buffer)
(insert (propertize "elel" 'face 'elel-heading)
" " (abbreviate-file-name (expand-file-name elel-root))
(cond (elel-views-show-hidden " (all views)") (""))
"\n\n")
(cl-mapc
(lambda (v count)
(let* ((beg (point))
(limit (plist-get (elel--view-plist v) :limit))
(count (cond (limit (min count limit)) (count))))
(insert (format "%6d %s%s\n" count (car v)
(cond
((plist-get (elel--view-plist v) :hidden)
(propertize " (hidden)" 'face 'elel-date))
(""))))
(put-text-property beg (point) 'elel-view v)))
shown counts)
(goto-char (point-min))
(forward-line (max 2 (1- line)))))
(defun elel-views-toggle-hidden ()
"List the hidden views, or hide them again."
(interactive)
(setq elel-views-show-hidden (not elel-views-show-hidden))
(elel-views-refresh))
(defun elel-views-update ()
"Update the index, then redraw."
(interactive)
(elel-index)
(elel-views-refresh))
(defun elel-views-open ()
"Open the view at point."
(interactive)
(let ((v (get-text-property (point) 'elel-view)))
(cond
((null v) (user-error "No view here"))
(t
(elel--show-summary (car v)
:query (cadr v)
:limit (plist-get (elel--view-plist v) :limit)
:threaded t)))))
;;;###autoload
(defun elel ()
"Show the views buffer."
(interactive)
(let ((buffer (get-buffer-create "*elel*")))
(with-current-buffer buffer
(elel-views-mode)
(condition-case err
(elel-views-refresh)
(user-error
(cond
;; The first time, there is no index yet: make one.
((string-match-p "no index yet" (error-message-string err))
(elel-index)
(elel-views-refresh))
((signal (car err) (cdr err)))))))
(switch-to-buffer buffer)))
;;; Writing notes
(defun elel-generate-id ()
"Make an ID that sorts by time, such as 20261117T143005-7f3a."
(format "%s-%04x" (format-time-string "%Y%m%dT%H%M%S") (random #x10000)))
(defun elel--now (&optional time)
"TIME (default: now) in ISO 8601, with a colon in the zone."
(let ((s (format-time-string "%Y-%m-%dT%H:%M:%S%z" time)))
(concat (substring s 0 -2) ":" (substring s -2))))
(defun elel--context ()
"Where the user is: the file of the current buffer, if outside the notes."
(cond
((and buffer-file-name
(not (string-prefix-p
(file-name-as-directory (expand-file-name elel-root))
(expand-file-name buffer-file-name))))
(abbreviate-file-name buffer-file-name))))
(defun elel--skeleton (format title id parent context)
"The text of a new note in FORMAT (\"org\" or \"txt\")."
(let ((date (elel--now)))
(cond
((string= format "org")
(concat "* " title "\n:PROPERTIES:\n"
":ID: " id "\n"
":DATE: " date "\n"
(and parent (concat ":PARENT: " parent "\n"))
(and context (concat ":CONTEXT: " context "\n"))
":END:\n"))
((concat "ID: " id "\n"
"Title: " title "\n"
"Date: " date "\n"
(and parent (concat "Parent: " parent "\n"))
(and context (concat "Context: " context "\n"))
"\n")))))
(defvar elel-capture-mode-map (make-sparse-keymap)
"Keymap of `elel-capture-mode'.")
;; Filled in separately, so that loading this file again updates the keys.
(let ((map elel-capture-mode-map))
(define-key map (vector 3 3) #'elel-capture-finish))
(define-minor-mode elel-capture-mode
"Minor mode while writing a new note.
\\<elel-capture-mode-map>Type \\[elel-capture-finish] to save the note and update the index."
:lighter " elel"
:keymap elel-capture-mode-map)
(defvar-local elel-capture-id nil
"The ID of the note being written in this buffer.")
(defun elel-capture-finish ()
"Save the new note, update the index, and leave the capture mode.
If `elel-suggest-after-capture' is non-nil, then show suggestions of
links and tags when the index is ready."
(interactive)
(let ((id elel-capture-id)
(marker (point-marker)))
(cond
((and id elel-suggest-after-capture)
(push (lambda () (elel-suggest id marker t)) elel--index-callbacks)
(save-buffer)
(elel-capture-mode -1)
(elel-index-async)
(message "elel: saved; indexing, then suggestions"))
(t
(save-buffer)
(elel-capture-mode -1)
(message "elel: saved; indexing")))))
;;;###autoload
(defun elel-new-note (title &optional parent)
"Start a new note with TITLE, as a child of PARENT if given.
The note is appended to `elel-capture-file'."
(interactive (list (read-string "Title: ") nil))
(let* ((file (expand-file-name elel-capture-file elel-root))
(format (or (file-name-extension file) "org"))
(context (elel--context))
(id (funcall elel-id-function)))
(make-directory (file-name-directory file) t)
(find-file file)
(goto-char (point-max))
(cond
((and (not (bobp)) (not (bolp))) (insert "\n")))
(cond
((> (buffer-size) 0)
(insert (cond ((string= format "txt") "\n\f\n") ("\n")))))
(insert (elel--skeleton format title id parent context))
(setq elel-capture-id id)
(elel-capture-mode 1)
(message "Write the note, then type C-c C-c")))
;;; Fixing missing IDs
(defconst elel--txt-key-regexp
"^\\(id\\|title\\|date\\|kind\\|tags\\|parent\\|links\\|context\\|summary\\):"
"Matches the first line of the header of a plain text note.")
(defun elel--insert-id (path line id)
"Give the note that starts at LINE of PATH the ID."
(with-current-buffer (find-file-noselect path)
(save-excursion
(goto-char (point-min))
(forward-line (1- line))
(cond
((string= (file-name-extension path) "org")
(forward-line 1)
(while (looking-at "[ \t]*\\(SCHEDULED\\|DEADLINE\\|CLOSED\\):")
(forward-line 1))
(cond
((looking-at "[ \t]*:PROPERTIES:[ \t]*$")
(forward-line 1)
(insert ":ID: " id "\n"))
((insert ":PROPERTIES:\n:ID: " id "\n:END:\n"))))
(t
(while (and (looking-at "[ \t]*$") (not (eobp)))
(forward-line 1))
(let ((case-fold-search t))
(cond
((looking-at elel--txt-key-regexp) (insert "ID: " id "\n"))
((insert "ID: " id "\n\n")))))))
(current-buffer)))
(defun elel-assign-ids ()
"Add an ID to every note that has none."
(interactive)
(elel-index)
(let ((issues (cl-remove-if-not
(lambda (i) (equal (alist-get 'issue i) "missing-id"))
(elel--call "check"))))
(cond
((null issues) (message "elel: every note has an ID"))
((y-or-n-p (format "Add IDs to %d notes? " (length issues)))
;; Work from the end of each file, so that line numbers stay valid.
(let ((sorted (sort (copy-sequence issues)
(lambda (a b)
(let ((pa (alist-get 'path a))
(pb (alist-get 'path b)))
(cond
((string< pa pb) t)
((string= pa pb)
(> (alist-get 'line a) (alist-get 'line b)))))))))
(dolist (i sorted)
(let ((b (get-file-buffer (alist-get 'path i))))
(cond
((and b (buffer-modified-p b))
(user-error "Save %s first" (buffer-name b))))))
(let (buffers)
(dolist (i sorted)
(cl-pushnew (elel--insert-id (alist-get 'path i)
(alist-get 'line i)
(funcall elel-id-function))
buffers))
(dolist (b buffers)
(with-current-buffer b (save-buffer))))
(elel-index))))))
;;; Checking
(defun elel--check-button (button)
"Visit the place of BUTTON."
(find-file (button-get button 'path))
(goto-char (point-min))
(forward-line (1- (button-get button 'line))))
(defun elel-check ()
"Report notes without IDs, duplicate IDs and dangling links."
(interactive)
(let ((issues (elel--call "check"))
(buffer (get-buffer-create "*elel check*")))
(with-current-buffer buffer
(let ((inhibit-read-only t))
(special-mode)
(erase-buffer)
(insert (propertize "elel check" 'face 'elel-heading)
(format " (%d)\n\n" (length issues)))
(dolist (i issues)
(insert (format "%-16s " (alist-get 'issue i)))
(insert-text-button
(or (alist-get 'title i) "(untitled)")
'path (alist-get 'path i)
'line (alist-get 'line i)
'action #'elel--check-button
'follow-link t)
(cond
((alist-get 'target i)
(insert " -> " (alist-get 'target i))))
(insert "\n"))
(goto-char (point-min))))
(switch-to-buffer buffer)))
;;; Links in the note files
;;
;; A link to a note is written [[note:ID][TITLE]] in every format, and
;; [[note::KIND:ID][TITLE]] when it has a type. The title is for the
;; reader; the ID is how the engine finds the note. In org, "note" is a
;; registered link type, so org follows, completes and exports these
;; links itself (see the end of this section).
(defun elel--note-id-here ()
"The ID of the note that the current buffer or point is about, or nil."
(cond
(elel-capture-id)
((derived-mode-p 'elel-summary-mode) (get-text-property (point) 'elel-id))
((bound-and-true-p elel-article-mode) elel-article-id)
((derived-mode-p 'org-mode) (org-entry-get nil "ID" t))))
(defun elel--choose-note ()
"Ask for a note by title, and return it.
The notes closest in meaning to the current note come first."
(let* ((here (ignore-errors (elel--note-id-here)))
(near (and here
(ignore-errors
(elel--search (format "like:\"%s\"" here) 50))))
(notes (append near
(cl-remove-if
(lambda (n)
(cl-find (elel--field n 'id) near
:key (lambda (x) (elel--field x 'id))
:test #'equal))
(elel--search ""))))
(table (mapcar
(lambda (n)
(cons (format "%s (%s)"
(elel--field n 'title)
(string-trim (elel--short-date n)))
n))
notes)))
(cond
(table
(cdr (assoc (completing-read
"Link to: "
(lambda (string pred action)
(cond
((eq action 'metadata)
(list 'metadata
(cons 'display-sort-function #'identity)
(cons 'cycle-sort-function #'identity)))
((complete-with-action action table string pred))))
nil t)
table)))
((user-error "No notes in the index")))))
(defun elel--link-string (id description &optional kind)
"The text of a link to the note ID, with DESCRIPTION and maybe KIND."
(concat "[[note:" (and kind (concat ":" kind ":")) id "]"
(and description (concat "[" description "]"))
"]"))
(defun elel-insert-link (&optional typed)
"Insert a link to a note, chosen by title.
If the region is active, its text becomes the description of the
link; otherwise the title of the note does. With a prefix argument
TYPED, also ask for the type of the link."
(interactive "P")
(let* ((note (elel--choose-note))
(kind (and typed
(let ((k (string-trim (read-string "Type of link: "))))
(and (not (string-empty-p k)) k))))
(description
(cond
((use-region-p)
(prog1 (buffer-substring-no-properties
(region-beginning) (region-end))
(delete-region (region-beginning) (region-end))))
((elel--field note 'title)))))
(insert (elel--link-string (elel--field note 'id) description kind))))
(defun elel--link-at-point ()
"The ID of the note link at point, or nil."
(let ((pos (point))
found)
(save-excursion
(beginning-of-line)
(while (and (not found)
(re-search-forward elel--body-link-regexp
(line-end-position) t))
(cond
((and (<= (match-beginning 0) pos) (<= pos (match-end 0)))
(setq found (match-string-no-properties 2))))))
found))
(defun elel-follow-link ()
"Open the note linked at point.
If there is no note link at point, do what \\`C-c C-o' normally does."
(interactive)
(let ((id (elel--link-at-point)))
(cond
(id (elel-open-note id))
((derived-mode-p 'org-mode) (call-interactively #'org-open-at-point))
((user-error "No note link at point")))))
(defun elel-open-this-note ()
"Open the note around point in the note buffer."
(interactive)
(let ((id (save-excursion
(cond
((string= (file-name-extension (or buffer-file-name "")) "org")
(org-back-to-heading t)
(org-entry-get nil "ID"))
((progn
(cond ((search-backward "\f" nil t) (forward-line 1))
((goto-char (point-min))))
(let ((case-fold-search t))
(re-search-forward "^id:[ \t]*\\(.+\\)$"
(line-end-position 8) t)))
(match-string-no-properties 1))))))
(cond
(id (elel-open-note (string-trim id)))
((user-error "No ID for this note")))))
(defvar elel-link-mode-map (make-sparse-keymap)
"Keymap of `elel-link-mode'.")
;; Filled in separately, so that loading this file again updates the keys.
(let ((map elel-link-mode-map))
(define-key map (vector 3 15) #'elel-follow-link)
(define-key map (vector 3 ?n ?l) #'elel-insert-link)
(define-key map (vector 3 ?n ?o) #'elel-open-this-note))
(define-minor-mode elel-link-mode
"Minor mode for the note files: follow and insert note links.
\\{elel-link-mode-map}"
:lighter " elel"
:keymap elel-link-mode-map)
(defun elel--maybe-link-mode ()
"Turn on `elel-link-mode' in org and text files under `elel-root'."
(cond
((and buffer-file-name
(member (file-name-extension buffer-file-name) (list "org" "txt"))
(string-prefix-p
(file-name-as-directory (expand-file-name elel-root))
(expand-file-name buffer-file-name)))
(elel-link-mode 1))))
(add-hook 'find-file-hook #'elel--maybe-link-mode)
;;;; The org link type
(defun elel--parse-path (path)
"Split the PATH of a note link into (KIND . ID).
KIND is nil for an untyped link, whose path is just the ID."
(cond
((string-match "\\`:\\([[:alnum:]_-]+\\):\\(.+\\)\\'" path)
(cons (match-string 1 path) (match-string 2 path)))
((cons nil path))))
(defun elel--org-follow (path _arg)
"Open the note of the org link whose path is PATH."
(elel-open-note (cdr (elel--parse-path path))))
(defun elel--org-complete (&optional _arg)
"Choose a note by title and return the path of a link to it."
(concat "note:" (elel--field (elel--choose-note) 'id)))
(defun elel--org-description (link desc)
"The description for LINK, if DESC is nil: the title of the note."
(or desc
(ignore-errors
(let* ((id (cdr (elel--parse-path (string-remove-prefix "note:" link))))
(data (car (elel--call "get" id))))
(elel--field (alist-get 'note data) 'title)))))
(defun elel--org-export (path description _backend _info)
"Export the link to PATH as just its DESCRIPTION."
(or description (cdr (elel--parse-path path))))
(with-eval-after-load 'org
(org-link-set-parameters
"note"
:follow #'elel--org-follow
:complete #'elel--org-complete
:insert-description #'elel--org-description
:export #'elel--org-export))
(provide 'elel)
;;; elel.el ends here
|