-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtlon-md.el
1229 lines (1066 loc) · 47.6 KB
/
tlon-md.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
;;; tlon-md.el --- Markdown functionality for Tlön -*- lexical-binding: t; fill-column: 80 -*-
;; Copyright (C) 2025
;; Author: Pablo Stafforini
;; This file is NOT part of GNU Emacs.
;; This program is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;;
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <https://www.gnu.org/licenses/>.
;;; Commentary:
;; Markdown functionality for Tlön.
;;; Code:
(require 'markdown-mode-extras)
(require 'tlon-core)
(require 'tlon-yaml)
;;;; User options
(defgroup tlon-md ()
"Markdown functionality."
:group 'tlon)
(defcustom tlon-md-special-characters
'(("bullet" . "•")
("en dash" . "–")
("em dash" . "—")
("opening single quote" . "‘")
("closing single quote" . "’")
("opening double quote" . "“")
("closing double quote" . "”")
("narrow non-break space" . " ")
("soft hyphen" . "")
("ellipsis" . "…"))
"Alist of special characters to insert in a Markdown file."
:group 'tlon-md
:type '(alist :key-type string :value-type string))
;;;; Variables
;;;;; Local variables
(defconst tlon-md-local-variables-line-start
"<!-- Local Variables:"
"Start of the first line that contains file local variables.")
(defconst tlon-md-local-variables-line-end
"End: -->"
"End of the last line that contains file local variables.")
;;;;; Markdown
;;;;;; Italics
;; We tweak the default value of `markdown-regex-italic' to make it analogous
;; to `markdown-regex-bold': the group that captures the leading character is a
;; proper capturing group, allowing us to prepend this character to the
;; replacement.
(setq markdown-regex-italic
"\\(?1:^\\|[^\\]\\)\\(?2:\\(?3:[*_]\\)\\(?4:[^ \n \\]\\|[^ \n *]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(?5:\\3\\)\\)")
;;;;;; Links
(defconst tlon-md-regexp-link-formatter
"\\(?%s:!\\)?\\(?%s:\\[\\)\\(?%s:\\^?\\(?:\\\\\\]\\|[^]]\\)*\\|\\)\\(?%s:\\]\\)\\(?%s:(\\)\\s-*\\(?%s:[^)]*?\\)\\(?:\\s-+\\(?%s:\"[^\"]*\"\\)\\)?\\s-*\\(?%s:)\\)"
"Formatter for a regexp pattern to match a Markdown link.
This copies `markdown-regex-link-inline' but replaces the digits in each capture
group with placeholders.")
;;;;;; Images
(defconst tlon-md-image
"!\\[\\(?1:.*?\\)\\](\\(?2:.*?\\)\\(?:\\s-*\"\\(?3:.*?\\)\"\\)?)"
"Pattern to match an image in a Markdown file.
The first group captures the alt text. The second group captures the image URL.
The third group captures the title.")
(defconst tlon-md-image-sans-alt
"!\\[\\](.*?\\(?:\\s-*\".*?\"\\)?)"
"Pattern to match an image without alt text in a Markdown file.")
;;;;;; Blockquote
;; TODO: make sure it works even when the blockquote does *not* span more than one line
(defconst tlon-md-blockquote
"\\(?1:\\(?:^[[:blank:]]*?>.*\n\\)+\\)"
"Pattern to match a blockquote in a Markdown file.
The pattern captures the entire blockquote, including the quote markers. This is
to allow for capturing multi-line quotes. To get the actual quote only, remove
them from the captured string as part of the post-processing.")
;;;;;; Math
(defconst tlon-md-math-power
"\\(?1:[[:digit:]]+\\)<sup>\\(?2:[n[:digit:]]+\\)</sup>"
"Regexp pattern for matching a number raised to a power.
The first group captures the base, and the second group captures
the exponent.")
(defconst tlon-md-math-big-number
"\\b\\(?1:[[:digit:]]\\{4,\\}\\(?:\\.[[:digit:]]+\\)?\\)\\b"
"Regexp pattern for matching a “big” number.
Currently, we define it as a number no smaller than 1000.")
;;;;;; Footnotes
(defconst tlon-md-footnote-start
"\\[\\^%s\\]:[[:space:]]"
"Regexp pattern to match the start of a footnote.
The placeholder is the footnote number.")
;;;;;; Headings
;; adapted from `markdown-regex-header'
(defconst tlon-md-heading-template
"^\\(?:\\(?1:[^\n -].*\\)\n\\(?:\\(?2:=+\\)\\|\\(?3:-+\\)\\)\\|\\(?4:%s[ ]+\\)\\(?5:.*?\\)\\(?6:[ ]+#+\\)?\\)$"
"Template to construct constants to match headings and subheadings.")
(defconst tlon-md-heading
(format tlon-md-heading-template "##")
"Regexp patern to match a top-level heading.")
(defconst tlon-md-subheading
(format tlon-md-heading-template "###+")
"Regexp patern to match a subheading.
A subheading is defined as any heading that is not top-level.")
;;;;; SSML
;;;;;; `emphasis'
;; https://docs.aws.amazon.com/polly/latest/dg/supportedtags.html#emphasis-tag
(defconst tlon-md-ssml-emphasis-levels
'("none" "reduced" "moderate" "strong")
"Admissible values for the `level' attribute of the `emphasis' SSML tag.")
(defconst tlon-tts-ssml-default-emphasis-level
"moderate"
"Default value for the `level' attribute of the `emphasis' SSML tag.")
;;;;;; `phoneme'
;; https://docs.aws.amazon.com/polly/latest/dg/supportedtags.html#phoneme-tag
(defconst tlon-md-ssml-phoneme-alphabets
'("ipa" "x-sampa")
"Admissible values for the `alphabet' attribute of the `phoneme' SSML tag.")
(defconst tlon-tts-ssml-phoneme-default-alphabet
"ipa"
"Default value for the `alphabet' attribute of the `phoneme' SSML tag.")
;;;;;; `prosody'
;; https://docs.aws.amazon.com/polly/latest/dg/supportedtags.html#prosody-tag
;; not currently supported
;;;;;; `say-as'
;; https://docs.aws.amazon.com/polly/latest/dg/supportedtags.html#say-as-tag
(defconst tlon-md-ssml-interpret-as-values
'("cardinal" "ordinal" "digits" "fraction" "unit" "date" "time" "telephone" "address" "interjection" "expletive" "spell-out" "characters" "verbatim")
"Admissible values for the `interpret-as' attribute of the SSML tag.")
;;;;; MDX
;;;;;; `Table'
;; TODO: develop
;; https://github.com/tlon-team/uqbar-issues#mdx-tag-syntax
;;;;; Common constants
(defconst tlon-tag-specs
`((:tag "AlternativeVoice"
:type mdx
:self-closing nil
:doc "Encloses text to be narrated in the alternative voice, as opposed to the main voice.")
(:tag "Aside"
:type mdx
:self-closing nil
:doc "Encloses text in an aside section.")
(:tag "break"
:attributes ((:name "time" :required t :valued t :group 2 :prompt "Time (e.g. \"1s\"): "))
:type ssml
:self-closing t
:doc "")
(:tag "Cite"
:attributes ((:name "bibKey" :required t :valued t :group 2 :reader tlon-md-cite-bibkey-reader)
(:name "locator" :required nil :valued t :group 4 :reader tlon-md-cite-locator-reader)
(:name "short" :required nil :valued nil :group 6 :reader tlon-md-cite-length-reader))
:type mdx
:self-closing t)
(:tag "emphasis"
:attributes ((:name "level" :required t :valued t :group 3 :reader tlon-md-emphasis-level-reader))
:type ssml
:self-closing nil
:doc "")
(:tag "Figure"
:attributes ((:name "src" :required t :valued t :group 3 :prompt "Image URL: ")
(:name "alt" :required nil :valued t :group 5 :prompt "Alt text: "))
:type mdx
:self-closing nil)
(:tag "Footnote"
:type mdx
:self-closing t
:doc "")
(:tag "lang"
:attributes ((:name "xml:lang" :required t :valued t :group 3 :reader tlon-md-lang-reader))
:type ssml
:self-closing nil
:doc "")
(:tag "Language"
:attributes ((:name "id" :required t :valued t :group 3 :prompt "Language: "))
:type mdx
:self-closing nil
:doc "Encloses text treated as belonging to that language (e.g. for the purposed of hyphenating it).")
(:tag "LiteralLink"
:attributes ((:name "src" :required t :valued t :group 3 :prompt "Link: "))
:type mdx
:self-closing nil
:doc "The URL of a regular link may be replaced by our scripts according to various
rules. To prevent these replacements with a particular link, enclose its texts
in this tag and pass the URL as the value of the `src' attribute.")
(:tag "Math"
:attributes ((:name "alt" :required nil :valued t :group 3 :prompt "Alt text: ")
(:name "display" :required nil :valued nil :group 5 :reader tlon-md-math-display-reader))
:type mdx
:self-closing nil)
(:tag "OurWorldInData"
:attributes ((:name "src" :required t :valued t :group 3 :prompt "Chart URL: ")
(:name "alt" :required nil :valued t :group 5 :prompt "Alt text: "))
:type mdx
:self-closing t
:doc "")
(:tag "phoneme"
:attributes ((:name "alphabet" :required t :valued t :group 3 :reader tlon-md-phoneme-alphabet-reader)
(:name "ph" :required t :valued t :group 5 :prompt "Phonetic symbols: "))
:type ssml
:self-closing nil
:doc "")
(:tag "ReplaceAudio"
:attributes ((:name "text" :required t :valued t :group 3 :prompt "Audio text: ")
(:name "role" :required nil :valued t :group 5 :prompt "Role: " :reader tlon-md-replace-audio-voice-reader))
:type mdx
:self-closing nil
:doc "Encloses text to be read based on the value of `text'.")
(:tag "Roman"
:type mdx
:self-closing nil
:doc "Encloses text to be displayed in small caps. It will also be read correctly in TTS narration.")
(:tag "say-as"
:attributes ((:name "interpret-as" :required t :valued t :group 3 :reader tlon-md-say-as-interpret-as-reader))
:type ssml
:self-closing nil
:doc "")
(:tag "Sidenote"
:type mdx
:self-closing t
:doc "")
(:tag "SimpleTable"
:attributes ((:name "alt" :required t :valued t :group 3 :prompt "Alt text: ")
(:name "include" :required nil :valued nil :group 5 :reader tlon-md-simple-table-include-reader))
:type mdx
:self-closing nil
:doc "Encloses a Markdown table.")
(:tag "SmallCaps"
:type mdx
:self-closing nil
:doc "Encloses text to be displayed in small caps.")
(:tag "sub"
:type html
:self-closing nil)
(:tag "sup"
:type html
:self-closing nil)
(:tag "q"
:type html
:self-closing nil)
(:tag "VisuallyHidden"
:type mdx
:self-closing nil
:doc "Text to be narrated, but not displayed.")
(:tag "voice"
:attributes ((:name "name" :required t :valued t :group 3 :prompt "Voice name: "))
:type ssml
:self-closing nil
:doc "")
(:tag "VoiceRole"
:attributes ((:name "role" :required t :valued t :group 3 :prompt "Role: " :reader tlon-md-replace-audio-voice-reader))
:type mdx
:self-closing nil
:doc "Encloses text to be read based on the value of `text'."))
"Property list of MDX tag attributes and patterns.
- `:group': the group number that captures the attribute. The value of the
attribute is captured in a separate group, numbered `:group' + 1. The entire
tag expression is captured in group number 1, and the text enclosed by the
tags, when the tag is not self-closing, is captured in group number 2.")
;;;; Functions
;;;;; Insertion
;;;;;; metadata
;;;;###autoload
(defun tlon-edit-yaml-field ()
"Edit the YAML field at point."
(interactive)
(cl-destructuring-bind (key value) (tlon-yaml-get-field-at-point)
(tlon-yaml-insert-field key value)))
;;;;;; Tags
;; TODO: revise to support multiple langs, including en
;;;###autoload
(defun tlon-insert-internal-link ()
"Insert a link to an entity at point.
The entity can be a tag or an author."
(interactive)
(tlon-ensure-markdown-mode)
(let* ((selection (when (use-region-p) (buffer-substring-no-properties (region-beginning) (region-end))))
(current-link (markdown-link-at-pos (point)))
(current-desc (nth 2 current-link))
(current-target (nth 3 current-link))
current-element-title)
(when current-target
(setq current-element-title
(tlon-md-get-title-in-link-target
current-target)))
(let* ((candidates (append
(tlon-metadata-lookup-all (tlon-metadata-in-repo) "title" "type" "article")
(tlon-metadata-lookup-all (tlon-metadata-in-repo) "title" "type" "author")
(tlon-metadata-lookup-all (tlon-metadata-in-repo) "title" "type" "tag")))
(new-element-title (completing-read "Selection: " candidates nil t
(or current-element-title selection)))
(new-target-file (tlon-metadata-lookup (tlon-metadata-in-repo) "file" "title" new-element-title))
(new-target-dir (file-relative-name
(file-name-directory new-target-file) (file-name-directory (buffer-file-name))))
(new-target (file-name-concat new-target-dir (file-name-nondirectory new-target-file)))
(new-desc (if (and current-desc (string= new-target current-target))
current-desc
(or selection new-element-title)))
(link (format "[%s](%s)" new-desc new-target)))
(when current-target
(markdown-mode-extras-delete-link))
(when selection
(delete-region (region-beginning) (region-end)))
(insert link))))
(defun tlon-md-get-title-in-link-target (target)
"Return the title of the tag to which the TARGET of a Markdown link points."
(let* ((file (expand-file-name target default-directory))
(title (tlon-metadata-lookup (tlon-metadata-in-repo) "title" "file" file)))
title))
(defun tlon-md-sort-elements-in-paragraph (separator)
"Sort the elements separated by SEPARATOR in the current paragraph."
(save-excursion
;; Get paragraph boundaries
(let* ((para-start (progn (backward-paragraph)
(skip-chars-forward "\n\t ")
(point)))
(para-end (progn (end-of-paragraph-text)
(point)))
;; Get paragraph text, separate the links
(para-text (buffer-substring-no-properties para-start para-end))
(link-list (mapcar 'ucs-normalize-NFD-string (split-string para-text separator)))
;; Trim and sort the links
(sorted-links (seq-sort-by 'downcase
(lambda (s1 s2)
(string-collate-lessp s1 s2 nil t))
(mapcar 'string-trim link-list))))
;; Clear the current paragraph
(delete-region para-start para-end)
;; Replace it with sorted links
(goto-char para-start)
(insert (mapconcat 'identity sorted-links separator)))))
;;;###autoload
(defun tlon-md-sort-related-entries ()
"Sort the links in the `related entries' section in current buffer.
If no section is found, do nothing."
(interactive)
(save-excursion
(goto-char (point-min))
(when (re-search-forward "^## Entradas relacionadas" nil t)
(forward-paragraph)
(tlon-md-sort-elements-in-paragraph " • "))))
;;;;;; Tag handling
(defun tlon-md-insert-or-edit-tag (tag)
"Insert or edit an MDX TAG pair at point or around the selected region."
(if (tlon-looking-at-tag-p tag)
(tlon-md-edit-tag)
(tlon-md-return-tag tag)))
(defun tlon-looking-at-tag-p (tag)
"Return t iff point is looking at TAG."
(let ((pattern (tlon-md-format-tag tag nil 'get-match-string)))
(thing-at-point-looking-at pattern)))
(defun tlon-md-edit-tag (&optional values content format)
"Edit tag at point.
Optionally, set the attribute VALUES and the tag CONTENT. FORMAT is one of
`get-match-string', `get-placeholders', `get-values', `insert-values', or
`insert-prompt'. If `get-match-string', return a regex pattern to match the tag
and capture its attribute values. Otherwise, return a cons cell with the tag
pair or the opening tag if it is self-closing. If `get-placeholders', return it
filled with placeholders. If `get-values', return it filled with VALUES. If
`insert-values', insert it filled with VALUES. If `insert-prompt', prompt the
user to insert VALUES."
(let* ((tag (tlon-get-tag-at-point))
(pattern (tlon-md-get-tag-pattern tag)))
;; Re-scan to get fresh match data
(goto-char (line-beginning-position))
(when (re-search-forward pattern (line-end-position) t)
(let* ((existing-values (or values (tlon-get-tag-attribute-values tag)))
(content (or content (match-string-no-properties 2)))
(beg (match-beginning 0))
(end (match-end 0)))
;; Store positions before we lose match data
(delete-region beg end)
(goto-char beg)
(tlon-md-return-tag tag existing-values content format)))))
(defun tlon-md-set-tag-attribute-value (tag attribute value)
"Set the VALUE of ATTRIBUTE for TAG."
(let ((values (tlon-get-tag-attribute-values tag))
(pos (cl-position attribute (tlon-get-tag-attribute-names tag) :test #'string=)))
(setcar (nthcdr pos values) value)
values))
(defun tlon-md-insert-attribute-value (attribute value &optional content)
"Insert an ATTRIBUTE VALUE in the tag at point.
If the tag already contains an attribute with the same name, replace its value."
(let ((tag (tlon-get-tag-at-point)))
(tlon-md-edit-tag (tlon-md-set-tag-attribute-value tag attribute value)
content 'insert-values)))
(defun tlon-md-return-tag (tag &optional values content format)
"Return a TAG or TAG pair at point or around the selected region.
VALUES is a list of attribute values. When non-nil, offer each value as the
initial input when prompting the user for the attribute value. CONTENT is the
text the tag pair encloses. FORMAT is one of `get-match-string',
`get-placeholders', `get-values', `insert-values' or `insert-prompt'. If
`get-match-string', return a regex pattern to match the tag and capture its
attribute values. Otherwise, return a cons cell with the tag pair or the opening
tag if it is self-closing. If `get-placeholders', return it filled with
placeholders. If `get-values', return it filled with VALUES. If `insert-values',
insert it filled with VALUES. If `insert-prompt', prompt the user to insert
VALUES."
;; TODO: add check that the length of the VALUES list matches the number of
;; tag attributes, and is nil when it takes no attributes. Similarly for
;; CONTENT and self-closing tag.
(let ((format (or format 'insert-prompt)))
(cl-destructuring-bind (open . close) (tlon-md-format-tag tag values format)
(if close
(if (use-region-p)
(let ((begin (region-beginning)))
(goto-char (region-end))
(insert close)
(goto-char begin)
(insert open))
(tlon-md-act-on-returned-tag (concat open (or content "") close) format))
(tlon-md-act-on-returned-tag open format)))))
(defun tlon-md-act-on-returned-tag (string format)
"Act on the returned STRING based on FORMAT.
FORMAT is one of `get-match-string', `get-placeholders', `get-values',
`insert-values' or `insert-prompt'. If `get-match-string', return a regex
pattern to match the tag and capture its attribute values. Otherwise, return a
cons cell with the tag pair or the opening tag if it is self-closing. If
`get-placeholders', return it filled with placeholders. If `get-values', return
it filled with VALUES. If `insert-values', insert it filled with VALUES. If
`insert-prompt', prompt the user to insert VALUES."
(pcase format
((or 'insert-prompt 'insert-values) (insert string))
((or 'get-match-string 'get-placeholders 'get-values) string)))
(defun tlon-md-format-tag (tag &optional values format)
"Return TAG with attribute VALUES in the appropriate format.
FORMAT is one of `get-match-string', `get-placeholders', `get-values',
`insert-values' or `insert-prompt'. If `get-match-string', return a regex
pattern to match the tag and capture its attribute values. Otherwise, return a
cons cell with the tag pair or the opening tag if it is self-closing. If
`get-placeholders', return it filled with placeholders. If `get-values', return
it filled with VALUES. If `insert-values', insert it filled with VALUES. If
`insert-prompt', prompt the user to insert VALUES."
(let* ((attributes (tlon-md-format-tag-with-attributes tag values format))
(self-closing-p (tlon-lookup tlon-tag-specs :self-closing :tag tag))
(format-string (if self-closing-p "\\(?1:%s\\)" "\\(?1:%s\\(?2:\\(.\\|\n\\)*?\\)%s\\)"))
(open-ending (if self-closing-p " />" ">"))
(open (concat "<" tag attributes open-ending))
(close (unless self-closing-p (concat "</" tag ">"))))
(pcase format
('get-match-string (format format-string open close))
((or 'get-placeholders 'get-values 'insert-values 'insert-prompt)
(if self-closing-p (list open) (cons open close))))))
(defun tlon-md-get-tag-filled (tag &optional values content)
"Return a TAG string with VALUES and CONTENT.
VALUES is a list of attribute values. When non-nil, offer each value as the
initial input when prompting the user for the attribute value. CONTENT is the
text the tag pair encloses."
(cl-destructuring-bind (open . close)
(tlon-md-format-tag tag values 'get-values)
(if close (concat open (or content "") close) open)))
(defun tlon-md-get-tag-to-fill (tag)
"Return a TAG string with placeholders for content and attribute values."
(cl-destructuring-bind (open . close)
(tlon-md-format-tag tag nil 'get-placeholders)
(if close (concat open "%s" close) open)))
(defun tlon-get-tag-at-point ()
"Return the name of the tag at point."
(let ((tags (mapcar (lambda (plist)
(plist-get plist :tag))
tlon-tag-specs)))
(catch 'found
(dolist (tag tags)
(when (tlon-looking-at-tag-p tag)
(throw 'found tag))))))
(defun tlon-get-tag-groups (tag &optional values)
"Return the attribute capture group numbers for TAG.
If VALUES is non-nil, return instead the capture group numbers for the attribute
values."
(let* ((attributes (tlon-lookup tlon-tag-specs :attributes :tag tag))
(groups (mapcar (lambda (attribute)
(plist-get attribute :group))
(if values
(seq-filter (lambda (attr)
(plist-get attr :valued))
attributes)
attributes))))
(if values (mapcar #'1+ groups) groups)))
(defun tlon-get-tag-attribute-names (tag)
"Return a list of all attribute names of TAG."
(let* ((attributes (tlon-lookup tlon-tag-specs :attributes :tag tag))
names)
(dolist (attribute attributes (reverse names))
(push (plist-get attribute :name) names))))
(defun tlon-get-tag-attribute-values (tag)
"Return a list of all attribute values of TAG at point."
(when (tlon-looking-at-tag-p tag)
(let* ((attributes (tlon-lookup tlon-tag-specs :attributes :tag tag))
values)
(dolist (attr attributes values)
(let* ((group (plist-get attr :group))
(valued (plist-get attr :valued))
(value (if valued
(match-string-no-properties (1+ group)) ; value group
(match-string-no-properties group)))) ; attribute group
(push value values)))
(nreverse values))))
;; Not currently used, but might come handy
(defun tlon-md-goto-tag-attribute-value (tag attribute)
"When point is on TAG, move to beginning of ATTRIBUTE value and return it."
(interactive)
(when (tlon-looking-at-tag-p tag)
(let* ((group (1+ (tlon-md-lookup-tag-attribute-property tag attribute :group))))
(when-let* ((values (tlon-get-tag-attribute-values tag))
(value (car values))
(pattern (tlon-md-format-attribute-with-placeholder tag attribute 'capture)))
(re-search-backward (format pattern value) nil t)
(goto-char (match-beginning group))
value))))
(defun tlon-md-lookup-tag-attribute-property (tag name property)
"For the attribute named NAME in TAG, return the value of the PROPERTY."
(let ((attributes (tlon-lookup tlon-tag-specs :attributes :tag tag)))
(tlon-lookup attributes property :name name)))
(defun tlon-md-format-tag-with-attributes (tag &optional values format)
"Format TAG attributes.
FORMAT is one of `get-match-string', `get-placeholders', `get-values' or
`insert-prompt'. If `get-match-string', return a regex string pattern to match
the tag attributes and capture its values. If `get-values', return string with
the attributes filled with VALUES. If `insert-prompt', prompt the user to insert
VALUES. If `get-placeholders', return it filled with placeholders."
(let* ((names (tlon-get-tag-attribute-names tag))
(list (if values
(cl-mapcar #'cons names values)
(mapcar #'list names)))
formatted)
(dolist (cons list formatted)
(let* ((name (car cons))
(value (cdr cons))
(format-string (tlon-md-format-attribute-with-placeholder
tag name (eq format 'get-match-string)))
(required-p (tlon-md-lookup-tag-attribute-property tag name :required))
(group (tlon-md-lookup-tag-attribute-property tag name :group))
(fun (or (tlon-md-lookup-tag-attribute-property tag name :reader)
(lambda ()
(read-string (tlon-md-lookup-tag-attribute-property tag name :prompt) value))))
(string (pcase format
('insert-prompt (tlon-md-format-tag-with-attributes-from-user required-p fun))
((or 'get-values 'insert-values) value))))
(setq formatted
(concat formatted
(pcase format
('get-match-string (tlon-make-attribute-pattern-searchable format-string group required-p))
((or 'get-values 'insert-values 'insert-prompt)
(when string ; don't insert nil values (typically optional attributes)
(format format-string string)))
('get-placeholders format-string))))))))
(defun tlon-md-format-attribute-with-placeholder (tag name &optional capture)
"Get a formatted string for the attribute NAME of TAG.
Include a placeholder for the attribute value, when it is a valued attribute. If
CAPTURE is non-nil, enclose the placeholder in a named capture group."
(let* ((valued-p (tlon-md-lookup-tag-attribute-property tag name :valued))
(group (tlon-md-lookup-tag-attribute-property tag name :group))
(attribute-template (if valued-p
(concat " " name)
"%s"))
(value-template (if capture
(format "=\"\\(?%s:%%s\\)\"" (1+ group))
"=\"%s\"")))
(concat attribute-template (when valued-p value-template))))
(defun tlon-make-attribute-pattern-searchable (pattern group &optional required greedy)
"Make attribute PATTERN with placeholders searchable.
Enclose the PATTERN in a capture group numbered GROUP. Replace the placeholders
with a greedy pattern if GREEDY is non-nil, and a lazy pattern otherwise.
Enclose each pattern in a capture group numbered consecutively starting after
the highest numbered group in the pattern. Unless REQUIRED is non-nil, make the
capture group optional."
(let* ((string (if greedy ".**" ".*?"))
(group-content (format pattern string))
(pattern (format "\\(?%s:%s\\)" group group-content)))
(if required pattern (concat pattern "?"))))
(defun tlon-md-format-tag-with-attributes-from-user (required-p fun)
"Prompt the user to set the value of tag attributes.
FUN is the function to read the attribute value. If REQUIRED-P is non-nil, keep
prompting the user until a non-empty string is entered."
(let ((string (funcall fun)))
(while (and required-p (string-empty-p string))
(setq string (funcall fun)))
string))
(defun tlon-md-get-tag-pattern (tag)
"Return a regexp pattern that matches a TAG expression."
(tlon-md-format-tag tag nil 'get-match-string))
;;;;;;; HTML
;;;###autoload
(defun tlon-html-insert-subscript ()
"Insert an HTML `sub' tag pair at point or around the selected region."
(interactive)
(tlon-md-insert-or-edit-tag "sub"))
;;;###autoload
(defun tlon-html-insert-superscript ()
"Insert an HTML `sup' tag pair at point or around the selected region."
(interactive)
(tlon-md-insert-or-edit-tag "sup"))
;;;###autoload
(defun tlon-html-insert-quote ()
"Insert an HTML `q' tag pair at point or around the selected region."
(interactive)
(tlon-md-insert-or-edit-tag "q"))
;;;;;;; MDX
;;;###autoload
(defun tlon-mdx-insert-aside ()
"Insert an MDX `Aside' tag pair at point or around the selected region."
(interactive)
(tlon-md-insert-or-edit-tag "Aside"))
(defun tlon-mdx-insert-cite ()
"Insert a `Cite' tag pair of TYPE at point or around the selected region."
(interactive)
(tlon-md-insert-or-edit-tag "Cite"))
(defun tlon-md-cite-bibkey-reader ()
"Prompt the user to select the `bibKey' attribute value of the `Cite' tag."
(car (citar-select-refs)))
(defvar tlon-locators)
(defun tlon-md-cite-locator-reader ()
"Prompt the user to select the `locator' attribute value of the `Cite' tag."
(let* ((selection (completing-read "Locator: " (push "" tlon-locators) nil t)))
(alist-get selection tlon-locators nil nil 'string=)))
(defun tlon-md-cite-length-reader ()
"Prompt the user to set the length of the `Cite' tag."
(let ((length (completing-read "Type? " '("short" "long") nil t)))
(if (string= length "short") " short" "")))
;;;###autoload
(defun tlon-mdx-insert-figure ()
"Insert a `Figure' tag pair at point or around the selected region.
Prompt the user to enter values for SRC and ALT. SRC is the image URL, and ALT
is the alt text."
(interactive)
(tlon-md-insert-or-edit-tag "Figure"))
;; TODO: offer language candidates
;;;###autoload
(defun tlon-mdx-insert-language ()
"Insert an MDX `Language' tag pair at point or around the selected region.
Prompt the user to select a LANGUAGE. The enclosed text will be interpreted as
written in that language."
(interactive)
(tlon-md-return-tag "Language"))
;;;###autoload
(defun tlon-mdx-insert-literal-link ()
"Insert an MDX `LiteralLink' tag pair at point or around the selected region.
Prompt the user to select a URL."
(interactive)
(tlon-md-insert-or-edit-tag "LiteralLink"))
;;;###autoload
(defun tlon-mdx-insert-math ()
"Insert an `Math' tag pair of TYPE at point or around the selected region."
(interactive)
(tlon-md-insert-or-edit-tag "Math")
(message "To set the “alt” text with AI, call `tlon-ai-translate-math' (`H-r a m')."))
(defun tlon-md-math-display-reader ()
"Prompt the user to set the display attribute for a `Math' tag."
(let ((display (completing-read "Type? " '("inline" "display"))))
(concat " " display)))
;;;###autoload
(defun tlon-mdx-insert-our-world-in-data ()
"Insert an `OurWorldInData' tag pair at point or around the selected region.
Prompt the user to enter a SRC value."
(interactive)
(tlon-md-insert-or-edit-tag "OurWorldInData"))
;;;###autoload
(defun tlon-mdx-insert-replace-audio ()
"Insert an MDX `ReplaceAudio' tag pair at point or around selected region.
Text enclosed by an `ReplaceAudio' tag pair will be displayed, but when narrated
the value of TEXT will be used instead."
(interactive)
(tlon-md-insert-or-edit-tag "ReplaceAudio"))
(defun tlon-md-replace-audio-voice-reader ()
"Prompt the user to select the `voice' attribute value for a `ReplaceAudio' tag.
- `\"inherit\"' is the voice with which the text surrounding the `ReplaceAudio'
tag is read.
- `\"main\"' is the voice used for reading the text body.
- `\"alternate\"' is the voice used for reading textual elements that are not
part of the main body, such as notes, quotes, and asides, as well as for
reading listener cues (such as cues introducing headings, images, and tables.
It is a voice of the same gender as the main voice.
- `\"male\"' and `\"female\"' are, respectively, male and female voices
different from the main voice. These voice roles may be used for reading text
that is attributed to people of a particular gender (e.g. quotes). The voice
is the same as the alternate voice of that gender.
- `\"alternate gender\"' is a voice of the gender other than that of the main
voice."
(completing-read "`voice': " '("inherit" "main" "alternate" "male" "female" "alternate gender") nil t))
;;;###autoload
(defun tlon-mdx-insert-romantlon-insert-mdx-roman ()
"Insert an MDX `Roman' tag pair at point or around the selected region.
Text enclosed by an `Roman' tag pair will be displayed in small caps."
(interactive)
(tlon-md-insert-or-edit-tag "Roman"))
;;;###autoload
(defun tlon-mdx-insert-small-caps ()
"Insert an MDX `SmallCaps' tag pair at point or around the selected region.
Text enclosed by an `SmallCaps' tag pair will be displayed in small caps.
Note: for Roman numerals, use `tlon-mdx-insert-romantlon-insert-mdx-roman':
`Roman' has exactly the same visual effects as `SmallCaps', but it also makes
the TTS engine read the numbers correctly."
(interactive)
(tlon-md-insert-or-edit-tag "SmallCaps"))
;; TODO: develop
;;;###autoload
(defun tlon-mdx-insert-table ()
"Insert an MDX `Table' tag pair at point or around the selected region."
(interactive)
(message "This command is not yet developed."))
;;;###autoload
(defun tlon-mdx-insert-simple-table ()
"Insert an MDX `SimpleTable' tag pair at point or around the selected region."
(interactive)
(tlon-md-insert-or-edit-tag "SimpleTable"))
(defun tlon-md-simple-table-include-reader ()
"Prompt the user to set the `include' attribute for a `SimpleTable' tag."
(let ((selection (completing-read "Include: " '("nothing" "everything" "body") nil t)))
(format " include=\"%s\"" selection)))
;;;###autoload
(defun tlon-mdx-insert-visually-hidden ()
"Insert an MDX `VisuallyHidden' tag pair at point or around selected region.
Text enclosed by a `VisuallyHidden' tag pair will be narrated, but not
displayed."
(interactive)
(tlon-md-insert-or-edit-tag "VisuallyHidden"))
;;;###autoload
(defun tlon-mdx-insert-voice-role ()
"Insert an MDX `VoiceRole' tag pair at point or around region.
Text enclosed by a `VoiceRole' tag pair will be narrated in the
alternative voice, as opposed to the main voice."
(interactive)
(tlon-md-insert-or-edit-tag "VoiceRole"))
;;;;;;;; Notes
(defun tlon-insert-note-marker (marker &optional overwrite)
"Insert note MARKER in the footnote at point.
If OVERWRITE is non-nil, replace the existing marker when present."
(if-let ((fn-data (tlon-md-get-note-bounds nil 'content-only)))
(let ((start (car fn-data)))
(goto-char start)
(let ((other-marker (car (remove marker (list (car (tlon-md-format-tag "Footnote" nil 'get-values))
(car (tlon-md-format-tag "Sidenote" nil 'get-values)))))))
(cond ((thing-at-point-looking-at (regexp-quote marker))
nil)
((thing-at-point-looking-at (regexp-quote other-marker))
(when overwrite
(replace-match marker)))
(t
(insert marker)))))
(user-error "Not in a footnote")))
;;;###autoload
(defun tlon-insert-footnote-marker (&optional overwrite)
"Insert a `Footnote' marker in the footnote at point.
Text enclosed by a `Footnote' tag pair will be displayed as a footnote, as
opposed to a sidenote.
If OVERWRITE is non-nil, or called interactively, replace the existing marker
when present."
(interactive)
(let ((overwrite (or overwrite (called-interactively-p 'any))))
transient-current-command
(tlon-insert-note-marker (car (tlon-md-format-tag "Footnote" nil 'insert-prompt)) overwrite)))
;;;###autoload
(defun tlon-insert-sidenote-marker (&optional overwrite)
"Insert a `Sidenote' marker in the footnote at point.
Text enclosed by a `Sidenote' tag pair will be displayed as a sidenote, as
opposed to a footnote.
If OVERWRITE is non-nil, or called interactively, replace the existing marker
when present."
(interactive)
(tlon-insert-note-marker (car (tlon-md-format-tag "Sidenote" nil 'insert-prompt)) overwrite))
;;;;;;; SSML
;;;###autoload
(defun tlon-tts-insert-ssml-break ()
"Insert a `break' SSML tag pair at point or around the selected region.
If TIME is nil, prompt the user to enter a value for the `time' attribute."
(interactive)
(tlon-md-insert-or-edit-tag "break"))
;;;###autoload
(defun tlon-tts-insert-ssml-emphasis ()
"Insert a `emphasis' SSML tag pair at point or around the selected region.
If LEVEL is nil, prompt the user to select a value for the `level' attribute."
(interactive)
(tlon-md-insert-or-edit-tag "emphasis"))
(defun tlon-md-emphasis-level-reader ()
"Prompt the user to set the `level' attribute value for a `emphasis' tag."
(completing-read "`emphasis': "
tlon-md-ssml-emphasis-levels nil t nil nil
tlon-tts-ssml-default-emphasis-level))
;;;###autoload
(defun tlon-tts-insert-ssml-lang ()
"Insert a `lang' SSML tag pair at point or around the selected region.
If LANGUAGE is nil. prompt the user to select a value for the `language'
attribute."
(interactive)
(tlon-md-insert-or-edit-tag "lang"))
;; TODO: check whether the two-letter code pairs should be separated by a hyphen or an underscore
(defun tlon-md-lang-reader ()
"Prompt the user to select the `lang' attribute value of the `lang' tag."
(tlon-select-language 'locale))
;;;###autoload
(defun tlon-tts-insert-ssml-phoneme ()
"Insert a `phoneme' SSML tag pair at point or around the selected region.
If ALPHABET or PH are nil, prompt the user to select a value for the `alphabet'
and `ph' attributes."
(interactive)
(tlon-md-insert-or-edit-tag "phoneme"))
(defun tlon-md-phoneme-alphabet-reader ()
"Prompt the user to select the `alphabet' attribute value for a `phoneme' tag."
(completing-read "`alphabet': "
tlon-md-ssml-phoneme-alphabets nil t nil nil
tlon-tts-ssml-phoneme-default-alphabet))
;;;###autoload
(defun tlon-tts-insert-ssml-say-as ()
"Insert a `say-as' SSML tag pair at point or around the selected region.
If INTERPRET-AS is nil, prompt the user to select a value for the `interpret-as'
attribute."
(interactive)
(tlon-md-insert-or-edit-tag "say-as"))
(defun tlon-md-say-as-interpret-as-reader ()
"Prompt the user to select the `interpret-as' attribute value for a `say-as' tag."
(completing-read "`interpret-as': " tlon-md-ssml-interpret-as-values))
;;;;;;;; Common functions
;;;;; Notes
(defun tlon-md-get-note (&optional n content-only)
"Return the note N.
If N is nil, return the note at point.
If CONTENT-ONLY is non-nil, return the beginning of the note content. The note
content is the note minus the marker that precedes it."
(when-let* ((bounds (tlon-md-get-note-bounds n content-only))
(begin (car bounds))
(end (cdr bounds)))
(string-trim (buffer-substring-no-properties begin end))))
(defun tlon-md-get-note-bounds (&optional n content-only)
"Return the start and end positions of note N.
If N is nil, return the note at point.
If CONTENT-ONLY is non-nil, return the beginning of the note content. The note
content is the note minus the marker that precedes it."
(save-excursion
(when n
(if-let ((id (concat "^" (number-to-string n))))
(goto-char (markdown-footnote-find-text id))
(user-error "Note %d not found" n)))
(when-let* ((begin (tlon-md-get-note-beginning content-only))
(end (tlon-md-get-note-end)))
(cons begin end))))
(defun tlon-md-get-note-beginning (&optional content-only)
"Return the beginning of the note at point.
If CONTENT-ONLY is non-nil, return the beginning of the note content. The note
content is the note minus the marker that precedes it."
(if-let ((fn-pos (markdown-footnote-text-positions))
(id (nth 0 fn-pos))
(start (nth 1 fn-pos)))
(if content-only
(markdown-footnote-find-text id)
start)
(save-excursion
(re-search-backward (format tlon-md-footnote-start "[[:digit:]]+") nil t)
(if content-only
(match-end 0)
(match-beginning 0)))))
(defun tlon-md-get-note-end ()
"Return the end of the note at point."
(let ((note-start (format tlon-md-footnote-start "[[:digit:]]+"))
(point (point)))
(save-excursion
(re-search-forward note-start nil t)
(while (<= (match-beginning 0) point)
(re-search-forward note-start nil t))
(1- (tlon-md-get-note-beginning)))))
;;;;; Note classification
(defun tlon-auto-classify-note-at-point ()