-
Notifications
You must be signed in to change notification settings - Fork 2
/
esh.el
1640 lines (1447 loc) · 63.2 KB
/
esh.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
;;; esh.el --- Use Emacs to highlight snippets in LaTeX and HTML documents -*- lexical-binding: t; -*-
;; Copyright (C) 2016 Clément Pit-Claudel
;; Author: Clément Pit-Claudel <[email protected]>
;; Package-Requires: ((emacs "24.3"))
;; Package-Version: 0.1
;; Keywords: faces
;; URL: https://github.com/cpitclaudel/esh
;; 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:
;; ESH is an extensible framework for exporting Emacs' syntax highlighting to
;; other languages, and for using Emacs to highlight code snippets embedded in
;; documents. Its LaTeX backend is a replacement for lstlistings, minted, etc.\
;; that uses Emacs' major-modes to syntax-highlight code blocks in your
;; documents.
;;
;; See URL `https://github.com/cpitclaudel/esh' for usage instructions.
;;; Code:
;; Can't depend on external packages
(require 'color)
(require 'tabify)
(require 'cl-lib)
(require 'esh-intervals)
(require 'regexp-opt)
(defconst esh--script-full-path
(or (and load-in-progress load-file-name)
(bound-and-true-p byte-compile-current-file)
(buffer-file-name))
"Full path of this script.")
(defconst esh--directory
(file-name-directory esh--script-full-path)
"Full path to directory of this script.")
;;; Misc utils
(defmacro esh--interactive-export (&rest body)
"Temporarily bump GC limits to let ESH do its thing in BODY.
Also kill temp buffers after completing BODY."
(declare (indent 0) (debug t))
`(let ((gc-cons-threshold (expt 2 26)))
(unwind-protect
(progn ,@body)
(esh--kill-temp-buffers))))
(defun esh--find-auto-mode (fpath)
"Find mode for FPATH.
There's no way to use the standard machinery (`set-auto-mode')
without also initializing the mode, which prevents us from
reusing the same buffer to process multiple source files.
Instead, go through `auto-mode-alist' ourselves."
(let ((mode (assoc-default fpath auto-mode-alist 'string-match)))
(unless mode
(error "No mode found for %S in auto-mode-alist" fpath))
(when (consp mode)
(error "Unexpected auto-mode spec for %S: %S" mode fpath))
mode))
(defun esh--filter-cdr (val alist)
"Remove conses in ALIST whose `cdr' is VAL."
;; FIXME phase this out once Emacs 25 is everywhere
(let ((kept nil))
(while alist
(let ((top (pop alist)))
(when (not (eq (cdr top) val))
(push top kept))))
(nreverse kept)))
(defvar esh-name-to-mode-alist nil
"Alist of block name → mode function.")
(defun esh-add-language (language mode)
"Teach ESH about a new LANGUAGE, highlighted with MODE.
For example, calling (esh-add-language \"ocaml\" \\='tuareg-mode)
allows you to use `tuareg-mode' for HTML blocks tagged
“src-ocaml”, or for LaTeX blocks tagged “ESH: ocaml”."
(unless (stringp language)
(user-error "`esh-add-language': language %S should be a string" language))
(unless (symbolp mode)
(user-error "`esh-add-language': mode %S should be a function" mode))
(add-to-list 'esh-name-to-mode-alist (cons language mode)))
(defun esh--resolve-mode-fn (fn-name)
"Translate FN-NAME to a function symbol.
Uses `esh-name-to-mode-alist'."
(or (cdr (assoc fn-name esh-name-to-mode-alist))
(intern (concat fn-name "-mode"))))
(defun esh-add-keywords (forms &optional how)
"Pass FORMS and HOW to `font-lock-add-keywords'.
See `font-lock-keywords' for information about the format of
elements of FORMS. This function does essentially the same thing
as `font-lock-add-keywords', with nicer indentation, a simpler
call signature, and a workaround for an Emacs bug."
(declare (indent 0))
;; Work around Emacs bug #24176
(setq font-lock-major-mode major-mode)
(font-lock-add-keywords nil forms how))
(defun esh--remove-final-newline ()
"Hide last newline of current buffer, if present.
The line is hidden, rather than removed entirely, because it may
have interesting text properties (e.g. `line-height')."
(goto-char (point-max))
;; There may not be a final newline in standalone mode
(when (eq (char-before) ?\n)
(put-text-property (1- (point)) (point) 'invisible t)))
(defun esh--insert-file-contents (fname)
"Like (`insert-file-contents' FNAME), but allow all local variables."
(let ((enable-local-variables :all))
(insert-file-contents fname)))
(defun esh--merge-sorted (s1 s2 pred)
"Merge two lists S1 S2 sorted by PRED."
(let ((acc nil))
(while (or s1 s2)
(cond
((and s1 s2)
(if (funcall pred (car s1) (car s2))
(push (pop s1) acc)
(push (pop s2) acc)))
(s1 (push (pop s1) acc))
(s2 (push (pop s2) acc))))
(nreverse acc)))
(defun esh--insert (&rest strs)
"Insert all non-nil elements of STRS."
(dolist (str strs)
(when str
(insert str))))
(defmacro esh--pp (x)
"Pretty-print X and its value, then return the value."
(declare (debug t))
(let ((xx (make-symbol "x")))
`(progn (prin1 ',x)
(princ "\n")
(let ((,xx ,x))
(pp ,xx)
(princ "\n")
,xx))))
(defun esh--join (strs sep)
"Joins STRS with SEP."
(mapconcat #'identity strs sep))
(defmacro esh--doplist (bindings &rest body)
"Bind PROP and VAR to pairs in PLIST and run BODY.
BINDINGS should be a list (PROP VAL PLIST).
\(fn (PROP VAL PLIST) BODY...)"
(declare (indent 1) (debug ((symbolp symbolp form) body)))
(pcase-let ((plist (make-symbol "plist"))
(`(,prop ,val ,plist-expr) bindings))
`(let ((,plist ,plist-expr))
(while ,plist
(let ((,prop (pop ,plist))
(,val (pop ,plist)))
,@body)))))
(defun esh--filter-plist (plist props)
"Remove PROPS from PLIST."
(let ((filtered nil))
(esh--doplist (prop val plist)
(unless (memq prop props)
(push prop filtered)
(push val filtered)))
(nreverse filtered)))
(defun esh--plist-keys (plist)
"Get the keys of PLIST."
(let ((keys nil))
(esh--doplist (k _ plist)
(push k keys))
(nreverse keys)))
;;; Copying buffers
(defun esh--number-or-0 (x)
"Return X if X is a number, 0 otherwise."
(if (numberp x) x 0))
(defun esh--augment-overlay (ov)
"Return a list of three values: the priorities of overlay OV, and OV."
(let ((pr (overlay-get ov 'priority)))
(if (consp pr)
(list (esh--number-or-0 (car pr)) (esh--number-or-0 (cdr pr)) ov)
(list (esh--number-or-0 pr) 0 ov))))
(defun esh--augmented-overlay-< (ov1 ov2)
"Compare two lists OV1 OV2 produced by `esh--augment-overlay'."
(or (< (car ov1) (car ov2))
(and (= (car ov1) (car ov2))
(< (cadr ov1) (cadr ov2)))))
(defun esh--buffer-overlays (buf)
"Collects overlays of BUF, in order of increasing priority."
(let* ((ovs (with-current-buffer buf (overlays-in (point-min) (point-max))))
(augmented (mapcar #'esh--augment-overlay ovs))
(sorted (sort augmented #'esh--augmented-overlay-<)))
(mapcar #'cl-caddr sorted)))
(defconst esh--overlay-specific-props
'(after-string before-string evaporate isearch-open-invisible
isearch-open-invisible-temporary priority window)
"Properties that only apply to overlays.")
(defun esh--plists-get (prop plist1 plist2)
"Read property PROP from PLIST1, falling back to PLIST2."
(let ((mem (plist-member plist1 prop)))
(if mem (cadr mem) (plist-get plist2 prop))))
(defun esh--commit-overlays (buf)
"Copy overlays of BUF into current buffer's text properties.
We need to do this, because get-char-text-property considers at
most one overlay."
(let ((pt-min-diff (- (with-current-buffer buf (point-min)) (point-min))))
(dolist (ov (esh--buffer-overlays buf))
(let* ((start (max (point-min) (- (overlay-start ov) pt-min-diff)))
(end (min (point-max) (- (overlay-end ov) pt-min-diff)))
(ov-props (overlay-properties ov))
(cat-props (let ((symbol (plist-get ov-props 'category)))
(and symbol (symbol-plist symbol))))
(before-str (esh--plists-get 'before-string ov-props cat-props))
(after-str (esh--plists-get 'after-string ov-props cat-props))
(face (esh--plists-get 'face ov-props cat-props))
(props (esh--filter-plist (append cat-props ov-props)
(cons 'face esh--overlay-specific-props))))
(when face
(font-lock-prepend-text-property start end 'face face))
(when before-str
(font-lock-prepend-text-property start end 'esh--before before-str))
(when after-str
(font-lock-append-text-property start end 'esh--after after-str))
(add-text-properties start end props)))))
(defun esh--copy-buffer (buf)
"Copy contents and overlays of BUF into current buffer."
(insert-buffer-substring buf)
(esh--commit-overlays buf)
(dolist (var '(tab-width buffer-display-table buffer-invisibility-spec))
(set (make-local-variable var) (buffer-local-value var buf))))
(defmacro esh--with-copy-of-current-buffer (&rest body)
"Run BODY in a temporary copy of the current buffer."
(declare (indent 0) (debug t))
(let ((buf (make-symbol "buf")))
`(let ((,buf (current-buffer)))
(with-temp-buffer
(esh--copy-buffer ,buf)
,@body))))
;;; Segmenting buffers
(defun esh--buffer-ranges-from (start prop)
"Create a stream of buffer ranges from START.
Ranges are pairs of START..END positions in which all characters
have the same value of PROP or, if PROP is nil, of all
properties."
(let ((ranges nil)
(end nil))
(while (setq end (if prop (next-single-property-change start prop)
(next-property-change start)))
(push (cons start end) ranges)
(setq start end))
(push (cons start (point-max)) ranges)
(nreverse ranges)))
(defun esh--buffer-ranges (&optional prop)
"Create a stream of buffer ranges.
Ranges are pairs of START..END positions in which all characters
have the same value of PROP or, if PROP is nil, of all
properties."
(esh--buffer-ranges-from 1 prop))
;;; Extracting faces and properties
(defun esh--extract-props (props pos)
"Read PROPS from POS as an ALIST of (PROP . VAL)."
(let ((alist nil))
(esh--doplist (prop val (text-properties-at pos))
(when (and (memq prop props) val)
(push (cons prop val) alist)))
(nreverse alist)))
(defun esh--face-get (face attribute)
"Read ATTRIBUTE from (potentially anonymous) FACE.
Does not take inheritance into account."
(cond ((listp face)
(if (plist-member face attribute)
(plist-get face attribute)
'unspecified))
(t (face-attribute face attribute))))
(defun esh--single-face-attribute (face attribute)
"Read ATTRIBUTE from (potentially anonymous) FACE.
Takes inheritance into account."
(let* ((attr (esh--face-get face attribute))
(rel-p (face-attribute-relative-p attribute attr))
(inherit (esh--face-get face :inherit)))
(if (and rel-p
(not (eq inherit 'default))
(or (listp inherit) (facep inherit)))
(let ((merge-with (esh--single-face-attribute inherit attribute)))
(merge-face-attribute attribute attr merge-with))
attr)))
(defun esh--faces-attribute (faces attribute)
"Read ATTRIBUTE from FACES.
Faces is a list of (possibly anonymous) faces."
(let ((attr 'unspecified))
(while (and faces (face-attribute-relative-p attribute attr))
(let ((merge-with (esh--single-face-attribute (pop faces) attribute)))
(setq attr (merge-face-attribute attribute attr merge-with))))
attr))
(defun esh--faces-at-point (pos)
"Compute list of faces at POS."
;; No need to consider overlay properties here, since they've been converted
;; to text properties in previous steps.
(let ((face (get-text-property pos 'face)))
;; `face' is either a face, like `font-lock-keyword-face' or (:weight bold), or a
;; list of those, so the following is an attempt at distinguishing those.
(if (and (listp face) (not (keywordp (car face))))
face
(list face))))
;; Caching this function speeds things up by about 5%
(defun esh--extract-face-attributes (face-attributes faces)
"Extract FACE-ATTRIBUTES from FACES."
(esh--filter-cdr 'unspecified
(mapcar (lambda (attr) (cons attr (esh--faces-attribute faces attr)))
face-attributes)))
(defun esh--extract-pos-face-attributes (face-attributes pos)
"Extract FACE-ATTRIBUTES from POS."
(let ((faces (esh--faces-at-point pos)))
(and faces ;; Empty list of faces → no face attributes
(esh--extract-face-attributes face-attributes faces))))
(defvar-local esh--invisible-replacement-string nil)
(defun esh--glyph-to-string (c)
"Convert glyph C to char."
(propertize (char-to-string (glyph-char c)) 'face (glyph-face c)))
(defun esh--invisible-replacement-string ()
"Compute or return string to display for invisible regions."
(or esh--invisible-replacement-string
(setq-local
esh--invisible-replacement-string
(mapconcat #'esh--glyph-to-string
(or (char-table-extra-slot buffer-display-table 4)
(char-table-extra-slot standard-display-table 4)) ""))))
(defun esh--invisible-p (val)
"Determine whether invisible:VAL makes text invisible.
Returns either nil (not invisible), or a string (the text that
the invisible range is replaced with)."
(let ((invisible (invisible-p val)))
(pcase invisible
(`t "")
(`nil nil)
(_ (esh--invisible-replacement-string)))))
;;; Massaging properties
(defun esh--replace-region (from to str prop)
"Replace FROM .. TO with STR, keeping all props but PROP."
(let* ((str-keys (esh--plist-keys (text-properties-at 0 str)))
(plist (esh--filter-plist (text-properties-at from) `(,prop ,@str-keys))))
(goto-char from)
(delete-region from to)
(insert str)
(add-text-properties from (+ from (length str)) plist)))
(defun esh--parse-composition (components)
"Translate composition COMPONENTS into a string."
(let ((chars (list (aref components 0)))
(nrules (/ (length components) 2)))
(dotimes (nrule nrules)
(let* ((rule (aref components (+ 1 (* 2 nrule))))
(char (aref components (+ 2 (* 2 nrule)))))
(pcase rule
(`(Br . Bl) (push char chars))
(_ (error "Unsupported composition COMPONENTS")))))
(concat (nreverse chars))))
(defun esh--commit-compositions ()
"Apply compositions in current buffer.
This replaces each composed string by its composition, forgetting
the original string."
(pcase-dolist (`(,from . ,to) (nreverse (esh--buffer-ranges 'composition)))
(let ((comp-data (find-composition from nil nil t)))
(when comp-data
(pcase-let* ((`(,_ ,_ ,components ,relative-p ,_ ,_) comp-data)
(str (if relative-p (concat components)
(esh--parse-composition components))))
(esh--replace-region from to str '(composition)))))))
(defun esh--commit-replacing-display-specs ()
"Apply replacing display specs in current buffer."
(pcase-dolist (`(,from . ,to) (nreverse (esh--buffer-ranges 'display)))
(let ((display (get-text-property from 'display)))
(when (stringp display)
(esh--replace-region from to display 'display)))))
(defun esh--commit-before-strings ()
"Apply before-string specs in current buffer."
(pcase-dolist (`(,from . ,_) (nreverse (esh--buffer-ranges 'esh--before)))
(let ((strs (get-text-property from 'esh--before)))
(goto-char from)
(insert (mapconcat #'identity strs "")))))
(defun esh--commit-after-strings ()
"Apply after-string specs in current buffer."
(pcase-dolist (`(,from . ,to) (nreverse (esh--buffer-ranges 'esh--after)))
(let ((strs (get-text-property from 'esh--after)))
(goto-char to)
(insert (mapconcat #'identity strs "")))))
(defun esh--commit-specs ()
"Commit various text properties as concrete text in the buffer."
(esh--commit-before-strings)
(esh--commit-after-strings)
(esh--commit-replacing-display-specs)
(esh--commit-compositions))
(defun esh--mark-newlines (&optional additional-props)
"Add `esh--newline' and ADDITIONAL-PROPS text properties to each \\n.
The value of `esh--newline' is either `empty' or `non-empty' (we
need this to add a dummy element on empty lines to prevent LaTeX
from complaining about underful hboxes). Adding these properties
also makes it easy to group ranges by line, which yields a
significant speedup when processing long files (compared to
putting all lines in one large interval tree)."
(goto-char (point-min))
(while (search-forward "\n" nil t)
;; (point-at-bol 0) is beginning of previous line
;; (match-beginning 0) is end of previous line
;; Inclusion of (point) prevents collapsing of adjacent properties
(let* ((empty (= (point-at-bol 0) (match-beginning 0)))
(newline (cons (point) (if empty 'empty 'non-empty))))
(add-text-properties (match-beginning 0) (match-end 0)
`(esh--newline ,newline ,@additional-props)))))
(defun esh--translate-invisibility (range)
"Replace value of `invisible' text property in RANGE by a string.
The string indicates what the corresponding text should be
replaced with. It is nil if the text should in fact be visible."
(let* ((alist (cl-caddr range))
(invisible (assq 'invisible (cl-caddr range))))
(when invisible
(let ((repl (esh--invisible-p (cdr invisible))))
(if repl (setf (cdr invisible) repl)
(setf (cl-caddr range) (assq-delete-all 'invisible alist)))))))
;;; Constructing a stream of events
(defun esh--annotate-ranges (ranges text-props face-attrs)
"Annotate each range in RANGES with a property alist.
Returns a list of (START END ALIST); the keys of ALIST are
properties in TEXT-PROPS or face attributes in FACE-ATTRS; its
values are the values of these properties. START is inclusive;
END is exclusive."
(let ((acc nil))
(pcase-dolist (`(,start . ,end) ranges)
(let* ((props-alist (esh--extract-props text-props start))
(attrs-alist (esh--extract-pos-face-attributes face-attrs start))
(merged-alist (nconc attrs-alist props-alist)))
(push (list start end merged-alist) acc)))
(nreverse acc)))
(defun esh--ranges-to-events (ranges props)
"Generate opening and closing events from annotated RANGES.
Each returned element has one of the following forms:
(\\='open POSITION (PROPERTY . VALUE))
(\\='close POSITION (PROPERTY . VALUE))
Each PROPERTY is one of PROPS."
(let ((events nil)
(prev-alist nil)
(prev-end nil))
(pcase-dolist (`(,start ,end ,alist) ranges)
(let ((break-here (or (assq 'esh--break prev-alist) (assq 'esh--break alist))))
(dolist (prop props)
(let ((old (assq prop prev-alist))
(new (assq prop alist)))
(when (or break-here (not (equal old new)))
(when old
(push `(close ,start ,old) events))
(when new
(push `(open ,start ,new) events))))))
(setq prev-end end)
(setq prev-alist alist))
(dolist (pair prev-alist)
(push `(close ,prev-end ,pair) events))
(nreverse events)))
(defun esh--event-property (event)
"Read property changed by EVENT."
(car (nth 2 event)))
;;; Building property trees
(defun esh--events-to-intervals (events ranking)
"Parse sequence of EVENTS into lists of intervals.
Returns a list of lists suitable for consumption by
`esh-intervals-make-doctree' and containing one entry per
property in RANKING."
(let ((ints-tbl (make-hash-table :test #'eq)))
(dolist (property ranking)
(puthash property nil ints-tbl))
(dolist (event events)
(pcase event
(`(open ,pos ,annot)
;; `car' of (gethash … …) becomes a partially constructed interval…
(push `(,pos nil . ,annot) (gethash (car annot) ints-tbl)))
(`(close ,pos ,annot)
;; …which gets completed here:
(esh-assert (equal annot (cddr (car (gethash (car annot) ints-tbl)))))
(setf (cadr (car (gethash (car annot) ints-tbl))) pos))))
(let ((int-lists nil))
(dolist (property ranking)
(push (nreverse (gethash property ints-tbl)) int-lists))
(nreverse int-lists))))
;;; High-level interface to tree-related code
(defun esh--buffer-to-document-tree
(text-props face-attrs ranking range-filter merge-annots)
"Construct a property tree from the current buffer.
TEXT-PROPS and FACE-ATTRS specify which properties to keep track
of. RANKING ranks all these properties in order of tolerance to
splitting (if a property comes late in this list, ESH will try to
preserve this property's spans when resolving conflicts).
RANGE-FILTER is applied to the list of (annotated) ranges in the
buffer before constructing property trees. Splitting is needed
because in Emacs text properties can overlap in ways that are not
representable as a tree. MERGE-ANNOTS: see
`esh-intervals-ints-to-document'."
(let* ((ranges (esh--buffer-ranges))
(ann-ranges (esh--annotate-ranges ranges text-props face-attrs)))
(dolist (range ann-ranges)
(funcall range-filter range))
(let* ((events (esh--ranges-to-events ann-ranges ranking))
(ints (esh--events-to-intervals events ranking))
(doctree (esh-intervals-make-doctree
ints (point-min) (point-max) merge-annots)))
(esh-intervals-doctree-map-annots #'esh--normalize-suppress-defaults doctree)
doctree)))
;;; Fontifying
(defun esh--font-lock-ensure ()
"Wrapper around `font-lock-ensure'."
(if (fboundp 'font-lock-ensure)
(font-lock-ensure)
(with-no-warnings (font-lock-fontify-buffer))))
(defconst esh--missing-mode-template
(concat ">>> (void-function %S); did you forget to `require'"
" a dependency, or to restart the server? <<<%s"))
(defun esh--missing-mode-error-msg (mode)
"Construct an error message about missing MODE."
(propertize (format esh--missing-mode-template mode " ")
'face 'error 'font-lock-face 'error))
(defvar esh--temp-buffers nil
"Alist of (MODE . BUFFER).
These are temporary buffers, used for highlighting.")
(defun esh--kill-temp-buffers ()
"Kill buffers in `esh--temp-buffers'."
(mapc #'kill-buffer (mapcar #'cdr esh--temp-buffers))
(setq esh--temp-buffers nil))
(defun esh--make-temp-buffer (mode)
"Get temp buffer for MODE from `esh--temp-buffers'.
If no such buffer exist, create one and add it to BUFFERS. In
all cases, the buffer is erased, and a message is added to it if
the required mode isn't available."
(save-match-data
(let ((buf (cdr (assq mode esh--temp-buffers)))
(mode-boundp (fboundp mode)))
(unless buf
(setq buf (generate-new-buffer " *temp*"))
(with-current-buffer buf
(funcall (if mode-boundp mode #'fundamental-mode)))
(push (cons mode buf) esh--temp-buffers))
(with-current-buffer buf
(erase-buffer)
(unless mode-boundp
(insert (esh--missing-mode-error-msg mode))))
buf)))
(defvar esh-pre-highlight-hook nil)
(defvar esh-post-highlight-hook nil) ;; FIXME document these
(defun esh--export-buffer (export-fn)
"Refontify current buffer, then invoke EXPORT-FN.
EXPORT-FN should do the actual exporting."
(run-hook-with-args 'esh-pre-highlight-hook)
(esh--font-lock-ensure)
(run-hook-with-args 'esh-post-highlight-hook)
(funcall export-fn))
(defun esh--export-str (str mode-fn export-fn)
"Fontify STR in a MODE-FN buffer, then invoke EXPORT-FN.
EXPORT-FN should do the actual exporting."
(with-current-buffer (esh--make-temp-buffer mode-fn)
(insert str)
(esh--export-buffer export-fn)))
(defun esh--export-file (source-path export-fn)
"Fontify contents of SOURCE-PATH, then invoke EXPORT-FN."
(let ((mode-fn (esh--find-auto-mode source-path)))
(with-current-buffer (esh--make-temp-buffer mode-fn)
(esh--insert-file-contents source-path)
(esh--export-buffer export-fn))))
;;; Cleaning up face attributes and text properties
(defun esh--normalize-color (color)
"Return COLOR as a hex string.
`color-rgb-to-hex', used to work fine, until it got broken in
7b00e956b485d8ade03c870cbdd0ae086348737b."
(unless (member color '("unspecified-fg" "unspecified-bg" "" nil))
(upcase (if (= (aref color 0) ?#)
(substring color 1)
(pcase-let ((`(,r ,g ,b) (color-name-to-rgb color)))
(format "%02x%02x%02x" (* 255 r) (* 255 g) (* 255 b)))))))
(defun esh--normalize-underline (underline)
"Normalize UNDERLINE."
(pcase underline
(`nil nil)
(`t '(nil . line))
((pred stringp) `(,(esh--normalize-color underline) . line))
((pred listp) `(,(esh--normalize-color (plist-get underline :color)) .
,(or (plist-get underline :style) 'line)))
(_ (error "Unexpected underline %S" underline))))
(defun esh--normalize-weight (weight)
"Normalize WEIGHT."
(pcase weight
((or `thin `ultralight `ultra-light) 100)
((or `extralight `extra-light) 200)
((or `light) 300)
((or `demilight `semilight `semi-light `book) 400)
((or `normal `medium `regular) 500)
((or `demi `demibold `semibold `semi-bold) 600)
((or `bold) 700)
((or `extrabold `extra-bold `black) 800)
((or `ultrabold `ultra-bold) 900)
(_ (error "Unexpected weight %S" weight))))
(defun esh--normalize-height (height)
"Normalize HEIGHT to a relative (float) height."
(let* ((default-height (face-attribute 'default :height))
(height (merge-face-attribute :height height default-height)))
(unless (eq height default-height)
(/ height (float default-height)))))
(defun esh--normalize-slant (slant)
"Normalize SLANT."
(pcase slant
((or `italic `oblique `normal) slant)
(_ (error "Unexpected slant %S" slant))))
(defun esh--normalize-box (box)
"Normalize face attribute BOX.
Numeric values are undocumented, but `face-attribute' sometimes
returns 1 instead of t."
(pcase box
(`nil nil)
(`t `(1 nil nil))
((pred stringp) `(1 ,(esh--normalize-color box) nil))
((pred numberp) `(,box nil nil))
((pred listp) `(,(or (plist-get box :line-width) 1)
,(esh--normalize-color (plist-get box :color))
,(plist-get box :style)))
(_ (error "Unexpected box %S" box))))
(defun esh--normalize-display (display)
"Normalize attribute DISPLAY."
(pcase display
(`nil `(raise nil))
(`(raise ,amount) `(raise ,(unless (= amount 0) amount)))
(_ (error "Unexpected display property %S" display))))
(defun esh--normalize-attribute (property value)
"Normalize VALUE of PROPERTY."
(pcase property
(:foreground (esh--normalize-color value))
(:background (esh--normalize-color value))
(:underline (esh--normalize-underline value))
(:weight (esh--normalize-weight value))
(:height (esh--normalize-height value))
(:slant (esh--normalize-slant value))
(:box (esh--normalize-box value))
(`display (esh--normalize-display value))
(_ value)))
(defun esh--attribute-redundant-p (property value)
"Check whether PROPERTY and VALUE can be safely dropped."
(equal value
(pcase property
((or :foreground :background)
(let* ((default (face-attribute 'default property)))
(esh--normalize-attribute property default)))
(:underline nil)
(:weight 500)
(:slant 'normal)
(:box nil)
(_ (not value)))))
(defun esh--normalize-suppress-defaults (annotation)
"Normalize VALUE of PROPERTY (both in ANNOTATION).
`:foreground' and `:background' values that match the `default'
face are suppressed. Redundant property-value pairs (nil boxes
or underlines, for example) are also suppressed.
\(fn (PROPERTY . VALUE))"
(pcase-let ((`(,property . ,value) annotation))
(setq value (esh--normalize-attribute property value))
(unless (esh--attribute-redundant-p property value)
(cons property value))))
(defun esh--normalize-defaults (annotation)
"Normalize the pair ANNOTATION of the `default' face.
Useful when exporting the properties of the default face,
e.g. when rendering a buffer as HTML, htmlfontify-style.
\(fn (PROPERTY . VALUE))"
(pcase-let ((`(,property . ,value) annotation))
(unless (eq property :height)
(setq value (esh--normalize-attribute property value)))
(when (or (member property '(:foreground :background))
(not (esh--attribute-redundant-p property value)))
(cons property value))))
;;; Producing LaTeX
(defconst esh--latex-props
'(display invisible line-height esh--newline esh--break))
(defconst esh--latex-face-attrs
'(:underline :background :foreground :weight :slant :box :height))
(defconst esh--latex-priorities
`(;; Fine to split
,@'(esh--break line-height :underline :foreground :weight :height :background)
;; Should not split
,@'(:slant :box display esh--newline invisible))
"Priority order for text properties in LaTeX export.
See `esh--resolve-event-conflicts'.")
(eval-and-compile
(defconst esh--latex-specials
'(;; Special characters
(?$ . "\\$") (?% . "\\%") (?& . "\\&")
(?{ . "\\{") (?} . "\\}") (?_ . "\\_") (?# . "\\#")
;; https://tex.stackexchange.com/questions/67997/
(?\\ . "\\textbackslash{}") (?^ . "\\textasciicircum{}")
(?~ . "\\textasciitilde{}")
;; A few ligatures
(?` . "{`}") (?' . "{'}") (?< . "{<}") (?> . "{>}")
;; Characters that behave differently in inline and block modes
(?\s . "\\ESHSpace{}") (?- . "\\ESHDash{}"))))
(defconst esh--latex-specials-re
(eval-when-compile
(regexp-opt-charset (mapcar #'car esh--latex-specials))))
(defconst esh--latex-specials-vector
(eval-when-compile
(let* ((max-idx (apply #'max (mapcar #'car esh--latex-specials)))
(vect (make-vector (1+ max-idx) nil)))
(pcase-dolist (`(,from . ,to) esh--latex-specials)
(aset vect from to))
vect)))
(defun esh--latex-substitute-specials (beg)
"Escape LaTeX specials in BEG .. `point-max'."
(goto-char beg)
(while (re-search-forward esh--latex-specials-re nil t)
(let ((special (char-after (match-beginning 0))))
(replace-match (aref esh--latex-specials-vector special) t t))))
(defvar esh--latex-escape-alist nil
"Alist of additional ‘char → LaTeX string’ mappings.")
(defun esh-latex-add-unicode-substitution (char-str latex-cmd)
"Register an additional ‘unicode char → LaTeX command’ mapping.
CHAR-STR is a one-character string; LATEX-CMD is a latex command."
(unless (and (stringp char-str) (eq (length char-str) 1))
(user-error "%S: %S should be a one-character string"
'esh-latex-add-unicode-substitution char-str))
(add-to-list 'esh--latex-escape-alist (cons (aref char-str 0) latex-cmd)))
(defun esh--latex-escape-1 (char)
"Escape CHAR for use with pdfLaTeX."
(unless (featurep 'esh-latex-escape)
(load-file (expand-file-name "esh-latex-escape.el" esh--directory)))
(or (cdr (assq char esh--latex-escape-alist))
(let ((repl (gethash char (with-no-warnings esh-latex-escape-table))))
(and repl (format "\\ESHMathSymbol{%s}" repl)))))
(defun esh--latex-escape-unicode-char (c)
"Replace character C with an equivalent LaTeX command."
(let* ((translation (esh--latex-escape-1 c)))
(unless translation
(error "No LaTeX equivalent found for character `%c'.
Use (esh-latex-add-unicode-substitution \"%c\" \"\\\\someCommand\") to add one" c c))
(format "\\ESHUnicodeSubstitution{%s}" translation)))
(defun esh--latex-wrap-special-char (char)
"Wrap CHAR in \\ESHSpecialChar{…}."
(format "\\ESHSpecialChar{%c}" char))
(defvar esh-substitute-unicode-symbols nil
"If non-nil, attempt to substitute Unicode symbols in code blocks.
Symbols are replaced by their closest LaTeX equivalent. This
option is most useful with pdfLaTeX; with XeLaTeX or LuaLaTeX, it
should probably be turned off (customize \\ESHFallbackFont
instead).")
(defun esh--latex-wrap-non-ascii (beg)
"Wrap non-ASCII characters in BEG .. `point-max'.
If `esh-substitute-unicode-symbols' is nil, wrap non-ASCII characters into
\\ESHSpecialChar{}. Otherwise, replace them by their LaTeX equivalents
and wrap them in \\ESHUnicodeSubstitution{}."
;; TODO benchmark against trivial loop
(let* ((range "[^\000-\177]")
(fun (if esh-substitute-unicode-symbols
#'esh--latex-escape-unicode-char
#'esh--latex-wrap-special-char)))
(goto-char beg)
(while (re-search-forward range nil t)
(replace-match (funcall fun (char-after (match-beginning 0))) t t))))
(defun esh--mark-non-ascii ()
"Tag non-ASCII characters of current buffer.
Puts text property `non-ascii' on non-ascii characters."
(goto-char (point-min))
(while (re-search-forward "[^\000-\177]" nil t)
;; Need property values to be distinct, hence (point)
(put-text-property (match-beginning 0) (match-end 0) 'non-ascii (point))))
(defun esh--latex-range-filter (range)
"Filter properties of RANGE.
Remove most of the properties on ranges marked with
`esh--newline' (keep only `invisible' and `line-height'
properties), and remove `line-height' properties on others."
(esh--translate-invisibility range)
(let ((alist (cl-caddr range)))
(cond
((assq 'esh--newline alist)
(let ((new-alist nil))
(dolist (pair alist)
(when (memq (car pair) '(invisible line-height esh--newline esh--break))
(push pair new-alist)))
(setf (cl-caddr range) new-alist)))
((assq 'line-height alist)
(setf (cl-caddr range) (assq-delete-all 'line-height alist))))))
(defvar esh--latex-source-buffer-for-export nil
"Buffer that text nodes point to.")
(defun esh--latex-insert-substituted (str)
"Insert STR, escaped for LaTeX.
Point must be at end of buffer."
(let ((pt (point)))
(insert str)
(esh--latex-substitute-specials pt)
(esh--latex-wrap-non-ascii pt)
(goto-char (point-max))))
(defun esh--latex-export-plain-text (start end)
"Insert escaped text from range START..END.
Text is read from `esh--latex-source-buffer-for-export'. Point
must be at end of buffer."
(esh--latex-insert-substituted
(with-current-buffer esh--latex-source-buffer-for-export
(buffer-substring-no-properties start end))))
(defun esh--latex-export-subtrees (l r trees)
"Export TREES to LaTeX.
L .. R is the range covered by TREES; if TREES is nil, this
function exports a plain text range."
(if (null trees) (esh--latex-export-plain-text l r)
(dolist (tree trees)
(esh--latex-export-doctree tree))))
(defun esh--latex-export-wrapped (before l r trees after)
"Export TREES, wrapped in BEFORE and AFTER.
L .. R is the range covered by TREES."
(insert before)
(esh--latex-export-subtrees l r trees)
(insert after))
(defun esh--latex-export-wrapped-if (val before-fmt l r trees after)
"Export TREES, possibly wrapped.
If VAL is non-nil, wrap SUBTREES in (format BEFORE-FMT VAL) and
AFTER. L .. R is the range covered by TREES."
(declare (indent 1))
(if (null val)
(esh--latex-export-subtrees l r trees)
(esh--latex-export-wrapped (format before-fmt val) l r trees after)))
(defun esh--latex-export-doctree-1 (property val l r subtrees)
"Export SUBTREES wrapped in a LaTeX implementation of PROPERTY: VAL.
L .. R is the range covered by SUBTREES (if SUBTREES is nil, then
PROPERTY and VAL apply directly to a text range)."
(pcase property
(:foreground
(esh--latex-export-wrapped-if val
"\\textcolor[HTML]{%s}{" l r subtrees "}"))
(:background
;; FIXME: Force all lines to have the the same height?
;; Could use \\vphantom{'g}\\smash{…}
(esh--latex-export-wrapped-if val
"\\ESHColorBox{%s}{" l r subtrees "}"))
(:weight
(esh--latex-export-wrapped
(cond
((< val 500) "\\ESHWeightLight{")
((> val 500) "\\ESHWeightBold{")
(t "\\ESHWeightRegular{"))
l r subtrees "}"))
(:height
(esh--latex-export-wrapped-if val
"\\textscale{%0.2g}{" l r subtrees "}"))
(:slant
(esh--latex-export-wrapped
(pcase val
(`italic "\\ESHSlantItalic{")
(`oblique "\\ESHSlantOblique{")
(`normal "\\ESHSlantNormal{"))
l r subtrees "}"))
(:underline
(esh--latex-export-wrapped
(pcase val
(`(,color . ,type)
;; There are subtle spacing issues with \\ESHUnder, so don't
;; use it unless the underline needs to be colored.
(let* ((prefix (if color "\\ESHUnder" "\\u"))
(command (format "%s%S" prefix type))
(arg (if color (format "{\\color[HTML]{%s}}" color) "")))
(format "%s%s{" command arg))))
l r subtrees "}"))
(:box
(esh--latex-export-wrapped
(pcase val
(`(,line-width ,color ,style)
(unless (eq style nil)
(error "Unsupported box style %S" style))
(format "\\ESHBox{%s}{%.2fpt}{" (or color ".") (abs line-width)))
(_ (error "Unexpected box %S" val)))
l r subtrees "}"))
(`display
(pcase val
(`(raise ,amount)
(esh--latex-export-wrapped-if amount
"\\ESHRaise{%.2f}{" l r subtrees "}"))
(_ (error "Unexpected display property %S" val))))
(`invisible
(when val (insert val)))
(`line-height
(unless (floatp val)
(error "Unexpected line-height property %S" val))
(esh--latex-export-wrapped-if val
"\\ESHStrut{%.2g}" l r subtrees ""))
(`esh--newline
(esh--latex-export-wrapped-if (eq (cdr val) 'empty)
"\\ESHEmptyLine{}" l r subtrees ""))
(`esh--break (esh--latex-export-subtrees l r subtrees))
(_ (error "Unexpected property %S" property))))
(defun esh--latex-export-doctree (doctree)
"Export DOCTREE to LaTeX."