-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
lua-mode.el
2291 lines (1981 loc) · 90.6 KB
/
lua-mode.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
;;; lua-mode.el --- a major-mode for editing Lua scripts -*- lexical-binding: t -*-
;; Author: 2011-2013 immerrr <[email protected]>
;; 2010-2011 Reuben Thomas <[email protected]>
;; 2006 Juergen Hoetzel <[email protected]>
;; 2004 various (support for Lua 5 and byte compilation)
;; 2001 Christian Vogler <[email protected]>
;; 1997 Bret Mogilefsky <[email protected]> starting from
;; tcl-mode by Gregor Schmid <[email protected]>
;; with tons of assistance from
;; Paul Du Bois <[email protected]> and
;; Aaron Smith <[email protected]>.
;;
;; URL: https://immerrr.github.io/lua-mode
;; Version: 20221027
;; Package-Requires: ((emacs "24.3"))
;;
;; This file is NOT part of Emacs.
;;
;; This program is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;;
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <https://www.gnu.org/licenses/>.
;; Keywords: languages, processes, tools
;; This field is expanded to commit SHA and commit date during the
;; archive creation.
;; Revision: $Format:%h (%cD)$
;;
;;; Commentary:
;; lua-mode provides support for editing Lua, including automatic
;; indentation, syntactical font-locking, running interactive shell,
;; Flymake checks with luacheck, interacting with `hs-minor-mode' and
;; online documentation lookup.
;; The following variables are available for customization (see more via
;; `M-x customize-group lua`):
;; - Var `lua-indent-level':
;; indentation offset in spaces
;; - Var `lua-indent-string-contents':
;; set to `t` if you like to have contents of multiline strings to be
;; indented like comments
;; - Var `lua-indent-nested-block-content-align':
;; set to `nil' to stop aligning the content of nested blocks with the
;; open parenthesis
;; - Var `lua-indent-close-paren-align':
;; set to `t' to align close parenthesis with the open parenthesis,
;; rather than with the beginning of the line
;; - Var `lua-mode-hook':
;; list of functions to execute when lua-mode is initialized
;; - Var `lua-documentation-url':
;; base URL for documentation lookup
;; - Var `lua-documentation-function': function used to
;; show documentation (`eww` is a viable alternative for Emacs 25)
;; These are variables/commands that operate on the Lua process:
;; - Var `lua-default-application':
;; command to start the Lua process (REPL)
;; - Var `lua-default-command-switches':
;; arguments to pass to the Lua process on startup (make sure `-i` is there
;; if you expect working with Lua shell interactively)
;; - Cmd `lua-start-process': start new REPL process, usually happens automatically
;; - Cmd `lua-kill-process': kill current REPL process
;; These are variables/commands for interaction with the Lua process:
;; - Cmd `lua-show-process-buffer': switch to REPL buffer
;; - Cmd `lua-hide-process-buffer': hide window showing REPL buffer
;; - Var `lua-always-show': show REPL buffer after sending something
;; - Cmd `lua-send-buffer': send whole buffer
;; - Cmd `lua-send-current-line': send current line
;; - Cmd `lua-send-defun': send current top-level function
;; - Cmd `lua-send-region': send active region
;; - Cmd `lua-restart-with-whole-file': restart REPL and send whole buffer
;; To enable on-the-fly linting, make sure you have the luacheck
;; program installed (available from luarocks) and activate
;; `flymake-mode'.
;; See "M-x apropos-command ^lua-" for a list of commands.
;; See "M-x customize-group lua" for a list of customizable variables.
;;; Code:
(eval-when-compile
(require 'cl-lib))
(require 'comint)
(require 'newcomment)
(require 'rx)
;; rx-wrappers for Lua
(eval-when-compile
;; Silence compilation warning about `compilation-error-regexp-alist' defined
;; in compile.el.
(require 'compile))
(eval-and-compile
(if (fboundp #'rx-let)
(progn
;; Emacs 27+ way of customizing rx
(defvar lua--rx-bindings)
(setq
lua--rx-bindings
'((symbol (&rest x) (seq symbol-start (or x) symbol-end))
(ws (* (any " \t")))
(ws+ (+ (any " \t")))
(lua-name (symbol (seq (+ (any alpha "_")) (* (any alnum "_")))))
(lua-funcname (seq lua-name (* ws "." ws lua-name)
(opt ws ":" ws lua-name)))
(lua-funcheader
;; Outer (seq ...) is here to shy-group the definition
(seq (or (seq (symbol "function") ws (group-n 1 lua-funcname))
(seq (group-n 1 lua-funcname) ws "=" ws
(symbol "function")))))
(lua-number
(seq (or (seq (+ digit) (opt ".") (* digit))
(seq (* digit) (opt ".") (+ digit)))
(opt (regexp "[eE][+-]?[0-9]+"))))
(lua-assignment-op (seq "=" (or buffer-end (not (any "=")))))
(lua-operator (or "+" "-" "*" "/" "%" "^" "#" "==" "~=" "<=" ">=" "<"
">" "=" ";" ":" "," "." ".." "..."))
(lua-keyword-operator (symbol "and" "not" "or"))
(lua-keyword
(symbol "break" "do" "else" "elseif" "end" "for" "function"
"goto" "if" "in" "local" "repeat" "return"
"then" "until" "while"))
(lua-up-to-9-variables
(seq (group-n 1 lua-name) ws
(? "," ws (group-n 2 lua-name) ws
(? "," ws (group-n 3 lua-name) ws
(? "," ws (group-n 4 lua-name) ws
(? "," ws (group-n 5 lua-name) ws
(? "," ws (group-n 6 lua-name) ws
(? "," ws (group-n 7 lua-name) ws
(? "," ws (group-n 8 lua-name) ws
(? "," ws (group-n 9 lua-name) ws))))))))))))
(defmacro lua-rx (&rest regexps)
(eval `(rx-let ,lua--rx-bindings
(rx ,@regexps))))
(defun lua-rx-to-string (form &optional no-group)
(rx-let-eval lua--rx-bindings
(rx-to-string form no-group))))
(progn
;; Pre-Emacs 27 way of customizing rx
(defvar lua-rx-constituents)
(defvar rx-parent)
(defun lua-rx-to-string (form &optional no-group)
"Lua-specific replacement for `rx-to-string'.
See `rx-to-string' documentation for more information FORM and
NO-GROUP arguments."
(let ((rx-constituents lua-rx-constituents))
(rx-to-string form no-group)))
(defmacro lua-rx (&rest regexps)
"Lua-specific replacement for `rx'.
See `rx' documentation for more information about REGEXPS param."
(cond ((null regexps)
(error "No regexp"))
((cdr regexps)
(lua-rx-to-string `(and ,@regexps) t))
(t
(lua-rx-to-string (car regexps) t))))
(defun lua--new-rx-form (form)
"Add FORM definition to `lua-rx' macro.
FORM is a cons (NAME . DEFN), see more in `rx-constituents' doc.
This function enables specifying new definitions using old ones:
if DEFN is a list that starts with `:rx' symbol its second
element is itself expanded with `lua-rx-to-string'. "
(let ((form-definition (cdr form)))
(when (and (listp form-definition) (eq ':rx (car form-definition)))
(setcdr form (lua-rx-to-string (cadr form-definition) 'nogroup)))
(push form lua-rx-constituents)))
(defun lua--rx-symbol (form)
;; form is a list (symbol XXX ...)
;; Skip initial 'symbol
(setq form (cdr form))
;; If there's only one element, take it from the list, otherwise wrap the
;; whole list into `(or XXX ...)' form.
(setq form (if (eq 1 (length form))
(car form)
(append '(or) form)))
(and (fboundp 'rx-form) ; Silence Emacs 27's byte-compiler.
(rx-form `(seq symbol-start ,form symbol-end) rx-parent)))
(setq lua-rx-constituents (copy-sequence rx-constituents))
(mapc 'lua--new-rx-form
`((symbol lua--rx-symbol 1 nil)
(ws . "[ \t]*") (ws+ . "[ \t]+")
(lua-name :rx (symbol (regexp "[[:alpha:]_]+[[:alnum:]_]*")))
(lua-funcname
:rx (seq lua-name (* ws "." ws lua-name)
(opt ws ":" ws lua-name)))
(lua-funcheader
;; Outer (seq ...) is here to shy-group the definition
:rx (seq (or (seq (symbol "function") ws (group-n 1 lua-funcname))
(seq (group-n 1 lua-funcname) ws "=" ws
(symbol "function")))))
(lua-number
:rx (seq (or (seq (+ digit) (opt ".") (* digit))
(seq (* digit) (opt ".") (+ digit)))
(opt (regexp "[eE][+-]?[0-9]+"))))
(lua-assignment-op
:rx (seq "=" (or buffer-end (not (any "=")))))
(lua-operator
:rx (or "+" "-" "*" "/" "%" "^" "#" "==" "~=" "<=" ">=" "<"
">" "=" ";" ":" "," "." ".." "..."))
(lua-keyword-operator
:rx (symbol "and" "not" "or"))
(lua-keyword
:rx (symbol "break" "do" "else" "elseif" "end" "for" "function"
"goto" "if" "in" "local" "repeat" "return"
"then" "until" "while"))
(lua-up-to-9-variables
:rx (seq (group-n 1 lua-name) ws
(? "," ws (group-n 2 lua-name) ws
(? "," ws (group-n 3 lua-name) ws
(? "," ws (group-n 4 lua-name) ws
(? "," ws (group-n 5 lua-name) ws
(? "," ws (group-n 6 lua-name) ws
(? "," ws (group-n 7 lua-name) ws
(? "," ws (group-n 8 lua-name) ws
(? "," ws (group-n 9 lua-name) ws)))))))))))))))
;; Local variables
(defgroup lua nil
"Major mode for editing Lua code."
:prefix "lua-"
:group 'languages)
(defcustom lua-indent-level 3
"Amount by which Lua subexpressions are indented."
:type 'integer
:group 'lua
:safe #'integerp)
(defcustom lua-comment-start "-- "
"Default value of `comment-start'."
:type 'string
:group 'lua)
(defcustom lua-comment-start-skip "---*[ \t]*"
"Default value of `comment-start-skip'."
:type 'string
:group 'lua)
(defcustom lua-default-application "lua"
"Default application to run in Lua process.
Can be a string, where it denotes a command to be executed to
start Lua process, or a (HOST . PORT) cons, that can be used to
connect to Lua process running remotely."
:type '(choice (string)
(cons string integer))
:group 'lua)
(defcustom lua-default-command-switches (list "-i")
"Command switches for `lua-default-application'.
Should be a list of strings."
:type '(repeat string)
:group 'lua)
(make-variable-buffer-local 'lua-default-command-switches)
(defcustom lua-always-show t
"*Non-nil means display lua-process-buffer after sending a command."
:type 'boolean
:group 'lua)
(defcustom lua-documentation-function 'browse-url
"Function used to fetch the Lua reference manual."
:type `(radio (function-item browse-url)
,@(when (fboundp 'eww) '((function-item eww)))
,@(when (fboundp 'w3m-browse-url) '((function-item w3m-browse-url)))
(function :tag "Other function"))
:group 'lua)
(defcustom lua-documentation-url
(or (and (file-readable-p "/usr/share/doc/lua/manual.html")
"file:///usr/share/doc/lua/manual.html")
"http://www.lua.org/manual/5.1/manual.html")
"URL pointing to the Lua reference manual."
:type 'string
:group 'lua)
(defvar lua-process nil
"The active Lua process")
(defvar lua-process-buffer nil
"Buffer used for communication with the Lua process.")
(defun lua--customize-set-prefix-key (prefix-key-sym prefix-key-val)
(cl-assert (eq prefix-key-sym 'lua-prefix-key))
(set prefix-key-sym (if (and prefix-key-val (> (length prefix-key-val) 0))
;; read-kbd-macro returns a string or a vector
;; in both cases (elt x 0) is ok
(elt (read-kbd-macro prefix-key-val) 0)))
(if (fboundp 'lua-prefix-key-update-bindings)
(lua-prefix-key-update-bindings)))
(defcustom lua-prefix-key "\C-c"
"Prefix for all lua-mode commands."
:type 'string
:group 'lua
:set 'lua--customize-set-prefix-key
:get (lambda (sym)
(let ((val (eval sym)))
(if val (single-key-description (eval sym)) ""))))
(defvar lua-mode-menu (make-sparse-keymap "Lua")
"Keymap for lua-mode's menu.")
(defvar lua-prefix-mode-map
(eval-when-compile
(let ((result-map (make-sparse-keymap)))
(mapc (lambda (key_defn)
(define-key result-map (read-kbd-macro (car key_defn)) (cdr key_defn)))
'(("C-l" . lua-send-buffer)
("C-f" . lua-search-documentation)))
result-map))
"Keymap that is used to define keys accessible by `lua-prefix-key'.
If the latter is nil, the keymap translates into `lua-mode-map' verbatim.")
(defvar lua--electric-indent-chars
(mapcar #'string-to-char '("}" "]" ")")))
(defvar lua-mode-map
(let ((result-map (make-sparse-keymap)))
(unless (boundp 'electric-indent-chars)
(mapc (lambda (electric-char)
(define-key result-map
(read-kbd-macro
(char-to-string electric-char))
#'lua-electric-match))
lua--electric-indent-chars))
(define-key result-map [menu-bar lua-mode] (cons "Lua" lua-mode-menu))
(define-key result-map [remap backward-up-list] 'lua-backward-up-list)
;; handle prefix-keyed bindings:
;; * if no prefix, set prefix-map as parent, i.e.
;; if key is not defined look it up in prefix-map
;; * if prefix is set, bind the prefix-map to that key
(if lua-prefix-key
(define-key result-map (vector lua-prefix-key) lua-prefix-mode-map)
(set-keymap-parent result-map lua-prefix-mode-map))
result-map)
"Keymap used in lua-mode buffers.")
(defvar lua-electric-flag t
"If t, electric actions (like automatic reindentation) will happen when an electric
key like `{' is pressed")
(make-variable-buffer-local 'lua-electric-flag)
(defcustom lua-prompt-regexp "[^\n]*\\(>[\t ]+\\)+$"
"Regexp which matches the Lua program's prompt."
:type 'regexp
:group 'lua)
(defcustom lua-traceback-line-re
;; This regexp skips prompt and meaningless "stdin:N:" prefix when looking
;; for actual file-line locations.
"^\\(?:[\t ]*\\|.*>[\t ]+\\)\\(?:[^\n\t ]+:[0-9]+:[\t ]*\\)*\\(?:\\([^\n\t ]+\\):\\([0-9]+\\):\\)"
"Regular expression that describes tracebacks and errors."
:type 'regexp
:group 'lua)
(defvar lua--repl-buffer-p nil
"Buffer-local flag saying if this is a Lua REPL buffer.")
(make-variable-buffer-local 'lua--repl-buffer-p)
(defun lua--compilation-find-file (fn marker filename directory &rest formats)
"Return Lua REPL buffer when looking for \"stdin\" file in it."
(if (and
lua--repl-buffer-p
(string-equal filename "stdin")
;; NOTE: this doesn't traverse `compilation-search-path' when
;; looking for filename.
(not (file-exists-p (expand-file-name
filename
(when directory (expand-file-name directory))))))
(current-buffer)
(apply fn marker filename directory formats)))
(advice-add 'compilation-find-file :around #'lua--compilation-find-file)
(defun lua--compilation-goto-locus (fn msg mk end-mk)
"When message points to Lua REPL buffer, go to the message itself.
Usually, stdin:XX line number points to nowhere."
(let ((errmsg-buf (marker-buffer msg))
(error-buf (marker-buffer mk)))
(if (and (with-current-buffer errmsg-buf lua--repl-buffer-p)
(eq error-buf errmsg-buf))
(progn
(compilation-set-window (display-buffer (marker-buffer msg)) msg)
(goto-char msg))
(funcall fn msg mk end-mk))))
(advice-add 'compilation-goto-locus :around #'lua--compilation-goto-locus)
(defcustom lua-indent-string-contents nil
"If non-nil, contents of multiline string will be indented.
Otherwise leading amount of whitespace on each line is preserved."
:group 'lua
:type 'boolean
:safe #'booleanp)
(defcustom lua-indent-nested-block-content-align t
"If non-nil, the contents of nested blocks are indented to
align with the column of the opening parenthesis, rather than
just forward by `lua-indent-level'."
:group 'lua
:type 'boolean
:safe #'booleanp)
(defcustom lua-indent-close-paren-align t
"If non-nil, close parenthesis are aligned with their open
parenthesis. If nil, close parenthesis are aligned to the
beginning of the line."
:group 'lua
:type 'boolean
:safe #'booleanp)
(defcustom lua-jump-on-traceback t
"*Jump to innermost traceback location in *lua* buffer. When this
variable is non-nil and a traceback occurs when running Lua code in a
process, jump immediately to the source code of the innermost
traceback location."
:type 'boolean
:group 'lua)
(defcustom lua-mode-hook nil
"Hooks called when Lua mode fires up."
:type 'hook
:group 'lua)
(defvar lua-region-start (make-marker)
"Start of special region for Lua communication.")
(defvar lua-region-end (make-marker)
"End of special region for Lua communication.")
(defvar lua-emacs-menu
'(["Restart With Whole File" lua-restart-with-whole-file t]
["Kill Process" lua-kill-process t]
["Hide Process Buffer" lua-hide-process-buffer t]
["Show Process Buffer" lua-show-process-buffer t]
["Beginning Of Proc" lua-beginning-of-proc t]
["End Of Proc" lua-end-of-proc t]
["Set Lua-Region Start" lua-set-lua-region-start t]
["Set Lua-Region End" lua-set-lua-region-end t]
["Send Lua-Region" lua-send-lua-region t]
["Send Current Line" lua-send-current-line t]
["Send Region" lua-send-region t]
["Send Proc" lua-send-proc t]
["Send Buffer" lua-send-buffer t]
["Search Documentation" lua-search-documentation t])
"Emacs menu for Lua mode.")
;; the whole defconst is inside eval-when-compile, because it's later referenced
;; inside another eval-and-compile block
(eval-and-compile
(defconst
lua--builtins
(let*
((modules
'("_G" "_VERSION" "assert" "collectgarbage" "dofile" "error" "getfenv"
"getmetatable" "ipairs" "load" "loadfile" "loadstring" "module"
"next" "pairs" "pcall" "print" "rawequal" "rawget" "rawlen" "rawset"
"require" "select" "setfenv" "setmetatable" "tonumber" "tostring"
"type" "unpack" "xpcall" "self"
("bit32" . ("arshift" "band" "bnot" "bor" "btest" "bxor" "extract"
"lrotate" "lshift" "replace" "rrotate" "rshift"))
("coroutine" . ("create" "isyieldable" "resume" "running" "status"
"wrap" "yield"))
("debug" . ("debug" "getfenv" "gethook" "getinfo" "getlocal"
"getmetatable" "getregistry" "getupvalue" "getuservalue"
"setfenv" "sethook" "setlocal" "setmetatable"
"setupvalue" "setuservalue" "traceback" "upvalueid"
"upvaluejoin"))
("io" . ("close" "flush" "input" "lines" "open" "output" "popen"
"read" "stderr" "stdin" "stdout" "tmpfile" "type" "write"))
("math" . ("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "cosh"
"deg" "exp" "floor" "fmod" "frexp" "huge" "ldexp" "log"
"log10" "max" "maxinteger" "min" "mininteger" "modf" "pi"
"pow" "rad" "random" "randomseed" "sin" "sinh" "sqrt"
"tan" "tanh" "tointeger" "type" "ult"))
("os" . ("clock" "date" "difftime" "execute" "exit" "getenv"
"remove" "rename" "setlocale" "time" "tmpname"))
("package" . ("config" "cpath" "loaded" "loaders" "loadlib" "path"
"preload" "searchers" "searchpath" "seeall"))
("string" . ("byte" "char" "dump" "find" "format" "gmatch" "gsub"
"len" "lower" "match" "pack" "packsize" "rep" "reverse"
"sub" "unpack" "upper"))
("table" . ("concat" "insert" "maxn" "move" "pack" "remove" "sort"
"unpack"))
("utf8" . ("char" "charpattern" "codepoint" "codes" "len"
"offset")))))
(cl-labels
((module-name-re (x)
(concat "\\(?1:\\_<"
(if (listp x) (car x) x)
"\\_>\\)"))
(module-members-re (x) (if (listp x)
(concat "\\(?:[ \t]*\\.[ \t]*"
"\\_<\\(?2:"
(regexp-opt (cdr x))
"\\)\\_>\\)?")
"")))
(concat
;; common prefix:
;; - beginning-of-line
;; - or neither of [ '.', ':' ] to exclude "foo.string.rep"
;; - or concatenation operator ".."
"\\(?:^\\|[^:. \t]\\|[.][.]\\)"
;; optional whitespace
"[ \t]*"
"\\(?:"
;; any of modules/functions
(mapconcat (lambda (x) (concat (module-name-re x)
(module-members-re x)))
modules
"\\|")
"\\)"))))
"A regexp that matches Lua builtin functions & variables.
This is a compilation of 5.1, 5.2 and 5.3 builtins taken from the
index of respective Lua reference manuals.")
(defvar lua-font-lock-keywords
`(;; highlight the hash-bang line "#!/foo/bar/lua" as comment
("^#!.*$" . font-lock-comment-face)
;; Builtin constants
(,(lua-rx (symbol "true" "false" "nil"))
. font-lock-constant-face)
;; Keywords
(,(lua-rx (or lua-keyword lua-keyword-operator))
. font-lock-keyword-face)
;; Labels used by the "goto" statement
;; Highlights the following syntax: ::label::
(,(lua-rx "::" ws lua-name ws "::")
. font-lock-constant-face)
;; Highlights the name of the label in the "goto" statement like
;; "goto label"
(,(lua-rx (symbol (seq "goto" ws+ (group-n 1 lua-name))))
(1 font-lock-constant-face))
;; Highlight Lua builtin functions and variables
(,lua--builtins
(1 font-lock-builtin-face) (2 font-lock-builtin-face nil noerror))
(,(lua-rx (symbol "for") ws+ lua-up-to-9-variables)
(1 font-lock-variable-name-face)
(2 font-lock-variable-name-face nil noerror)
(3 font-lock-variable-name-face nil noerror)
(4 font-lock-variable-name-face nil noerror)
(5 font-lock-variable-name-face nil noerror)
(6 font-lock-variable-name-face nil noerror)
(7 font-lock-variable-name-face nil noerror)
(8 font-lock-variable-name-face nil noerror)
(9 font-lock-variable-name-face nil noerror))
(,(lua-rx (symbol "function") (? ws+ lua-funcname) ws "(" ws lua-up-to-9-variables)
(1 font-lock-variable-name-face)
(2 font-lock-variable-name-face nil noerror)
(3 font-lock-variable-name-face nil noerror)
(4 font-lock-variable-name-face nil noerror)
(5 font-lock-variable-name-face nil noerror)
(6 font-lock-variable-name-face nil noerror)
(7 font-lock-variable-name-face nil noerror)
(8 font-lock-variable-name-face nil noerror)
(9 font-lock-variable-name-face nil noerror))
(,(lua-rx lua-funcheader)
(1 font-lock-function-name-face))
;; local x, y, z
;; local x = .....
;;
;; NOTE: this is intentionally below funcheader matcher, so that in
;;
;; local foo = function() ...
;;
;; "foo" is fontified as function-name-face, and variable-name-face is not applied.
(,(lua-rx (symbol "local") ws+ lua-up-to-9-variables)
(1 font-lock-variable-name-face)
(2 font-lock-variable-name-face nil noerror)
(3 font-lock-variable-name-face nil noerror)
(4 font-lock-variable-name-face nil noerror)
(5 font-lock-variable-name-face nil noerror)
(6 font-lock-variable-name-face nil noerror)
(7 font-lock-variable-name-face nil noerror)
(8 font-lock-variable-name-face nil noerror)
(9 font-lock-variable-name-face nil noerror))
(,(lua-rx (or (group-n 1
"@" (symbol "author" "copyright" "field" "release"
"return" "see" "usage" "description"))
(seq (group-n 1 "@" (symbol "param" "class" "name")) ws+
(group-n 2 lua-name))))
(1 font-lock-keyword-face t)
(2 font-lock-variable-name-face t noerror)))
"Default expressions to highlight in Lua mode.")
(defvar lua-imenu-generic-expression
`(("Requires" ,(lua-rx (or bol ";") ws (opt (seq (symbol "local") ws)) (group-n 1 lua-name) ws "=" ws (symbol "require")) 1)
(nil ,(lua-rx (or bol ";") ws (opt (seq (symbol "local") ws)) lua-funcheader) 1))
"Imenu generic expression for lua-mode. See `imenu-generic-expression'.")
(defvar lua-sexp-alist '(("then" . "end")
("function" . "end")
("do" . "end")
("repeat" . "until")))
(defvar lua-mode-abbrev-table nil
"Abbreviation table used in lua-mode buffers.")
(define-abbrev-table 'lua-mode-abbrev-table
'(("end" "end" lua-indent-line :system t)
("else" "else" lua-indent-line :system t)
("elseif" "elseif" lua-indent-line :system t)))
(defvar lua-mode-syntax-table
(with-syntax-table (copy-syntax-table)
;; main comment syntax: begins with "--", ends with "\n"
(modify-syntax-entry ?- ". 12")
(modify-syntax-entry ?\n ">")
;; main string syntax: bounded by ' or "
(modify-syntax-entry ?\' "\"")
(modify-syntax-entry ?\" "\"")
;; single-character binary operators: punctuation
(modify-syntax-entry ?+ ".")
(modify-syntax-entry ?* ".")
(modify-syntax-entry ?/ ".")
(modify-syntax-entry ?^ ".")
(modify-syntax-entry ?% ".")
(modify-syntax-entry ?> ".")
(modify-syntax-entry ?< ".")
(modify-syntax-entry ?= ".")
(modify-syntax-entry ?~ ".")
(syntax-table))
"`lua-mode' syntax table.")
;;;###autoload
(define-derived-mode lua-mode prog-mode "Lua"
"Major mode for editing Lua code."
:abbrev-table lua-mode-abbrev-table
:syntax-table lua-mode-syntax-table
:group 'lua
(setq-local font-lock-defaults '(lua-font-lock-keywords ;; keywords
nil ;; keywords-only
nil ;; case-fold
nil ;; syntax-alist
nil ;; syntax-begin
))
(setq-local syntax-propertize-function
'lua--propertize-multiline-bounds)
(setq-local parse-sexp-lookup-properties t)
(setq-local indent-line-function 'lua-indent-line)
(setq-local beginning-of-defun-function 'lua-beginning-of-proc)
(setq-local end-of-defun-function 'lua-end-of-proc)
(setq-local comment-start lua-comment-start)
(setq-local comment-start-skip lua-comment-start-skip)
(setq-local comment-use-syntax t)
(setq-local fill-paragraph-function #'lua--fill-paragraph)
(with-no-warnings
(setq-local comment-use-global-state t))
(setq-local imenu-generic-expression lua-imenu-generic-expression)
(when (boundp 'electric-indent-chars)
;; If electric-indent-chars is not defined, electric indentation is done
;; via `lua-mode-map'.
(setq-local electric-indent-chars
(append electric-indent-chars lua--electric-indent-chars)))
(add-hook 'flymake-diagnostic-functions #'lua-flymake nil t)
;; setup menu bar entry (XEmacs style)
(if (and (featurep 'menubar)
(boundp 'current-menubar)
(fboundp 'set-buffer-menubar)
(fboundp 'add-menu)
(not (assoc "Lua" current-menubar)))
(progn
(set-buffer-menubar (copy-sequence current-menubar))
(add-menu nil "Lua" lua-emacs-menu)))
;; Append Lua menu to popup menu for Emacs.
(if (boundp 'mode-popup-menu)
(setq mode-popup-menu
(cons (concat mode-name " Mode Commands") lua-emacs-menu)))
;; hideshow setup
(unless (assq 'lua-mode hs-special-modes-alist)
(add-to-list 'hs-special-modes-alist
`(lua-mode
,(regexp-opt (mapcar 'car lua-sexp-alist) 'words) ;start
,(regexp-opt (mapcar 'cdr lua-sexp-alist) 'words) ;end
nil lua-forward-sexp))))
;;;###autoload
(add-to-list 'auto-mode-alist '("\\.lua\\'" . lua-mode))
;;;###autoload
(add-to-list 'interpreter-mode-alist '("lua" . lua-mode))
(defun lua-electric-match (arg)
"Insert character and adjust indentation."
(interactive "P")
(let (blink-paren-function)
(self-insert-command (prefix-numeric-value arg)))
(if lua-electric-flag
(lua-indent-line))
(blink-matching-open))
;; private functions
(defun lua--fill-paragraph (&optional justify region)
;; Implementation of forward-paragraph for filling.
;;
;; This function works around a corner case in the following situations:
;;
;; <>
;; -- some very long comment ....
;; some_code_right_after_the_comment
;;
;; If point is at the beginning of the comment line, fill paragraph code
;; would have gone for comment-based filling and done the right thing, but it
;; does not find a comment at the beginning of the empty line before the
;; comment and falls back to text-based filling ignoring comment-start and
;; spilling the comment into the code.
(save-excursion
(while (and (not (eobp))
(progn (move-to-left-margin)
(looking-at paragraph-separate)))
(forward-line 1))
(let ((fill-paragraph-handle-comment t))
(fill-paragraph justify region))))
(defun lua-prefix-key-update-bindings ()
(let (old-cons)
(if (eq lua-prefix-mode-map (keymap-parent lua-mode-map))
;; if prefix-map is a parent, delete the parent
(set-keymap-parent lua-mode-map nil)
;; otherwise, look for it among children
(if (setq old-cons (rassoc lua-prefix-mode-map lua-mode-map))
(delq old-cons lua-mode-map)))
(if (null lua-prefix-key)
(set-keymap-parent lua-mode-map lua-prefix-mode-map)
(define-key lua-mode-map (vector lua-prefix-key) lua-prefix-mode-map))))
(defun lua-set-prefix-key (new-key-str)
"Changes `lua-prefix-key' properly and updates keymaps
This function replaces previous prefix-key binding with a new one."
(interactive "sNew prefix key (empty string means no key): ")
(lua--customize-set-prefix-key 'lua-prefix-key new-key-str)
(message "Prefix key set to %S" (single-key-description lua-prefix-key))
(lua-prefix-key-update-bindings))
(defun lua-string-p (&optional pos)
"Returns true if the point is in a string."
(save-excursion (elt (syntax-ppss pos) 3)))
(defun lua--containing-double-hyphen-start-pos ()
"Return position of the beginning comment delimiter (--).
Emacs syntax framework does not consider comment delimiters as
part of the comment itself, but for this package it is useful to
consider point as inside comment when it is between the two hyphens"
(and (eql (char-before) ?-)
(eql (char-after) ?-)
(1- (point))))
(defun lua-comment-start-pos (&optional parsing-state)
"Return position of comment containing current point.
If point is not inside a comment, return nil."
(unless parsing-state (setq parsing-state (syntax-ppss)))
(and
;; Not a string
(not (nth 3 parsing-state))
;; Syntax-based comment
(or (and (nth 4 parsing-state) (nth 8 parsing-state))
(lua--containing-double-hyphen-start-pos))))
(defun lua-comment-or-string-p (&optional pos)
"Returns true if the point is in a comment or string."
(save-excursion (let ((parse-result (syntax-ppss pos)))
(or (elt parse-result 3) (lua-comment-start-pos parse-result)))))
(defun lua-comment-or-string-start-pos (&optional pos)
"Returns start position of string or comment which contains point.
If point is not inside string or comment, return nil."
(save-excursion
(when pos (goto-char pos))
(or (elt (syntax-ppss pos) 8)
(lua--containing-double-hyphen-start-pos))))
;; They're propertized as follows:
;; 1. generic-comment
;; 2. generic-string
;; 3. equals signs
(defconst lua-ml-begin-regexp
"\\(?:\\(?1:-\\)-\\[\\|\\(?2:\\[\\)\\)\\(?3:=*\\)\\[")
(defun lua-try-match-multiline-end (end)
"Try to match close-bracket for multiline literal around point.
Basically, detect form of close bracket from syntactic
information provided at point and re-search-forward to it."
(let ((comment-or-string-start-pos (lua-comment-or-string-start-pos)))
;; Is there a literal around point?
(and comment-or-string-start-pos
;; It is, check if the literal is a multiline open-bracket
(save-excursion
(goto-char comment-or-string-start-pos)
(looking-at lua-ml-begin-regexp))
;; Yes it is, look for it matching close-bracket. Close-bracket's
;; match group is determined by match-group of open-bracket.
(re-search-forward
(format "]%s\\(?%s:]\\)"
(match-string-no-properties 3)
(if (match-beginning 1) 1 2))
end 'noerror))))
(defun lua-try-match-multiline-begin (limit)
"Try to match multiline open-brackets.
Find next opening long bracket outside of any string/comment.
If none can be found before reaching LIMIT, return nil."
(let (last-search-matched)
(while
;; This loop will iterate skipping all multiline-begin tokens that are
;; inside strings or comments ending either at EOL or at valid token.
(and (setq last-search-matched
(re-search-forward lua-ml-begin-regexp limit 'noerror))
;; Ensure --[[ is not inside a comment or string.
;;
;; This includes "---[[" sequence, in which "--" at the beginning
;; creates a single-line comment, and thus "-[[" is no longer a
;; multi-line opener.
;;
;; XXX: need to ensure syntax-ppss beyond (match-beginning 0) is
;; not calculated, or otherwise we'll need to flush the cache.
(lua-comment-or-string-start-pos (match-beginning 0))))
last-search-matched))
(defun lua-match-multiline-literal-bounds (limit)
;; First, close any multiline literal spanning from previous block. This will
;; move the point accordingly so as to avoid double traversal.
(or (lua-try-match-multiline-end limit)
(lua-try-match-multiline-begin limit)))
(defun lua--propertize-multiline-bounds (start end)
"Put text properties on beginnings and ends of multiline literals.
Intended to be used as a `syntax-propertize-function'."
(save-excursion
(goto-char start)
(while (lua-match-multiline-literal-bounds end)
(when (match-beginning 1)
(put-text-property (match-beginning 1) (match-end 1)
'syntax-table (string-to-syntax "!")))
(when (match-beginning 2)
(put-text-property (match-beginning 2) (match-end 2)
'syntax-table (string-to-syntax "|"))))))
(defun lua-indent-line ()
"Indent current line for Lua mode.
Return the amount the indentation changed by."
(let (indent
(case-fold-search nil)
;; save point as a distance to eob - it's invariant w.r.t indentation
(pos (- (point-max) (point))))
(back-to-indentation)
(if (lua-comment-or-string-p)
(setq indent (lua-calculate-string-or-comment-indentation)) ;; just restore point position
(setq indent (max 0 (lua-calculate-indentation))))
(when (not (equal indent (current-column)))
(delete-region (line-beginning-position) (point))
(indent-to indent))
;; If initial point was within line's indentation,
;; position after the indentation. Else stay at same point in text.
(if (> (- (point-max) pos) (point))
(goto-char (- (point-max) pos)))
indent))
(defun lua-calculate-string-or-comment-indentation ()
"This function should be run when point at (current-indentation) is inside string"
(if (and (lua-string-p) (not lua-indent-string-contents))
;; if inside string and strings aren't to be indented, return current indentation
(current-indentation)
;; At this point, we know that we're inside comment, so make sure
;; close-bracket is unindented like a block that starts after
;; left-shifter.
(let ((left-shifter-p (looking-at "\\s *\\(?:--\\)?\\]\\(?1:=*\\)\\]")))
(save-excursion
(goto-char (lua-comment-or-string-start-pos))
(+ (current-indentation)
(if (and left-shifter-p
(looking-at (format "--\\[%s\\["
(match-string-no-properties 1))))
0
lua-indent-level))))))
(defun lua--signum (x)
"Return 1 if X is positive, -1 if negative, 0 if zero."
;; XXX: backport from cl-extras for Emacs24
(cond ((> x 0) 1) ((< x 0) -1) (t 0)))
(defun lua--ensure-point-within-limit (limit backward)
"Return non-nil if point is within LIMIT going forward.
With BACKWARD non-nil, return non-nil if point is within LIMIT
going backward.
If point is beyond limit, move it onto limit."
(if (= (lua--signum (- (point) limit))
(if backward 1 -1))
t
(goto-char limit)
nil))
(defun lua--escape-from-string (&optional backward)
"Move point outside of string if it is inside one.
By default, point is placed after the string, with BACKWARD it is
placed before the string."
(interactive)
(let ((parse-state (syntax-ppss)))
(when (nth 3 parse-state)
(if backward
(goto-char (nth 8 parse-state))
(parse-partial-sexp (point) (line-end-position) nil nil (syntax-ppss) 'syntax-table))
t)))
(defun lua-find-regexp (direction regexp &optional limit)
"Searches for a regular expression in the direction specified.
Direction is one of \\='forward and \\='backward.
Matches in comments and strings are ignored. If the regexp is