-
Notifications
You must be signed in to change notification settings - Fork 19
/
crystal-mode.el
2803 lines (2587 loc) · 107 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-2016 Jason Pellerin
;; 2016-2018 crystal-lang-tools
;; Authors: Jason Pellerin
;; crystal-lang-tools
;; URL: https://github.com/crystal-lang-tools/emacs-crystal-mode
;; Created: Tue Jun 23 2015
;; Keywords: languages crystal
;; Version: 0.2.0
;; Package-Requires: ((emacs "24.4"))
;; Based on on ruby-mode.el
;; This file is not 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:
(require 'compile)
(require 'xref nil :noerror) ; xref is new in Emacs 25.1
(defgroup crystal nil
"Major mode for editing Crystal code."
:prefix "crystal-"
:group 'languages
:link '(url-link :tag "Github" "https://github.com/crystal-lang-tools/emacs-crystal-mode")
:link '(emacs-commentary-link :tag "Commentary" "crystal-mode"))
(defconst crystal-block-beg-keywords
'("class" "module" "def" "if" "unless" "case" "select" "while" "until" "for" "begin" "do"
"macro" "lib" "enum" "struct" "describe" "it" "union" "annotation")
"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" "union" "annotation"))
"\\|"
(regexp-opt '("if" "unless" "case" "select" "while" "until" "for" "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
'("then" "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-hanging-re
(regexp-opt crystal-modifier-beg-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\\|union\\|annotation\\)"
"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-use-smie t)
(defvar crystal-mode-map
(let ((map (make-sparse-keymap)))
(unless crystal-use-smie
(define-key map (kbd "M-C-b") 'crystal-backward-sexp)
(define-key map (kbd "M-C-f") 'crystal-forward-sexp)
(define-key map (kbd "M-C-q") 'crystal-indent-exp))
(when crystal-use-smie
(define-key map (kbd "M-C-d") 'smie-down-list))
(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)
(define-key map (kbd "C-c C-j") 'crystal-def-jump)
(define-key map (kbd "C-x 4 C-c C-j") 'crystal-def-jump-other-window)
map)
"Keymap used in Crystal mode.")
(defvar crystal-buffer-name "*crystal*")
(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" crystal-backward-sexp
:visible (not crystal-use-smie)]
["Backward Sexp" backward-sexp
:visible crystal-use-smie]
["Forward Sexp" crystal-forward-sexp
:visible (not crystal-use-smie)]
["Forward Sexp" forward-sexp
:visible crystal-use-smie]
["Indent Sexp" crystal-indent-exp
:visible (not crystal-use-smie)]
["Indent Sexp" prog-indent-sexp
:visible crystal-use-smie]
"--"
["Jump to Definition" crystal-def-jump t]
["Format" crystal-tool-format t]
("Tool"
["Expand macro" crystal-tool-expand t]
["Show context" crystal-tool-context t]
["Show imp" crystal-tool-imp t])
("Spec"
["Switch" crystal-spec-switch t]
["Call line" crystal-spec-line t]
["Call buffer" crystal-spec-buffer t]
["Call project" crystal-spec-all t])))
(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.")
(defcustom crystal-indent-tabs-mode nil
"Indentation can insert tabs in Crystal mode if this is non-nil."
:type 'boolean
:group 'crystal
:safe 'booleanp)
(defcustom crystal-indent-level 2
"Indentation of Crystal statements."
:type 'integer
:group 'crystal
:safe 'integerp)
(defcustom crystal-executable "crystal"
"Location of Crystal executable."
:type 'string
:group 'crystal)
(defcustom crystal-comment-column (default-value 'comment-column)
"Indentation column of comments."
:type 'integer
:group 'crystal
:safe 'integerp)
(defconst crystal-alignable-keywords '(if while unless until begin case select for def macro class struct)
"Keywords that can be used in `crystal-align-to-stmt-keywords'.")
(defcustom crystal-align-to-stmt-keywords '(def)
"Keywords after which we align the expression body to statement.
When nil, an expression that begins with one these keywords is
indented to the column of the keyword. Example:
tee = if foo
bar
else
qux
end
If this value is t or contains a symbol with the name of given
keyword, the expression is indented to align to the beginning of
the statement:
tee = if foo
bar
else
qux
end
Only has effect when `crystal-use-smie' is t.
"
:type `(choice
(const :tag "None" nil)
(const :tag "All" t)
(repeat :tag "User defined"
(choice ,@(mapcar
(lambda (kw) (list 'const kw))
crystal-alignable-keywords))))
:group 'crystal
:safe 'listp
:version "24.4")
(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)
(defcustom crystal-encoding-map
'((us-ascii . nil) ;; Do not put coding: us-ascii
(shift-jis . cp932) ;; Emacs charset name of Shift_JIS
(shift_jis . cp932) ;; MIME charset name of Shift_JIS
(japanese-cp932 . cp932)) ;; Emacs charset name of CP932
"Alist to map encoding name from Emacs to Crystal.
Associating an encoding name with nil means it needs not be
explicitly declared in magic comment."
:type '(repeat (cons (symbol :tag "From") (symbol :tag "To")))
:group 'crystal)
(defcustom crystal-insert-encoding-magic-comment nil
"Insert a magic Crystal encoding comment upon save if this is non-nil.
The encoding will be auto-detected. The format of the encoding comment
is customizable via `crystal-encoding-magic-comment-style'.
When set to `always-utf8' an utf-8 comment will always be added,
even if it's not required."
:type 'boolean :group 'crystal)
(defcustom crystal-encoding-magic-comment-style 'crystal
"The style of the magic encoding comment to use."
:type '(choice
(const :tag "Emacs Style" emacs)
(const :tag "Crystal Style" crystal)
(const :tag "Custom Style" custom))
:group 'crystal
:version "24.4")
(defcustom crystal-custom-encoding-magic-comment-template "# encoding: %s"
"A custom encoding comment template.
It is used when `crystal-encoding-magic-comment-style' is set to `custom'."
:type 'string
:group 'crystal
:version "24.4")
(defcustom crystal-use-encoding-map t
"Use `crystal-encoding-map' to set encoding magic comment if this is non-nil."
:type 'boolean :group 'crystal)
;;; SMIE support
(require 'smie)
(defmacro crystal-smie-debug (message &rest format-args)
`(progn
(when crystal-smie-verbose-p
(message (format ,message ,@format-args)))
nil))
;; Declare variable that we need from the smie package
(defvar smie--parent)
(defun crystal-smie-toggle-debug ()
"Toggle debug mode off and on for indentation."
(interactive)
(setq crystal-smie-verbose-p (not crystal-smie-verbose-p)))
(defvar crystal-smie-verbose-p nil
"Emit context information about the current syntax state.")
(defun crystal-smie-rules-verbose (kind token)
(let ((value (crystal-smie-rules kind token)))
(when crystal-smie-verbose-p
(message
"[verbose-crystal-smie-rules] [kind: %s] [token: %s] sibling-p:%s parent:%s hanging:%s == %s"
kind token
(ignore-errors (smie-rule-sibling-p))
(ignore-errors (if smie--parent
smie--parent
"nil"))
(ignore-errors (smie-rule-hanging-p))
value))
value))
(defcustom crystal-smie-grammar
(smie-prec2->grammar
(smie-merge-prec2s
(smie-bnf->prec2
'((id)
(stmts (g-stmt)
(g-stmt ";" stmts))
(g-stmt (b-stmt)
;; if unless while untile (suffix express)
(g-stmt "iuwu-mod" b-stmt))
(b-stmt (dot-stmt)
(b-stmt "," b-stmt)
(b-stmt "=" b-stmt)
(id " @ " b-stmt))
;;(t-stmt (dot-stmt) (dot-stmt "?" t-stmt ":" t-stmt))
(dot-stmt (stmt) (stmt "." dot-stmt))
(type (id)
(type "::" id))
(type-spec (":" type))
(stmt ("def" stmts-rescue-stmts "end")
("begin" stmts-rescue-stmts "end")
("do" stmts-rescue-stmts "end")
("module" stmts "end")
("class" stmts "end")
("annotation" stmts "end")
;; c-binding
("lib" stmts"end")
("struct" stmts "end")
("fun" id "(" stmts ")" type-spec)
("enum" stmts "end")
("union" stmts "end")
;; control exp
("if" if-body "end")
("unless" stmts "end")
("while" stmts "end")
("until" ielsei "end")
("case" cases "end")
("select" cases "end")
("->{" stmts "}")
;; macro
("macro" stmts "end")
("{%if%}" if-macro-body "{%end%}")
("{%unless%}" stmts "{%end%}")
("{%for%}" stmts "{%end%}")
("{%begin%}" stmts "{%end%}")
;; nested macro
("\{%if%}" if-nest-macro-body "\{%end%}")
("\{%unless%}" stmts "\{%end%}")
("\{%for%}" stmts "\{%end%}")
("\{%begin%}" stmts "\{%end%}")
;; array, hash...
("[" expseq "]")
("{{" b-stmt "}}")
("{{" id "}}")
("{" hashvals "}")
("{" stmts "}"))
(formal-params ("opening-|" b-stmt "closing-|"))
(stmts-rescue-stmts (stmts)
(stmts-rescue-stmts "rescue" stmts-rescue-stmts)
(stmts-rescue-stmts "ensure" stmts))
(expseq (b-stmt)) ;;(expseq "," expseq)
(hashvals (dot-stmt "=>" dot-stmt) (hashvals "," hashvals))
(ielsei (stmts) (stmts "else" stmts))
(if-body (ielsei) (if-body "elsif" if-body))
(cases (b-stmt "then" stmts)
(cases "when" cases)
(cases "in" cases)
(stmts "else" stmts))
(ielsei-macro (stmts) (stmts "{%else%}" stmts))
(if-macro-body (ielsei-macro) (if-macro-body "{%elsif%}" if-macro-body))
(ielsei-nest-macro (stmts) (stmts "\{%else%}" stmts))
(if-nest-macro-body (ielsei-nest-macro) (if-nest-macro-body "\{%elsif%}" if-nest-macro-body)))
'((assoc ";") (right " @ ") (assoc ",") (right "="))
'((assoc "when") (assoc "in"))
'((assoc "elsif"))
'((assoc "{%elsif%}"))
'((assoc "\{%elsif%}"))
'((assoc "rescue" "ensure"))
'((assoc ",")))
(smie-precs->prec2
'((right "=")
(right "+=" "-=" "*=" "/=" "%=" "**=" "&=" "|=" "^="
"<<=" ">>=" "&&=" "||=")
(left ".." "...")
(left "+" "-")
(left "*" "/" "%" "**")
(left "&&" "||")
(left "^" "&" "|")
(nonassoc "<=>")
(nonassoc ">" ">=" "<" "<=")
(nonassoc "==" "===" "!=")
(nonassoc "=~" "!~")
(left "<<" ">>")
(right ".")))))
"Grammar definition for Crystal.")
(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")
(let ((backward-tok (save-excursion (crystal-smie--backward-token)))
(semi-p
(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")))
(save-excursion
(forward-comment 1)
(eq (char-after) ?.))))))
(when (member backward-tok
'("{%if%}" "{%for%}" "{%elsif%}" "{%else%}" "{%unless%}" "{%begin%}"
"\{%if%}" "\{%for%}" "\{%elsif%}" "\{%else%}" "\{%unless%}" "\{%begin%}"
"{%end%}"))
(setq semi-p t))
semi-p)))
(defun crystal-smie--redundant-do-p (&optional skip)
(save-excursion
(if skip (backward-word 1))
(member (nth 2 (smie-backward-sexp ";")) '("while" "until" "for"))))
;; this handles "macro def ... end" blocks
(defun crystal-smie--redundant-macro-def-p (&optional skip)
(save-excursion
(if skip (backward-word 1))
(member (nth 2 (smie-backward-sexp ";")) '("macro"))))
(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--forward-token ()
(let ((pos (point)))
(skip-chars-forward " \t")
(cond
((looking-at "\\\\{%")
(forward-char 3)
(skip-chars-forward " \t")
(let ((tok (smie-default-forward-token)))
(if (member tok '("end" "else" "elsif"))
(concat "\{%" tok "%}")
";")))
((looking-at "{%")
(forward-char 2)
(skip-chars-forward " \t")
(let ((tok (smie-default-forward-token)))
(if (member tok '("end" "else" "elsif"))
(concat "{%" tok "%}")
";")))
((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)))
(when dot
(setq tok (concat "." tok)))
(when (and (equal tok "?")
(not (memq (preceding-char) '(?\s ?\t ?\n)))) ;bug#12
(setq tok ""))
(cond
((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))
((equal tok "def")
(let ((is-abstract (save-excursion
(backward-word 1)
(looking-at "abstract"))))
(cond
((equal is-abstract t) ";")
((not (crystal-smie--redundant-macro-def-p 'skip)) tok)
((> (save-excursion (forward-comment (point-max)) (point))
(line-end-position))
(crystal-smie--forward-token)) ;Fully redundant.
(t ";"))))
((equal tok "do")
(cond
((not (crystal-smie--redundant-do-p 'skip)) tok)
((> (save-excursion (forward-comment (point-max)) (point))
(line-end-position))
(crystal-smie--forward-token)) ;Fully redundant.
(t ";")))
(t
tok)))))))))
(defun crystal-smie--backward-token ()
(let ((pos (point)))
(forward-comment (- (point)))
(cond
((looking-back "%}" (line-beginning-position))
(let ((macro-prefix "{%")
(macro-suffix "%}"))
(when (re-search-backward "{%" nil t)
(when (eq ?\\ (char-before))
(setq macro-prefix "\{%"))
(save-excursion
(forward-char 2)
(skip-chars-forward " \t")
(let ((tok (smie-default-forward-token)))
(if (member tok '("if" "else" "elsif" "end"
"unless" "for" "while" "begin"))
(concat macro-prefix tok macro-suffix)
";"))))))
((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))
";")
((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)))
(when dot
(setq tok (concat "." tok)))
(when (and (equal tok "?")
(not (memq (preceding-char) '(?\s ?\t ?\n)))) ;; bug#12
(setq tok ""))
(when (and (eq ?: (char-before)) (string-match "\\`\\s." tok))
(forward-char -1) (setq tok (concat ":" tok))) ;; bug#15208.
(cond
((member tok '("unless" "if" "while" "until"))
(if (crystal-smie--bosp)
tok "iuwu-mod"))
((equal tok "|")
(cond
((crystal-smie--opening-pipe-p) "opening-|")
((crystal-smie--closing-pipe-p) "closing-|")
(t tok)))
((string-match-p "\\`|[*&]\\'" tok)
(forward-char 1)
(substring tok 1))
((and (equal tok "") (eq ?\\ (char-before)) (looking-at "\n"))
(forward-char -1) (crystal-smie--backward-token))
((equal tok "def")
(let ((is-abstract (save-excursion
(backward-word 1)
(looking-at "abstract"))))
(cond
((equal is-abstract t) ";")
((not (crystal-smie--redundant-macro-def-p)) tok)
((> (save-excursion (forward-word 1)
(forward-comment (point-max)) (point))
(line-end-position))
(crystal-smie--backward-token)) ;Fully redundant.
(t ";"))))
((equal tok "do")
(cond
((not (crystal-smie--redundant-do-p)) tok)
((> (save-excursion (forward-word 1)
(forward-comment (point-max)) (point))
(line-end-position))
(crystal-smie--backward-token)) ;Fully redundant.
(t ";")))
(t
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)
(or (eq t crystal-align-to-stmt-keywords)
(memq (intern keyword) crystal-align-to-stmt-keywords)))
(defun crystal-smie--current-line-with-visibility-p ()
(save-excursion
(beginning-of-line)
(looking-at "^[ \t]*\\(private\\|protected\\)?[ \t]*\\(macro\\|class\\|struct\\|annotation\\)")))
(defun crystal-smie--current-line-indentation ()
"Return the indentation of the current line."
(save-excursion
(current-indentation)))
(defun crystal-smie--previous-line-with-visibility-p ()
(save-excursion
(forward-line -1)
(beginning-of-line)
(looking-at "^[ \t]*\\(private\\|protected\\)?[ \t]*\\(macro\\|class\\|struct\\|annotation\\)")))
(defun crystal-smie--previous-line-indentation ()
"Return the indentation of the previous line."
(save-excursion
(forward-line -1)
(current-indentation)))
(defun crystal-smie--parent-indentation (parent-pos)
(save-excursion
(goto-char parent-pos)
(current-indentation)))
(defun crystal-smie-rules (kind token)
(pcase (cons kind token)
(`(:list-intro . ";") -2)
(`(:list-intro . nil) -2)
(`(: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 . ",")
;; (message "forward-token: %s, backward-token: %s"
;; (crystal-smie--forward-token)
;; (crystal-smie--backward-token))
;; (if (and (smie-rule-parent-p "(")
;; (smie-rule-hanging-p))
;; (crystal-smie--indent-to-stmt)
;; (smie-rule-separator kind)))
(`(:after . ,(or `"{%else%}" `"{%elsif%}" `"\{%else%}" `"\{%elsif%}"))
(smie-rule-parent crystal-indent-level))
(`(:before . ";")
(cond
((and smie--parent (smie-rule-parent-p "macro" "class" "struct"))
(cons 'column
(+ (crystal-smie--parent-indentation (nth 1 smie--parent))
crystal-indent-level)))
((smie-rule-parent-p "def" "begin" "do" "module" "lib" "enum" "union"
"while" "until" "unless" "if" "then" "elsif" "else" "when" "in"
"macro" "class" "struct" "annotation"
"{%if%}" "{%for%}" "{%elsif%}" "{%else%}" "{%unless%}" "{%begin%}"
"\{%if%}" "\{%for%}" "\{%elsif%}" "\{%else%}" "\{%unless%}" "\{%begin%}"
"rescue" "ensure" "{")
(smie-rule-parent crystal-indent-level))
))
(`(:before . "end")
(cond
((and smie--parent (smie-rule-parent-p "macro" "class" "struct"))
(cons 'column
(crystal-smie--parent-indentation (nth 1 smie--parent))))
))
(`(:before . ,(or `"(" `"[" `"{"))
(cond
((and (equal token "{")
(not (smie-rule-prev-p "(" "{" "[" "," "=>" "=" "return" ";"))
(save-excursion
(forward-comment -1)
(not (eq (preceding-char) ?:))))
;; Curly block opener.
(crystal-smie--indent-to-stmt))
((smie-rule-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'?
(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 . "@")
(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" `"then" `"elsif" `"rescue" `"ensure"
`"{%else%}" `"{%elsif%}" `"\{%else%}" `"\{%elsif%}"))
(smie-rule-parent))
(`(:before . ,(or `"when" `"in"))
;; Align to the previous `when', but look up the virtual
;; indentation of `case'.
(if (smie-rule-sibling-p) 0 (smie-rule-parent)))
(`(:after . ,(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)))))
(`(:before . "iuwu-mod")
(smie-rule-parent crystal-indent-level))))
(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."
;;(message "[crystal-imenu-create-index-in-block] prefix: %s, beg: %s, end: %s" prefix beg end)
(let ((index-alist '()) (case-fold-search nil)
name next pos decl sing)
(goto-char beg)
(while (re-search-forward "^\\s *\\(private\\|protected\\)?\\s *\\(\\(class\\s +\\|\\(class\\s *<<\\s *\\)\\|struct\\s +\\|\\(struct\\s *<<\\s *\\)\\|module\\s +\\|annotation\\s +\\)\\([^\(<\n ]+\\)\\|\\(def\\|alias\\)\\s +\\([^\(\n ]+\\)\\)" end t)
(setq sing (match-beginning 4))
(setq decl (match-string 7))
(setq next (match-end 0))
(setq name (or (match-string 6) (match-string 8)))
(setq pos (match-beginning 0))
;;(message "[crystal-imenu-create-index-in-block]sing: %s, decl: %s, name: %s, pos: %s, next: %s"
;; sing decl name pos next)
(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-smie--regexp-test ()
"Use for test imenu-create"
(interactive)
(goto-char (point-min))
(while (re-search-forward "^\\s *\\(private\\|protected\\)?\\s *\\(\\(class\\s +\\|\\(class\\s *<<\\s *\\)\\|struct\\s +\\|\\(struct\\s *<<\\s *\\)\\|module\\s +\\|annotation\\s +\\)\\([^\(<\n ]+\\)\\|\\(def\\|alias\\)\\s +\\([^\(\n ]+\\)\\)" nil t)
(message "match-string[1]: %s" (match-string 1))
(message "match-string[2]: %s" (match-string 2))
(message "match-string[3]: %s" (match-string 3))
(message "match-string[4]: %s" (match-string 4))
(message "match-string[5]: %s" (match-string 5))
(message "match-string[6]: %s" (match-string 6))
(message "match-string[7]: %s" (match-string 7))
(message "match-string[8]: %s" (match-string 8))))
(defun crystal-accurate-end-of-block (&optional end)