forked from dotmilk/emacs-crystal-mode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcrystal-mode.el
1870 lines (1733 loc) · 69.6 KB
/
crystal-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
;;; crystal-mode.el --- Major mode for editing Crystal files
;; Copyright (C) 2015 Jason Pellerin
;; Authors: Jason Pellerin
;; URL: https://github.com/jpellerin/emacs-crystal-mode
;; Created: Tue Jun 23 2015
;; Keywords: languages crystal
;; Version 0.1
;; Based on on ruby-mode.el
;; Copyright (C) 1994-2015 Free Software Foundation, Inc.
;; Authors: Yukihiro Matsumoto
;; Nobuyoshi Nakada
;; URL: http://www.emacswiki.org/cgi-bin/wiki/RubyMode
;; Created: Fri Feb 4 14:49:13 JST 1994
;; Keywords: languages ruby
;; Version: 1.2
;; This file is part of GNU Emacs.
;; GNU Emacs 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.
;; GNU Emacs 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 GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; Provides font-locking, indentation support, and navigation for Crystal code.
;;
;; If you're installing manually, you should add this to your .emacs
;; file after putting it on your load path:
;;
;; (autoload 'crystal-mode "crystal-mode" "Major mode for crystal files" t)
;; (add-to-list 'auto-mode-alist '("\\.cr$" . crystal-mode))
;; (add-to-list 'interpreter-mode-alist '("crystal" . crystal-mode))
;;
;; Still needs more docstrings; search below for TODO.
;;; Code:
(defgroup crystal nil
"Major mode for editing Crystal code."
:prefix "crystal-"
:group 'languages)
(defconst crystal-block-beg-keywords
'("class" "module" "def" "if" "unless" "case" "while" "until" "begin" "do"
"macro" "lib" "enum" "struct")
"Keywords at the beginning of blocks.")
(defconst crystal-block-beg-re
(regexp-opt crystal-block-beg-keywords)
"Regexp to match the beginning of blocks.")
(defconst crystal-non-block-do-re
(regexp-opt '("while" "until" "rescue") 'symbols)
"Regexp to match keywords that nest without blocks.")
(defconst crystal-indent-beg-re
(concat "^\\(\\s *" (regexp-opt '("class" "module" "def" "macro" "lib" "enum" "struct"))
"\\|"
(regexp-opt '("if" "unless" "case" "while" "until" "begin"))
"\\)\\_>")
"Regexp to match where the indentation gets deeper.")
(defconst crystal-modifier-beg-keywords
'("if" "unless" "while" "until")
"Modifiers that are the same as the beginning of blocks.")
(defconst crystal-modifier-beg-re
(regexp-opt crystal-modifier-beg-keywords)
"Regexp to match modifiers same as the beginning of blocks.")
(defconst crystal-modifier-re
(regexp-opt (cons "rescue" crystal-modifier-beg-keywords))
"Regexp to match modifiers.")
(defconst crystal-block-mid-keywords
'("else" "elsif" "when" "rescue" "ensure")
"Keywords where the indentation gets shallower in middle of block statements.")
(defconst crystal-block-mid-re
(regexp-opt crystal-block-mid-keywords)
"Regexp to match where the indentation gets shallower in middle of block statements.")
(defconst crystal-block-op-keywords
'("and" "or" "not")
"Regexp to match boolean keywords.")
(defconst crystal-block-hanging-re
(regexp-opt (append crystal-modifier-beg-keywords crystal-block-op-keywords))
"Regexp to match hanging block modifiers.")
(defconst crystal-block-end-re "\\_<end\\_>")
(defconst crystal-defun-beg-re
'"\\(def\\|class\\|module\\|macro\\|lib\\|struct\\|enum\\)"
"Regexp to match the beginning of a defun, in the general sense.")
(defconst crystal-attr-re
'"\\(@\\[\\)\\(.*\\)\\(\\]\\)"
"Regexp to match attributes preceding a method or type")
(defconst crystal-singleton-class-re
"class\\s *<<"
"Regexp to match the beginning of a singleton class context.")
(eval-and-compile
(defconst crystal-here-doc-beg-re
"\\(<\\)<\\(-\\)?\\(\\([a-zA-Z0-9_]+\\)\\|[\"]\\([^\"]+\\)[\"]\\|[']\\([^']+\\)[']\\)"
"Regexp to match the beginning of a heredoc.")
(defconst crystal-expression-expansion-re
"\\(?:[^\\]\\|\\=\\)\\(\\\\\\\\\\)*\\(#\\({[^}\n\\\\]*\\(\\\\.[^}\n\\\\]*\\)*}\\|\\(\\$\\|@\\|@@\\)\\(\\w\\|_\\)+\\|\\$[^a-zA-Z \n]\\)\\)"))
(defun crystal-here-doc-end-match ()
"Return a regexp to find the end of a heredoc.
This should only be called after matching against `crystal-here-doc-beg-re'."
(concat "^"
(if (match-string 2) "[ \t]*" nil)
(regexp-quote
(or (match-string 4)
(match-string 5)
(match-string 6)))))
(defconst crystal-delimiter
(concat "[?$/%(){}#\"'`.:]\\|<<\\|\\[\\|\\]\\|\\_<\\|\\<\\("
crystal-block-beg-re
"\\)\\_>\\|" crystal-block-end-re
"\\|^=begin\\|" crystal-here-doc-beg-re))
(defconst crystal-negative
(concat "^[ \t]*\\(\\(" crystal-block-mid-re "\\)\\>\\|"
crystal-block-end-re "\\|}\\|\\]\\)")
"Regexp to match where the indentation gets shallower.")
(defconst crystal-operator-re "[-,.+*/%&|^~=<>:]\\|\\\\$"
"Regexp to match operators.")
(defconst crystal-symbol-chars "a-zA-Z0-9_"
"List of characters that symbol names may contain.")
(defconst crystal-symbol-re (concat "[" crystal-symbol-chars "]")
"Regexp to match symbols.")
(defvar crystal-mode-map
(let ((map (make-sparse-keymap)))
(define-key map (kbd "M-C-p") 'crystal-beginning-of-block)
(define-key map (kbd "M-C-n") 'crystal-end-of-block)
(define-key map (kbd "C-c {") 'crystal-toggle-block)
(define-key map (kbd "C-c '") 'crystal-toggle-string-quotes)
map)
"Keymap used in Crystal mode.")
(easy-menu-define
crystal-mode-menu
crystal-mode-map
"Crystal Mode Menu"
'("Crystal"
["Beginning of Block" crystal-beginning-of-block t]
["End of Block" crystal-end-of-block t]
["Toggle Block" crystal-toggle-block t]
"--"
["Toggle String Quotes" crystal-toggle-string-quotes t]
"--"
["Backward Sexp" backward-sexp]
["Forward Sexp" forward-sexp]
["Indent Sexp" prog-indent-sexp]))
(defvar crystal-mode-syntax-table
(let ((table (make-syntax-table)))
(modify-syntax-entry ?\' "\"" table)
(modify-syntax-entry ?\" "\"" table)
(modify-syntax-entry ?\` "\"" table)
(modify-syntax-entry ?# "<" table)
(modify-syntax-entry ?\n ">" table)
(modify-syntax-entry ?\\ "\\" table)
(modify-syntax-entry ?$ "." table)
(modify-syntax-entry ?_ "_" table)
(modify-syntax-entry ?: "_" table)
(modify-syntax-entry ?< "." table)
(modify-syntax-entry ?> "." table)
(modify-syntax-entry ?& "." table)
(modify-syntax-entry ?| "." table)
(modify-syntax-entry ?% "." table)
(modify-syntax-entry ?= "." table)
(modify-syntax-entry ?/ "." table)
(modify-syntax-entry ?+ "." table)
(modify-syntax-entry ?* "." table)
(modify-syntax-entry ?- "." table)
(modify-syntax-entry ?\; "." table)
(modify-syntax-entry ?\( "()" table)
(modify-syntax-entry ?\) ")(" table)
(modify-syntax-entry ?\{ "(}" table)
(modify-syntax-entry ?\} "){" table)
(modify-syntax-entry ?\[ "(]" table)
(modify-syntax-entry ?\] ")[" table)
table)
"Syntax table to use in Crystal mode.")
(defconst crystal-indent-level 2
"Indentation of Crystal statements.")
(defconst crystal-alignable-keywords '(begin def class macro while until))
(defcustom crystal-align-chained-calls nil
"If non-nil, align chained method calls.
Each method call on a separate line will be aligned to the column
of its parent.
Only has effect when `crystal-use-smie' is t."
:type 'boolean
:group 'crystal
:safe 'booleanp
:version "24.4")
(defcustom crystal-deep-arglist t
"Deep indent lists in parenthesis when non-nil.
Also ignores spaces after parenthesis when `space'.
Only has effect when `crystal-use-smie' is nil."
:type 'boolean
:group 'crystal
:safe 'booleanp)
;; FIXME Woefully under documented. What is the point of the last `t'?.
(defcustom crystal-deep-indent-paren '(?\( ?\[ ?\] t)
"Deep indent lists in parenthesis when non-nil.
The value t means continuous line.
Also ignores spaces after parenthesis when `space'.
Only has effect when `crystal-use-smie' is nil."
:type '(choice (const nil)
character
(repeat (choice character
(cons character (choice (const nil)
(const t)))
(const t) ; why?
)))
:group 'crystal)
(defcustom crystal-deep-indent-paren-style 'space
"Default deep indent style.
Only has effect when `crystal-use-smie' is nil."
:type '(choice (const t) (const nil) (const space))
:group 'crystal)
;;; SMIE support
(require 'smie)
(defconst crystal-smie-grammar
(smie-prec2->grammar
(smie-merge-prec2s
(smie-bnf->prec2
'((id)
(insts (inst) (insts ";" insts))
(inst (exp) (inst "iuwu-mod" exp))
(exp (exp1) (exp "," exp) (exp "=" exp)
(id " @ " exp))
(exp1 (exp2) (exp2 "?" exp1 ":" exp1))
(exp2 (exp3) (exp3 "." exp2))
(exp3 ("def" insts "end")
("begin" insts-rescue-insts "end")
("do" insts "end")
("class" insts "end") ("module" insts "end") ("struct" insts "end")
("lib" insts "end") ("enum" insts "end")
("[" expseq "]")
("{" hashvals "}")
("{" insts "}")
("{{" exp "}}")
("{{" id "}}")
("while" insts "end")
("until" insts "end")
("unless" insts "end")
("if" if-body "end")
("->{" proc-body "}")
("macro" insts "end")
("{%" exp "%}")
("{%for%}" insts "{%end%}")
("{%if%}" if-macro-body "{%end%}")
("{%unless%}" insts "{%end%}")
("case" cases "end"))
;;(macro-cmd (inst) (forexp))
;;(macro-cmds (macro-cmd) (macro-cmds ";" macro-cmds))
;;(macro-start ("{%" macro-cmd "%}"))
;;(macro-block (macro-start macroinsts "{%end%}"))
;;(macro-code ("{%" macro-cmds "%}"))
;; FIXME this is wrong
;;(macro-inst (inst) (macro-block) (macro-code))
;;(macro-insts (macro-inst) (macro-insts ";" macro-insts))
;;(macro-body (macro-insts))
(macro-exp (for-head))
(formal-params ("opening-|" exp "closing-|"))
(for-head (exp "in" exp))
(proc-body (insts))
(cases (cases "when" cases) (insts "else" insts))
(expseq (exp) );;(expseq "," expseq)
(hashvals (id "=>" exp1) (hashvals "," hashvals))
(insts-rescue-insts (insts)
(insts-rescue-insts "rescue" insts-rescue-insts)
(insts-rescue-insts "ensure" insts-rescue-insts))
(ielsei (insts) (insts "else" insts))
(if-body (ielsei) (if-body "elsif" if-body))
(ielsei-macro (insts) (insts "{%else%}" insts))
(if-macro-body (ielsei-macro) (if-macro-body "{%elsif%}" if-macro-body))
)
'((nonassoc "in") (assoc ";") (right " @ ")
(assoc ",") (right "="))
'((assoc "when"))
'((assoc "elsif"))
'((assoc "{%elsif%}"))
'((assoc "rescue" "ensure"))
'((assoc ",")))
(smie-precs->prec2
'((right "=")
(right "+=" "-=" "*=" "/=" "%=" "**=" "&=" "|=" "^="
"<<=" ">>=" "&&=" "||=")
(left ".." "...")
(left "+" "-")
(left "*" "/" "%" "**")
(left "&&" "||")
(left "^" "&" "|")
(nonassoc "<=>")
(nonassoc ">" ">=" "<" "<=")
(nonassoc "==" "===" "!=")
(nonassoc "=~" "!~")
(left "<<" ">>")
(right "."))))))
(defun crystal-smie--eoms ()
(save-excursion
(forward-char -2)
(looking-at "%}")
)
)
(defun crystal-smie--bosp ()
(save-excursion (skip-chars-backward " \t")
(or (bolp) (memq (char-before) '(?\; ?=)))))
(defun crystal-smie--implicit-semi-p ()
(save-excursion
(skip-chars-backward " \t")
(not (or (bolp)
(memq (char-before) '(?\[ ?\())
(and (memq (char-before)
'(?\; ?- ?+ ?* ?/ ?: ?. ?, ?\\ ?& ?> ?< ?% ?~ ?^))
;; Not a binary operator symbol.
(not (eq (char-before (1- (point))) ?:))
;; Not the end of a regexp or a percent literal.
(not (memq (car (syntax-after (1- (point)))) '(7 15))))
(and (eq (char-before) ?\?)
(equal (save-excursion (crystal-smie--backward-token)) "?"))
(and (eq (char-before) ?=)
;; Not a symbol :==, :!=, or a foo= method.
(string-match "\\`\\s." (save-excursion
(crystal-smie--backward-token))))
(and (eq (char-before) ?|)
(member (save-excursion (crystal-smie--backward-token))
'("|" "||")))
(and (eq (car (syntax-after (1- (point)))) 2)
(member (save-excursion (crystal-smie--backward-token))
'("iuwu-mod" "and" "or")))
(save-excursion
(forward-comment 1)
(eq (char-after) ?.))))))
(defun crystal-smie--opening-pipe-p ()
(save-excursion
(if (eq ?| (char-before)) (forward-char -1))
(skip-chars-backward " \t\n")
(or (eq ?\{ (char-before))
(looking-back "\\_<do" (- (point) 2)))))
(defun crystal-smie--closing-pipe-p ()
(save-excursion
(if (eq ?| (char-before)) (forward-char -1))
(and (re-search-backward "|" (line-beginning-position) t)
(crystal-smie--opening-pipe-p))))
(defun crystal-smie--args-separator-p (pos)
(and
(< pos (line-end-position))
(or (eq (char-syntax (preceding-char)) '?w)
;; FIXME: Check that the preceding token is not a keyword.
;; This isn't very important most of the time, though.
(and (memq (preceding-char) '(?! ??))
(eq (char-syntax (char-before (1- (point)))) '?w)))
(save-excursion
(goto-char pos)
(or (and (eq (char-syntax (char-after)) ?w)
(not (looking-at (regexp-opt '("unless" "if" "while" "until"
"else" "elsif" "do" "end")
'symbols))))
(memq (car (syntax-after pos)) '(7 15))
(looking-at "[([]\\|[-+!~]\\sw\\|:\\(?:\\sw\\|\\s.\\)")))))
(defun crystal-smie--at-dot-call ()
(and (eq ?w (char-syntax (following-char)))
(eq (char-before) ?.)
(not (eq (char-before (1- (point))) ?.))))
(defun crystal-smie--end-of-macro ()
"Go to the end of the enclosing macro"
(re-search-forward "%}")
)
(defun crystal-smie--forward-token ()
(let ((pos (point)))
(skip-chars-forward " \t")
(cond
((looking-at "{%")
;; (message "at a macro stmt")
(forward-char 2)
(skip-chars-forward " \t")
(let ((tok (smie-default-forward-token)))
(if (member tok '("if" "else" "end" "elsif" "unless" "for"))
(concat "{%" tok "%}")
";"
)
)
;; (let ((tok (concat "{%" (smie-default-forward-token) "%}")))
;; (message "at %s %s" (point) (char-after))
;; (re-search-forward "%}")
;; (message "NOW at %s %s" (point) (char-after))
;; (cond (member tok tok)
;; (t ";"))
;; )
)
((and (looking-at "\n") (looking-at "\\s\"")) ;A heredoc.
;; Tokenize the whole heredoc as semicolon.
(goto-char (scan-sexps (point) 1))
";")
((and (looking-at "[\n#]")
(crystal-smie--implicit-semi-p)) ;Only add implicit ; when needed.
(if (eolp) (forward-char 1) (forward-comment 1))
";")
(t
(forward-comment (point-max))
(cond
((and (< pos (point))
(save-excursion
(crystal-smie--args-separator-p (prog1 (point) (goto-char pos)))))
" @ ")
((looking-at ":\\s.+")
(goto-char (match-end 0)) (match-string 0)) ;bug#15208.
((looking-at "\\s\"") "") ;A string.
(t
(let ((dot (crystal-smie--at-dot-call))
(tok (smie-default-forward-token)))
;; (message "default forward tok '%s'" tok)
(when dot
(setq tok (concat "." tok)))
(cond
((equal tok "abstract") ; abstract def doesn't open a block
(if (looking-at "\s+def")
(progn
(goto-char (match-end 0))
"adef")
tok))
((member tok '("unless" "if" "while" "until"))
(if (save-excursion (forward-word -1) (crystal-smie--bosp))
tok "iuwu-mod"))
((string-match-p "\\`|[*&]?\\'" tok)
(forward-char (- 1 (length tok)))
(setq tok "|")
(cond
((crystal-smie--opening-pipe-p) "opening-|")
((crystal-smie--closing-pipe-p) "closing-|")
(t tok)))
((and (equal tok "") (looking-at "\\\\\n"))
(goto-char (match-end 0)) (crystal-smie--forward-token))
(t
;; (message "forward '%s'" tok)
tok)))))))))
(defun crystal-smie--backward-token ()
(let ((pos (point)))
(forward-comment (- (point)))
(cond
;; FIXME why do these never fire?
;; treat macro expr similarly to heredocs? go backwards and tokenize
;; as the last token inside of the macro expr
;;((looking-at crystal-macro-cmd-re) "{%end%}")
;;((looking-at crystal-macro-end-cmd-re) (match-string 1))
((looking-back "%}")
;; (message "looking back at a macro cmd")
;; scan backawards to {%
(re-search-backward "{%")
;; (message "at %s %s" (point) (char-after))
(save-excursion
(forward-char 2)
(skip-chars-forward " \t")
;; fixme only if token is in if/else/for/end/while/unless
(let ((tok (smie-default-forward-token)))
(if (member tok '("if" "else" "end" "elsif" "unless" "for"))
(concat "{%" tok "%}")
";"))))
((and (> pos (line-end-position)) (crystal-smie--implicit-semi-p))
(skip-chars-forward " \t") ";")
((and (bolp) (not (bobp))) ;Presumably a heredoc.
;; Tokenize the whole heredoc as semicolon.
(goto-char (scan-sexps (point) -1))
;; (message "back to heredoc")
";")
((and (> pos (point)) (not (bolp))
(crystal-smie--args-separator-p pos))
;; We have "ID SPC ID", which is a method call, but it binds less tightly
;; than commas, since a method call can also be "ID ARG1, ARG2, ARG3".
;; In some textbooks, "e1 @ e2" is used to mean "call e1 with arg e2".
" @ ")
(t
(let ((tok (smie-default-backward-token))
(dot (crystal-smie--at-dot-call)))
;; (message "default backward tok is '%s'" tok)
(when dot
;; (message "back dot")
(setq tok (concat "." tok)))
(when (and (eq ?: (char-before)) (string-match "\\`\\s." tok))
;; (message "back :")
(forward-char -1) (setq tok (concat ":" tok))) ;; bug#15208.
(cond
((member tok '("unless" "if" "while" "until"))
;; (message "back if while")
(if (crystal-smie--bosp)
tok "iuwu-mod"))
((equal tok "|")
;; (message "back pipe")
(cond
((crystal-smie--opening-pipe-p) "opening-|")
((crystal-smie--closing-pipe-p) "closing-|")
(t tok)))
((string-match-p "\\`|[*&]\\'" tok)
;; (message "back backtick")
(forward-char 1)
(substring tok 1))
((and (equal tok "") (eq ?\\ (char-before)) (looking-at "\n"))
;; (message "back escaped")
(forward-char -1) (crystal-smie--backward-token))
((equal tok "def")
;; special case for abstract def which doesn't open a block
(if (looking-back "abstract\s+")
(progn (goto-char (match-beginning 0))
"adef")
tok))
(t
;; (message "backward '%s'" tok)
tok)))))))
(defun crystal-smie--indent-to-stmt ()
(save-excursion
(smie-backward-sexp ";")
(cons 'column (smie-indent-virtual))))
(defun crystal-smie--indent-to-stmt-p (keyword)
(memq (intern keyword) crystal-alignable-keywords))
(defun crystal-smie-rules (kind token)
;; (message "indent '%s' '%s'" kind token)
(pcase (cons kind token)
(`(:elem . basic) crystal-indent-level)
;; "foo" "bar" is the concatenation of the two strings, so the second
;; should be aligned with the first.
(`(:elem . args) (if (looking-at "\\s\"") 0))
;; (`(:after . ",") (smie-rule-separator kind))
(`(:before . ";")
;; (message "Before ;")
(cond
((smie-rule-parent-p "def" "begin" "do" "class" "module" "{%for%}"
"while" "until" "unless" "macro" "lib" "enum" "struct"
"if" "elsif" "else" "when" "{%if%}"
"{%elsif%}" "{%else%}" "{%unless%}"
"rescue" "ensure" "{")
;; (message "Still got this one %s" (smie-indent--parent))
(smie-rule-parent crystal-indent-level))
;; For (invalid) code between switch and case.
;; (if (smie-parent-p "switch") 4)
))
(`(:before . ,(or `"(" `"[" `"{"))
;; (message "Before ( [ {")
(cond
((and (equal token "{")
(not (smie-rule-prev-p "(" "{" "[" "," "=>" "=" "return" ";"))
(save-excursion
(forward-comment -1)
(not (eq (preceding-char) ?:))))
;; Curly block opener.
;; (message "curly block opener")
(crystal-smie--indent-to-stmt))
((smie-rule-hanging-p)
;; (message "hanging p")
;; Treat purely syntactic block-constructs as being part of their parent,
;; when the opening token is hanging and the parent is not an
;; open-paren.
(cond
((eq (car (smie-indent--parent)) t) nil)
;; When after `.', let's always de-indent,
;; because when `.' is inside the line, the
;; additional indentation from it looks out of place.
((smie-rule-parent-p ".")
(let (smie--parent)
(save-excursion
;; Traverse up the parents until the parent is "." at
;; indentation, or any other token.
(while (and (let ((parent (smie-indent--parent)))
(goto-char (cadr parent))
(save-excursion
(unless (integerp (car parent)) (forward-char -1))
(not (crystal-smie--bosp))))
(progn
(setq smie--parent nil)
(smie-rule-parent-p "."))))
(smie-rule-parent))))
(t (smie-rule-parent))))))
(`(:after . ,(or `"(" "[" "{"))
;; FIXME: Shouldn't this be the default behavior of
;; `smie-indent-after-keyword'?
;; (message "After ([{")
(save-excursion
(forward-char 1)
(skip-chars-forward " \t")
;; `smie-rule-hanging-p' is not good enough here,
;; because we want to reject hanging tokens at bol, too.
(unless (or (eolp) (forward-comment 1))
(cons 'column (current-column)))))
(`(:before . " @ ")
;; (message "Before @")
(save-excursion
(skip-chars-forward " \t")
(cons 'column (current-column))))
(`(:before . "do") (crystal-smie--indent-to-stmt))
(`(:before . ".")
(if (smie-rule-sibling-p)
(and crystal-align-chained-calls 0)
crystal-indent-level))
(`(:before . ,(or `"else" `"elsif" `"rescue" `"ensure" `"{%else%}" `"{%elsif%}"))
(smie-rule-parent))
(`(:before . "when")
;; Align to the previous `when', but look up the virtual
;; indentation of `case'.
(if (smie-rule-sibling-p) 0 (smie-rule-parent)))
(`(:after . ,(or "=" "iuwu-mod" "+" "-" "*" "/" "&&" "||" "%" "**" "^" "&"
"<=>" ">" "<" ">=" "<=" "==" "===" "!=" "<<" ">>"
"+=" "-=" "*=" "/=" "%=" "**=" "&=" "|=" "^=" "|"
"<<=" ">>=" "&&=" "||=" "and" "or"))
(and (smie-rule-parent-p ";" nil)
(smie-indent--hanging-p)
crystal-indent-level))
(`(:after . ,(or "?" ":")) crystal-indent-level)
(`(:before . ,(guard (memq (intern-soft token) crystal-alignable-keywords)))
(when (not (crystal--at-indentation-p))
(if (crystal-smie--indent-to-stmt-p token)
(crystal-smie--indent-to-stmt)
(cons 'column (current-column)))))
))
(defun crystal--at-indentation-p (&optional point)
(save-excursion
(unless point (setq point (point)))
(forward-line 0)
(skip-chars-forward " \t")
(eq (point) point)))
(defun crystal-imenu-create-index-in-block (prefix beg end)
"Create an imenu index of methods inside a block."
(let ((index-alist '()) (case-fold-search nil)
name next pos decl sing)
(goto-char beg)
(while (re-search-forward "^\\s *\\(\\(class\\s +\\|\\(class\\s *<<\\s *\\)\\|module\\s +\\)\\([^\(<\n ]+\\)\\|\\(def\\|alias\\)\\s +\\([^\(\n ]+\\)\\)" end t)
(setq sing (match-beginning 3))
(setq decl (match-string 5))
(setq next (match-end 0))
(setq name (or (match-string 4) (match-string 6)))
(setq pos (match-beginning 0))
(cond
((string= "alias" decl)
(if prefix (setq name (concat prefix name)))
(push (cons name pos) index-alist))
((string= "def" decl)
(if prefix
(setq name
(cond
((string-match "^self\." name)
(concat (substring prefix 0 -1) (substring name 4)))
(t (concat prefix name)))))
(push (cons name pos) index-alist)
(crystal-accurate-end-of-block end))
(t
(if (string= "self" name)
(if prefix (setq name (substring prefix 0 -1)))
(if prefix (setq name (concat (substring prefix 0 -1) "::" name)))
(push (cons name pos) index-alist))
(crystal-accurate-end-of-block end)
(setq beg (point))
(setq index-alist
(nconc (crystal-imenu-create-index-in-block
(concat name (if sing "." "#"))
next beg) index-alist))
(goto-char beg))))
index-alist))
(defun crystal-imenu-create-index ()
"Create an imenu index of all methods in the buffer."
(nreverse (crystal-imenu-create-index-in-block nil (point-min) nil)))
(defun crystal-accurate-end-of-block (&optional end)
"Jump to the end of the current block or END, whichever is closer."
(let (state
(end (or end (point-max))))
(save-restriction
(back-to-indentation)
(narrow-to-region (point) end)
(smie-forward-sexp))))
(defun crystal-mode-variables ()
"Set up initial buffer-local variables for Crystal mode."
(setq indent-tabs-mode nil)
(smie-setup crystal-smie-grammar #'crystal-smie-rules
:forward-token #'crystal-smie--forward-token
:backward-token #'crystal-smie--backward-token)
(setq-local comment-start "# ")
(setq-local comment-end "")
(setq-local comment-start-skip "#+ *")
(setq-local parse-sexp-ignore-comments t)
(setq-local parse-sexp-lookup-properties t)
(setq-local paragraph-start (concat "$\\|" page-delimiter))
(setq-local paragraph-separate paragraph-start)
(setq-local paragraph-ignore-fill-prefix t))
(defvar crystal--electric-indent-chars '(?. ?\) ?} ?\]))
(defun crystal--electric-indent-p (char)
(cond
((memq char crystal--electric-indent-chars)
;; Reindent after typing a char affecting indentation.
(crystal--at-indentation-p (1- (point))))
((memq (char-after) crystal--electric-indent-chars)
;; Reindent after inserting something in front of the above.
(crystal--at-indentation-p (1- (point))))
((or (and (>= char ?a) (<= char ?z)) (memq char '(?_ ?? ?! ?:)))
(let ((pt (point)))
(save-excursion
(skip-chars-backward "[:alpha:]:_?!")
(and (crystal--at-indentation-p)
(looking-at (regexp-opt (cons "end" crystal-block-mid-keywords)))
;; Outdent after typing a keyword.
(or (eq (match-end 0) pt)
;; Reindent if it wasn't a keyword after all.
(eq (match-end 0) (1- pt)))))))))
(defun crystal-special-char-p (&optional pos)
"Return t if the character before POS is a special character.
If omitted, POS defaults to the current point.
Special characters are `?', `$', `:' when preceded by whitespace,
and `\\' when preceded by `?'."
(setq pos (or pos (point)))
(let ((c (char-before pos)) (b (and (< (point-min) pos)
(char-before (1- pos)))))
(cond ((or (eq c ??) (eq c ?$)))
((and (eq c ?:) (or (not b) (eq (char-syntax b) ? ))))
((eq c ?\\) (eq b ??)))))
(defun crystal-singleton-class-p (&optional pos)
(save-excursion
(when pos (goto-char pos))
(forward-word -1)
(and (or (bolp) (not (eq (char-before (point)) ?_)))
(looking-at crystal-singleton-class-re))))
(defun crystal-expr-beg (&optional option)
"Check if point is possibly at the beginning of an expression.
OPTION specifies the type of the expression.
Can be one of `heredoc', `modifier', `expr-qstr', `expr-re'. `macro-cmd'"
(save-excursion
(store-match-data nil)
(let ((space (skip-chars-backward " \t"))
(start (point)))
(cond
((bolp) t)
((progn
(forward-char -1)
(and (looking-at "\\?")
(or (eq (char-syntax (char-before (point))) ?w)
(crystal-special-char-p))))
nil)
((looking-at crystal-operator-re))
((eq option 'heredoc)
(and (< space 0) (not (crystal-singleton-class-p start))))
((or (looking-at "[\\[({,;]")
(and (looking-at "[!?]")
(or (not (eq option 'modifier))
(bolp)
(save-excursion (forward-char -1) (looking-at "\\Sw$"))))
(and (looking-at crystal-symbol-re)
(skip-chars-backward crystal-symbol-chars)
(cond
((looking-at (regexp-opt
(append crystal-block-beg-keywords
crystal-block-op-keywords
crystal-block-mid-keywords)
'words))
(goto-char (match-end 0))
(not (looking-at "\\s_")))
((eq option 'expr-qstr)
(looking-at "[a-zA-Z][a-zA-z0-9_]* +%[^ \t}]"))
((eq option 'expr-re)
(looking-at "[a-zA-Z][a-zA-z0-9_]* +/[^ \t]"))
((eq option 'macro-cmd)
(looking-at "{%"))
((eq option 'macro-var)
(looking-at "{{"))
(t nil)))))))))
(defun crystal-forward-string (term &optional end no-error expand)
"Move forward across one balanced pair of string delimiters.
Skips escaped delimiters. If EXPAND is non-nil, also ignores
delimiters in interpolated strings.
TERM should be a string containing either a single, self-matching
delimiter (e.g. \"/\"), or a pair of matching delimiters with the
close delimiter first (e.g. \"][\").
When non-nil, search is bounded by position END.
Throws an error if a balanced match is not found, unless NO-ERROR
is non-nil, in which case nil will be returned.
This command assumes the character after point is an opening
delimiter."
(let ((n 1) (c (string-to-char term))
(re (concat "[^\\]\\(\\\\\\\\\\)*\\("
(if (string= term "^") ;[^] is not a valid regexp
"\\^"
(concat "[" term "]"))
(when expand "\\|\\(#{\\)")
"\\)")))
(while (and (re-search-forward re end no-error)
(if (match-beginning 3)
(crystal-forward-string "}{" end no-error nil)
(> (setq n (if (eq (char-before (point)) c)
(1- n) (1+ n))) 0)))
(forward-char -1))
(cond ((zerop n))
(no-error nil)
((error "Unterminated string")))))
(defun crystal-deep-indent-paren-p (c)
"TODO: document."
(cond ((listp crystal-deep-indent-paren)
(let ((deep (assoc c crystal-deep-indent-paren)))
(cond (deep
(or (cdr deep) crystal-deep-indent-paren-style))
((memq c crystal-deep-indent-paren)
crystal-deep-indent-paren-style))))
((eq c crystal-deep-indent-paren) crystal-deep-indent-paren-style)
((eq c ?\( ) crystal-deep-arglist)))
(defun crystal-parse-partial (&optional end in-string nest depth pcol indent)
"TODO: document throughout function body."
(or depth (setq depth 0))
(or indent (setq indent 0))
(when (re-search-forward crystal-delimiter end 'move)
(let ((pnt (point)) w re expand)
(goto-char (match-beginning 0))
(cond
((and (memq (char-before) '(?@ ?$)) (looking-at "\\sw"))
(goto-char pnt))
((looking-at "[\"`]") ;skip string
(cond
((and (not (eobp))
(crystal-forward-string (buffer-substring (point) (1+ (point)))
end t t))
nil)
(t
(setq in-string (point))
(goto-char end))))
((looking-at "'")
(cond
((and (not (eobp))
(re-search-forward "[^\\]\\(\\\\\\\\\\)*'" end t))
nil)
(t
(setq in-string (point))
(goto-char end))))
((looking-at "/=")
(goto-char pnt))
((looking-at "/")
(cond
((and (not (eobp)) (crystal-expr-beg 'expr-re))
(if (crystal-forward-string "/" end t t)
nil
(setq in-string (point))
(goto-char end)))
(t
(goto-char pnt))))
((looking-at "%")
(cond
((and (not (eobp))
(crystal-expr-beg 'expr-qstr)
(not (looking-at "%="))
(not (looking-at "%}"))
(looking-at "%[QqrxWw]?\\([^a-zA-Z0-9 \t\n{]\\)"))
(goto-char (match-beginning 1))
(setq expand (not (memq (char-before) '(?q ?w))))
(setq w (match-string 1))
(cond
((string= w "[") (setq re "]["))
((string= w "{") (setq re "}{"))
((string= w "(") (setq re ")("))
((string= w "<") (setq re "><"))
((and expand (string= w "\\"))
(setq w (concat "\\" w))))
(unless (cond (re (crystal-forward-string re end t expand))
(expand (crystal-forward-string w end t t))
(t (re-search-forward
(if (string= w "\\")
"\\\\[^\\]*\\\\"
(concat "[^\\]\\(\\\\\\\\\\)*" w))
end t)))
(setq in-string (point))
(goto-char end)))
(t
(goto-char pnt))))
((looking-at "\\?") ;skip ?char
(cond
((and (crystal-expr-beg)
(looking-at "?\\(\\\\C-\\|\\\\M-\\)*\\\\?."))
(goto-char (match-end 0)))
(t
(goto-char pnt))))
((looking-at "\\$") ;skip $char
(goto-char pnt)
(forward-char 1))
((looking-at "#") ;skip comment
(forward-line 1)
(goto-char (point))
)
((looking-at "[\\[{(]")
(let ((deep (crystal-deep-indent-paren-p (char-after))))
(if (and deep (or (not (eq (char-after) ?\{)) (crystal-expr-beg)))
(progn
(and (eq deep 'space) (looking-at ".\\s +[^# \t\n]")
(setq pnt (1- (match-end 0))))
(setq nest (cons (cons (char-after (point)) pnt) nest))
(setq pcol (cons (cons pnt depth) pcol))
(setq depth 0))
(setq nest (cons (cons (char-after (point)) pnt) nest))
(setq depth (1+ depth))))
(goto-char pnt)
)
((looking-at "[])}]")
(if (crystal-deep-indent-paren-p (matching-paren (char-after)))
(setq depth (cdr (car pcol)) pcol (cdr pcol))
(setq depth (1- depth)))
(setq nest (cdr nest))
(goto-char pnt))
((looking-at crystal-block-end-re)
(if (or (and (not (bolp))
(progn
(forward-char -1)
(setq w (char-after (point)))
(or (eq ?_ w)
(eq ?. w))))
(progn
(goto-char pnt)
(setq w (char-after (point)))
(or (eq ?_ w)
(eq ?! w)
(eq ?? w))))
nil
(setq nest (cdr nest))
(setq depth (1- depth)))
(goto-char pnt))
((looking-at "def\\s +[^(\n;]*")
(if (or (bolp)
(progn
(forward-char -1)
(not (eq ?_ (char-after (point))))))
(progn
(setq nest (cons (cons nil pnt) nest))