-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathfont-lock-studio.el
3180 lines (2724 loc) · 119 KB
/
font-lock-studio.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
;;; font-lock-studio.el --- Debugger for Font Lock keywords. -*- lexical-binding: t; -*-
;; Copyright (C) 2013-2017,2022,2025 Anders Lindgren
;; Author: Anders Lindgren
;; Keywords: faces, tools
;; Created: 2013-12-07
;; Version: 0.0.9
;; URL: https://github.com/Lindydancer/font-lock-studio
;; Package-Requires: ((emacs "24.3"))
;; 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 <http://www.gnu.org/licenses/>.
;;; Commentary:
;; Interactive debugger for font-lock keywords (Emacs syntax
;; highlighting rules).
;;
;; Font Lock Studio lets you *single-step* Font Lock keywords --
;; matchers, highlights, and anchored rules, so that you can see what
;; happens when a buffer is fontified. You can set *breakpoints* on
;; or inside rules and *run* until one has been hit. When inside a
;; rule, matches are *visualized* using a palette of background
;; colors. The *explainer* can describe a rule in plain-text English.
;; Tight integration with *Edebug* allows you to step into Lisp
;; expressions that are part of the Font Lock keywords.
;; Usage:
;;
;; When using the debugger, an *interface buffer* is displayed, it
;; contains all the keywords and is used for navigation and
;; visalization of match data.
;;
;; When Font Lock Studio is started, comments and strings are
;; pre-colored, as they are part of the earlier *syntactic phase*
;; (which isn't supported by Font Lock Studio).
;;
;; Start the debugger by typing `M-x font-lock-studio RET'. Press `?'
;; or see the menu for available commands.
;;
;; Why use a debugger?:
;;
;; You might be the author of Font Lock keywords for a major more, you
;; might simply want to add your own personal highlighting rules, or
;; you simply would like to know more about how Font Lock keywords
;; work.
;;
;; Regardless of your background and ambition, there is a world of
;; difference between simply reading Font Lock keywords and being able
;; to step through the rules and exactly see what they do. In fact, as
;; part of writing Font Lock Studio, I learned some new Font Lock
;; tricks from various major modes -- despite having 15+ years of
;; experience with Font Lock.
;; Example:
;;
;; For a buffer using `html-mode', the interface buffer looks the
;; following. Other major modes typically have more and more complex
;; rules. The arrow on the left indicates the current active location.
;; A corresponding arrow in the source buffer is placed at the current
;; search location.
;;
;;
;; ========================
;; === Font Lock Studio ===
;; ========================
;; --------------------------------------------------
;; => "<\\([!?][_:[:alpha:]][-_.:[:alnum:]]*\\)"
;; (1 font-lock-keyword-face)
;; --------------------------------------------------
;; "</?\\([_[:alpha:]][-_.[:alnum:]]*\\)\\(?::\\([_:[:alpha:]]
;; [-_.:[:alnum:]]*\\)\\)?"
;; (1
;; (if
;; (match-end 2)
;; sgml-namespace-face font-lock-function-name-face))
;; (2 font-lock-function-name-face nil t)
;; --------------------------------------------------
;; "\\(?:^\\|[ \t]\\)\\([_[:alpha:]][-_.[:alnum:]]*\\)\\(?::
;; \\([_:[:alpha:]][-_.:[:alnum:]]*\\)\\)?=[\"']"
;; (1
;; (if
;; (match-end 2)
;; sgml-namespace-face font-lock-variable-name-face))
;; (2 font-lock-variable-name-face nil t)
;; --------------------------------------------------
;; "[&%][_:[:alpha:]][-_.:[:alnum:]]*;?"
;; (0 font-lock-variable-name-face)
;; --------------------------------------------------
;; "<\\(b\\(?:ig\\|link\\)\\|cite\\|em\\|h[1-6]\\|rev\\|s\\(?:
;; mall\\|trong\\)\\|t\\(?:itle\\|t\\)\\|var\\|[bisu]\\)
;; \\([ \t][^>]*\\)?>\\([^<]+\\)</\\1>"
;; (3
;; (cdr
;; (assoc-string
;; (match-string 1)
;; sgml-tag-face-alist t))
;; prepend)
;; ==================================================
;; Public state:
;; Debug on error : YES
;; Debug on quit : YES
;; Explain rules : YES
;; Show compiled code : NO
;;
;; Press space to single step through all the keywords. "n" will go
;; the the next keyword, "b" will set a breakpoint, "g" will run to
;; the end (or to the next breakpoint) and "q" will quit.
;;
;; In the following screenshot, you will see the debugger in action.
;; The user has stepped into the last rule (for the second out of
;; three times) -- the matches are visualized in the regexp, in the
;; source buffer and in the highlight rule. In addition, *auto
;; explainer* is active so the rule is described in english.
;; Furthermore, the red text means a *breakpoint* is set, in this case
;; on a highlight rule, which is part of a Font Lock keyword rule.
;;
;; ![See doc/demo.png for screenshot of Font Lock Studio](doc/demo.png)
;; Features:
;;
;; Stepping:
;;
;; You can single *step into*, *over*, and *out* of Font Lock
;; keywords. *Anchored* rules are fully supported. In addition, you
;; can *run* to the end or to the next breakpoint.
;;
;; Breakpoints:
;;
;; You can set breakpoints on part of the keyword, like the matcher
;; (e.g. the regexp), a highlight rule, or inside an anchored highlight
;; rule.
;;
;; If you want to step or run without stopping on breakpoints, prefix
;; the command with `C-u'.
;;
;; Note that in an anchored rule, you can set a breakpoints either on
;; the entire rule or on an individual part. In the former case, only
;; the outer parentheses are highlighted.
;;
;; Match Data Visualization:
;;
;; After the *matcher* of a keyword or anchored highlight has been
;; executed, the match data (whatever the search found) is visualized
;; using background colors in the source buffer, in the regexp, and
;; over the corresponding highlight rule or rules. If part of a regexp
;; or a highlight didn't match, it is not colored, this can for
;; example happen when the postfix regexp operator `?' is used.
;;
;; Note that an inner match group gets precedence over an outer group.
;; This can lead to situations where a highlight rule gets a color
;; that doesn't appear in the regexp or in the source buffer. For
;; example, the matcher "\\(abc\\)" will be colored with the color for
;; match 1, while the higlight rule `(0 a-face)' gets the color for
;; match 0.
;;
;; Normalized keywords:
;;
;; The keywords presented in the interface have been normalized. For
;; example, instead of
;;
;; ("xyz" . font-lock-type-face)
;;
;; the keyword
;;
;; ("xyz" (0 font-lock-type-face))
;;
;; is shown. See `font-lock-studio-normalize-keywords' for details.
;;
;; Explainer:
;;
;; The *explainer* echoes a human-readble description of the current
;; part of the Font Lock keywords. This help you to understand that
;; all those `nil':s and `t':s in the rules actually mean.
;;
;; When using the *auto explainer*, Font Lock Studio echoes the
;; explanation after each command.
;;
;; Edebug -- the Emacs Lisp debugger:
;;
;; Tight integration with Edebug allows you to single-step expressions
;; embedded in the keywords in the interface buffer, and it allows you
;; to instrument called functions for debugging in their source file.
;;
;; Follow mode awareness:
;;
;; The search location in the source buffer is visualized by an
;; overlay arrow and by updating the point. If the source buffer is
;; visible in multiple side-by-side windows and Follow mode is
;; enabled, the search location will be shown in a suitable windows to
;; minimize scrolling.
;; Tips and trix:
;;
;; The "Hanging Emacs" problem:
;;
;; Traditionally, if you use a function as a matcher and that function
;; doesn't return -- Emacs hangs and all you can do is to kill it and
;; restart. (I know from personal experience that it's not uncommon
;; for functions that parse text to hang -- for example, when you have
;; forgotten to check for the end-of-buffer.) When using font-lock
;; studio, you can simply press `C-q' to exit.
;;
;; If you have a source file that hangs Emacs when loaded, first
;; disable font-lock using `M-x global-font-lock-mode RET' before
;; loading the file, and finally launch Font-Lock studio.
;;
;; `cc-mode' keywords:
;;
;; The keywords provided by major modes like `c-mode', `objc-mode',
;; `cpp-mode' that are based on `cc-mode' contain *byte-compiled*
;; font-lock keywords, which are unreadable and undebugable. To use
;; corresponding keywords with *uncompiled* code, copy the file
;; `cc-fonts.el', replace explicit calls to `byte-compile' with `eval'
;; and issue `M-x eval-buffer RET'.
;; Implementation overview:
;;
;; State-machine fontification engine:
;;
;; Font Lock Studio provides it's own fontification engine, designed
;; to for things needed by a debugger such as single-stepping and
;; breakpoints. This fontification engine lacks a lot of features of
;; the real font-lock fontification engine, such as the speed and the
;; ability to refontify when the buffer is modified.
;;
;; The fontification engine can be used without an interface buffer.
;;
;; Regexp decomposer:
;;
;; In order for to visualize the groups in regexp:s that corresponds
;; to matches, they must be located. This requires a non-trivial
;; *regexp parser*.
;; Other Font Lock Tools:
;;
;; This package is part of a suite of font-lock tools. The other
;; tools in the suite are:
;;
;;
;; Font Lock Profiler:
;;
;; A profiler for font-lock keywords. This package measures time and
;; counts the number of times each part of a font-lock keyword is
;; used. For matchers, it counts the total number and the number of
;; successful matches.
;;
;; The result is presented in table that can be sorted by count or
;; time. The table can be expanded to include each part of the
;; font-lock keyword.
;;
;; In addition, this package can generate a log of all font-lock
;; events. This can be used to verify font-lock implementations,
;; concretely, this is used for back-to-back tests of the real
;; font-lock engine and Font Lock Studio, an interactive debugger for
;; font-lock keywords.
;;
;;
;; Highlight Refontification:
;;
;; Minor mode that visualizes how font-lock refontifies a buffer.
;; This is useful when developing or debugging font-lock keywords,
;; especially for keywords that span multiple lines.
;;
;; The background of the buffer is painted in a rainbow of colors,
;; where each band in the rainbow represent a region of the buffer
;; that has been refontified. When the buffer is modified, the
;; rainbow is updated.
;;
;;
;; Faceup:
;;
;; Emacs is capable of highlighting buffers based on language-specific
;; `font-lock' rules. This package makes it possible to perform
;; regression test for packages that provide font-lock rules.
;;
;; The underlying idea is to convert text with highlights ("faces")
;; into a plain text representation using the Faceup markup
;; language. This language is semi-human readable, for example:
;;
;; «k:this» is a keyword
;;
;; By comparing the current highlight with a highlight performed with
;; stable versions of a package, it's possible to automatically find
;; problems that otherwise would have been hard to spot.
;;
;; This package is designed to be used in conjunction with Ert, the
;; standard Emacs regression test system.
;;
;; The Faceup markup language is a generic markup language, regression
;; testing is merely one way to use it.
;;
;;
;; Face Explorer:
;;
;; Library and tools for faces and text properties.
;;
;; This library is useful for packages that convert syntax highlighted
;; buffers to other formats. The functions can be used to determine
;; how a face or a face text property looks, in terms of primitive
;; face attributes (e.g. foreground and background colors). Two sets
;; of functions are provided, one for existing frames and one for
;; fictitious displays, like 8 color tty.
;;
;; In addition, the following tools are provided:
;;
;; - `face-explorer-list-faces' -- list all available faces. Like
;; `list-faces-display' but with information on how a face is
;; defined. In addition, a sample for the selected frame and for a
;; fictitious display is shown.
;;
;; - `face-explorer-describe-face' -- Print detailed information on
;; how a face is defined, and list all underlying definitions.
;;
;; - `face-explorer-describe-face-prop' -- Describe the `face' text
;; property at the point in terms of primitive face attributes.
;; Also show how it would look on a fictitious display.
;;
;; - `face-explorer-list-display-features' -- Show which features a
;; display supports. Most graphical displays support all, or most,
;; features. However, many tty:s don't support, for example,
;; strike-through. Using specially constructed faces, the resulting
;; buffer will render differently in different displays, e.g. a
;; graphical frame and a tty connected using `emacsclient -nw'.
;;
;; - `face-explorer-list-face-prop-examples' -- Show a buffer with an
;; assortment of `face' text properties. A sample text is shown in
;; four variants: Native, a manually maintained reference vector,
;; the result of `face-explorer-face-prop-attributes' and
;; `face-explorer-face-prop-attributes-for-fictitious-display'. Any
;; package that convert a buffer to another format (like HTML, ANSI,
;; or LaTeX) could use this buffer to ensure that everything work as
;; intended.
;;
;; - `face-explorer-list-overlay-examples' -- Show a buffer with a
;; number of examples of overlays, some are mixed with `face' text
;; properties. Any package that convert a buffer to another format
;; (like HTML, ANSI, or LaTeX) could use this buffer to ensure that
;; everything work as intended.
;;
;; - `face-explorer-tooltip-mode' -- Minor mode that shows tooltips
;; containing text properties and overlays at the mouse pointer.
;;
;; - `face-explorer-simulate-display-mode' -- Minor mode for make a
;; buffer look like it would on a fictitious display. Using this
;; you can, for example, see how a theme would look in using dark or
;; light background, a 8 color tty, or on a grayscale graphical
;; monitor.
;;
;;
;; Font Lock Regression Suite:
;;
;; A collection of example source files for a large number of
;; programming languages, with ERT tests to ensure that syntax
;; highlighting does not accidentally change.
;;
;; For each source file, font-lock reference files are provided for
;; various Emacs versions. The reference files contains a plain-text
;; representation of source file with syntax highlighting, using the
;; format "faceup".
;;
;; Of course, the collection source file can be used for other kinds
;; of testing, not limited to font-lock regression testing.
;;; Code:
;; ----------------------------------------
;; Note: Everything above "Code" will be part of the GitHub README.md
;; file.
;; Naming convention:
;;
;; Source buffer -- the buffer being fontified.
;;
;; Interface buffer -- the buffer containing the debugger interface.
;;
;; Control buffer -- a buffer holding information about the
;; fontification using buffer-local variables,
;; typically the interface buffer. However, the
;; fontification engine can be used by itself, in
;; which case this can be any buffer including a
;; temporary buffer and the source buffer itself.
;; Known Problems:
;;
;; - Sometimes, the interface buffer is not displayed. (Could it be
;; that it is first shown, then it tries to show the source buffer
;; and it reuses the same window?)
;; Open issues:
;;
;; - Is C-u really a good idea for non-stop? It doesn't show up in the
;; menu and C-h m. Maybe do something like "s" steps and "S" steps
;; nonstop. (Note: There is no shifted space.)
;;
;; - A hidden compiled matched in an anchored rule without pre, post,
;; and matcher (which is illegal, by the way) is rendered "(;;
;; Compiled code (hidden))". This doesn't look that good as the
;; closing parenthesis is drawn at the end of the comment. For now,
;; I guess we can live with it. (See C mode for an example.)
;;
;; - Replace "predicate" with "form", to makes it easier to call.
;; However, keeping the lambda construct makes it clearer that that
;; it's a callback.
;;
;; - Maybe rename `font-lock-studio-fontify-step' to avoid confusion
;; with the normal step commands. However, I need a good name,
;; "tick-state-machine"?
;; Future ideas:
;;
;; - Support for debugging the "syntactic" font-lock phase.
;;
;; - Collect statistics, including timing information.
;;
;; - Disable rules. (Could use the same mechanism used by
;; breakpoints.)
;;
;; - Breakpoints in source buffer.
;;
;; - Save and restore breakpoints.
;;
;; - Visualize when a keyword has been normalized.
;;
;; - Customize support.
;;
;; - Print code better (indented, font-locked, lambda and parameter
;; list on the same line).
;;
;; - bind debug-on-error and debug-on-quit temporarily (like edebug does).
;; Random notes:
;;
;; Note on the syntax: Inside a backtick-lambda, "abc" is the value of
;; the expression "abc" at the time the lambda is called, and ",abc"
;; is the current value.
;;
;; Interface buffer:
;;
;; After each command, the interface buffer is erased and filled with
;; new content using a *renderer*. Or, rather, that is how it is
;; intended to work. However, when doing so, windows displaying the
;; buffer drop their start position. Instead, when the interface
;; buffer is drawn, it replaces the existing content line-by-line.
;;
;; ----------------------------------------
;; Byte-compile support
;;
(eval-when-compile
(defvar follow-mode))
(declare-function follow-post-command-hook "follow.el")
(declare-function edebug-instrument-function "edebug.el")
(declare-function edebug-read-and-maybe-wrap-form "edebug.el")
;; ----------------------------------------
;; Variables
;;
;; --------------------
;; Public variables
;;
(defvar font-lock-studio-color-list-light '("chartreuse1"
"tan1"
"PaleTurquoise2"
"gold1"
"grey85"
"OliveDrab2"
"Yellow")
"*List of light colors suitable for match data visualization.")
(defvar font-lock-studio-color-list-medium '("Cyan"
"Orange"
"OliveDrab3"
"grey75"
"yellow3"
"orchid1")
"*List of medium colors suitable for match data visualization.")
(defvar font-lock-studio-color-list-dark '("DeepSkyBlue"
"chocolate"
"Green"
"grey65"
"gold3"
"orchid3")
"*List of dark colors suitable for match data visualization.")
(defvar font-lock-studio-color-scheme 'light-to-dark
"*The preferred colors used for match data visualization.
This can be one of:
`dark-to-light' -- Start with light colors, end with dark.
`light-to-dark' -- Start with dark colors, end with light.
`light' -- Light colors.
`medium' -- Medium colors.
`dark' -- Dark colors.")
(defvar font-lock-studio-color-list
(cond ((eq font-lock-studio-color-scheme 'dark-to-light)
(append font-lock-studio-color-list-dark
font-lock-studio-color-list-medium
font-lock-studio-color-list-light))
((eq font-lock-studio-color-scheme 'light-to-dark)
(append font-lock-studio-color-list-light
font-lock-studio-color-list-medium
font-lock-studio-color-list-dark))
((eq font-lock-studio-color-scheme 'light)
font-lock-studio-color-list-light)
((eq font-lock-studio-color-scheme 'medium)
font-lock-studio-color-list-medium)
((eq font-lock-studio-color-scheme 'dark)
font-lock-studio-color-list-dark)
(t
(error "Unexpected color scheme")))
"*List of colors used to visualize matches in control and source buffers.")
(defvar font-lock-studio-anchored-search-region-face 'region
"*Face used to visualize the anchored search region.
Normally, the region is between the point and the end of the
line. However, if the pre-match form returns a position (greater
than the point), this is used as the end of the region.")
;; Note: This is the value of the *variable* `font-lock-warning-face',
;; not the actual face, as this respects user-configuration.
(defvar font-lock-studio-breakpoint-face font-lock-warning-face
"Face used to visualize breakpoints in the interface buffer.
This can be a symbol representing the actual face or a face or a
property list suitable for the `face' special property.")
(defvar font-lock-studio-auto-explain t
"*When non-nil, a human-readable explanation is echoed after each command.
The explanation is only echoed if no other message is present.
See also `font-lock-studio-toggle-auto-explain'.")
(defvar font-lock-studio-major-mode-alias
'((c-mode cpp-mode objc-mode))
"*List of major modes considered equal.
When setting a breakpoint in a buffer, the breakpoint will also
be set for buffers considered aliases, provided they have an
identical font-lock keyword.
Each element is a list of major modes. The first element in the
list is used as key in `font-lock-studio-major-mode-breakpoints-alist'.")
(defvar font-lock-studio-show-compiled-code nil
"*When nil, compiled code is not shown in Font Lock Studio.
See also `font-lock-studio-toggle-show-compiled-code'.")
(defvar font-lock-studio-show-public-state t
"*When non-nil, show public state variables in Font Lock Studio.
See also `font-lock-studio-toggle-show-public-state'")
(defvar font-lock-studio-show-internal-state nil
"*When non-nil, show internal state variables in Font Lock Studio.
See also `font-lock-studio-toggle-show-internal-state'")
;; --------------------
;; Internal variables
;;
;; ----------
;; Persistent variables
;;
;; The following represent the current state in the fontification
;; state machine.
;; Implementation note: Since keywords can be modified between
;; sessions, the keyword number can't be used here. Instead, the full
;; keyword is saved.
(defvar font-lock-studio-major-mode-breakpoints-alist nil
"Alist from major mode to list of breakpoints.
Each breakpoint is on the form:
(FULLKWRD COUNT)
(FULLKWRD COUNT HIGHLIGHT)
(FULLKWRD COUNT HIGHLIGHT ANCHOR-STATE)
Above, FULLKWRD is the full keyword (compared using `equal'),
COUNT is the N:th occurrence of the keyword (typically 1),
HIGHLIGHT is a number, and ANCHOR-STATE a number or one of
`:pre', `:matcher', or `:post'.")
;; ----------
;; Fontification engine
;;
(defvar font-lock-studio-buffer nil
"The source buffer Font Lock Studio is associated with.")
(defvar font-lock-studio-region nil
"The region, as a pair of markers, that Font Lock Studio was applied to.")
(defvar font-lock-studio-keywords nil
"Normalized Font-Lock keywords of the source buffer.")
(defvar font-lock-studio-case-fold-search nil
"Non-nil means search is case-insensitive.
This corresponds to `font-lock--case-fold-search' of the srouce buffer.")
(defvar font-lock-studio-multiline nil
"Non-nil means support multiline keywords.
This corresponds to `font-lock-multiline' of the source buffer.")
;; TODO: Replace :done with nil?
(defvar font-lock-studio-keyword-number nil
"The keyword number currently active, or :done.")
(defvar font-lock-studio-highlight-number nil
"The highlight number in the current keyword, or nil.")
(defvar font-lock-studio-anchored-state nil
"Where we are in a anchored match.
It can take on the following values:
nil -- Not at anchored rule, or before stepping into one.
:pre -- Before the pre-match form should be evaluated.
:matcher -- Before searching for a match
NUMBER -- the next highlight number to fontify.
:post -- After matcher failed, but before the post-match-form.")
(defvar font-lock-studio-fontify-breakpoints '()
"Breakpoints in the current Font Lock Studio session.
Elements on one of the forms:
(KWRD)
(KWRD HIGHLIGHT)
(KWRD HIGHLIGHT ANCHOR-STATE)
Above, KWRD and HIGHLIGHT are numbers and ANCHOR-STATE a number or
one of `:pre', `:matcher', or `:post'.")
(defvar font-lock-studio-point nil
"Current search point in the source buffer.")
(defvar font-lock-studio-anchored-limit nil
"The search limit of the current anchored rule.
This is typically the end of the current line, but can be
overridden by the pre-match form.")
(defvar font-lock-studio-keyword-match-data nil
"Currently active match data.")
(defvar font-lock-studio-keyword-match-data-saved nil
"The match data of the keyword, saved during an anchored highlight rule.")
(defvar font-lock-studio-original-font-lock-mode nil
"Non-nil if Font-lock mode should be restored in the source buffer.")
(defvar font-lock-studio-edebug-active nil
"Non-nil when Edebug should debug expressions in the interface buffer.")
(defvar font-lock-studio-edebug-expression-point nil
"Point in the interface buffer where a debuggable form is located.
When Edebug is used, this form is used instead of the actual form
in the font-lock keywords. The effect is that Edebug can be used
directly in the interface buffer.")
;; ----------
;; Interface buffer
;;
(defvar font-lock-studio-window-configuration nil
"The window configuration at the time Font-Lock studio was stated.")
(defvar font-lock-studio-overlays '()
"List of active overlays in the source buffer.")
;; ------------------------------------------------------------
;; Helpers
;; Amazingly, there is no `assert' function in the core Emacs Lisp
;; language of modern Emacs versions.
;;
;; Once upon a time, the package `cl' provided one along other useful
;; functions inspired by Common Lisp. Unfortunately, `cl' has been
;; deprecated and replaced with `cl-lib' which tries to make Emacs
;; Lisp into a Common Lisp. For us that don't want that it leaves us
;; without those functions.
(defmacro font-lock-studio-assert (form)
"Issue an error if FORM is non-nil."
`(unless ,form
(error ,(format "Assertion failed: %s" form))))
;; ------------------------------------------------------------
;;;###autoload
(defun font-lock-studio (&optional arg)
"Interactively debug the font-lock keywords of the current buffer.
With \\[universal-argument] prefix (when ARG is non-nil), create
a new, unique, interface buffer."
(interactive "P")
(font-lock-studio-region (point-min) (point-max) arg))
;;;###autoload
(defun font-lock-studio-region (beg end &optional arg)
"Interactively debug the font-lock keywords between BEG and END.
With \\[universal-argument] prefix (when ARG is non-nil), create
a new, unique, interface buffer."
(interactive "rP")
(let ((name "*Font Lock Studio*"))
(if arg
(setq name (generate-new-buffer-name name)))
(let ((interface-buffer (get-buffer-create name))
(orig-buffer (current-buffer)))
;; Exit existing session.
(with-current-buffer interface-buffer
(font-lock-studio-finish))
;; Start new session.
(font-lock-set-defaults)
(let ((keywords font-lock-keywords))
(with-current-buffer interface-buffer
(font-lock-studio-mode)
(set (make-local-variable 'font-lock-studio-window-configuration)
(current-window-configuration))
(make-local-variable 'font-lock-studio-overlays)
(make-local-variable 'overlay-arrow-position)
(font-lock-studio-fontify-start orig-buffer beg end)
(font-lock-studio-fontify-restart)
(select-window (display-buffer interface-buffer))
(font-lock-studio-render)
(font-lock-studio-show-source))))))
(defun font-lock-studio-finish ()
"Restore the source buffer to it's original state.
Used when restarting and when the interface buffer is killed."
(when (and font-lock-studio-buffer
(buffer-live-p font-lock-studio-buffer))
(font-lock-studio-remove-source-overlays)
(with-current-buffer font-lock-studio-buffer
(when overlay-arrow-position
(move-marker overlay-arrow-position nil)
(setq overlay-arrow-position nil)))
(font-lock-studio-fontify-done)))
(eval-when-compile
;; Same as used by font-lock.el
;; We use this to preserve or protect things when modifying text properties.
(defmacro font-lock-studio-save-buffer-state (&rest body)
"Eval BODY, silencing modifications and inhibiting hooks."
(declare (indent 0) (debug t))
`(let ((inhibit-point-motion-hooks t))
(with-silent-modifications
,@body))))
;; ------------------------------------------------------------
;; The interface buffer.
;;
;; --------------------
;; The major mode.
;;
(define-derived-mode font-lock-studio-mode special-mode "Font-Lock-Studio"
"Major mode for the Font Lock Studio interface buffer.
\\{font-lock-studio-mode-map}"
(add-hook 'kill-buffer-hook 'font-lock-studio-finish t t))
;; --------------------
;; Keymap and menu.
;;
(let ((map font-lock-studio-mode-map))
(define-key map " " 'font-lock-studio-step-into)
(define-key map "E" 'font-lock-studio-step-into-and-debug)
(define-key map "I" 'font-lock-studio-instrument-matcher)
(define-key map "M" 'font-lock-studio-show-match-data)
(define-key map "l" 'font-lock-studio-update-interface-buffer)
(define-key map "e" 'font-lock-studio-eval-in-source-buffer)
(define-key map "m" 'font-lock-studio-step-keyword-match)
(define-key map "n" 'font-lock-studio-next-keyword)
(define-key map "o" 'font-lock-studio-step-out)
(define-key map "q" 'font-lock-studio-quit)
(define-key map "s" 'font-lock-studio-step-over)
(define-key map "w" 'font-lock-studio-display-source)
(define-key map "x" 'font-lock-studio-explain-state-at-point)
(define-key map "k" 'font-lock-studio-goto-keyword-at-point)
(define-key map "a" 'font-lock-studio-restart)
(define-key map "g" 'font-lock-studio-run)
;; Skip commands.
(define-key map "in" 'font-lock-studio-skip-to-next-keyword)
(define-key map "io" 'font-lock-studio-skip-out)
(define-key map "is" 'font-lock-studio-skip-over)
;; Breakpoints
(define-key map "b" 'font-lock-studio-set-breakpoint)
(define-key map "u" 'font-lock-studio-unset-breakpoint)
;; Toggle commands.
(define-key map "ti" 'font-lock-studio-toggle-show-internal-state)
(define-key map "tp" 'font-lock-studio-toggle-show-public-state)
(define-key map "tc" 'font-lock-studio-toggle-show-compiled-code)
(define-key map "tx" 'font-lock-studio-toggle-auto-explain)
(define-key map "te" 'font-lock-studio-toggle-debug-on-error)
(define-key map "tq" 'font-lock-studio-toggle-debug-on-quit)
)
(defvar font-lock-studio-mode-menus
'("Font Lock Studio"
["Step Into" font-lock-studio-step-into]
["Step Over" font-lock-studio-step-over]
["Step Out" font-lock-studio-step-out]
["Next Keyword" font-lock-studio-next-keyword]
["Step Keyword Match" font-lock-studio-step-keyword-match]
["Run" font-lock-studio-run]
["Restart" font-lock-studio-restart]
"----"
["Eval in Source" font-lock-studio-eval-in-source-buffer]
["Step Into and Debug" font-lock-studio-step-into-and-debug]
["Instrument Matcher" font-lock-studio-instrument-matcher]
"----"
["Skip to Next Keyword" font-lock-studio-skip-to-next-keyword]
["Skip Out" font-lock-studio-skip-out]
["Skip Over" font-lock-studio-skip-over]
"----"
["Set Breakpoint" font-lock-studio-set-breakpoint]
["Unset Breakpoint" font-lock-studio-unset-breakpoint]
"----"
["Show Internal State" font-lock-studio-toggle-show-internal-state
:style toggle :selected font-lock-studio-show-internal-state]
["Show Public State" font-lock-studio-toggle-show-public-state
:style toggle :selected font-lock-studio-show-public-state]
["Show Compiled Code" font-lock-studio-toggle-show-compiled-code
:style toggle :selected font-lock-studio-show-compiled-code]
["Auto Explain" font-lock-studio-toggle-auto-explain
:style toggle :selected font-lock-studio-auto-explain]
["Debug on Error" font-lock-studio-toggle-debug-on-error
:style toggle :selected debug-on-error]
["Debug on Quit" font-lock-studio-toggle-debug-on-quit
:style toggle :selected debug-on-quit]
"----"
["Explain State at Point" font-lock-studio-explain-state-at-point]
["Display Source" font-lock-studio-display-source]
["Show Match Data" font-lock-studio-show-match-data]
["Update Interface Buffer" font-lock-studio-update-interface-buffer]
["Quit" font-lock-studio-quit]
))
(easy-menu-define
font-lock-studio-menu font-lock-studio-mode-map
"Font Lock Studio menus" font-lock-studio-mode-menus)
;; --------------------
;; Renderer -- Fills the interface buffer with content.
;;
;; ----------
;; TAB prettyfier -- prints TAB characters as \t.
(defmacro font-lock-studio-with-clean-output-to-string (&rest body)
"Eval BODY like `progn', collect, clean, and return output as string.
Tab characters are emitted as \\t. Binds `indent-tabs-mode' to
nil to ensure that indentation doesn't contain tab characters."
`(let ((indent-tabs-mode nil))
(replace-regexp-in-string
"\t" "\\t"
(with-output-to-string
,@body)
t t)))
;; ----------
;; "Inserter" that reuse existing content.
;;
;; The `font-lock-studio-render' function is written so that it
;; appears as though it clears the buffer and inserts new content.
;; However, if it should neively do so, things like window starts
;; would no long work. Instead, this checks if the buffer already
;; happened to contain what is inserted, and if so, reuse the existing
;; text by simply copying text properties to it.
;;
;; Clearly, this is optimized for the case when the same content is
;; written to the buffer over and over again, which is the case here.
(defvar font-lock-studio-insert-accumulated ""
"Accumulated inserted text, for asserting correctness.")
(defvar font-lock-studio-insert-debug-overlay nil)
;; Even though this package should work with old Emacs versions, the
;; intention is that modern names should be used. In this case,
;; however, the modern name is `cl-position' (from cl-lib) and the old
;; `position' (from cl). Unfortunately, there is no way to write the
;; code so that it works in both worlds, hence this function.
(defun font-lock-studio-position (item seq)
"Find the first occurrence of ITEM in SEQ.
Return the index of the matching item, or nil if not found."
(let ((count 0)
(len (length seq))
(res nil))
(while (< count len)
(if (eq item (aref seq count))
(progn
(setq res count)
(setq len 0)) ; Break the loop
(setq count (+ count 1))))
res))
(defun font-lock-studio-insert (s)
"Insert (or replace) text S at point like `insert'.
If there is text at point, reusing it rather than inserting new
to ensure that visible windows aren't redisplayed."
(setq font-lock-studio-insert-accumulated
(concat font-lock-studio-insert-accumulated s))
(while (not (equal s ""))
(let* ((end-pos (font-lock-studio-position ?\n s))
(line (if end-pos
(substring s 0 (+ end-pos 1))
s))
(len (length line))