Repository navigation
Expand file tree
/
Copy pathabv-script.el
More file actions
718 lines (643 loc) · 33 KB
/
Copy pathabv-script.el
File metadata and controls
718 lines (643 loc) · 33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
;;; abv-script.el --- Script-Objects for abv -*- lexical-binding: t; -*-
;; Copyright (C) 2025 Alexander Prähauser
;; Author: Alexander Prähauser <ahprae@protonmail.com>
;; Keywords: abbrev
;; 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:
;;
;;; Code:
(require 'cl-lib)
(require 'abv-generics)
(cl-defstruct (abv-string-neighborhood
(:constructor abv-string-neighborhood-create))
"Neighborhood of a piece within its formal surroundings.
Slots hold strings:
- previous: formal string immediately to the left of the piece,
- string: the piece itself,
- next: formal string immediately to the right of the piece.
- point-min?: starts the neighborhoot at point min?;
- point-max?.
- mode-sentence-start?: non-nil when the syntax of the current
major mode's table recognizes a sentence start before the piece
(see `abv-mode-sentence-start-p'); nil when unknown or
inapplicable, so string expansions keep the plain script
decision."
previous string next point-min? point-max?
mode-sentence-start?
)
(defconst scr--usual-capital-pairs
(mapcar (lambda (c) (cons c (downcase c)))
(number-sequence ?A ?Z))
"The usual (UPPER . LOWER) pairs of the ASCII letters A-Z.")
(defun abv-capitalize-first-word (string &optional pairs)
"Return STRING with the first letter of its first word upcased.
A letter is a car or cdr of a cell in PAIRS, an alist of
\(UPPER . LOWER) character pairs; PAIRS defaults to the usual
A-Z pairs of `abv-script--usual-capital-pairs'. Only that first
letter is upcased; every other character of STRING is returned
untouched, so later words and the rest of the first word survive
intact. Leading non-letters are skipped; when the first letter
is a capital already, or STRING holds no letter at all, return
STRING unchanged."
(let* ((pairs (or pairs scr--usual-capital-pairs))
(pos (cl-position-if (lambda (ch)
(or (assq ch pairs) (rassq ch pairs)))
string))
(lower (and pos (rassq (aref string pos) pairs))))
(if lower
(concat (substring string 0 pos)
(char-to-string (car lower))
(substring string (1+ pos)))
string)))
(defun abv-decapitalize-first-word (string &optional pairs)
"Return STRING with the first letter of its first word downcased.
A letter is a car or cdr of a cell in PAIRS, an alist of
\(UPPER . LOWER) character pairs; PAIRS defaults to the usual
A-Z pairs of `abv-script--usual-capital-pairs'. Only that first
letter is downcased; every other character of STRING is returned
untouched, so later words and the rest of the first word survive
intact. Leading non-letters are skipped; when the first letter
is a lowercase already, or STRING holds no letter at all, return
STRING unchanged."
(let* ((pairs (or pairs scr--usual-capital-pairs))
(pos (cl-position-if (lambda (ch)
(or (assq ch pairs) (rassq ch pairs)))
string))
(upper (and pos (assq (aref string pos) pairs))))
(if upper
(concat (substring string 0 pos)
(char-to-string (cdr upper))
(substring string (1+ pos)))
string)))
(defclass abv-script ()
((letters :initarg :letters :initform
(cl-loop for c from ?a to ?z collect c)
:type list
:documentation "List of characters treated as letters.
Defaults to the latin lowercase letters.")
(capital-pairs :initarg :capital-pairs
:initform (mapcar (lambda (c) (cons c (downcase c)))
(number-sequence ?A ?Z))
:documentation "Alist of (UPPER . LOWER)
character pairs of the script, used by `abv-capitalized-word-p'
to recognize capitalized words. Extensions like (?É . ?é) slot
in naturally. The default holds the usual A-Z/a-z pairs (see
`abv-script--usual-capital-pairs'); nil disables capitalized
word recognition.")
(phoneme-graph :initarg :phoneme-graph
:initform nil
:type (or null list)
:documentation "Alist mapping letters to
abv-phoneme objects. Each entry is (LETTER . PHONEME) where LETTER is
usually a character or string used as a letter in the script and
PHONEME is an `abv-phoneme' instance representing the canonical
phonetic value of that letter. The rx classes vow/cns expand
through this graph; when nil, a naive vowel fallback is used.")
(morph-separator-signs :initarg :morph-separator-signs
:initform '(?- ?/)
:type list
:documentation "Characters that separate
morphemes inside a word.")
(word-separator-signs :initarg :word-separator-signs
:initform '(?\ )
:type list
:documentation "Characters that separate
words.")
(line-separator-signs :initarg :line-separator-signs
:initform '(?\n)
:type list
:documentation "Characters that separate
lines.")
(subsentence-separator-signs :initarg :subsentence-separator-signs
:initform '(?, ?\; ?: ?…)
:type list
:documentation "Marks that separate
clauses within a sentence.")
(sentence-separator-signs :initarg :sentence-separator-signs
:initform '(?. ?? ?!)
:type list
:documentation "Marks that separate
sentences.")
(opening-bracket-signs :initarg :opening-bracket-signs
:initform '(?\( ?\{ ?\[ ?\")
:type list
:documentation "Opening bracket
characters.")
(closing-bracket-signs :initarg :closing-bracket-signs
:initform '(?\) ?\} ?\] ?\")
:type list
:documentation "Closing bracket characters.")
(standalone-separator-signs :initarg :standalone-separator-signs
:initform '(?—)
:type list
:documentation "Standalone separators
such as em dash.")
(quotation-signs :initarg :quotation-signs
:initform '(?\")
:type list
:documentation "Quotation signs.")
(morph-separator-form :initarg :morph-separator-form
:initform 'ms
:documentation "Rx form for a morph-separator.")
(word-separator-form :initarg :word-separator-form
:initform '(or ws ls)
:documentation "Rx form for a word/line separator.")
(line-separator-form :initarg :line-separator-form
:initform 'ls
:documentation "Rx form for a word/line separator.")
(paragraph-separator-form :initarg :paragraph-separator-form
:initform '(seq ls (+ ls))
:documentation "Rx form for a word/line separator.")
(subsentence-separator-form :initarg :subsentence-separator-form
:initform '(seq ss (or ws ls string-end))
:documentation "Rx form for a subsentence
separator followed by optional spacing. The string-end
alternative lets a clause separator at the buffer end complete,
so the clause before it dispatches and expands instead of the
form falling through to the closing-bracket form behind it.")
(sentence-separator-form :initarg :sentence-separator-form
:initform '(seq Ss (*? (or Ss cb)) (or ws ls string-end))
:documentation "Rx form for a sentence separator,
optionally followed by more sentence/closing brackets, then spacing
or the string end.")
(opening-bracket-form :initarg :opening-bracket-form
:initform '(seq (or ws ls string-start) (+ ob))
:documentation "Rx form for an opening bracket
followed by spacing.")
(closing-bracket-form :initarg :closing-bracket-form
:initform '(seq cb (*? (or Ss cb)) (or ss ws ls string-end))
:documentation "Rx form for a closing bracket,
optionally followed by more closings or sentence stops, then a
subsentence separator, spacing or the string end.")
(standalone-separator-form :initarg :standalone-separator-form
:initform '(seq (or ws ls) sts ws)
:documentation "Rx form for a standalone
separator between spacing.")
(quotation-form :initarg :quotation-form
:initform '(or (seq (or ws ls string-start) (+ qs))
(seq qs (*? (or Ss cb)) (or ss ws ls string-end)))
:documentation "Rx form for quotations."))
:documentation "Script configuration used to split text and to
classify separators. This class contains separator characters and an
optional set of letters used for coarse tokenization.")
(defvar scr--forms-slots-cache (make-hash-table :test 'equal)
"Cache of matching slot names for `abv-script--forms'.
Keys are (CLASS . SUBSTRINGS), values are lists of slot names in
class slot order. The slot set of a class is assumed fixed after
its definition, so entries never need invalidation.")
(defun scr--forms (script &rest substrings)
"Return a list of all forms from SCRIPT matching SUBSTRINGS.
This inspects all class slots of SCRIPT's class. For each
slot, if its name contains any of the strings in the SUBSTRINGS
list, its value in the SCRIPT object is collected.
Returns a list of the non-nil values of these slots.
The name-to-slot matching is memoized per class in
`abv-script--forms-slots-cache'; only the slot values are
read fresh on each call."
(let* ((class (eieio-object-class script))
(key (cons class substrings))
(names (or (gethash key scr--forms-slots-cache)
(puthash key
(delq nil
(mapcar
(lambda (slot)
(let* ((name (oref slot name))
(sname (and name
(symbol-name name))))
(when (and sname
(cl-loop
for sub in substrings
thereis (string-match-p
(regexp-quote sub)
sname)))
name)))
(eieio-class-slots class)))
scr--forms-slots-cache))))
(delq nil (mapcar (lambda (name) (slot-value script name)) names))))
(cl-defgeneric scr-combined-separator-rx (script abv-script &optional exclude)
"Return an rx form that matches any separator form of SCRIPT.
Optionally EXCLUDE a list of forms.")
(cl-defmethod scr-combined-separator-rx ((script abv-script) &optional exclude &key exclude-kinds)
"Return an rx form that matches any separator form of SCRIPT.
Optionally EXCLUDE a list of forms.
If EXCLUDE-KINDS is given, exclude any of the kinds in it."
(let* ((all-forms (scr--separator-forms script))
(forms (if exclude
(cl-remove-if (lambda (f) (member f exclude)) all-forms)
all-forms))
(forms (if exclude-kinds
(cl-remove-if (lambda (f) (cl-some (lambda (kind)
(member kind (flatten-list f)))
exclude-kinds))
all-forms)
forms)))
(when forms
`(+ (or ,@(nreverse forms))))))
(defun scr--separator-forms (script)
"Return a list of all separator forms from SCRIPT.
This inspects all class slots whose names contain the substring
\"separator-form\", \"bracket-form\", or \"quotation-form\".
It returns a list of the non-nil values of these slots."
(scr--forms script "separator-form" "bracket-form" "quotation-form"))
;;;; Healing scripts persisted with historical defaults
(defconst scr--historical-default-forms
'((sentence-separator-form
(seq Ss (*? (or Ss cb)) (or ws ls)))
(subsentence-separator-form
(seq ss (or ws ls)))
(closing-bracket-form
(seq cb (*? (or Ss cb)) (or ws ls string-end)))
(quotation-form
(or (seq (or ws ls string-start) (+ qs))
(seq qs (*? (or Ss cb)) (or ws ls string-end)))))
"Separator form values that earlier `abv-script' defaults used.
Persisted collections embed their languages' scripts with the
initforms of the abv version that saved them, so a later change
of a default never reaches them. These are the forms before the
default change that gave the sentence form its trailing
`string-end' and the closing-bracket and quotation forms their
`ss' alternative, without which a closing bracket before a
subsentence separator does not separate and the piece before it
glues onto the bracket, say \"wd)\" before a comma, and stops
expanding; and before the subsentence form got its own
`string-end' alternative, without which a clause separator at
the buffer end does not complete and the separator run behind a
closing bracket, \"}\\:\" say, dispatches the sexp before the
bracket instead of the clause before the separator.
`abv-script-heal-stale-forms' resets slots still carrying one of
these values to the current default; a slot a user customized
away from every default stays untouched.")
(defun scr--class-default-form (class slot)
"Return CLASS's current default form for SLOT, or nil.
A fresh prototype instance of CLASS supplies the default; classes
that cannot be constructed without initargs fall back to
`abv-script'. A missing or unbound SLOT yields nil."
(let ((proto (condition-case nil
(make-instance class)
(error (make-instance 'abv-script)))))
(and (slot-exists-p proto slot)
(slot-boundp proto slot)
(slot-value proto slot))))
(defun scr-heal-stale-forms (script)
"Reset stale separator-form slots of SCRIPT to the current defaults.
Only slots whose value structurally equals one of the historical
defaults of `abv-script--historical-default-forms' are reset to
the default of SCRIPT's class, so customized forms survive and a
fresh script heals nothing. Modify SCRIPT in place and return
non-nil when any slot changed. The collection loader runs this on
every language script, see `abv-collection--heal-language-scripts'."
(let ((changed nil))
(dolist (cell scr--historical-default-forms)
(let* ((slot (car cell))
(value (and (slot-exists-p script slot)
(slot-boundp script slot)
(slot-value script slot))))
(when (and value (member value (cdr cell)))
(let ((default (scr--class-default-form
(eieio-object-class script) slot)))
(when (and default (not (equal value default)))
(setf (slot-value script slot) default)
(setq changed t))))))
changed))
(defcustom scr-separator-hierarchy
'(paragraph-separator-form
sentence-separator-form
subsentence-separator-form
standalone-separator-form
line-separator-form
word-separator-form
morph-separator-form)
"Separator form slots ordered from the highest to the lowest separator.
Backward parses bound the region they expand by the separator form
of their own level plus every higher one, see
`abv-script-form-and-higher': a sentence parse stops at sentence
and paragraph separators and never crosses into the paragraph
above it, a subsentence parse also stops at sentence separators,
and so on down to the word level. Reorder or extend the list when
scripts introduce further separator form slots; bracket and
quotation forms delimit sexps rather than the flow of text and
stay out of the hierarchy."
:type '(repeat symbol)
:group 'abv)
(defun scr--hierarchy-prefix (slot)
"Return the hierarchy slots up to and including SLOT.
`abv-script-separator-hierarchy' is ordered from the highest to
the lowest separator, so the returned prefix holds SLOT as its
last element and every higher slot before it. SLOT alone is
returned when it is no entry of the hierarchy."
(if (memq slot scr-separator-hierarchy)
(cl-loop for name in scr-separator-hierarchy
collect name
until (eq name slot))
(list slot)))
(defun scr-form-and-higher (script slot)
"Return an rx `or' of SLOT's form and every higher separator form.
The higher forms are the values of the slots preceding SLOT in
`abv-script-separator-hierarchy'. Slots missing in SCRIPT or
holding nil are skipped, so the result can cover fewer forms; nil
is returned when neither SLOT nor a higher slot carries a form.
Pass the result as the delimiter of a backward parse so the parse
never crosses into the thing above its own level."
(let ((forms (delq nil
(mapcar (lambda (name)
(and (slot-exists-p script name)
(slot-boundp script name)
(slot-value script name)))
(scr--hierarchy-prefix slot)))))
(and forms (cons 'or forms))))
(cl-defmethod scr-string-separation-sequence ((script abv-script) string &optional leave-morphs?
)
"Split STRING by combined separator regexp into an ordered alist.
If LEAVE-MORPHS? is non-nil, morphological separators are not
treated as separators.
The alist contains cells of the form (TEXT . TYPE), where TYPE
is either piece or formal. piece is a sequence of
non-separator characters, and formal is a sequence of
separator characters.
The order of cells in the returned list corresponds to the order
in the original STRING."
(let* ((rx-form (if leave-morphs?
(scr-combined-separator-rx script '(ms))
(scr-combined-separator-rx script)))
(rx (and rx-form (abv-rx-to-string script rx-form)))
(str (or string ""))
(pos 0)
(out '()))
(if (not rx)
(list (cons str 'piece))
(while (string-match rx str pos)
(let ((mb (match-beginning 0)) (me (match-end 0)))
(when (> mb pos)
(push (cons (substring str pos mb) 'piece) out))
(push (cons (substring str mb me) 'formal) out)
(setq pos me)))
(when (< pos (length str))
(push (cons (substring str pos) 'piece) out))
(nreverse out))))
(cl-defmethod scr-separation-sequence-typed-germ ((_script abv-script)
sep-seq position)
"Return neighborhood for the PIECE at 0-based POSITION in SEP-SEQ.
SEP-SEQ is an ordered list of cons cells (TEXT . TYPE) as produced by
`abv-script-string-separation-sequence'. Only TYPE \"piece\" cells are
counted to compute POSITION. The neighborhood contains the nearest
formal strings surrounding that piece, if any."
(let ((pieces (seq-filter (lambda (cell) (eq (cdr cell) 'piece)) sep-seq)))
(if (> (length pieces) position)
(let* ((target-cell (nth position pieces))
(target-text (car target-cell))
(target-pos (seq-position sep-seq target-cell))
(prev-formal-cell (seq-find (lambda (cell) (eq (cdr cell) 'formal))
(reverse (seq-subseq sep-seq 0 target-pos))))
(next-formal-cell (seq-find (lambda (cell) (eq (cdr cell) 'formal))
(seq-subseq sep-seq (1+ target-pos)))))
(abv-string-neighborhood-create
:previous (if prev-formal-cell (car prev-formal-cell) "")
:string target-text
:next (if next-formal-cell (car next-formal-cell) "")))
(abv-string-neighborhood-create :previous "" :string "" :next ""))))
(defun scr--germ-expand (script beg end sub-fn min-pos max-pos)
"Helper to expand [BEG, END] to include adjacent separators.
BEG and END are integer positions.
SUB-FN is a function of two arguments (start, end) that
returns the substring.
MIN-POS and MAX-POS are the boundaries for expansion."
(let ((rx (abv-rx-to-string script (scr-combined-separator-rx script)))
(left beg)
(right end))
(when rx
;; expand left
(while (and (> left min-pos)
(let ((sub (funcall sub-fn (1- left) left)))
(and (> (length sub) 0)
(string-match-p (concat "^" rx "$") sub))))
(setq left (1- left)))
;; expand right
(while (and (< right max-pos)
(let ((sub (funcall sub-fn right (1+ right))))
(and (> (length sub) 0)
(string-match-p (concat "^" rx "$") sub))))
(setq right (1+ right))))
(cons left right)))
(cl-defmethod scr-germ ((script abv-script) (object string) where)
"Return neighborhood of substring WHERE in OBJECT for SCRIPT.
WHERE is a cons (BEG . END) with 0-based indices.
OBJECT is a string."
(pcase-let* ((`(,beg . ,end) where)
(expanded (scr--germ-expand script beg end
(lambda (l r) (substring object l r))
0 (length object))))
(abv-string-neighborhood-create
:previous (substring object (car expanded) beg)
:string (substring object beg end)
:next (substring object end (cdr expanded)))))
(cl-defmethod scr-germ ((script abv-script) (object buffer) where)
"Return neighborhood of substring WHERE in OBJECT for SCRIPT.
WHERE is a cons (BEG . END) with 0-based indices.
OBJECT is a buffer."
(with-current-buffer object
(pcase-let* ((`(,beg . ,end) where)
(expanded (scr--germ-expand script beg end
#'buffer-substring-no-properties
(point-min) (point-max))))
(abv-string-neighborhood-create
:previous (buffer-substring-no-properties (car expanded) beg)
:string (buffer-substring-no-properties beg end)
:next (buffer-substring-no-properties end (cdr expanded))))))
(defun scr--char-in-p (ch set)
"Return non-nil when CH is a member of SET.
SET is a list of characters."
(and (characterp ch) (memq ch set)))
(defconst scr--char-class-map '((morph-separator-signs . :morph-separator) (word-separator-signs . :word-separator) (line-separator-signs . :line-separator) (subsentence-separator-signs . :subsentence-separator) (sentence-separator-signs . :sentence-separator) (quotation-signs . :quotation) (opening-bracket-signs . :opening-bracket) (closing-bracket-signs . :closing-bracket) (standalone-separator-signs . :standalone-separator)) "Alist mapping `abv-script' slot names to character classes.
Used by `abv-script--classify-char' to classify a character
based on which separator list it belongs to. A character in
several sign lists classifies by the FIRST matching entry, so
the order fixes the precedence; quotation signs come before the
brackets, letting the default script's double quote classify as
a quotation rather than as a bracket.")
(cl-defmethod scr--classify-char ((script abv-script) ch)
"Return a separator type symbol for CH or the symbol \"word\".
SCRIPT is an `abv-script' instance. Continuous runs of the same
category will later be grouped into a single token."
(or (cl-loop for (slot . class) in scr--char-class-map
when (memq ch (slot-value script slot))
return class)
'word))
;; (cl-defmethod abv-script--split-by-separators ((script abv-script) string)
;; "Split STRING into a list of tokens using SCRIPT.
;; Return a list of `abv--lang-token' in left-to-right order. Tokens are
;; runs of word characters or runs of the same separator category."
;; (abv-script-string-separation-sequence script string)
;; (let* ((chars (string-to-list (or string "")))
;; (out '())
;; (current nil))
;; (dolist (ch chars)
;; (let* ((cls (abv-script--classify-char script ch))
;; (s (char-to-string ch)))
;; (if (null current)
;; (setq current (abv--lang-token-create :type cls :text s))
;; (if (eq (abv--lang-token-type current) cls)
;; (setf (abv--lang-token-text current)
;; (concat (abv--lang-token-text current) s))
;; (push current out)
;; (setq current (abv--lang-token-create :type cls :text s))))))
;; (when current (push current out))
;; (nreverse out)))
(cl-defmethod scr-collect-separator-chars ((script abv-script))
"Return a de-duplicated list of all separator characters in SCRIPT."
(let* ((separator-slots '(morph-separator-signs
word-separator-signs
line-separator-signs
subsentence-separator-signs
sentence-separator-signs
opening-bracket-signs
closing-bracket-signs
standalone-separator-signs
quotation-signs))
(all-chars (mapcan (lambda (slot) (copy-sequence (slot-value script slot)))
separator-slots)))
(delete-dups all-chars)))
(cl-defmethod scr-separator-regexps ((script abv-script))
"Return a list of regexp strings for each separator form in SCRIPT.
This inspects all class slots whose names contain the substring
\"separator-form\". For each non-nil rx form found, compile it to a
regexp string using `abv-rx-to-string'. The order follows the class
slot order."
(let* ((slots (eieio-class-slots (eieio-object-class script)))
(rxs nil))
(dolist (slot slots (nreverse rxs))
(let* ((name (oref slot name))
(sname (and name (symbol-name name))))
(when (and sname (string-match-p "separator-form" sname))
(let* ((form (slot-value script name))
(rx (and form (abv-rx-to-string script form))))
(when rx (push rx rxs))))))))
;; Internal constants for rx atom expansion.
(defconst abv-rx--atom-templates
'((ltt . (+ (any :letters)))
(ms . (+ (any :morph-separator-signs)))
(ws . (+ (any :word-separator-signs)))
(ls . (+ (any :line-separator-signs)))
(ss . (+ (any :subsentence-separator-signs)))
(Ss . (+ (any :sentence-separator-signs)))
(ob . (+ (any :opening-bracket-signs)))
(cb . (+ (any :closing-bracket-signs)))
(sts . (+ (any :standalone-separator-signs)))
(qs . (+ (any :quotation-signs))))
"Mapping of special atoms to rx template forms.
The cdr of each cons is an rx form template that will be spliced into
user-provided rx. Placeholders in templates are keywords like
`:word-separator-signs' and are replaced with the script-specific
character set before calling `rx-to-string'. Templates intentionally
store the forms as written, not as evaluated strings.")
(defconst abv-rx--keyword-slot-alist
'((:letters . letters)
(:morph-separator-signs . morph-separator-signs)
(:word-separator-signs . word-separator-signs)
(:line-separator-signs . line-separator-signs)
(:subsentence-separator-signs . subsentence-separator-signs)
(:sentence-separator-signs . sentence-separator-signs)
(:opening-bracket-signs . opening-bracket-signs)
(:closing-bracket-signs . closing-bracket-signs)
(:standalone-separator-signs . standalone-separator-signs)
(:quotation-signs . quotation-signs))
"Map template placeholders to `abv-script' slots.")
(defconst scr--rx-key-slots
(mapcar #'cdr abv-rx--keyword-slot-alist)
"Slots `abv-rx-to-rx' can read while expanding atom templates.")
(defvar scr--rx-string-cache (make-hash-table :test 'equal)
"Memoization table for `abv-rx-to-string' on `abv-script' receivers.
Keys combine the rx FORM with the values of every character-set
slot of `abv-script--rx-key-slots', so entries stay correct no
matter how scripts are mutated. Values are compiled regexp
strings, or nil for an empty required character set.")
(defvar scr--rx-string-cache-limit 512
"Maximum number of entries kept in `abv-script--rx-string-cache'.
The table is emptied wholesale when the limit is exceeded.")
(defun abv-rx--expand-template (template script)
"Expand a TEMPLATE form using SCRIPT.
Replace keyword placeholders with the corresponding character strings
from SCRIPT. Return a new tree suitable for `rx-to-string'. Signal
failure via `throw' with tag `abv-rx-fail' when a required character
set is empty."
(cl-labels
((abv-subst (node)
(cond
((keywordp node)
(let* ((slot (alist-get node abv-rx--keyword-slot-alist))
(lst (and slot (slot-value script slot))))
(unless (and lst (listp lst) (> (length lst) 0))
(throw 'abv-rx-fail nil))
(apply #'string lst)))
((consp node) (cons (abv-subst (car node)) (mapcar #'abv-subst (cdr node))))
(t node))))
(abv-subst (copy-tree template))))
(cl-defmethod abv-rx-to-rx ((script abv-script) form)
"Translate rx FORM with special atoms into a plain rx form."
(cl-labels
((walk (f)
(cond
((symbolp f)
(let ((tpl (alist-get f abv-rx--atom-templates)))
(if tpl
(abv-rx--expand-template tpl script)
f)))
((consp f)
;; Keep the operator in car intact; expand leaves in cdr.
(cons (car f) (mapcar #'walk (cdr f))))
(t f))))
(walk form)))
(cl-defmethod abv-rx-to-string ((script abv-script) form)
"Translate rx FORM with special atoms into a regexp string.
Special atoms are ms, ws, ls, ss, Ss, ob, cb and sts. Any other
constructs are treated as regular rx. Return nil when a required
character set in SCRIPT is empty. The implementation walks FORM and
replaces each leaf that is one of the special atoms with an rx template
constructed from SCRIPT, then calls rx-to-string.
Results are memoized in `abv-script--rx-string-cache': the cache
key is FORM together with the values of every character-set slot
an atom template can reference, so cached entries remain valid
even when scripts are mutated later."
(let* ((key (cons form
(mapcar (lambda (slot)
(and (slot-boundp script slot)
(slot-value script slot)))
scr--rx-key-slots)))
(hit (gethash key scr--rx-string-cache
'scr--rx-cache-miss)))
(if (eq hit 'scr--rx-cache-miss)
(let ((rx (catch 'abv-rx-fail
(rx-to-string (abv-rx-to-rx script form) t))))
(when (>= (hash-table-count scr--rx-string-cache)
scr--rx-string-cache-limit)
(clrhash scr--rx-string-cache))
(puthash key rx scr--rx-string-cache)
rx)
hit)))
(provide 'abv-script)
;;; abv-script.el ends here
;; Local Variables:
;; read-symbol-shorthands: (("lt-" . "abv-language-table-")
;; ("lng-" . "abv-language-")
;; ("st-" . "abv-sublingual-table-")
;; ("tl-" . "abv-typed-layout-")
;; ("coll-" . "abv-collection-")
;; ("pt-" . "abv-programming-table-")
;; ("elmt-" . "abv-emacs-lisp-mode-table-")
;; ("lmt-" . "abv-LaTeX-mode-table-")
;; ("mo-" . "abv-morph-")
;; ("scr-" . "abv-script-")
;; ("ic-" . "abv-icicles-")
;; ("ti-" . "abv-table-integrate-")
;; ("ev-" . "abv-english-verbs-")
;; ("cls-" . "abv-corpus-language-statistics-")
;; ("lcp-" . "abv-language-cache-persist-"))
;; End: