-
Notifications
You must be signed in to change notification settings - Fork 21
/
gnuplot-context.el
2267 lines (1950 loc) · 80.9 KB
/
gnuplot-context.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
;;; gnuplot-context.el -- context-sensitive help and completion for gnuplot -*- lexical-binding: t -*-
;; Copyright (C) 2012-2013 Jon Oddie <jonxfield@gmail.com>
;; Author: Jon Oddie <jonxfield@gmail.com>
;; URL: https://github.com/emacs-gnuplot/gnuplot
;; This file is not part of GNU Emacs.
;; This program is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;;
;; This file enhances gnuplot-mode with context-sensitive completion,
;; ElDoc support, and info page lookup for gnuplot script and shell
;; buffers.
;;
;; Usage
;; =====
;;
;; Make sure to byte-compile this file, or things will be noticeably
;; slow.
;;
;; Summary of key bindings:
;; C-c C-d read info page for construction at point
;; C-u C-c C-d prompt for info page to read
;; C-c M-h, C-c C-/ pop up multi-line ElDoc string for construction
;; at point
;;
;; Gnuplot's context sensitive mode is best controlled using Customize
;; (M-x customize-group gnuplot): simply enable the
;; `gnuplot-context-sensitive-mode' setting. You may also want to turn
;; on `gnuplot-tab-completion' so that the TAB key does auto-completion
;; on lines which are already indented. (This just sets the Emacs
;; variable `tab-always-indent' to `complete' in Gnuplot buffers).
;;
;; If you need to turn context sensitivity on or off from Lisp code
;; for some reason, call the function
;; `gnuplot-context-sensitive-mode', which behaves like a minor mode.
;;
;; With `eldoc-mode' support, gnuplot-mode will show one-line syntax
;; hints automatically in the echo area. Whether eldoc-mode is active
;; or not, you can always pop up a longer description of syntax using
;; `gnuplot-help-function' (C-c C-/ or C-c M-h). ElDoc support also
;; requires an additional file of help strings, `gnuplot-eldoc.el',
;; which should be included in recent Gnuplot releases. If it didn't
;; come with your Gnuplot installation, you'll need to grab a recent
;; source distribution of Gnuplot from http://gnuplot.info, and use
;; the `doc2texi.el' program in the docs/ directory to create it. So
;; long as the file is on your Emacs load path somewhere it will be
;; loaded automatically when needed.
;;
;; You can customize gnuplot-mode to turn on eldoc mode automatically
;; using variable `gnuplot-eldoc-mode'. Simply calling `eldoc-mode'
;; will also work.
;;
;; Internal details
;; ================
;;
;; Gnuplot's command language has a fair amount of syntactic
;; complexity, and the only way I could think of to support these
;; features was to do a complete parse of the command line. So that's
;; what this package does. Instead of building a parse tree, it
;; matches up until the token at point, and then either makes a list
;; of possible completions, or sets the variables `gnuplot-eldoc' and
;; `gnuplot-info-at-point' based on where it is in the grammar at that
;; point.
;;
;; The parsing/matching process happens in two phases: tokenizing
;; (`gnuplot-tokenize') and matching (`gnuplot-match-pattern'). In
;; order to be able to construct a full list of possible completions
;; via backtracking, the matching algorithm simulates a simple stack
;; machine with continuations. At byte-compile time, the PEG-like
;; grammar in S-expression notation (`gnuplot-grammar') is compiled
;; down into a vector of "machine code" for the parsing machine (see
;; `gnuplot-compile-pattern', `gnuplot-compile-grammar' and
;; `gnuplot-compiled-grammar'). This is complicated, but it seems to
;; work well enough, and it saves on the Emacs call stack.
;;
;; Compiling the grammar does require increasing `max-lisp-eval-depth'
;; modestly. This shouldn't cause any problems on modern machines, and
;; it only needs to be done once, at byte-compilation time.
;;
;; The parsing machine and compiler are partially based on the
;; description in Medeiros and Ierusalimschy 2008, "A Parsing Machine
;; for PEGs" (http://dl.acm.org/citation.cfm?doid=1408681.1408683).
;;
;; The pattern-matching language
;; =============================
;;
;; The gnuplot-mode grammar (see `gnuplot-compiled-grammar') is a list
;; of rules (RULE PATTERN), with each pattern written in S-expression
;; notation as follows:
;;
;; any
;; Match any token
;;
;; name, number, string, separator
;; Match a token of the given type. "Separator" is semicolon, the
;; statement separator.
;;
;; Any other symbol
;; Match another named rule in the grammar. May be recursive.
;;
;; "STRING"
;; Match literally: a token with exactly the text "STRING".
;;
;; (kw KEYWORD ALIASES ...)
;; Match abbreviated Gnuplot keywords. KEYWORD can be a string or
;; a cons (PREFIX . SUFFIX). In the latter case, this pattern
;; will match PREFIX plus any number of characters from the
;; beginning of SUFFIX. Any literal string from ALIASES will
;; also match. The token-id of the matching token is mutated to
;; the canonical value of KEYWORD.
;; Example:
;; (kw ("linew" ."idth") "lw") matches "linew", "linewi",
;; ... "linewidth" as well as "lw". Any of these tokens will
;; appear as "linewidth" in subsequent processing. (This is
;; important for the "info-keyword" form, see below).
;;
;; The other pattern forms combine simpler patterns, much like regular
;; expressions or PEGs (parsing expression grammars):
;;
;; (sequence { (:eldoc "eldoc string") }
;; { (:info "info page") }
;; { (:no-info) }
;; PATTERN PATTERN... )
;; Match all the PATTERNs in sequence or fail. Sequences can also
;; have optional ElDoc strings and info pages associated with
;; them; the innermost ElDoc or info page around point is the one
;; shown to the user. Alternatively, either property may be a
;; symbol, which should be a function to be called to get the
;; real value. Finally, if no ElDoc string is specified but the
;; variable `gnuplot-eldoc-hash' contains a value for the name of
;; the info page at point, that value is used as the ElDoc string
;; instead.
;;
;; For better readability, sequence forms can also be written as
;; a vector, omitting the `sequence': [PATTERN PATTERN ...]
;;
;; (either PATTERN PATTERN...)
;; Match the first PATTERN to succeed, or fail if none
;; matches. Like regexp `|'.
;;
;; (many PATTERN)
;; Match PATTERN zero or more times, greedily; like regexp
;; `*'. Unlike a regular expression matcher, the parsing machine
;; will not backtrack and try to match fewer times if a later
;; part of the pattern fails. This applies equally to the other
;; non-deterministic forms "either" and "maybe".
;;
;; (maybe PATTERN)
;; Match PATTERN zero or one times, like regexp `?'.
;;
;; (capture NAME PATTERN)
;; Match PATTERN, capturing the tokens in a capture group named
;; NAME. Capture groups are stored in `gnuplot-captures'
;; and can be retrieved using `gnuplot-capture-group'. This is
;; used to store the plotting style, which we need in order to
;; give the correct ElDoc string for "using" clauses, and for
;; info keywords (see below)
;;
;; (info-keyword PATTERN)
;; Match PATTERN, and use whatever the value of the first token
;; it matches is to look up info pages for this pattern. Most
;; Gnuplot info pages have the same name as the keyword they
;; document, so by using this we only have to put :info
;; properties on the few that don't, such as "set".
;;
;; For convenience, "many", "maybe", "capture" and "info-keyword"
;; wrap the rest of their arguments in an implicit "sequence" form,
;; so we can write (maybe "," expression) instead of
;; (maybe (sequence "," expression))
;;
;; (delimited-list PATTERN SEPARATOR)
;; Match a list of PATTERNs separated by SEPARATOR. Sugar for:
;; (sequence PATTERN (many (sequence SEPARATOR PATTERN)))
;;
;; (assert LISP-FORM)
;; Evaluate LISP-FORM and fail if it returns NIL. We need this in
;; the patterns for "plot" and "splot" to check whether the
;; command at point should be parsed in parametric mode or
;; not. See `gnuplot-guess-parametric-p'.
;;
;;
;; Bugs, TODOs, etc.
;; =======================
;;
;; It would be useful to complete on user-defined functions and
;; variables as well as built-ins.
;;
;; Completion probably will not work in continuation lines entered
;; into the gnuplot interaction buffer.
;;
;; It would be better to pop up longer syntax descriptions in a
;; temporary window, rather than making the echo area grow to fit
;; many lines.
;;
;; In ElDoc mode, we parse the whole line every time the user stops
;; typing. This is wasteful; should cache things in text properties
;; instead.
;;
;; The pattern matching engine uses backtracking, which can take
;; exponential time. So far it seems "fast enough" in actual use.
;;
;; The patterns don't really distinguish between "plot" and "splot"
;; for things like plot styles, binary arguments, etc.
;;
;; Some other the patterns are probably not quite right, especially for
;; things like abbreviated keywords, and features that I don't use
;; myself like "fit". Hopefully anyone bothered by this will submit
;; patches ;-)
;;
;; It would be possible to provide more helpful ElDoc strings for
;; sub-parts of complicated options like "cntrparam". This is a time
;; and maintenance issue rather than a technical one.
;;; Code:
(require 'cl-lib)
(require 'gnuplot)
(require 'eldoc)
(require 'info)
(require 'info-look)
;;;; The tokenizer.
(cl-defstruct gnuplot-token
start ; Buffer start position
end ; Buffer end position
id ; Text
type) ; a symbol: name, number, string, operator, separator
(defvar gnuplot-operator-regexp
(eval-when-compile
(regexp-opt
'("(" ")" "(" ")" "{" "," "}" "[" ":" "]" "!" "**" "-" "+" "~" "!" "*" "/"
"%" "+" "-" "." "<" "<=" ">" ">=" "==" "!=" "eq" "ne" "&" "^" "|" "&&" "||"
"?" ":" "=" "$")))
"Regexp to match Gnuplot operators for tokenizing.")
(eval-when-compile
(defmacro gnuplot-tokenize-by-regexps (&rest rules)
`(cond ,@(mapcar
(lambda (rule)
(let ((regexp (car rule))
(token-type (cadr rule)))
`((looking-at ,regexp)
(let ((str (match-string-no-properties 0)))
(forward-char (length str))
(make-gnuplot-token :id str
:type ',token-type
:start (match-beginning 0)
:end (match-end 0))))))
rules))))
(defun gnuplot-tokenize (&optional completing-p)
"Tokenize the Gnuplot command at point.
Return a list of `gnuplot-token' objects.
If COMPLETING-P is non-nil, omits the token at point if it is a
name; otherwise continues tokenizing up to the token at point. FIXME."
(let ((tokens '())
(stop-point (min (point)
(gnuplot-point-at-end-of-command))))
(save-excursion
(if (save-excursion ; HACK FIXME
(gnuplot-beginning-of-continuation)
(looking-at "\\s-*if\\s-*("))
(gnuplot-beginning-of-continuation)
(gnuplot-beginning-of-command))
(while
;; Skip whitespace and continuation lines
(progn
(skip-syntax-forward "-" stop-point)
(while (looking-at "\\\\\n")
(forward-line)
(skip-syntax-forward "-" stop-point))
;; Don't tokenize anything starting after point
(and (not (looking-at "#"))
(< (point) stop-point)))
(let* ((from (point))
(token
(cond
((gnuplot-tokenize-by-regexps
("[[:alpha:]_][[:alpha:]0-9_]*" name)
("[0-9]+\\(\\.[0-9]*\\)?\\([eE][+-]?[0-9]+\\)?\\|\\.[0-9]+\\([eE][+-]?[0-9]+\\)?" number)
(gnuplot-operator-regexp operator)
(";" separator)))
((looking-at "['\"]")
(let* ((bounds (bounds-of-thing-at-point 'sexp))
(to (or (cdr bounds) stop-point)))
(goto-char to)
(make-gnuplot-token
:id (buffer-substring-no-properties from to)
:type 'string
:start from :end to)))
(t (error
"Gnuplot-tokenize: bad token beginning %s"
(buffer-substring-no-properties (point) stop-point))))))
(push token tokens))))
;; If we are looking for completions, AND if the last token
;; read is a name, AND if point is within the bounds of the
;; last token, then discard it. The matching function
;; generates a list of all possible tokens that could appear
;; in that position for completion.
(if (and completing-p
tokens
(eq (gnuplot-token-type (car tokens)) 'name)
(<= (point) (gnuplot-token-end (car tokens))))
(pop tokens))
(nreverse tokens)))
;;;; The pattern and grammar compiler
;;
;; These functions compile the source S-expression grammar into a
;; vector of instructions for the parsing machine,
;; `gnuplot-match-pattern'. Its state consists of a program counter
;; (PC), a position in the list of tokens, a call stack, and a second
;; stack of backtracking entries (continuations). Its "machine
;; instructions" are the following:
;;
;; (any)
;; Match any token (fails only at end of command).
;;
;; (literal LITERAL NO-COMPLETE)
;; Match token with `gnuplot-token-id' LITERAL or fail. If we
;; have reached the token before point, include LITERAL in the
;; completion list unless NO-COMPLETE is non-`nil'.
;;
;; (token-type TYPE)
;; Match a token with `gnuplot-token-type' TYPE, or fail.
;;
;; (keyword REGEXP NAME)
;; Match any token whose `gnuplot-token-id' matches REGEXP. Use
;; NAME for the completion list.
;;
;; (jump OFFSET FIXED)
;; Jump to (set PC to) OFFSET if FIXED is non-nil, otherwise to
;; PC + OFFSET
;;
;; (call OFFSET FIXED)
;; Like "jump", but push a return address onto the stack for
;; (return). (The compiler adds the name of the rule being called
;; as a fourth element on the end of the list, but this is just a
;; comment for debugging purposes).
;;
;; (return)
;; Return to the PC address on top of the stack, or finish
;; matching if stack is empty. (Usually this doesn't happen,
;; because the machine stops as soon as it gets to the token at
;; point).
;;
;; (choice OFFSET)
;; Push a backtracking entry for location PC + OFFSET onto the
;; backtracking stack. Backtracking entries save the contents of
;; the call stack, position in the token list, the values of
;; capture groups, and the record of loop progress (see below).
;;
;; (check-progress)
;; Break out of infinite loops, like (many (many ...)). Checks
;; an alist of conses (pc . tokens) for the position in the token
;; stream the last time this instruction was reached, and breaks
;; out of the loop if stuck in the same place; otherwise pushes a
;; new entry onto the list.
;;
;; (fail)
;; Pop the most recent backtracking entry and continue from
;; there, or fail the whole match if out of backtrack
;; points. Failing to match returns the remainder of the token
;; list, although we don't currently use this for anything.
;;
;; (commit OFFSET)
;; Discard one backtracking point and jump to PC + OFFSET. This
;; is used to make the (either) form non-deterministic.
;;
;; (push TYPE VALUE)
;; Push an entry for an eldoc or info string (specified by TYPE)
;; onto the stack.
;;
;; (pop TYPE)
;; Pop something off the stack; checks that it has the expected
;; TYPE, for safety.
;;
;; (save-start NAME)
;; Open a capture group named NAME. Pushes an entry onto
;; `gnuplot-captures' with current position in token list as the
;; start of the group.
;;
;; (save-end NAME)
;; Close the capture group named NAME. Finds the topmost entry in
;; `gnuplot-captures' with this name and sets its endpoint to the
;; current position in token list. Error if no group with that
;; name is found.
;;
;; (label NAME)
;; This should never be reached and will cause an error. The
;; compiler inserts it at the beginning of compiled rules only
;; for debugging purposes.
;;
(eval-and-compile
;; Compile a single pattern into a list of instructions. Leaves
;; calls to other rules as symbolic instructions (call SYMBOL) and
;; jumps, commits etc. as relative offsets; these are resolved into
;; absolute locations by `gnuplot-compile-grammar', below.
(defun gnuplot-compile-pattern (pat)
(cond
;; Strings match a single token literally
((stringp pat)
;; Don't add non-words to completion lists
(let ((wordp (string-match-p "^\\sw\\(\\sw\\|\\s_\\)*$" pat)))
`((literal ,pat ,(not wordp)))))
;; Symbols match token types or calls to other patterns
((symbolp pat)
(cl-case pat
((any) `((any)))
((name number string separator) `((token-type ,pat)))
(t `((call ,pat)))))
;; Syntactic sugar: write sequences (sequence ...) as vectors [...]
((vectorp pat)
(gnuplot-compile-pattern
(append '(sequence) pat '())))
;; Other forms combine simpler patterns
(t
(let ((type (car pat)))
(cl-case type
;; (sequence...): concatenate patterns, with optional eldoc
;; and info strings
((sequence)
(cl-destructuring-bind
(subpats eldoc info)
(gnuplot-filter-arg-list (cdr pat))
(let ((eldoc-push '()) (eldoc-pop '())
(info-push '()) (info-pop '())
(compiled
(mapcar 'gnuplot-compile-pattern subpats)))
(if eldoc
(setq eldoc-push `((push eldoc ,eldoc))
eldoc-pop `((pop eldoc))))
(if info
(if (eq info :no-info)
(setq info-push '((push no-scan t))
info-pop '((pop no-scan)))
(setq info-push `((push info ,info))
info-pop `((pop info)))))
(apply 'append
`(,info-push
,eldoc-push
,@compiled
,eldoc-pop
,info-pop)))))
;; (either...): choose between patterns
((either)
(cond
((= (length pat) 2) ; trivial case
(gnuplot-compile-pattern (cadr pat)))
((> (length pat) 3) ; could be more efficient...
(gnuplot-compile-pattern (gnuplot-either-helper pat)))
(t ; two patterns
(let* ((pat1 (cadr pat))
(pat2 (cl-caddr pat))
(pat1-c (gnuplot-compile-pattern pat1))
(pat2-c (gnuplot-compile-pattern pat2))
(pat1-l (length pat1-c))
(pat2-l (length pat2-c)))
`((choice ,(+ pat1-l 2))
,@pat1-c
(commit ,(+ pat2-l 1))
,@pat2-c)))))
;; Repetition (*)
((many)
(let* ((pat1 (cons 'sequence (cdr pat)))
(pat1-c (gnuplot-compile-pattern pat1))
(pat1-l (length pat1-c)))
`((choice ,(+ pat1-l 3))
(check-progress) ; bail out of infinite loops
,@pat1-c
(commit ,(- (+ pat1-l 2))))))
;; Repetition (+)
((many1)
(let* ((pat1 (cdr pat)))
(gnuplot-compile-pattern
`(sequence ,@pat1 (many ,@pat1)))))
;; Optional (?)
((maybe)
(let* ((pat1 (cons 'sequence (cdr pat)))
(pat1-c (gnuplot-compile-pattern pat1))
(pat1-l (length pat1-c)))
`((choice ,(+ pat1-l 1))
,@pat1-c)))
;; Syntactic sugar for delimited lists
((delimited-list)
(let* ((item (cadr pat))
(sep (cl-caddr pat)))
(gnuplot-compile-pattern
`(sequence ,item (many (sequence ,sep ,item))))))
;; keywords
((kw)
(cl-destructuring-bind (regex name)
(gnuplot-keyword-helper (cdr pat))
`((keyword ,regex ,name))))
;; Capturing groups
((capture)
(let* ((name (cadr pat))
(pat1 (cons 'sequence (cddr pat)))
(pat1-c (gnuplot-compile-pattern pat1)))
`((save-start ,name)
,@pat1-c
(save-end ,name))))
;; Use the first token as an info keyword
((info-keyword)
(let* ((pat1 (cons 'sequence (cdr pat)))
(pat1-c (gnuplot-compile-pattern pat1)))
`((push info first-token)
,@pat1-c
(pop info))))
;; Assertions
((assert)
(let* ((form (cadr pat)))
`((assert ,form))))
(t
(error "Gnuplot-compile-pattern: bad pattern form %s" pat)))))))
;; Helper function for destructuring (sequence ...) forms in patterns
;; Takes the cdr of the sequence form, returns a list (PATTERNS ELDOC
;; INFO).
(defun gnuplot-filter-arg-list (args)
(let ((accum '())
(eldoc nil) (info nil))
(dolist (item args)
(let ((type (car-safe item)))
(cl-case type
((:eldoc) (setq eldoc (cadr item)))
((:no-info) (setq info :no-info)) ; inhibit stack scanning
((:info) (setq info (cadr item)))
(t (push item accum)))))
(list (reverse accum) eldoc info)))
;; Helper function for compiling (kw...) patterns
;; Takes the cdr of the kw form, returns a list (REGEXP KEYWORD)
(defun gnuplot-keyword-helper (args)
(let ((keyword (car args)) (aliases (cdr args)))
(when (consp keyword)
(let ((pre (car keyword)) (suf (cdr keyword)))
(setq keyword (concat pre suf))
(while (progn
(push pre aliases)
(not (zerop (length suf))))
(setq pre (concat pre (substring suf 0 1))
suf (substring suf 1)))))
(let ((regex
(concat "^"
(regexp-opt (cons keyword aliases))
"$")))
(list regex keyword))))
;; Helper function for compiling (either ...) patterns. Rewrites
;; alternates (either A B C) into (either A (either B (either C D)))
(defun gnuplot-either-helper (pat)
(if (= (length pat) 3)
pat
`(either ,(cadr pat)
,(gnuplot-either-helper
(cons 'either (cddr pat))))))
;; Compile the grammar (a list of rule-pattern pairs (RULE PATTERN))
;; into a single vector of matching-machine instructions. Compiles
;; each pattern individually, then "links" them into one vector,
;; converting symbolic (call ...) instructions into numeric offsets
(defun gnuplot-compile-grammar (grammar start-symbol)
(let ((compiled-pats '()) ; Alist of (name . instructions)
;; Reserve space for a jump to the start symbol
(code-length 1))
;; Compile each rule and find the total number of instructions
(dolist (item grammar)
(let* ((name (car item))
(pat (cadr item))
(code (gnuplot-compile-pattern pat)))
(push (cons name code) compiled-pats)
;; Reserve space for a label at the beginning and (return) at
;; the end
(setq code-length (+ code-length 2 (length code)))))
;; Copy instructions into a single vector
(let ((object-code (make-vector code-length nil))
(name->offset (make-hash-table))
(i 1))
(setf (aref object-code 0) `(jump ,start-symbol))
(dolist (chunk compiled-pats)
(let ((name (car chunk))
(code (cdr chunk)))
(setf (aref object-code i) `(label ,name))
(cl-incf i)
(puthash name i name->offset)
(while code
(setf (aref object-code i) (car code)
code (cdr code)
i (1+ i)))
(setf (aref object-code i) '(return)
i (1+ i))))
;; Resolve symbolic and relative jumps
(let ((pattern-name nil))
(dotimes (i (length object-code))
(let ((inst (aref object-code i)))
(cl-case (car inst)
((label)
(setq pattern-name (cadr inst)))
((jump call choice commit)
(cond
((symbolp (cadr inst))
(let* ((name (cadr inst))
(location (gethash name name->offset)))
(if (not location)
(error
(concat "gnuplot-compile-grammar: "
"No rule found for symbol `%s' in pattern `%s'")
name pattern-name))
(setcdr inst `(,location ,name))))
((numberp (cadr inst))
(let* ((offset (cadr inst))
(location (+ offset i)))
(setcdr inst `(,location))))
(t
(error "Gnuplot-compile-grammar: bad instruction %s" inst))))))))
object-code))))
;;; The grammar.
(defvar gnuplot-compiled-grammar
(eval-when-compile
(let ((max-lisp-eval-depth 600))
(gnuplot-compile-grammar
'((expression
[infix-expression (maybe "?" expression ":" expression)])
(prefix-operator
(either "!" "~" "-" "+"))
(infix-operator
(either "**" "*" "/" "%" "+" "-" "." "<" "<=" ">" ">=" "==" "!=" "eq" "ne"
"&" "^" "|" "&&" "||"))
(infix-expression
[(many prefix-operator)
primary-expression
(many infix-operator expression)])
(primary-expression
[(either number string parenthesized-expression
column-ref complex-number function-call name)
(many "!")
(maybe "**" infix-expression)
(maybe substring-range)])
(function-call
(either
(info-keyword
[(either "abs" "acos" "acosh" "arg" "asin" "asinh" "atan" "atan2" "atanh"
"besj0" "besj1" "besy0" "besy1" "ceil" "column" "columnhead"
"cos" "cosh" "defined" "erf" "erfc" "exists" "exp" "floor"
"gamma" "gprintf" "ibeta" "igamma" "imag" "int" "inverf"
"invnorm" "lambertw" "lgamma" "log" "log10" "norm" "real"
"sgn" "sin" "sinh" "sprintf" "sqrt" "strftime" "stringcolumn"
"strlen" "strptime" "strstrt" "substr" "tan" "tanh" "timecolumn"
"tm_hour" "tm_mday" "tm_min" "tm_mon" "tm_sec" "tm_wday"
"tm_yday" "tm_year" "valid" "value" "word" "words" "rand")
parenthesized-expression])
[(:info "elliptic_integrals")
(either "EllipticK" "EllipticE" "EllipticPi")
parenthesized-expression]
[name
parenthesized-expression]))
(parenthesized-expression
["(" comma-list ")"])
(complex-number
["{" (maybe "-") number "," (maybe "-") number "}"])
(column-ref
["$" number])
(substring-range-component
(maybe (either "*" expression)))
(substring-range
["[" (delimited-list substring-range-component ":" 2 2) "]"])
;;; Assignments
(lhs
[name (maybe "(" (delimited-list name "," 1) ")")])
(assignment
[lhs "=" (either assignment expression)])
;;; Lists of expressions
(comma-list
(delimited-list (either assignment expression) ","))
(colon-list
(delimited-list expression ":"))
(tuple
["(" (delimited-list expression "," 2 3) ")"])
;;; Commands
(command
(info-keyword
(either plot-command splot-command replot-command fit-command print-command
set-command cd-command call-command simple-command
eval-command load-command lower-raise-command pause-command
save-command system-command test-command undefine-command
update-command assignment if-command new-if-command do-command)))
(command-list
(delimited-list command separator))
(block ["{" command-list (maybe separator) "}"])
;;; old-style one-line if(..) command
(if-command
(info-keyword
"if" parenthesized-expression command-list
(maybe separator "else" command-list)))
;;; new-style block-structured if
(new-if-command
(info-keyword
"if" parenthesized-expression block
(maybe "else" block)))
;;; block-structured "do"
(do-command
(info-keyword "do" iteration-spec block))
;;; PLOT, SPLOT commands
(plot-command
[(kw ("pl" . "ot"))
(either
;; Parametric ranges
[(assert (gnuplot-guess-parametric-p))
(maybe t-axis-range) (maybe x-axis-range) (maybe y-axis-range)]
;; Non-parametric ranges
[(maybe x-axis-range) (maybe y-axis-range)])
plot-body])
(splot-command
[ ;; This capturing group lets `gnuplot-find-using-eldoc' know
;; that this is an splot command
(capture :splot-command (kw ("spl" . "ot")))
(either
;; Parametric ranges
[(assert (gnuplot-guess-parametric-p))
(maybe u-axis-range) (maybe v-axis-range)
(maybe x-axis-range) (maybe y-axis-range) (maybe z-axis-range)]
;; Non-parametric ranges
[(maybe x-axis-range) (maybe y-axis-range) (maybe z-axis-range)])
plot-body])
(replot-command [(kw "replot") plot-body])
;; Axis ranges
(axis-range-component
(maybe (either "*" expression)))
(axis-range-body
(delimited-list axis-range-component ":" 2 3))
(axis-range
[(:info "ranges")
"[" (maybe (maybe name "=") axis-range-body) "]"])
(x-axis-range [(:eldoc "X RANGE: [{<dummy>=}<min>:<max>]") axis-range])
(y-axis-range [(:eldoc "Y RANGE: [{<dummy>=}<min>:<max>]") axis-range])
(z-axis-range [(:eldoc "Z RANGE: [{<dummy>=}<min>:<max>]") axis-range])
(t-axis-range [(:eldoc "T RANGE: [{<dummy>=}<min>:<max>]") axis-range])
(u-axis-range [(:eldoc "U RANGE: [{<dummy>=}<min>:<max>]") axis-range])
(v-axis-range [(:eldoc "V RANGE: [{<dummy>=}<min>:<max>]") axis-range])
;; Body of a plot/splot command. Should really be different for
;; parametric vs non-parametric, but that's too hard.
(plot-body
(delimited-list
[(maybe iteration-spec) plot-expression plot-modifiers]
","))
;; Iteration: for [... ]
(iteration-spec
[(:info "iteration")
(many1
"for" "[" name
(either ["=" (delimited-list expression ":")]
["in" expression])
"]")])
;; Expressions to plot can be preceded by any number of
;; assignments, with or without commas
(plot-expression
[(many [(:no-info) assignment (maybe ",")])
expression])
;;; Plot/splot modifiers
;; These should probably be more different for plot and splot ...
(plot-modifiers (many (either plot-modifier datafile-modifier)))
(plot-modifier
(info-keyword
(either
;; simple one-word modifiers
(kw "nohidden3d") (kw "nocontours") (kw "nosurface")
;; word followed by expression
[(either
(kw ("lines" . "tyle") "ls")
(kw ("linet" . "ype") "lt")
(kw ("linew" . "idth") "lw")
(kw ("pointt" . "ype") "pt")
(kw ("points" . "ize") "ps")
(kw ("pointi" . "nterval") "pi"))
expression]
;; others defined below
title-modifier notitle-modifier axes-modifier with-modifier
linecolor-modifier fillstyle-modifier)))
(title-modifier
[(kw ("t" . "itle")) expression])
(notitle-modifier
[(:info "title")
(kw ("not" . "itle"))
(maybe string)])
(axes-modifier
[(kw ("ax" . "es")) (either "x1y1" "x1y2" "x2y1" "x2y2")])
(linecolor-modifier
[(kw ("linec" . "olor") "lc") color-spec])
(fillstyle-modifier
[(kw "fillstyle" "fs")
;; fill-style also used by "set style fill"
fill-style])
(fill-style
[(either
"empty"
[(maybe "transparent")
(either "pattern" "solid")
(maybe (either fill-style-border-clause expression))])
(maybe fill-style-border-clause)])
(fill-style-border-clause
(either "noborder" [(kw ("bo" . "rder")) expression]))
(color-spec
[(:info "colorspec")
(either
(kw ("var" . "iable"))
[(kw ("pal" . "ette"))
(either "z"
[(either "frac" "cb") expression])]
[(kw ("rgb" . "color"))
(either (kw ("var" . "iable")) string)])])
(with-modifier
[(:info "plotting_styles")
(kw ("w" . "ith"))
;; plotting-style also used for "set style data"
(capture :with-style plotting-style)])
(plotting-style
(info-keyword
(either
;; Simple styles that take no arguments
(kw ("l" . "ines")) (kw ("i" . "mpulses")) (kw ("p" . "oints"))
(kw ("linesp" . "oints") "lp") (kw ("d" . "ots")) (kw ("yerrorl" . "ines"))
(kw ("errorl" . "ines")) (kw ("xerrorl" . "ines")) (kw ("xyerrorl" . "ines"))
(kw ("ye" . "rrorbars")) (kw ("e" . "rrorbars")) (kw ("xe" . "rrorbars"))
(kw ("xye" . "rrorbars")) (kw "boxes") (kw ("hist" . "ograms"))
(kw ("boxer" . "rorbars")) (kw ("boxx" . "yerrorbars")) (kw ("st" . "eps"))
(kw ("fs" . "teps")) (kw ("his" . "teps")) (kw ("fin" . "ancebars"))
(kw ("can" . "dlesticks")) (kw ("pm" . "3d"))
(kw ("cir" . "cles"))
;; Image styles all use the same info page
[(:info "image")
(either (kw ("ima" . "ge"))
(kw ("rgbima" . "ge"))
(kw ("rgba" . "lpha")))]
;; More complicated styles defined below
labels-style-clause
filledcurves-style-clause
vectors-style-clause)))
(labels-style-clause
[(kw "labels")
(maybe textcolor-spec)])
(filledcurves-style-clause
[(kw ("filledc" . "urves"))
(maybe
(either
"closed"
["xy" "=" expression "," expression]
[(maybe (either "above" "below"))
(maybe [(either "x1" "x2" "y1" "y2")
(maybe "=" expression)])]))])
(vectors-style-clause
[(kw ("vec" . "tors"))
(many
(either
"nohead" "head" "heads" "filled" "empty" "nofilled" "front" "back"
[(kw "arrowstyle" "as") expression]
["size" (delimited-list expression ",")]
linestyle-spec))])
;;; Various style specifiers, used in different places
(linestyle-spec
(many1
(either
[(kw ("lines" . "tyle") "ls") expression]
[(kw ("linet" . "ype") "lt") expression]
[(kw ("linew" . "idth") "lw") expression])))
(textcolor-spec
[(kw "textcolor" "tc")
(either "default"
["lt" expression]
color-spec)])
(pointsize-spec [(kw "pointsize" "ps") expression])
;;; Datafile modifiers
(datafile-modifier
(info-keyword
(either binary-modifier
[(maybe "nonuniform") (kw ("mat" . "rix"))]
index-modifier every-modifier
thru-modifier using-modifier
smooth-modifier
"volatile" "noautoscale")))
(index-modifier
[(kw ("i" . "ndex"))