forked from Reagankm/renpy-mode
-
Notifications
You must be signed in to change notification settings - Fork 1
/
renpy.el
1612 lines (1515 loc) · 60.7 KB
/
renpy.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
;;; renpy.el --- Major mode for editing Ren'Py files -*- lexical-binding: t; -*-
;; Copyright (C) 2003-2013
;; Free Software Foundation, Inc.
;; Copyright (C) 2018-2019
;; Billy Wade
;; Copyright (C) 2020
;; Reagan Middlebrook
;; Copyright (C) 2023
;; Morgan Willcock
;; Author: Dave Love <[email protected]>, PyTom <[email protected]>
;; Keywords: languages
;; Maintainer: Reagan Middlebrook <[email protected]>
;; Package-Requires: ((emacs "27.1"))
;; URL: https://github.com/Reagankm/renpy-mode
;; Version: 0.3
;; This program is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; A major mode for Ren'Py based on Dave Love's python.el.
;;; Code:
(require 'imenu)
(eval-when-compile
(require 'rx))
(defgroup renpy nil
"Major mode for editing Ren'Py files."
:tag "Ren'Py"
:prefix "renpy-"
:group 'languages
:link '(emacs-commentary-link "renpy"))
;;;###autoload
(add-to-list 'auto-mode-alist '("\\.rpym?\\'" . renpy-mode))
;;;; Search patterns
(defmacro renpy-rx (&rest regexps)
"Extended version of `rx' for translation of form REGEXPS."
`(rx-let (;; User defined names.
(name
(seq symbol-start
(or alpha "_")
(0+ (or alphanumeric "_"))
symbol-end))
(image-name
(seq symbol-start
(1+ (or alphanumeric "_"))
symbol-end))
;; Labels. It is not a logical error if the label definition
;; doesn't begin at the start of the line.
(label-keyword
(seq line-start (0+ space) "label" symbol-end))
;; Screens.
(screen-keyword
(seq line-start "screen" symbol-end))
;; Styles.
(style-keyword
(seq line-start "style" symbol-end))
;; Transforms
(transform-keyword
(seq line-start "transform" symbol-end))
;; Images.
(image-keyword
(seq line-start "image" symbol-end))
;; Define or default. Allow indentation for use in explicit init
;; blocks or within a screen.
(default-or-define-keyword
(seq line-start (0+ space) (or "default" "define") symbol-end))
;; Init.
(init-keyword
(seq line-start "init" symbol-end))
(init-argument
(seq symbol-start (or "hide" "in" "offset" "python") symbol-end))
;; Keywords from sphinx/source/keywords.py.
(keyword
(seq symbol-start
(or "$" "False" "IF" "None" "True" "add" "always" "and"
"animation" "areapicker" "as" "assert" "async" "at"
"attribute" "auto" "await" "bar" "behind" "block" "break"
"button" "call" "camera" "choice" "circles" "class"
"clear" "clockwise" "contains" "continue"
"counterclockwise" "def" "default" "define" "del"
"dismiss" "drag" "draggroup" "elif" "else" "event"
"except" "expression" "finally" "fixed" "for" "frame"
"from" "function" "global" "grid" "group" "has" "hbox"
"hide" "hotbar" "hotspot" "if" "image" "imagebutton"
"imagemap" "import" "in" "index" "init" "input" "is"
"jump" "key" "knot" "label" "lambda" "layeredimage" "menu"
"monologue" "mousearea" "music" "nearrect" "new"
"nointeract" "nonlocal" "not" "null" "nvl" "offset" "old"
"on" "onlayer" "or" "parallel" "pass" "pause" "play"
"python" "queue" "raise" "repeat" "return" "rpy" "scene"
"screen" "show" "showif" "side" "sound" "stop" "strings"
"style" "sustain" "tag" "take" "testcase" "text"
"textbutton" "time" "timer" "transclude" "transform"
"translate" "try" "use" "vbar" "vbox" "viewport" "voice"
"vpgrid" "while" "window" "with" "yield" "zorder")
symbol-end))
;; Classes and functions from
;; https://www.renpy.org/doc/html/py-function-class-index.html.
;; Note: Any name containing a "." was ommited to try and keep the
;; highlighting consistent with the use of other python modules.
;; Variables were not included for the same reason.
(class-or-function
(seq symbol-start
(or "AddToSet" "AlphaBlend" "AlphaDissolve" "AlphaMask"
"AnimatedValue" "At" "Attribute" "AudioData"
"AudioPositionValue" "add" "BarValue" "Borders"
"BrightnessMatrix" "Call" "CaptureFocus" "Character"
"ClearFocus" "Color" "ColorizeMatrix" "ComposeTransition"
"Composite" "Condition" "ConditionSwitch" "Confirm"
"ContrastMatrix" "Crop" "CropMove" "DictInputValue"
"DictValue" "DisableAllInputValues" "Dissolve" "Drag"
"DragGroup" "DynamicDisplayable" "DynamicImage" "Editor"
"EndReplay" "Fade" "FieldInputValue" "FieldValue"
"FileAction" "FileCurrentPage" "FileCurrentScreenshot"
"FileDelete" "FileJson" "FileLoad" "FileLoadable"
"FileNewest" "FilePage" "FilePageName"
"FilePageNameInputValue" "FilePageNext" "FilePagePrevious"
"FileSave" "FileSaveName" "FileScreenshot" "FileSlotName"
"FileTakeScreenshot" "FileTime" "FileUsedSlots" "Fixed"
"Flatten" "FontGroup" "Frame" "Function" "Gallery"
"GamepadCalibrate" "GamepadExists" "GetCharacterVolume"
"GetFocusRect" "GetTooltip" "Grid" "HBox" "Help" "Hide"
"HideInterface" "HistoryEntry" "HueMatrix"
"IdentityMatrix" "If" "Image" "ImageDissolve" "InputValue"
"InvertMatrix" "InvertSelected" "Jump" "Language"
"LayeredImage" "LayeredImageProxy" "Lexer" "Live2D"
"MainMenu" "Matrix" "MixerValue" "Model"
"MouseDisplayable" "MouseMove" "MoveTransition" "Movie"
"MultiPersistent" "MultipleTransition" "MusicRoom"
"NoRollback" "Notify" "Null" "NullAction" "nvl_clear"
"nvl_hide" "nvl_menu" "nvl_show" "OffsetMatrix"
"OpacityMatrix" "OpenDirectory" "OpenURL"
"ParameterizedText" "Pause" "PauseAudio" "Pixellate"
"Placeholder" "Play" "PlayCharacterVoice" "Preference"
"PushMove" "Queue" "QueueEvent" "QuickLoad" "QuickSave"
"Quit" "RemoveFromSet" "Replay" "RestartStatement"
"Return" "RollForward" "Rollback" "RollbackToIdentifier"
"RotateMatrix" "remap" "Sample" "SaturationMatrix"
"ScaleMatrix" "ScreenVariableInputValue"
"ScreenVariableValue" "Screenshot" "Scroll" "SelectedIf"
"SensitiveIf" "SepiaMatrix" "SetCharacterVolume" "SetDict"
"SetField" "SetLocalVariable" "SetMixer" "SetMute"
"SetScreenVariable" "SetVariable" "SetVoiceMute" "Show"
"ShowMenu" "ShowTransient" "ShowingSwitch" "SideImage"
"Skip" "SlottedNoRollback" "SnowBlossom" "Solid" "Sprite"
"SpriteManager" "Start" "StaticValue" "Stop" "Style"
"StylePreference" "Swing" "Text" "Tile" "TintMatrix"
"ToggleDict" "ToggleField" "ToggleFocus"
"ToggleLocalVariable" "ToggleMute" "ToggleScreen"
"ToggleScreenVariable" "ToggleSetMembership"
"ToggleVariable" "ToggleVoiceMute" "Tooltip" "Transform"
"translate_define" "translate_font" "VBox"
"VariableInputValue" "VariableValue" "VoiceReplay"
"voice_can_replay" "voice_replay" "voice_sustain" "With"
"XScrollValue" "YScrollValue" "_" "__" "_get_voice_info"
"_p" "_window_hide" "_window_show")
symbol-end))
(transform-property
(seq word-start
(or "additive" "align" "alignaround" "alpha" "anchor" "angle"
"around" "blend" "blur" "corner1" "corner2" "crop"
"crop_relative" "delay" "events" "fit" "matrixanchor"
"matrixcolor" "matrixtransform" "maxsize" "mesh"
"mesh_pad" "nearest" "offset" "perspective" "pos" "radius"
"rotate" "rotate_pad" "shader" "size" "subpixel"
"transform_anchor" "xalign" "xanchor" "xcenter" "xoffset"
"xpan" "xpos" "xsize" "xtile" "xycenter" "xysize" "xzoom"
"yalign" "yanchor" "ycenter" "yoffset" "ypan" "ypos"
"ysize" "ytile" "yzoom" "zoom" "zpos")
symbol-end))
;; User Interface statements from
;; https://www.renpy.org/doc/html/screens.html#common-properties.
(ui-statement
(seq word-start
(or "at" "default_focus" "id" "style" "style_prefix"
"style_group" "style_suffix" "focus" "tooltip" "arguments"
"properties")
word-end))
;; Style properties from
;; https://www.renpy.org/doc/html/std-style-property-index.html.
(style-prefix
(seq word-start
(or "idle" "hover" "selected" "insensitive" "selected_idle"
"selected_hover" "selected_insensitive")
?_
word-start))
(style-prefix-text
(seq symbol-start "text_" word-start))
(style-prefix-scrollbar
(seq symbol-start (optional ?v) "scrollbar_" word-start))
(style-prefix-side
(seq symbol-start "side_" word-start))
(style-prefix-viewport
(seq symbol-start "viewport_" word-start))
(style-position
(seq word-start
(or "alt" "xpos" "ypos" "pos" "xanchor" "yanchor" "anchor"
"xalign" "yalign" "align" "xcenter" "ycenter" "xoffset"
"yoffset" "offset" "xmaximum" "ymaximum" "maximum"
"xminimum" "yminimum" "minimum" "xsize" "ysize" "xysize"
"xfill" "yfill" "area" "mipmap")
symbol-end))
(style-text
(seq word-start
(or "antialias" "adjust_spacing" "altruby_style" "black_color"
"bold" "caret" "color" "first_indent" "font" "size"
"italic" "justify" "kerning" "language" "layout"
"line_leading" "line_overlap_split" "line_spacing"
"min_width" "newline_indent" "outlines" "style"
"outline_scaling" "rest_indent" "ruby_style"
"slow_abortable" "slow_cps" "slow_cps_multiplier"
"strikethrough" "text_align" "underline"
"hyperlink_functions" "vertical" "hinting")
symbol-end))
(style-window
(seq word-start
(or "background" "foreground" "left_padding" "right_padding"
"xpadding" "top_padding" "bottom_padding" "ypadding"
"padding" "size_group" "modal")
symbol-end))
(style-button
(seq word-start
(or "child" "hover_sound" "activate_sound" "mouse"
"focus_mask" "keyboard_focus" "key_events")
symbol-end))
(style-bar
(seq word-start
(or "bar_vertical" "bar_invert" "bar_resizing" "left_gutter"
"right_gutter" "top_gutter" "bottom_gutter" "left_bar"
"right_bar" "top_bar" "bottom_bar" "base_bar" "thumb"
"thumb_shadow" "thumb_offset" "mouse" "unscrollable"
"keyboard_focus")
symbol-end))
(style-box
(seq word-start
(or "spacing" "first_spacing" "box_reverse" "box_wrap"
"box_wrap_spacing" "order_reverse")
symbol-end))
(style-grid
(seq word-start
(or "spacing" "xspacing" "yspacing")
symbol-end))
(style-fixed
(seq word-start
(or "fit_first" "xfit" "yfit")
symbol-end))
(style-margin
(seq word-start
(or "left_margin" "right_margin" "xmargin" "top_margin"
"bottom_margin" "ymargin" "margin")
symbol-end))
;; Warper functions from
;; https://www.renpy.org/doc/html/atl.html#warpers.
(warper
(seq symbol-start
(or "pause" "linear" "ease" "easein" "easeout"
"ease_back" "ease_bounce" "ease_circ" "ease_cubic"
"ease_elastic" "ease_expo" "ease_quad" "ease_quart"
"ease_quint" "easein_back" "easein_bounce" "easein_circ"
"easein_cubic" "easein_elastic" "easein_expo"
"easein_quad" "easein_quart" "easein_quint"
"easeout_back" "easeout_bounce" "easeout_circ"
"easeout_cubic" "easeout_elastic" "easeout_expo"
"easeout_quad" "easeout_quart" "easeout_quint")
symbol-end)))
(rx ,@regexps)))
;;;; Font lock
(defvar renpy-font-lock-keywords
`(,(rx symbol-start
;; From v 2.7 Keywords reference.
;; def and class dealt with separately below
(or "and" "as" "assert" "break" "continue" "del" "elif" "else"
"except" "exec" "finally" "for" "from" "global" "if"
"import" "in" "is" "lambda" "not" "or" "pass" "print"
"raise" "return" "try" "while" "with" "yield"
;; Not real keywords, but close enough to be fontified as such
"self" "True" "False"
;; Python 3
"nonlocal")
symbol-end)
(,(rx symbol-start "None" symbol-end) ; see Keywords in 2.7 manual
. font-lock-constant-face)
;; Definitions
(,(rx symbol-start (group "class") (1+ space) (group (1+ (or word ?_))))
(1 font-lock-keyword-face) (2 font-lock-type-face))
(,(rx symbol-start (group "def") (1+ space) (group (1+ (or word ?_))))
(1 font-lock-keyword-face) (2 font-lock-function-name-face))
;; Top-level assignments are worth highlighting.
(,(rx line-start (group (1+ (or word ?_))) (0+ space)
(opt (or "+" "-" "*" "**" "/" "//" "&" "%" "|" "^" "<<" ">>")) "=")
(1 font-lock-variable-name-face))
;; Decorators.
(,(rx line-start (* (any " \t")) (group "@" (1+ (or word ?_))
(0+ "." (1+ (or word ?_)))))
(1 font-lock-type-face))
;; Built-ins. (The next three blocks are from
;; `__builtin__.__dict__.keys()' in Python 2.7) These patterns
;; are debatable, but they at least help to spot possible
;; shadowing of builtins.
(,(rx symbol-start (or
;; exceptions
"ArithmeticError" "AssertionError" "AttributeError"
"BaseException" "DeprecationWarning" "EOFError"
"EnvironmentError" "Exception" "FloatingPointError"
"FutureWarning" "GeneratorExit" "IOError" "ImportError"
"ImportWarning" "IndentationError" "IndexError" "KeyError"
"KeyboardInterrupt" "LookupError" "MemoryError" "NameError"
"NotImplemented" "NotImplementedError" "OSError"
"OverflowError" "PendingDeprecationWarning" "ReferenceError"
"RuntimeError" "RuntimeWarning" "StandardError"
"StopIteration" "SyntaxError" "SyntaxWarning" "SystemError"
"SystemExit" "TabError" "TypeError" "UnboundLocalError"
"UnicodeDecodeError" "UnicodeEncodeError" "UnicodeError"
"UnicodeTranslateError" "UnicodeWarning" "UserWarning"
"ValueError" "Warning" "ZeroDivisionError"
;; Python 2.7
"BufferError" "BytesWarning" "WindowsError")
symbol-end)
. font-lock-type-face)
(,(rx (or line-start (not (any ". \t"))) (* (any " \t")) symbol-start
(group (or
;; callable built-ins, fontified when not appearing as
;; object attributes
"abs" "all" "any" "apply" "basestring" "bool" "buffer" "callable"
"chr" "classmethod" "cmp" "coerce" "compile" "complex"
"copyright" "credits" "delattr" "dict" "dir" "divmod"
"enumerate" "eval" "execfile" "exit" "file" "filter" "float"
"frozenset" "getattr" "globals" "hasattr" "hash" "help"
"hex" "id" "input" "int" "intern" "isinstance" "issubclass"
"iter" "len" "license" "list" "locals" "long" "map" "max"
"min" "object" "oct" "open" "ord" "pow" "property" "quit"
"range" "raw_input" "reduce" "reload" "repr" "reversed"
"round" "set" "setattr" "slice" "sorted" "staticmethod"
"str" "sum" "super" "tuple" "type" "unichr" "unicode" "vars"
"xrange" "zip"
;; Python 2.7.
"bin" "bytearray" "bytes" "format" "memoryview" "next" "print"))
symbol-end)
(1 font-lock-builtin-face))
(,(rx symbol-start (or
;; other built-ins
"True" "False" "None" "Ellipsis"
"_" "__debug__" "__doc__" "__import__" "__name__" "__package__")
symbol-end)
. font-lock-builtin-face)
;; Ren'Py 8.0.3
(,(renpy-rx (group label-keyword) (1+ space) (group name))
(1 font-lock-keyword-face) (2 font-lock-function-name-face))
(,(renpy-rx (group screen-keyword) (1+ space) (group name))
(1 font-lock-keyword-face) (2 font-lock-function-name-face))
(,(renpy-rx (group style-keyword) (1+ space) (group name))
(1 font-lock-keyword-face) (2 font-lock-variable-name-face))
(,(renpy-rx (group transform-keyword) (1+ space) (group name))
(1 font-lock-keyword-face) (2 font-lock-function-name-face))
(,(renpy-rx (group image-keyword) (1+ space) (group image-name))
(1 font-lock-keyword-face) (2 font-lock-variable-name-face)
;; Anchored match for attribute names.
(,(renpy-rx (group image-name))
(save-excursion
(search-forward-regexp "=" (line-end-position) t))
nil
(0 font-lock-preprocessor-face)))
(,(renpy-rx default-or-define-keyword)
(0 font-lock-keyword-face)
;; Anchored match for anything that looks like a valid name.
(,(renpy-rx name)
(save-excursion
(search-forward-regexp "=" (line-end-position) t))
nil
(0 font-lock-variable-name-face)))
(,(renpy-rx init-keyword)
(0 font-lock-keyword-face)
;; Anchored match for what may follow an init keyword.
(,(renpy-rx init-argument)
(save-excursion
(search-forward-regexp "=" (line-end-position) t))
nil
(0 font-lock-keyword-face)))
;; Properties passed to a scrollbar.
(,(renpy-rx style-prefix-scrollbar
(optional style-prefix)
(or style-bar style-position transform-property))
. font-lock-type-face)
;; Properties passed to a side.
(,(renpy-rx style-prefix-side
(optional style-prefix)
(or style-position transform-property))
. font-lock-type-face)
;; Properties passed to a text displayable.
(,(renpy-rx style-prefix-text
(optional style-prefix)
(or style-position style-text transform-property))
. font-lock-type-face)
;; Properties passed to a viewport.
(,(renpy-rx style-prefix-viewport
(optional style-prefix)
(or style-position transform-property))
. font-lock-type-face)
;; All style properties with optional prefix.
(,(renpy-rx (optional style-prefix)
(or style-position style-text style-window
style-button style-bar style-box style-grid
style-fixed style-margin transform-property))
. font-lock-type-face)
(,(renpy-rx keyword) . font-lock-keyword-face)
(,(renpy-rx class-or-function) . font-lock-builtin-face)
(,(renpy-rx ui-statement) . font-lock-builtin-face)
(,(renpy-rx transform-property) . font-lock-type-face)
(,(renpy-rx warper) . font-lock-constant-face)))
(defconst renpy-syntax-propertize-function
;; Make outer chars of matching triple-quote sequences into generic
;; string delimiters. Fixme: Is there a better way?
;; First avoid a sequence preceded by an odd number of backslashes.
(syntax-propertize-rules
(;; Backrefs don't work in syntax-propertize-rules!
(concat "\\(?:\\([RUru]\\)[Rr]?\\|\\(?:\\=\\|[^\\]\\)\\(?:\\\\.\\)*\\)?" ;Prefix.
"\\(?:\\('\\)'\\('\\)\\|\\(?2:\"\\)\"\\(?3:\"\\)\\)")
(3 (ignore (renpy-quote-syntax))))
;; This doesn't really help.
;;((rx (and ?\\ (group ?\n))) (1 " "))
))
(defun renpy-quote-syntax ()
"Put `syntax-table' property correctly on triple quote.
Used for syntactic keywords. N is the match number (1, 2 or 3)."
;; Given a triple quote, we have to check the context to know
;; whether this is an opening or closing triple or whether it's
;; quoted anyhow, and should be ignored. (For that we need to do
;; the same job as `syntax-ppss' to be correct and it seems to be OK
;; to use it here despite initial worries.) We also have to sort
;; out a possible prefix -- well, we don't _have_ to, but I think it
;; should be treated as part of the string.
;; Test cases:
;; ur"""ar""" x='"' # """
;; x = ''' """ ' a
;; '''
;; x '"""' x """ \"""" x
(save-excursion
(goto-char (match-beginning 0))
(let ((syntax (save-match-data (syntax-ppss))))
(cond
((eq t (nth 3 syntax)) ; after unclosed fence
;; Consider property for the last char if in a fenced string.
(goto-char (nth 8 syntax)) ; fence position
(skip-chars-forward "uUrR") ; skip any prefix
;; Is it a matching sequence?
(if (eq (char-after) (char-after (match-beginning 2)))
(put-text-property (match-beginning 3) (match-end 3)
'syntax-table (string-to-syntax "|"))))
((match-end 1)
;; Consider property for initial char, accounting for prefixes.
(put-text-property (match-beginning 1) (match-end 1)
'syntax-table (string-to-syntax "|")))
(t
;; Consider property for initial char, accounting for prefixes.
(put-text-property (match-beginning 2) (match-end 2)
'syntax-table (string-to-syntax "|")))))))
;; This isn't currently in `font-lock-defaults' as probably not worth
;; it -- we basically only mess with a few normally-symbol characters.
;; (defun renpy-font-lock-syntactic-face-function (state)
;; "`font-lock-syntactic-face-function' for Renpy mode.
;; Returns the string or comment face as usual, with side effect of putting
;; a `syntax-table' property on the inside of the string or comment which is
;; the standard syntax table."
;; (if (nth 3 state)
;; (save-excursion
;; (goto-char (nth 8 state))
;; (condition-case nil
;; (forward-sexp)
;; (error nil))
;; (put-text-property (1+ (nth 8 state)) (1- (point))
;; 'syntax-table (standard-syntax-table))
;; 'font-lock-string-face)
;; (put-text-property (1+ (nth 8 state)) (line-end-position)
;; 'syntax-table (standard-syntax-table))
;; 'font-lock-comment-face))
;;;; Keymap and syntax
(defvar renpy-mode-map
(let ((map (make-sparse-keymap)))
;; Mostly taken from renpy-mode.el.
(define-key map ":" #'renpy-electric-colon)
(define-key map "\177" #'renpy-backspace)
(define-key map "\C-c<" #'renpy-shift-left)
(define-key map "\C-c>" #'renpy-shift-right)
(define-key map "\C-c\C-k" #'renpy-mark-block)
(define-key map "\C-c\C-j" #'imenu)
(define-key map "\C-c\C-n" #'renpy-next-statement)
(define-key map "\C-c\C-p" #'renpy-previous-statement)
(define-key map "\C-c\C-u" #'renpy-beginning-of-block)
(easy-menu-define renpy-menu map "Ren'Py Mode menu"
`("Ren'Py"
:help "Ren'Py-specific Features"
["Shift region left" renpy-shift-left :active mark-active
:help "Shift by a single indentation step"]
["Shift region right" renpy-shift-right :active mark-active
:help "Shift by a single indentation step"]
"-"
["Mark block" renpy-mark-block
:help "Mark innermost block around point"]
["Mark def/class" mark-defun
:help "Mark innermost definition around point"]
"-"
["Start of block" renpy-beginning-of-block
:help "Go to start of innermost definition around point"]
["End of block" renpy-end-of-block
:help "Go to end of innermost definition around point"]
["Start of def/class" beginning-of-defun
:help "Go to start of innermost definition around point"]
["End of def/class" end-of-defun
:help "Go to end of innermost definition around point"]))
map))
;; Fixme: add toolbar stuff for useful things like symbol help, send
;; region, at least. (Shouldn't be specific to Renpy, obviously.)
;; eric has items including: (un)indent, (un)comment, restart script,
;; run script, debug script; also things for profiling, unit testing.
(defvar renpy-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))
;;;; Utility stuff
(defsubst renpy-in-string-comment ()
"Return non-nil if point is in a Renpy literal (a comment or string)."
;; We don't need to save the match data.
(nth 8 (syntax-ppss)))
(defconst renpy-space-backslash-table
(let ((table (copy-syntax-table renpy-mode-syntax-table)))
(modify-syntax-entry ?\\ " " table)
table)
"`renpy-mode-syntax-table' with backslash given whitespace syntax.")
(defun renpy-skip-comments-blanks (&optional backward)
"Skip comments and blank lines.
BACKWARD non-nil means go backwards, otherwise go forwards.
Backslash is treated as whitespace so that continued blank lines
are skipped. Doesn't move out of comments -- should be outside
or at end of line."
(let ((arg (if backward
;; If we're in a comment (including on the trailing
;; newline), forward-comment doesn't move backwards out
;; of it. Don't set the syntax table round this bit!
(let ((syntax (syntax-ppss)))
(if (nth 4 syntax)
(goto-char (nth 8 syntax)))
(- (point-max)))
(point-max))))
(with-syntax-table renpy-space-backslash-table
(forward-comment arg))))
(defun renpy-backslash-continuation-line-p ()
"Non-nil if preceding line ends with backslash that is not in a comment."
(and (eq ?\\ (char-before (line-end-position 0)))
(not (syntax-ppss-context (syntax-ppss)))))
(defun renpy-continuation-line-p ()
"Return non-nil if current line continues a previous one.
The criteria are that the previous line ends in a backslash outside
comments and strings, or that point is within brackets/parens."
(or (renpy-backslash-continuation-line-p)
(let ((depth (syntax-ppss-depth
(save-excursion ; syntax-ppss with arg changes point
(syntax-ppss (line-beginning-position))))))
(or (> depth 0)
(if (< depth 0) ; Unbalanced brackets -- act locally
(save-excursion
(condition-case ()
(progn (backward-up-list) t) ; actually within brackets
(error nil))))))))
(defun renpy-comment-line-p ()
"Return non-nil if and only if current line has only a comment."
(save-excursion
(end-of-line)
(when (eq 'comment (syntax-ppss-context (syntax-ppss)))
(back-to-indentation)
(looking-at (rx (or (syntax comment-start) line-end))))))
(defun renpy-blank-line-p ()
"Return non-nil if and only if current line is blank."
(save-excursion
(beginning-of-line)
(looking-at "\\s-*$")))
(defun renpy-beginning-of-string ()
"Go to beginning of string around point.
Do nothing if not in string."
(let ((state (syntax-ppss)))
(when (eq 'string (syntax-ppss-context state))
(goto-char (nth 8 state)))))
(defun renpy-open-block-statement-p (&optional bos)
"Return non-nil if statement at point opens a block.
Any statement that ends in a colon opens a block. BOS non-nil
means point is known to be at beginning of statement."
(save-excursion
(unless bos (renpy-beginning-of-statement))
(and (< (point) (progn
(renpy-end-of-statement)
(renpy-skip-comments-blanks t)
(point)))
(eq ?: (char-before)))))
(defun renpy-close-block-statement-p (&optional bos)
"Return non-nil if current line is a statement closing a block.
BOS non-nil means point is at beginning of statement.
The criteria are that the line isn't a comment or in string and
starts with keyword `raise', `break', `continue' or `pass'."
(save-excursion
(unless bos (renpy-beginning-of-statement))
(back-to-indentation)
(looking-at (rx (or "return" "raise" "break" "continue" "pass")
symbol-end))))
(defun renpy-outdent-p ()
"Return non-nil if current line should outdent a level."
(save-excursion
(back-to-indentation)
(and (looking-at (rx (and (or "else" "finally" "except" "elif")
symbol-end)))
(not (renpy-in-string-comment))
;; Ensure there's a previous statement and move to it.
(zerop (renpy-previous-statement))
(not (renpy-close-block-statement-p t))
;; Fixme: check this
(not (renpy-open-block-statement-p)))))
;;;; Indentation.
(defcustom renpy-indent 4
"Number of columns for a unit of indentation in Renpy mode.
See also `\\[renpy-guess-indent]'"
:group 'renpy
:type 'integer)
(put 'renpy-indent 'safe-local-variable 'integerp)
(defcustom renpy-guess-indent nil
"Non-nil means Renpy mode guesses `renpy-indent' for the buffer."
:type 'boolean
:group 'renpy)
(defcustom renpy-indent-string-contents t
"Non-nil means indent contents of multi-line strings together.
This means indent them the same as the preceding non-blank line.
Otherwise preserve their indentation.
This only applies to `doc' strings, i.e. those that form statements;
the indentation is preserved in others."
:type '(choice (const :tag "Align with preceding" t)
(const :tag "Preserve indentation" nil))
:group 'renpy)
(defcustom renpy-honour-comment-indentation nil
"Non-nil means indent relative to preceding comment line.
Only do this for comments where the leading comment character is
followed by space. This doesn't apply to comment lines, which
are always indented in lines with preceding comments."
:type 'boolean
:group 'renpy)
(defcustom renpy-continuation-offset 4
"Number of columns of additional indentation for continuation lines.
Continuation lines follow a backslash-terminated line starting a
statement."
:group 'renpy
:type 'integer)
(defun renpy-guess-indent ()
"Guess step for indentation of current buffer.
Set `renpy-indent' locally to the value guessed."
(interactive)
(save-excursion
(save-restriction
(widen)
(goto-char (point-min))
(let (done indent)
(while (and (not done) (not (eobp)))
(when (and (re-search-forward (rx ?: (0+ space)
(or (syntax comment-start)
line-end))
nil 'move)
(renpy-open-block-statement-p))
(save-excursion
(renpy-beginning-of-statement)
(let ((initial (current-indentation)))
(if (zerop (renpy-next-statement))
(setq indent (- (current-indentation) initial)))
(if (and indent (>= indent 2) (<= indent 8)) ; sanity check
(setq done t))))))
(when done
(when (/= indent (default-value 'renpy-indent))
(setq-local renpy-indent indent)
(unless (= tab-width renpy-indent)
(setq indent-tabs-mode nil)))
indent)))))
;; Alist of possible indentations and start of statement they would
;; close. Used in indentation cycling (below).
(defvar renpy-indent-list nil
"Internal use.")
;; Length of the above
(defvar renpy-indent-list-length nil
"Internal use.")
;; Current index into the alist.
(defvar renpy-indent-index nil
"Internal use.")
(defun renpy-calculate-indentation ()
"Calculate Renpy indentation for line at point."
(setq renpy-indent-list nil
renpy-indent-list-length 1)
(save-excursion
(beginning-of-line)
(let ((syntax (syntax-ppss))
start)
(cond
((eq 'string (syntax-ppss-context syntax)) ; multi-line string
(cond
;; Indentation for Ren'Py dialogue strings, which are allowed to
;; span multiple lines.
;; FIXME: Should this be a user preference?
((renpy-in-script-statement-p)
(goto-char (nth 8 syntax))
(+ (current-column) (if (eq (skip-syntax-forward "|\"") 1)
;; Align with the inside of a single quote.
1
;; No adjustment for a triple quote.
;; FIXME: Should this be a user preference?
0)))
((not renpy-indent-string-contents)
(current-indentation))
;; Only respect `renpy-indent-string-contents' in doc
;; strings (defined as those which form statements).
((not (save-excursion
(renpy-beginning-of-statement)
(looking-at (rx (or (syntax string-delimiter)
(syntax string-quote))))))
(current-indentation))
(t
;; Find indentation of preceding non-blank line within string.
(setq start (nth 8 syntax))
(forward-line -1)
(while (and (< start (point)) (looking-at "\\s-*$"))
(forward-line -1))
(current-indentation))))
((renpy-continuation-line-p) ; after backslash, or bracketed
(let ((point (point))
(open-start (cadr syntax))
(backslash (renpy-backslash-continuation-line-p))
(colon (eq ?: (char-before (1- (line-beginning-position))))))
(if open-start
;; Inside bracketed expression.
(progn
(goto-char (1+ open-start))
;; Look for first item in list (preceding point) and
;; align with it, if found.
(if (with-syntax-table renpy-space-backslash-table
(let ((parse-sexp-ignore-comments t))
(condition-case ()
(progn (forward-sexp)
(backward-sexp)
(< (point) point))
(error nil))))
;; Extra level if we're backslash-continued or
;; following a key.
(if (or backslash colon)
(+ renpy-indent (current-column))
(current-column))
;; Otherwise indent relative to statement start, one
;; level per bracketing level.
(goto-char (1+ open-start))
(renpy-beginning-of-statement)
(+ (current-indentation) (* (car syntax) renpy-indent))))
;; Otherwise backslash-continued.
(forward-line -1)
(if (renpy-continuation-line-p)
;; We're past first continuation line. Align with
;; previous line.
(current-indentation)
;; First continuation line. Indent one step, with an
;; extra one if statement opens a block.
(renpy-beginning-of-statement)
(+ (current-indentation) renpy-continuation-offset
(if (renpy-open-block-statement-p t)
renpy-indent
0))))))
((bobp) 0)
;; Fixme: Like renpy-mode.el; not convinced by this.
((looking-at (rx (0+ space) (syntax comment-start)
(not (any " \t\n")))) ; non-indentable comment
(current-indentation))
((and renpy-honour-comment-indentation
;; Back over whitespace, newlines, non-indentable comments.
(catch 'done
(while (cond ((bobp) nil)
((not (forward-comment -1))
nil) ; not at comment start
;; Now at start of comment -- trailing one?
((/= (current-column) (current-indentation))
nil)
;; Indentable comment, like renpy-mode.el?
((and (looking-at (rx (syntax comment-start)
(or space line-end)))
(/= 0 (current-column)))
(throw 'done (current-column)))
;; Else skip it (loop).
(t))))))
(t
(renpy-indentation-levels)
;; Prefer to indent comments with an immediately-following
;; statement, e.g.
;; ...
;; # ...
;; def ...
(when (and (> renpy-indent-list-length 1)
(renpy-comment-line-p))
(forward-line)
(unless (renpy-comment-line-p)
(let ((elt (assq (current-indentation) renpy-indent-list)))
(setq renpy-indent-list
(nconc (delete elt renpy-indent-list)
(list elt))))))
(caar (last renpy-indent-list)))))))
;; Cycling through the possible indentations with successive TABs.
;; These don't need to be buffer-local since they're only relevant
;; during a cycle.
(defun renpy-initial-text ()
"Text of line following indentation and ignoring any trailing comment."
(save-excursion
(buffer-substring (progn
(back-to-indentation)
(point))
(max (point)
(progn
(end-of-line)
(renpy-skip-comments-blanks t)
(point))))))
(defconst renpy-block-pairs
'(("else" "if" "showif" "elif" "while" "for" "try" "except")
("elif" "if" "showif" "elif")
("except" "try" "except")
("finally" "else" "try" "except"))
"Alist of keyword matches.
The car of an element is a keyword introducing a statement which
can close a block opened by a keyword in the cdr.")
(defun renpy-first-word ()
"Return first word (actually symbol) on the line."
(save-excursion
(back-to-indentation)
(current-word t)))
(defun renpy-indentation-levels ()
"Return a list of possible indentations for this line.
It is assumed not to be a continuation line or in a multi-line string.
Includes the default indentation and those which would close all
enclosing blocks. Elements of the list are actually pairs:
\(INDENTATION . TEXT), where TEXT is the initial text of the
corresponding block opening (or nil)."
(save-excursion
(let ((initial "")
levels indent)
;; Only one possibility immediately following a block open
;; statement, assuming it doesn't have a `suite' on the same line.
(cond
((save-excursion (and (renpy-previous-statement)
(renpy-open-block-statement-p t)
(setq indent (current-indentation))
;; Check we don't have something like:
;; if ...: ...
(if (progn (renpy-end-of-statement)
(renpy-skip-comments-blanks t)
(eq ?: (char-before)))
(setq indent (+ renpy-indent indent)))))
(push (cons indent initial) levels))
;; Only one possibility for comment line immediately following
;; another.
((save-excursion
(when (renpy-comment-line-p)
(forward-line -1)
(if (renpy-comment-line-p)
(push (cons (current-indentation) initial) levels)))))
;; Fixme: Maybe have a case here which indents (only) first
;; line after a lambda.
(t
(let ((start (car (assoc (renpy-first-word) renpy-block-pairs))))
(renpy-previous-statement)
;; Is this a valid indentation for the line of interest?
(unless (or (if start ; potentially only outdentable
;; Check for things like:
;; if ...: ...
;; else ...:
;; where the second line need not be outdented.
(not (member (renpy-first-word)
(cdr (assoc start
renpy-block-pairs)))))
;; Not sensible to indent to the same level as
;; previous `return' &c.
(renpy-close-block-statement-p))
(push (cons (current-indentation) (renpy-initial-text))
levels))
(while (renpy-beginning-of-block)
(when (or (not start)
(member (renpy-first-word)
(cdr (assoc start renpy-block-pairs))))
(push (cons (current-indentation) (renpy-initial-text))
levels))))))
(prog1 (or levels (setq levels '((0 . ""))))
(setq renpy-indent-list levels
renpy-indent-list-length (length renpy-indent-list))))))
;; This is basically what `renpy-indent-line' would be if we didn't
;; do the cycling.
(defun renpy-indent-line-1 (&optional leave)
"Subroutine of `renpy-indent-line'.
Does non-repeated indentation. LEAVE non-nil means leave
indentation if it is valid, i.e. one of the positions returned by
`renpy-calculate-indentation'."
(let ((target (renpy-calculate-indentation))
(pos (- (point-max) (point))))
(if (or (= target (current-indentation))
;; Maybe keep a valid indentation.
(and leave renpy-indent-list
(assq (current-indentation) renpy-indent-list)))
(if (< (current-column) (current-indentation))
(back-to-indentation))
(beginning-of-line)
(delete-horizontal-space)
(indent-to target)
(if (> (- (point-max) pos) (point))
(goto-char (- (point-max) pos))))))
(defun renpy-indent-line ()
"Indent current line as Renpy code.
When invoked via `indent-for-tab-command', cycle through possible
indentations for current line. The cycle is broken by a command
different from `indent-for-tab-command', i.e. successive TABs do
the cycling."
(interactive)
(if (and (eq this-command 'indent-for-tab-command)
(eq last-command this-command))
(if (= 1 renpy-indent-list-length)
(message "Sole indentation")
(progn (setq renpy-indent-index
(% (1+ renpy-indent-index) renpy-indent-list-length))
(beginning-of-line)
(delete-horizontal-space)
(indent-to (car (nth renpy-indent-index renpy-indent-list)))
(if (renpy-block-end-p)
(let ((text (cdr (nth renpy-indent-index
renpy-indent-list))))