forked from francogarcia/godot-gdscript.el
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgodot-gdscript.el
3983 lines (3643 loc) · 169 KB
/
godot-gdscript.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
;;; godot-gdscript.el --- Major mode for editing Godot Engine GDScript files
;; Original code Python Mode (from `python.el'):
;; Copyright (C) 2003--2015 Free Software Foundation, Inc.
;; Godot-GDScript Mode:
;; Copyright (C) 2015--2017 Franco Eusébio Garcia
;; Author: Franco Eusébio Garcia <[email protected]>
;; URL: https://github.com/francogarcia/godot-gdscript.el
;; Version: 0.0.1
;; Keywords: languages
;;; License:
;; This file not shipped as 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 is a draft to add support for GDScript in Emacs. GDScript is the
;; language which Godot Game Engine uses to prototype and implement games. Godot
;; is an open-source game engine, available at: <http://www.godotengine.org/>.
;; The mode uses Fabián E. Gallina's `python.el' as the basis and reference for
;; the implementation, due to the similarities between GDScript and Python
;; syntax. However, as some keywords and operators do differ, `python-mode' is
;; not derived; instead, its code is changed to support the GDScript language.
;; Package-Requires: ((emacs "24.3"))
;;; Code:
(require 'ansi-color)
(require 'cl-lib)
(require 'comint)
(require 'json)
;; Avoid compiler warnings (disable due to package-lint-current-buffer).
;; (defvar view-return-to-alist)
;; (defvar compilation-error-regexp-alist)
;; (defvar outline-heading-end-regexp)
;; (defvar ffap-alist)
;; (defvar electric-indent-inhibit)
;; (autoload 'comint-mode "comint")
;;;###autoload
(add-to-list 'auto-mode-alist (cons (purecopy "\\.gd\\'") 'godot-gdscript-mode))
;;;###autoload
(add-to-list 'interpreter-mode-alist (cons (purecopy "godot-gdscript[0-9.]*") 'godot-gdscript-mode))
(defgroup godot-gdscript nil
"Godot Engine GDScript Language support for developing games using Emacs."
:group 'languages
:version "24.3"
:link '(emacs-commentary-link "godot-gdscript"))
;;; Bindings
(defvar godot-gdscript-mode-map
(let ((map (make-sparse-keymap)))
;; Movement
(define-key map [remap backward-sentence] 'godot-gdscript-nav-backward-block)
(define-key map [remap forward-sentence] 'godot-gdscript-nav-forward-block)
(define-key map [remap backward-up-list] 'godot-gdscript-nav-backward-up-list)
(define-key map "\C-c\C-j" 'imenu)
;; Indent specific
(define-key map "\177" 'godot-gdscript-indent-dedent-line-backspace)
(define-key map (kbd "<backtab>") 'godot-gdscript-indent-dedent-line)
(define-key map "\C-c<" 'godot-gdscript-indent-shift-left)
(define-key map "\C-c>" 'godot-gdscript-indent-shift-right)
;; Skeletons
(define-key map "\C-c\C-tc" 'godot-gdscript-skeleton-class)
(define-key map "\C-c\C-td" 'godot-gdscript-skeleton-def)
(define-key map "\C-c\C-tf" 'godot-gdscript-skeleton-for)
(define-key map "\C-c\C-ti" 'godot-gdscript-skeleton-if)
(define-key map "\C-c\C-tt" 'godot-gdscript-skeleton-try)
(define-key map "\C-c\C-tw" 'godot-gdscript-skeleton-while)
;; Shell interaction
(define-key map "\C-c\C-g" 'godot-gdscript-run-godot-editor)
(define-key map "\C-c\C-p" 'godot-gdscript-run-project-in-godot)
(define-key map "\C-c\C-s" 'godot-gdscript-run-current-scene-in-godot)
(define-key map "\C-c\C-e" 'godot-gdscript-edit-current-scene-in-godot)
(define-key map "\C-c\C-r" 'godot-gdscript-run-current-script-in-godot)
(define-key map "\C-c\C-dp" 'godot-gdscript-run-project-in-godot-debug-mode)
(define-key map "\C-c\C-ds" 'godot-gdscript-run-current-scene-in-godot-debug-mode)
(define-key map "\C-c\C-z" 'godot-gdscript-shell-switch-to-shell)
;; Some util commands
(define-key map "\C-c\C-v" 'godot-gdscript-check)
;; Utilities
(substitute-key-definition 'complete-symbol 'completion-at-point
map global-map)
(easy-menu-define godot-gdscript-menu map "Godot-Gdscript Mode menu"
`("Godot-Gdscript"
:help "Godot-Gdscript-specific Features"
["Shift region left" godot-gdscript-indent-shift-left :active mark-active
:help "Shift region left by a single indentation step"]
["Shift region right" godot-gdscript-indent-shift-right :active mark-active
:help "Shift region right by a single indentation step"]
"-"
["Start of def/class" beginning-of-defun
:help "Go to start of outermost definition around point"]
["End of def/class" end-of-defun
:help "Go to end of definition around point"]
["Mark def/class" mark-defun
:help "Mark outermost definition around point"]
["Jump to def/class" imenu
:help "Jump to a class or function definition"]
"--"
("Skeletons")
"---"
["Switch to shell" godot-gdscript-shell-switch-to-shell
:help "Switch to running inferior Godot-Gdscript process"]
["Run Godot Engine editor" godot-gdscript-run-godot-editor
:help "Run Godot Editor as a subprocess of Emacs, loading this project into it"]
["Run project" godot-gdscript-run-project-in-godot
:help "Run the current project in Godot Engine"]
["Run current scene" godot-gdscript-run-current-scene-in-godot
:help "Run the current scene in Godot Engine"]
["Edit scene in Godot Engine" godot-gdscript-edit-current-scene-in-godot
:help "Edit the current scene in Godot Engine"]
["Run current script" godot-gdscript-run-current-script-in-godot
:help "Run the current script in Godot Engine"]
["Run project (debug mode)" godot-gdscript-run-project-in-godot-debug-mode
:help "Run the project in Godot Engine, using the debug mode option"]
["Run scene (debug mode)" godot-gdscript-run-current-scene-in-godot-debug-mode
:help "Run the current scene in Godot Engine, using the debug mode option"]
"----"
["Check file" godot-gdscript-check
:help "Check file for errors"]
["Complete symbol" completion-at-point
:help "Complete symbol before point"]))
map)
"Keymap for function `godot-gdscript-mode'.")
;;; Godot-Gdscript specialized rx
(eval-when-compile
(defconst godot-gdscript-rx-constituents
`((block-start . ,(rx symbol-start
(or "class" "elif" "else" "except" "finally" "for"
"func" "if" "try" "while" "with"
;; Multiplayer stuff
"puppet" "master" "remote" "remotesync")
symbol-end))
(dedenter . ,(rx symbol-start
(or "elif" "else" "except" "finally")
symbol-end))
(block-ender . ,(rx symbol-start
(or
"break" "continue" "pass" "raise" "return")
symbol-end))
(decorator . ,(rx line-start
(* space) ?@ (any letter ?_)
(* (any word ?_))))
(defun . ,(rx symbol-start (or "func" "class") symbol-end))
(if-name-main . ,(rx line-start "if" (+ space) "__name__"
(+ space) "==" (+ space)
(any ?' ?\") "__main__" (any ?' ?\")
(* space) ?:))
(symbol-name . ,(rx (any letter ?_) (* (any word ?_))))
(variable-declaration . ,(rx (or "const" "var")))
(open-paren . ,(rx (or "{" "[" "(")))
(close-paren . ,(rx (or "}" "]" ")")))
(simple-operator . ,(rx (any ?+ ?- ?/ ?& ?^ ?~ ?| ?* ?< ?> ?= ?%)))
;; FIXME: rx should support (not simple-operator).
(not-simple-operator . ,(rx
(not
(any ?+ ?- ?/ ?& ?^ ?~ ?| ?* ?< ?> ?= ?%))))
;; FIXME: Use regexp-opt.
(operator . ,(rx (or "+" "-" "/" "&" "^" "~" "|" "*" "<" ">"
"=" "%" "//" "<<" ">>" "<=" "!" "!="
"==" ">=" "||" "&&" "is" "not")))
;; FIXME: Use regexp-opt.
(assignment-operator . ,(rx (or "=" "+=" "-=" "*=" "/=" "//=" "%="
">>=" "<<=" "&=" "^=" "|=")))
(string-delimiter . ,(rx (and
;; Match even number of backslashes.
(or (not (any ?\\ ?\' ?\")) point
;; Quotes might be preceded by a escaped quote.
(and (or (not (any ?\\)) point) ?\\
(* ?\\ ?\\) (any ?\' ?\")))
(* ?\\ ?\\)
;; Match single or triple quotes of any kind.
(group (or "\"" "\"\"\"" "'" "'''")))))
(coding-cookie . ,(rx line-start ?# (* space)
(or
;; # coding=<encoding name>
(: "coding" (or ?: ?=) (* space) (group-n 1 (+ (or word ?-))))
;; # -*- coding: <encoding name> -*-
(: "-*-" (* space) "coding:" (* space)
(group-n 1 (+ (or word ?-))) (* space) "-*-")))))
"Additional Godot-Gdscript specific sexps for `godot-gdscript-rx'")
(defmacro godot-gdscript-rx (&rest regexps)
"Godot-Gdscript mode specialized rx macro.
This variant of `rx' supports common Godot-Gdscript named REGEXPS."
(let ((rx-constituents (append godot-gdscript-rx-constituents rx-constituents)))
(cond ((null regexps)
(error "No regexp"))
((cdr regexps)
(rx-to-string `(and ,@regexps) t))
(t
(rx-to-string (car regexps) t))))))
;;; Font-lock and syntax
(eval-when-compile
(defun godot-gdscript-syntax--context-compiler-macro (form type &optional syntax-ppss)
(pcase type
(`'comment
`(let ((ppss (or ,syntax-ppss (syntax-ppss))))
(and (nth 4 ppss) (nth 8 ppss))))
(`'string
`(let ((ppss (or ,syntax-ppss (syntax-ppss))))
(and (nth 3 ppss) (nth 8 ppss))))
(`'paren
`(nth 1 (or ,syntax-ppss (syntax-ppss))))
(_ form))))
(defun godot-gdscript-syntax-context (type &optional syntax-ppss)
"Return non-nil if point is on TYPE using SYNTAX-PPSS.
TYPE can be `comment', `string' or `paren'. It returns the start
character address of the specified TYPE."
(declare (compiler-macro godot-gdscript-syntax--context-compiler-macro))
(let ((ppss (or syntax-ppss (syntax-ppss))))
(pcase type
(`comment (and (nth 4 ppss) (nth 8 ppss)))
(`string (and (nth 3 ppss) (nth 8 ppss)))
(`paren (nth 1 ppss))
(_ nil))))
(defun godot-gdscript-syntax-context-type (&optional syntax-ppss)
"Return the context type using SYNTAX-PPSS.
The type returned can be `comment', `string' or `paren'."
(let ((ppss (or syntax-ppss (syntax-ppss))))
(cond
((nth 8 ppss) (if (nth 4 ppss) 'comment 'string))
((nth 1 ppss) 'paren))))
(defsubst godot-gdscript-syntax-comment-or-string-p (&optional ppss)
"Return non-nil if PPSS is inside 'comment or 'string."
(nth 8 (or ppss (syntax-ppss))))
(defsubst godot-gdscript-syntax-closing-paren-p ()
"Return non-nil if char after point is a closing paren."
(= (syntax-class (syntax-after (point)))
(syntax-class (string-to-syntax ")"))))
(define-obsolete-function-alias
'godot-gdscript-info-ppss-context #'godot-gdscript-syntax-context "24.3")
(define-obsolete-function-alias
'godot-gdscript-info-ppss-context-type #'godot-gdscript-syntax-context-type "24.3")
(define-obsolete-function-alias
'godot-gdscript-info-ppss-comment-or-string-p
#'godot-gdscript-syntax-comment-or-string-p "24.3")
(defvar godot-gdscript-font-lock-keywords
;; Keywords
`(,(rx symbol-start
(or
"and" "in" "is" "not" "or"
"null" "self"
"String" "bool" "float" "int"
;; Functions
;; Variant types
"AABB" "Array" "Basis" "ByteArray" "Color"
"ColorArray" "Dictionary" "Image" "InputEvent" "IntArray"
"Matrix3" "Matrix32" "NodePath" "Object" "Plane"
"Quat" "RID" "RealArray" "Rect2" "StringArray"
"Transform" "Vector2" "Vector2Array" "Vector3" "Vector3Array"
;; Language keywords
"assert" "break" "breakpoint" "class" "const" "continue"
"default" "do" "elif" "else" "enum"
"export" "extends" "for" "func" "if" "onready"
;; Multiplayer stuff
"puppet" "master" "remote" "remotesync"
"pass" "preload" "resume" "return" "setget"
"signal" "static" "tool" "var" "while" "yield")
symbol-end)
;; functions
(,(rx symbol-start "func" (1+ space) (group (1+ (or word ?_))))
(1 font-lock-function-name-face))
;; classes
(,(rx symbol-start "class" (1+ space) (group (1+ (or word ?_))))
(1 font-lock-type-face))
;; Constants
(,(rx symbol-start
(or
"PI" "false" "null" "true")
symbol-end) . font-lock-constant-face)
;; Decorators.
(,(rx line-start (* (any " \t")) (group "@" (1+ (or word ?_))
(0+ "." (1+ (or word ?_)))))
(1 font-lock-type-face))
;; Builtin Exceptions
(,(rx symbol-start
(or
"OK" "FAILED"
"ERR_UNAVAILABLE" "ERR_UNCONFIGURED" "ERR_UNAUTHORIZED"
"ERR_PARAMETER_RANGE_ERROR" "ERR_OUT_OF_MEMORY" "ERR_FILE_NOT_FOUND"
"ERR_FILE_BAD_DRIVE" "ERR_FILE_BAD_PATH" "ERR_FILE_NO_PERMISSION"
"ERR_FILE_ALREADY_IN_USE" "ERR_FILE_CANT_OPEN" "ERR_FILE_CANT_WRITE"
"ERR_FILE_CANT_READ" "ERR_FILE_UNRECOGNIZED" "ERR_FILE_CORRUPT"
"ERR_FILE_MISSING_DEPENDENCIES" "ERR_FILE_EOF" "ERR_CANT_OPEN"
"ERR_CANT_CREATE" "ERROR_QUERY_FAILED" "ERR_ALREADY_IN_USE"
"ERR_LOCKED" "ERR_TIMEOUT" "ERR_CANT_CONNECT" "ERR_CANT_RESOLVE"
"ERR_CONNECTION_ERROR" "ERR_CANT_AQUIRE_RESOURCE" "ERR_CANT_FORK"
"ERR_INVALID_DATA" "ERR_INVALID_PARAMETER" "ERR_ALREADY_EXISTS"
"ERR_DOES_NOT_EXIST" "ERR_DATABASE_CANT_READ" "ERR_DATABASE_CANT_WRITE"
"ERR_COMPILATION_FAILED" "ERR_METHOD_NOT_FOUND" "ERR_LINK_FAILED"
"ERR_SCRIPT_FAILED" "ERR_CYCLIC_LINK" "ERR_INVALID_DECLARATION"
"ERR_DUPLICATE_SYMBOL" "ERR_PARSE_ERROR" "ERR_BUSY"
"ERR_SKIP" "ERR_HELP" "ERR_BUG" "ERR_PRINTER_ON_FIRE"
"ERR_OMFG_THIS_IS_VERY_VERY_BAD" "ERR_WTF")
symbol-end) . font-lock-type-face)
;; Builtins
(,(rx symbol-start
(or
;; Inherited methods from Object
"connect" "emit" "get" "set_signal"
;; Inherited methods from Node
;; get_node() shorthand
;; <https://github.com/godotengine/godot/issues/4309>
"$"
;; (<https://github.com/godotengine/godot/blob/master/scene/scene_string_names.h>)
"_draw" "_enter_tree" "_enter_world" "_exit_tree" "_exit_world"
"_fixed_process" "_init" "_input" "_input" "_physics_process"
"_process" "_process" "_ready" "_unhandled_input"
"_unhandled_input" "_unhandled_key_input" "_unhandled_key_input"
;; (<https://github.com/godotengine/godot/blob/master/scene/main/node.cpp>)
"add_child" "add_to_group" "can_process" "duplicate" "find_node"
"get_child" "get_child_count" "get_children" "get_filename"
"get_groups" "get_index" "get_name" "get_node"
"get_node_and_resource" "get_owner" "get_parent" "get_path"
"get_path_to" "get_pause_mode" "get_physics_process_delta_time"
"get_position_in_parent" "get_process_delta_time"
"get_scene_instance_load_placeholder" "get_tree" "get_viewport"
"has_node" "has_node_and_resource" "is_a_parent_of"
"is_displayed_folded" "is_greater_than" "is_in_group"
"is_inside_tree" "is_physics_processing"
"is_physics_processing_internal" "is_processing"
"is_processing_input" "is_processing_internal"
"is_processing_unhandled_input"
"is_processing_unhandled_key_input"
"move_child" "print_stray_nodes" "print_tree" "print_tree_pretty"
"propagate_call" "propagate_notification" "queue_free" "raise"
"remove_and_skip" "remove_child" "remove_from_group" "replace_by"
"request_ready" "set_display_folded" "set_filename" "set_name"
"set_owner" "set_pause_mode" "set_physics_process"
"set_physics_process_internal" "set_process" "set_process_input"
"set_process_internal" "set_process_unhandled_input"
"set_process_unhandled_key_input"
"set_scene_instance_load_placeholder"
;; Missing functions from header
"basefunc" "call" "new" "instance"
;; Exported functions
;; (<https://github.com/godotengine/godot/blob/master/modules/gdscript/gdscript_functions.cpp>)
"Color8" "ColorN" "abs" "acos" "asin" "atan" "atan2" "bytes2var"
"cartesian2polar" "ceil" "char" "clamp" "convert" "cos" "cosh"
"db2linear" "decimals" "dectime" "deg2rad" "dict2inst" "ease"
"exp" "floor" "fmod" "fposmod" "funcref" "hash" "inst2dict"
"instance_from_id" "inverse_lerp" "is_inf" "is_instance_valid"
"is_nan" "len" "lerp" "linear2db" "load" "log" "max" "min"
"nearest_po2" "parse_json" "polar2cartesian" "pow" "print"
"print_stack" "printerr" "printraw" "prints" "printt" "rad2deg"
"rand_range" "rand_seed" "randf" "randi" "randomize" "range"
"range_lerp" "round" "seed" "sign" "sinh" "sqrt" "stepify" "str"
"str2var" "tan" "tanh" "to_json" "type_exists" "typeof"
"validate_json" "var2bytes" "var2str" "weakref" "wrapf" "wrapi"
"sin")
symbol-end) . font-lock-builtin-face)
;; assignments
;; support for a = b = c = 5
(,(lambda (limit)
(let ((re (godot-gdscript-rx (group (+ (any word ?. ?_)))
(? ?\[ (+ (not (any ?\]))) ?\]) (* space)
assignment-operator))
(res nil))
(while (and (setq res (re-search-forward re limit t))
(or (godot-gdscript-syntax-context 'paren)
(equal (char-after (point-marker)) ?=))))
res))
(1 font-lock-variable-name-face nil nil))
;; support for a, b, c = (1, 2, 3)
(,(lambda (limit)
(let ((re (godot-gdscript-rx (group (+ (any word ?. ?_))) (* space)
(* ?, (* space) (+ (any word ?. ?_)) (* space))
?, (* space) (+ (any word ?. ?_)) (* space)
assignment-operator))
(res nil))
(while (and (setq res (re-search-forward re limit t))
(goto-char (match-end 1))
(godot-gdscript-syntax-context 'paren)))
res))
(1 font-lock-variable-name-face nil nil))))
(defconst godot-gdscript-syntax-propertize-function
(syntax-propertize-rules
((godot-gdscript-rx string-delimiter)
(0 (ignore (godot-gdscript-syntax-stringify))))))
(defsubst godot-gdscript-syntax-count-quotes (quote-char &optional point limit)
"Count number of quotes around point (max is 3).
QUOTE-CHAR is the quote char to count. Optional argument POINT is
the point where scan starts (defaults to current point), and
LIMIT is used to limit the scan."
(let ((i 0))
(while (and (< i 3)
(or (not limit) (< (+ point i) limit))
(eq (char-after (+ point i)) quote-char))
(setq i (1+ i)))
i))
(defun godot-gdscript-syntax-stringify ()
"Put `syntax-table' property correctly on single/triple quotes."
(let* ((num-quotes (length (match-string-no-properties 1)))
(ppss (prog2
(backward-char num-quotes)
(syntax-ppss)
(forward-char num-quotes)))
(string-start (and (not (nth 4 ppss)) (nth 8 ppss)))
(quote-starting-pos (- (point) num-quotes))
(quote-ending-pos (point))
(num-closing-quotes
(and string-start
(godot-gdscript-syntax-count-quotes
(char-before) string-start quote-starting-pos))))
(cond ((and string-start (= num-closing-quotes 0))
;; This set of quotes doesn't match the string starting
;; kind. Do nothing.
nil)
((not string-start)
;; This set of quotes delimit the start of a string.
(put-text-property quote-starting-pos (1+ quote-starting-pos)
'syntax-table (string-to-syntax "|")))
((= num-quotes num-closing-quotes)
;; This set of quotes delimit the end of a string.
(put-text-property (1- quote-ending-pos) quote-ending-pos
'syntax-table (string-to-syntax "|")))
((> num-quotes num-closing-quotes)
;; This may only happen whenever a triple quote is closing
;; a single quoted string. Add string delimiter syntax to
;; all three quotes.
(put-text-property quote-starting-pos quote-ending-pos
'syntax-table (string-to-syntax "|"))))))
(defvar godot-gdscript-mode-syntax-table
(let ((table (make-syntax-table)))
;; Give punctuation syntax to ASCII that normally has symbol
;; syntax or has word syntax and isn't a letter.
(let ((symbol (string-to-syntax "_"))
(sst (standard-syntax-table)))
(dotimes (i 128)
(unless (= i ?_)
(if (equal symbol (aref sst i))
(modify-syntax-entry i "." table)))))
(modify-syntax-entry ?$ "." table)
(modify-syntax-entry ?% "." table)
;; exceptions
(modify-syntax-entry ?# "<" table)
(modify-syntax-entry ?\n ">" table)
(modify-syntax-entry ?' "\"" table)
(modify-syntax-entry ?` "$" table)
table)
"Syntax table for Godot-Gdscript files.")
(defvar godot-gdscript-dotty-syntax-table
(let ((table (make-syntax-table godot-gdscript-mode-syntax-table)))
(modify-syntax-entry ?. "w" table)
(modify-syntax-entry ?_ "w" table)
table)
"Dotty syntax table for Godot-Gdscript files.
It makes underscores and dots word constituent chars.")
;;; Indentation
(defcustom godot-gdscript-indent-offset 4
"Default indentation offset for Godot-Gdscript."
:group 'godot-gdscript
:type 'integer
:safe 'integerp)
(defcustom godot-gdscript-indent-guess-indent-offset t
"Non-nil tells Godot-Gdscript mode to guess `godot-gdscript-indent-offset' value."
:type 'boolean
:group 'godot-gdscript
:safe 'booleanp)
(defcustom godot-gdscript-indent-trigger-commands
'(indent-for-tab-command yas-expand yas/expand)
"Commands that might trigger a `godot-gdscript-indent-line' call."
:type '(repeat symbol)
:group 'godot-gdscript)
(define-obsolete-variable-alias
'godot-gdscript-indent 'godot-gdscript-indent-offset "24.3")
(define-obsolete-variable-alias
'godot-gdscript-guess-indent 'godot-gdscript-indent-guess-indent-offset "24.3")
(defvar godot-gdscript-indent-current-level 0
"Deprecated var available for compatibility.")
(defvar godot-gdscript-indent-levels '(0)
"Deprecated var available for compatibility.")
(make-obsolete-variable
'godot-gdscript-indent-current-level
"The indentation API changed to avoid global state.
The function `godot-gdscript-indent-calculate-levels' does not use it
anymore. If you were defadvising it and or depended on this
variable for indentation customizations, refactor your code to
work on `godot-gdscript-indent-calculate-indentation' instead."
"24.5")
(make-obsolete-variable
'godot-gdscript-indent-levels
"The indentation API changed to avoid global state.
The function `godot-gdscript-indent-calculate-levels' does not use it
anymore. If you were defadvising it and or depended on this
variable for indentation customizations, refactor your code to
work on `godot-gdscript-indent-calculate-indentation' instead."
"24.5")
(defun godot-gdscript-indent-guess-indent-offset ()
"Guess and set `godot-gdscript-indent-offset' for the current buffer."
(interactive)
(save-excursion
(save-restriction
(widen)
(goto-char (point-min))
(let ((block-end))
(while (and (not block-end)
(re-search-forward
(godot-gdscript-rx line-start block-start) nil t))
(when (and
(not (godot-gdscript-syntax-context-type))
(progn
(goto-char (line-end-position))
(godot-gdscript-util-forward-comment -1)
(if (equal (char-before) ?:)
t
(forward-line 1)
(when (godot-gdscript-info-block-continuation-line-p)
(while (and (godot-gdscript-info-continuation-line-p)
(not (eobp)))
(forward-line 1))
(godot-gdscript-util-forward-comment -1)
(when (equal (char-before) ?:)
t)))))
(setq block-end (point-marker))))
(let ((indentation
(when block-end
(goto-char block-end)
(godot-gdscript-util-forward-comment)
(current-indentation))))
(if (and indentation (not (zerop indentation)))
(set (make-local-variable 'godot-gdscript-indent-offset) indentation)
(message "Can't guess godot-gdscript-indent-offset, using defaults: %s"
godot-gdscript-indent-offset)))))))
(defun godot-gdscript-indent-context ()
"Get information about the current indentation context.
Context is returned in a cons with the form (STATUS . START).
STATUS can be one of the following:
keyword
-------
:after-comment
- Point is after a comment line.
- START is the position of the \"#\" character.
:inside-string
- Point is inside string.
- START is the position of the first quote that starts it.
:no-indent
- No possible indentation case matches.
- START is always zero.
:inside-paren
- Fallback case when point is inside paren.
- START is the first non space char position *after* the open paren.
:inside-paren-at-closing-nested-paren
- Point is on a line that contains a nested paren closer.
- START is the position of the open paren it closes.
:inside-paren-at-closing-paren
- Point is on a line that contains a paren closer.
- START is the position of the open paren.
:inside-paren-newline-start
- Point is inside a paren with items starting in their own line.
- START is the position of the open paren.
:inside-paren-newline-start-from-block
- Point is inside a paren with items starting in their own line
from a block start.
- START is the position of the open paren.
:after-backslash
- Fallback case when point is after backslash.
- START is the char after the position of the backslash.
:after-backslash-assignment-continuation
- Point is after a backslashed assignment.
- START is the char after the position of the backslash.
:after-backslash-block-continuation
- Point is after a backslashed block continuation.
- START is the char after the position of the backslash.
:after-backslash-dotted-continuation
- Point is after a backslashed dotted continuation. Previous
line must contain a dot to align with.
- START is the char after the position of the backslash.
:after-backslash-first-line
- First line following a backslashed continuation.
- START is the char after the position of the backslash.
:after-block-end
- Point is after a line containing a block ender.
- START is the position where the ender starts.
:after-block-start
- Point is after a line starting a block.
- START is the position where the block starts.
:after-line
- Point is after a simple line.
- START is the position where the previous line starts.
:at-dedenter-block-start
- Point is on a line starting a dedenter block.
- START is the position where the dedenter block starts."
(save-restriction
(widen)
(let ((ppss (save-excursion
(beginning-of-line)
(syntax-ppss))))
(cond
;; Beginning of buffer.
((= (line-number-at-pos) 1)
(cons :no-indent 0))
;; Inside a string.
((let ((start (godot-gdscript-syntax-context 'string ppss)))
(when start
(cons :inside-string start))))
;; Inside a paren.
((let* ((start (godot-gdscript-syntax-context 'paren ppss))
(starts-in-newline
(when start
(save-excursion
(goto-char start)
(forward-char)
(not
(= (line-number-at-pos)
(progn
(godot-gdscript-util-forward-comment)
(line-number-at-pos))))))))
(when start
(cond
;; Current line only holds the closing paren.
((save-excursion
(skip-syntax-forward " ")
(when (and (godot-gdscript-syntax-closing-paren-p)
(progn
(forward-char 1)
(not (godot-gdscript-syntax-context 'paren))))
(cons :inside-paren-at-closing-paren start))))
;; Current line only holds a closing paren for nested.
((save-excursion
(back-to-indentation)
(godot-gdscript-syntax-closing-paren-p))
(cons :inside-paren-at-closing-nested-paren start))
;; This line starts from a opening block in its own line.
((save-excursion
(goto-char start)
(when (and
starts-in-newline
(save-excursion
(back-to-indentation)
(looking-at (godot-gdscript-rx block-start))))
(cons
:inside-paren-newline-start-from-block start))))
(starts-in-newline
(cons :inside-paren-newline-start start))
;; General case.
(t (cons :inside-paren
(save-excursion
(goto-char (1+ start))
(skip-syntax-forward "(" 1)
(skip-syntax-forward " ")
(point))))))))
;; After backslash.
((let ((start (when (not (godot-gdscript-syntax-comment-or-string-p ppss))
(godot-gdscript-info-line-ends-backslash-p
(1- (line-number-at-pos))))))
(when start
(cond
;; Continuation of dotted expression.
((save-excursion
(back-to-indentation)
(when (eq (char-after) ?\.)
;; Move point back until it's not inside a paren.
(while (prog2
(forward-line -1)
(and (not (bobp))
(godot-gdscript-syntax-context 'paren))))
(goto-char (line-end-position))
(while (and (search-backward
"." (line-beginning-position) t)
(godot-gdscript-syntax-context-type)))
;; Ensure previous statement has dot to align with.
(when (and (eq (char-after) ?\.)
(not (godot-gdscript-syntax-context-type)))
(cons :after-backslash-dotted-continuation (point))))))
;; Continuation of block definition.
((let ((block-continuation-start
(godot-gdscript-info-block-continuation-line-p)))
(when block-continuation-start
(save-excursion
(goto-char block-continuation-start)
(re-search-forward
(godot-gdscript-rx block-start (* space))
(line-end-position) t)
(cons :after-backslash-block-continuation (point))))))
;; Continuation of assignment.
((let ((assignment-continuation-start
(godot-gdscript-info-assignment-continuation-line-p)))
(when assignment-continuation-start
(save-excursion
(goto-char assignment-continuation-start)
(cons :after-backslash-assignment-continuation (point))))))
;; First line after backslash continuation start.
((save-excursion
(goto-char start)
(when (or (= (line-number-at-pos) 1)
(not (godot-gdscript-info-beginning-of-backslash
(1- (line-number-at-pos)))))
(cons :after-backslash-first-line start))))
;; General case.
(t (cons :after-backslash start))))))
;; After beginning of block.
((let ((start (save-excursion
(back-to-indentation)
(godot-gdscript-util-forward-comment -1)
(when (equal (char-before) ?:)
(godot-gdscript-nav-beginning-of-block)))))
(when start
(cons :after-block-start start))))
;; At dedenter statement.
((let ((start (godot-gdscript-info-dedenter-statement-p)))
(when start
(cons :at-dedenter-block-start start))))
;; After normal line, comment or ender (default case).
((save-excursion
(back-to-indentation)
(skip-chars-backward " \t\n")
(godot-gdscript-nav-beginning-of-statement)
(cons
(cond ((godot-gdscript-info-current-line-comment-p)
:after-comment)
((save-excursion
(goto-char (line-end-position))
(godot-gdscript-util-forward-comment -1)
(godot-gdscript-nav-beginning-of-statement)
(looking-at (godot-gdscript-rx block-ender)))
:after-block-end)
(t :after-line))
(point))))))))
(defun godot-gdscript-indent--calculate-indentation ()
"Internal implementation of `godot-gdscript-indent-calculate-indentation'.
May return an integer for the maximum possible indentation at
current context or a list of integers. The latter case is only
happening for :at-dedenter-block-start context since the
possibilities can be narrowed to specific indentation points."
(save-restriction
(widen)
(save-excursion
(pcase (godot-gdscript-indent-context)
(`(:no-indent . ,_) 0)
(`(,(or :after-line
:after-comment
:inside-string
:after-backslash
:inside-paren-at-closing-paren
:inside-paren-at-closing-nested-paren) . ,start)
;; Copy previous indentation.
(goto-char start)
(current-indentation))
(`(,(or :after-block-start
:after-backslash-first-line
:inside-paren-newline-start) . ,start)
;; Add one indentation level.
(goto-char start)
(+ (current-indentation) godot-gdscript-indent-offset))
(`(,(or :inside-paren
:after-backslash-block-continuation
:after-backslash-assignment-continuation
:after-backslash-dotted-continuation) . ,start)
;; Use the column given by the context.
(goto-char start)
(current-column))
(`(:after-block-end . ,start)
;; Subtract one indentation level.
(goto-char start)
(- (current-indentation) godot-gdscript-indent-offset))
(`(:at-dedenter-block-start . ,_)
;; List all possible indentation levels from opening blocks.
(let ((opening-block-start-points
(godot-gdscript-info-dedenter-opening-block-positions)))
(if (not opening-block-start-points)
0 ; if not found default to first column
(mapcar (lambda (pos)
(save-excursion
(goto-char pos)
(current-indentation)))
opening-block-start-points))))
(`(,(or :inside-paren-newline-start-from-block) . ,start)
;; Add two indentation levels to make the suite stand out.
(goto-char start)
(+ (current-indentation) (* godot-gdscript-indent-offset 2)))))))
(defun godot-gdscript-indent--calculate-levels (indentation)
"Calculate levels list given INDENTATION.
Argument INDENTATION can either be an integer or a list of
integers. Levels are returned in ascending order, and in the
case INDENTATION is a list, this order is enforced."
(if (listp indentation)
(sort (copy-sequence indentation) #'<)
(let* ((remainder (% indentation godot-gdscript-indent-offset))
(steps (/ (- indentation remainder) godot-gdscript-indent-offset))
(levels (mapcar (lambda (step)
(* godot-gdscript-indent-offset step))
(number-sequence steps 0 -1))))
(reverse
(if (not (zerop remainder))
(cons indentation levels)
levels)))))
(defun godot-gdscript-indent--previous-level (levels indentation)
"Return previous level from LEVELS relative to INDENTATION."
(let* ((levels (sort (copy-sequence levels) #'>))
(default (car levels)))
(catch 'return
(dolist (level levels)
(when (funcall #'< level indentation)
(throw 'return level)))
default)))
(defun godot-gdscript-indent-calculate-indentation (&optional previous)
"Calculate indentation.
Get indentation of PREVIOUS level when argument is non-nil.
Return the max level of the cycle when indentation reaches the
minimum."
(let* ((indentation (godot-gdscript-indent--calculate-indentation))
(levels (godot-gdscript-indent--calculate-levels indentation)))
(if previous
(godot-gdscript-indent--previous-level levels (current-indentation))
(apply #'max levels))))
(defun godot-gdscript-indent-line (&optional previous)
"Internal implementation of `godot-gdscript-indent-line-function'.
Use the PREVIOUS level when argument is non-nil, otherwise indent
to the maximum available level. When indentation is the minimum
possible and PREVIOUS is non-nil, cycle back to the maximum
level."
(let ((follow-indentation-p
;; Check if point is within indentation.
(and (<= (line-beginning-position) (point))
(>= (+ (line-beginning-position)
(current-indentation))
(point)))))
(save-excursion
(indent-line-to
(godot-gdscript-indent-calculate-indentation previous))
(godot-gdscript-info-dedenter-opening-block-message))
(when follow-indentation-p
(back-to-indentation))))
(defun godot-gdscript-indent-calculate-levels ()
"Return possible indentation levels."
(godot-gdscript-indent--calculate-levels
(godot-gdscript-indent--calculate-indentation)))
(defun godot-gdscript-indent-line-function ()
"`indent-line-function' for Godot-Gdscript mode.
When the variable `last-command' is equal to one of the symbols
inside `godot-gdscript-indent-trigger-commands' it cycles possible
indentation levels from right to left."
(godot-gdscript-indent-line
(and (memq this-command godot-gdscript-indent-trigger-commands)
(eq last-command this-command))))
(defun godot-gdscript-indent-dedent-line ()
"De-indent current line."
(interactive "*")
(when (and (not (bolp))
(not (godot-gdscript-syntax-comment-or-string-p))
(= (current-indentation) (current-column)))
(godot-gdscript-indent-line t)
t))
(defun godot-gdscript-indent-dedent-line-backspace (arg)
"De-indent current line.
Argument ARG is passed to `backward-delete-char-untabify' when
point is not in between the indentation."
(interactive "*p")
(unless (godot-gdscript-indent-dedent-line)
(backward-delete-char-untabify arg)))
(put 'godot-gdscript-indent-dedent-line-backspace 'delete-selection 'supersede)
(defun godot-gdscript-indent-region (start end)
"Indent a Godot-Gdscript region automagically.
Called from a program, START and END specify the region to indent."
(let ((deactivate-mark nil))
(save-excursion
(goto-char end)
(setq end (point-marker))
(goto-char start)
(or (bolp) (forward-line 1))
(while (< (point) end)
(or (and (bolp) (eolp))
(when (and
;; Skip if previous line is empty or a comment.
(save-excursion
(let ((line-is-comment-p
(godot-gdscript-info-current-line-comment-p)))
(forward-line -1)
(not
(or (and (godot-gdscript-info-current-line-comment-p)
;; Unless this line is a comment too.
(not line-is-comment-p))
(godot-gdscript-info-current-line-empty-p)))))
;; Don't mess with strings, unless it's the
;; enclosing set of quotes.
(or (not (godot-gdscript-syntax-context 'string))
(eq
(syntax-after
(+ (1- (point))
(current-indentation)
(godot-gdscript-syntax-count-quotes (char-after) (point))))
(string-to-syntax "|")))
;; Skip if current line is a block start, a
;; dedenter or block ender.
(save-excursion
(back-to-indentation)
(not (looking-at
(godot-gdscript-rx
(or block-start dedenter block-ender))))))
(godot-gdscript-indent-line)))
(forward-line 1))
(move-marker end nil))))
(defun godot-gdscript-indent-shift-left (start end &optional count)
"Shift lines contained in region START END by COUNT columns to the left.
COUNT defaults to `godot-gdscript-indent-offset'. If region isn't
active, the current line is shifted. The shifted region includes
the lines in which START and END lie. An error is signaled if
any lines in the region are indented less than COUNT columns."
(interactive
(if mark-active
(list (region-beginning) (region-end) current-prefix-arg)
(list (line-beginning-position) (line-end-position) current-prefix-arg)))
(if count
(setq count (prefix-numeric-value count))
(setq count godot-gdscript-indent-offset))
(when (> count 0)
(let ((deactivate-mark nil))
(save-excursion
(goto-char start)
(while (< (point) end)
(if (and (< (current-indentation) count)
(not (looking-at "[ \t]*$")))
(error "Can't shift all lines enough"))
(forward-line))
(indent-rigidly start end (- count))))))
(add-to-list 'debug-ignored-errors "^Can't shift all lines enough")
(defun godot-gdscript-indent-shift-right (start end &optional count)
"Shift lines contained in region START END by COUNT columns to the right.
COUNT defaults to `godot-gdscript-indent-offset'. If region isn't
active, the current line is shifted. The shifted region includes
the lines in which START and END lie."
(interactive