22de9a83f2b7a77c12b3d6f062bb8a6e2b4d4756
[bpt/emacs.git] / lisp / progmodes / ruby-mode.el
1 ;;; ruby-mode.el --- Major mode for editing Ruby files
2
3 ;; Copyright (C) 1994-2014 Free Software Foundation, Inc.
4
5 ;; Authors: Yukihiro Matsumoto
6 ;; Nobuyoshi Nakada
7 ;; URL: http://www.emacswiki.org/cgi-bin/wiki/RubyMode
8 ;; Created: Fri Feb 4 14:49:13 JST 1994
9 ;; Keywords: languages ruby
10 ;; Version: 1.2
11
12 ;; This file is part of GNU Emacs.
13
14 ;; GNU Emacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
18
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
23
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26
27 ;;; Commentary:
28
29 ;; Provides font-locking, indentation support, and navigation for Ruby code.
30 ;;
31 ;; If you're installing manually, you should add this to your .emacs
32 ;; file after putting it on your load path:
33 ;;
34 ;; (autoload 'ruby-mode "ruby-mode" "Major mode for ruby files" t)
35 ;; (add-to-list 'auto-mode-alist '("\\.rb$" . ruby-mode))
36 ;; (add-to-list 'interpreter-mode-alist '("ruby" . ruby-mode))
37 ;;
38 ;; Still needs more docstrings; search below for TODO.
39
40 ;;; Code:
41
42 (defgroup ruby nil
43 "Major mode for editing Ruby code."
44 :prefix "ruby-"
45 :group 'languages)
46
47 (defconst ruby-block-beg-keywords
48 '("class" "module" "def" "if" "unless" "case" "while" "until" "for" "begin" "do")
49 "Keywords at the beginning of blocks.")
50
51 (defconst ruby-block-beg-re
52 (regexp-opt ruby-block-beg-keywords)
53 "Regexp to match the beginning of blocks.")
54
55 (defconst ruby-non-block-do-re
56 (regexp-opt '("while" "until" "for" "rescue") 'symbols)
57 "Regexp to match keywords that nest without blocks.")
58
59 (defconst ruby-indent-beg-re
60 (concat "^\\(\\s *" (regexp-opt '("class" "module" "def")) "\\|"
61 (regexp-opt '("if" "unless" "case" "while" "until" "for" "begin"))
62 "\\)\\_>")
63 "Regexp to match where the indentation gets deeper.")
64
65 (defconst ruby-modifier-beg-keywords
66 '("if" "unless" "while" "until")
67 "Modifiers that are the same as the beginning of blocks.")
68
69 (defconst ruby-modifier-beg-re
70 (regexp-opt ruby-modifier-beg-keywords)
71 "Regexp to match modifiers same as the beginning of blocks.")
72
73 (defconst ruby-modifier-re
74 (regexp-opt (cons "rescue" ruby-modifier-beg-keywords))
75 "Regexp to match modifiers.")
76
77 (defconst ruby-block-mid-keywords
78 '("then" "else" "elsif" "when" "rescue" "ensure")
79 "Keywords where the indentation gets shallower in middle of block statements.")
80
81 (defconst ruby-block-mid-re
82 (regexp-opt ruby-block-mid-keywords)
83 "Regexp to match where the indentation gets shallower in middle of block statements.")
84
85 (defconst ruby-block-op-keywords
86 '("and" "or" "not")
87 "Regexp to match boolean keywords.")
88
89 (defconst ruby-block-hanging-re
90 (regexp-opt (append ruby-modifier-beg-keywords ruby-block-op-keywords))
91 "Regexp to match hanging block modifiers.")
92
93 (defconst ruby-block-end-re "\\_<end\\_>")
94
95 (defconst ruby-defun-beg-re
96 '"\\(def\\|class\\|module\\)"
97 "Regexp to match the beginning of a defun, in the general sense.")
98
99 (defconst ruby-singleton-class-re
100 "class\\s *<<"
101 "Regexp to match the beginning of a singleton class context.")
102
103 (eval-and-compile
104 (defconst ruby-here-doc-beg-re
105 "\\(<\\)<\\(-\\)?\\(\\([a-zA-Z0-9_]+\\)\\|[\"]\\([^\"]+\\)[\"]\\|[']\\([^']+\\)[']\\)"
106 "Regexp to match the beginning of a heredoc.")
107
108 (defconst ruby-expression-expansion-re
109 "\\(?:[^\\]\\|\\=\\)\\(\\\\\\\\\\)*\\(#\\({[^}\n\\\\]*\\(\\\\.[^}\n\\\\]*\\)*}\\|\\(\\$\\|@\\|@@\\)\\(\\w\\|_\\)+\\)\\)"))
110
111 (defun ruby-here-doc-end-match ()
112 "Return a regexp to find the end of a heredoc.
113
114 This should only be called after matching against `ruby-here-doc-beg-re'."
115 (concat "^"
116 (if (match-string 2) "[ \t]*" nil)
117 (regexp-quote
118 (or (match-string 4)
119 (match-string 5)
120 (match-string 6)))))
121
122 (defconst ruby-delimiter
123 (concat "[?$/%(){}#\"'`.:]\\|<<\\|\\[\\|\\]\\|\\_<\\("
124 ruby-block-beg-re
125 "\\)\\_>\\|" ruby-block-end-re
126 "\\|^=begin\\|" ruby-here-doc-beg-re))
127
128 (defconst ruby-negative
129 (concat "^[ \t]*\\(\\(" ruby-block-mid-re "\\)\\>\\|"
130 ruby-block-end-re "\\|}\\|\\]\\)")
131 "Regexp to match where the indentation gets shallower.")
132
133 (defconst ruby-operator-re "[-,.+*/%&|^~=<>:]\\|\\\\$"
134 "Regexp to match operators.")
135
136 (defconst ruby-symbol-chars "a-zA-Z0-9_"
137 "List of characters that symbol names may contain.")
138
139 (defconst ruby-symbol-re (concat "[" ruby-symbol-chars "]")
140 "Regexp to match symbols.")
141
142 (defvar ruby-use-smie t)
143
144 (defvar ruby-mode-map
145 (let ((map (make-sparse-keymap)))
146 (unless ruby-use-smie
147 (define-key map (kbd "M-C-b") 'ruby-backward-sexp)
148 (define-key map (kbd "M-C-f") 'ruby-forward-sexp)
149 (define-key map (kbd "M-C-q") 'ruby-indent-exp))
150 (when ruby-use-smie
151 (define-key map (kbd "M-C-d") 'smie-down-list))
152 (define-key map (kbd "M-C-p") 'ruby-beginning-of-block)
153 (define-key map (kbd "M-C-n") 'ruby-end-of-block)
154 (define-key map (kbd "C-c {") 'ruby-toggle-block)
155 map)
156 "Keymap used in Ruby mode.")
157
158 (easy-menu-define
159 ruby-mode-menu
160 ruby-mode-map
161 "Ruby Mode Menu"
162 '("Ruby"
163 ["Beginning of Block" ruby-beginning-of-block t]
164 ["End of Block" ruby-end-of-block t]
165 ["Toggle Block" ruby-toggle-block t]
166 "--"
167 ["Backward Sexp" ruby-backward-sexp
168 :visible (not ruby-use-smie)]
169 ["Backward Sexp" backward-sexp
170 :visible ruby-use-smie]
171 ["Forward Sexp" ruby-forward-sexp
172 :visible (not ruby-use-smie)]
173 ["Forward Sexp" forward-sexp
174 :visible ruby-use-smie]
175 ["Indent Sexp" ruby-indent-exp
176 :visible (not ruby-use-smie)]
177 ["Indent Sexp" prog-indent-sexp
178 :visible ruby-use-smie]))
179
180 (defvar ruby-mode-syntax-table
181 (let ((table (make-syntax-table)))
182 (modify-syntax-entry ?\' "\"" table)
183 (modify-syntax-entry ?\" "\"" table)
184 (modify-syntax-entry ?\` "\"" table)
185 (modify-syntax-entry ?# "<" table)
186 (modify-syntax-entry ?\n ">" table)
187 (modify-syntax-entry ?\\ "\\" table)
188 (modify-syntax-entry ?$ "." table)
189 (modify-syntax-entry ?_ "_" table)
190 (modify-syntax-entry ?: "_" table)
191 (modify-syntax-entry ?< "." table)
192 (modify-syntax-entry ?> "." table)
193 (modify-syntax-entry ?& "." table)
194 (modify-syntax-entry ?| "." table)
195 (modify-syntax-entry ?% "." table)
196 (modify-syntax-entry ?= "." table)
197 (modify-syntax-entry ?/ "." table)
198 (modify-syntax-entry ?+ "." table)
199 (modify-syntax-entry ?* "." table)
200 (modify-syntax-entry ?- "." table)
201 (modify-syntax-entry ?\; "." table)
202 (modify-syntax-entry ?\( "()" table)
203 (modify-syntax-entry ?\) ")(" table)
204 (modify-syntax-entry ?\{ "(}" table)
205 (modify-syntax-entry ?\} "){" table)
206 (modify-syntax-entry ?\[ "(]" table)
207 (modify-syntax-entry ?\] ")[" table)
208 table)
209 "Syntax table to use in Ruby mode.")
210
211 (defcustom ruby-indent-tabs-mode nil
212 "Indentation can insert tabs in Ruby mode if this is non-nil."
213 :type 'boolean
214 :group 'ruby
215 :safe 'booleanp)
216
217 (defcustom ruby-indent-level 2
218 "Indentation of Ruby statements."
219 :type 'integer
220 :group 'ruby
221 :safe 'integerp)
222
223 (defcustom ruby-comment-column (default-value 'comment-column)
224 "Indentation column of comments."
225 :type 'integer
226 :group 'ruby
227 :safe 'integerp)
228
229 (defconst ruby-alignable-keywords '(if while unless until begin case for def)
230 "Keywords that can be used in `ruby-align-to-stmt-keywords'.")
231
232 (defcustom ruby-align-to-stmt-keywords '(def)
233 "Keywords after which we align the expression body to statement.
234
235 When nil, an expression that begins with one these keywords is
236 indented to the column of the keyword. Example:
237
238 tee = if foo
239 bar
240 else
241 qux
242 end
243
244 If this value is t or contains a symbol with the name of given
245 keyword, the expression is indented to align to the beginning of
246 the statement:
247
248 tee = if foo
249 bar
250 else
251 qux
252 end
253
254 Only has effect when `ruby-use-smie' is t.
255 "
256 :type `(choice
257 (const :tag "None" nil)
258 (const :tag "All" t)
259 (repeat :tag "User defined"
260 (choice ,@(mapcar
261 (lambda (kw) (list 'const kw))
262 ruby-alignable-keywords))))
263 :group 'ruby
264 :safe 'listp
265 :version "24.4")
266
267 (defcustom ruby-align-chained-calls nil
268 "If non-nil, align chained method calls.
269
270 Each method call on a separate line will be aligned to the column
271 of its parent.
272
273 Only has effect when `ruby-use-smie' is t."
274 :type 'boolean
275 :group 'ruby
276 :safe 'booleanp
277 :version "24.4")
278
279 (defcustom ruby-deep-arglist t
280 "Deep indent lists in parenthesis when non-nil.
281 Also ignores spaces after parenthesis when `space'.
282 Only has effect when `ruby-use-smie' is nil."
283 :type 'boolean
284 :group 'ruby
285 :safe 'booleanp)
286
287 ;; FIXME Woefully under documented. What is the point of the last `t'?.
288 (defcustom ruby-deep-indent-paren '(?\( ?\[ ?\] t)
289 "Deep indent lists in parenthesis when non-nil.
290 The value t means continuous line.
291 Also ignores spaces after parenthesis when `space'.
292 Only has effect when `ruby-use-smie' is nil."
293 :type '(choice (const nil)
294 character
295 (repeat (choice character
296 (cons character (choice (const nil)
297 (const t)))
298 (const t) ; why?
299 )))
300 :group 'ruby)
301
302 (defcustom ruby-deep-indent-paren-style 'space
303 "Default deep indent style.
304 Only has effect when `ruby-use-smie' is nil."
305 :type '(choice (const t) (const nil) (const space))
306 :group 'ruby)
307
308 (defcustom ruby-encoding-map
309 '((us-ascii . nil) ;; Do not put coding: us-ascii
310 (shift-jis . cp932) ;; Emacs charset name of Shift_JIS
311 (shift_jis . cp932) ;; MIME charset name of Shift_JIS
312 (japanese-cp932 . cp932)) ;; Emacs charset name of CP932
313 "Alist to map encoding name from Emacs to Ruby.
314 Associating an encoding name with nil means it needs not be
315 explicitly declared in magic comment."
316 :type '(repeat (cons (symbol :tag "From") (symbol :tag "To")))
317 :group 'ruby)
318
319 (defcustom ruby-insert-encoding-magic-comment t
320 "Insert a magic Ruby encoding comment upon save if this is non-nil.
321 The encoding will be auto-detected. The format of the encoding comment
322 is customizable via `ruby-encoding-magic-comment-style'.
323
324 When set to `always-utf8' an utf-8 comment will always be added,
325 even if it's not required."
326 :type 'boolean :group 'ruby)
327
328 (defcustom ruby-encoding-magic-comment-style 'ruby
329 "The style of the magic encoding comment to use."
330 :type '(choice
331 (const :tag "Emacs Style" emacs)
332 (const :tag "Ruby Style" ruby)
333 (const :tag "Custom Style" custom))
334 :group 'ruby
335 :version "24.4")
336
337 (defcustom ruby-custom-encoding-magic-comment-template "# encoding: %s"
338 "A custom encoding comment template.
339 It is used when `ruby-encoding-magic-comment-style' is set to `custom'."
340 :type 'string
341 :group 'ruby
342 :version "24.4")
343
344 (defcustom ruby-use-encoding-map t
345 "Use `ruby-encoding-map' to set encoding magic comment if this is non-nil."
346 :type 'boolean :group 'ruby)
347
348 ;;; SMIE support
349
350 (require 'smie)
351
352 ;; Here's a simplified BNF grammar, for reference:
353 ;; http://www.cse.buffalo.edu/~regan/cse305/RubyBNF.pdf
354 (defconst ruby-smie-grammar
355 (smie-prec2->grammar
356 (smie-merge-prec2s
357 (smie-bnf->prec2
358 '((id)
359 (insts (inst) (insts ";" insts))
360 (inst (exp) (inst "iuwu-mod" exp)
361 ;; Somewhat incorrect (both can be used multiple times),
362 ;; but avoids lots of conflicts:
363 (exp "and" exp) (exp "or" exp))
364 (exp (exp1) (exp "," exp) (exp "=" exp)
365 (id " @ " exp))
366 (exp1 (exp2) (exp2 "?" exp1 ":" exp1))
367 (exp2 (exp3) (exp3 "." exp2))
368 (exp3 ("def" insts "end")
369 ("begin" insts-rescue-insts "end")
370 ("do" insts "end")
371 ("class" insts "end") ("module" insts "end")
372 ("for" for-body "end")
373 ("[" expseq "]")
374 ("{" hashvals "}")
375 ("{" insts "}")
376 ("while" insts "end")
377 ("until" insts "end")
378 ("unless" insts "end")
379 ("if" if-body "end")
380 ("case" cases "end"))
381 (formal-params ("opening-|" exp "closing-|"))
382 (for-body (for-head ";" insts))
383 (for-head (id "in" exp))
384 (cases (exp "then" insts)
385 (cases "when" cases) (insts "else" insts))
386 (expseq (exp) );;(expseq "," expseq)
387 (hashvals (id "=>" exp1) (hashvals "," hashvals))
388 (insts-rescue-insts (insts)
389 (insts-rescue-insts "rescue" insts-rescue-insts)
390 (insts-rescue-insts "ensure" insts-rescue-insts))
391 (itheni (insts) (exp "then" insts))
392 (ielsei (itheni) (itheni "else" insts))
393 (if-body (ielsei) (if-body "elsif" if-body)))
394 '((nonassoc "in") (assoc ";") (right " @ ")
395 (assoc ",") (right "="))
396 '((assoc "when"))
397 '((assoc "elsif"))
398 '((assoc "rescue" "ensure"))
399 '((assoc ",")))
400
401 (smie-precs->prec2
402 '((right "=")
403 (right "+=" "-=" "*=" "/=" "%=" "**=" "&=" "|=" "^="
404 "<<=" ">>=" "&&=" "||=")
405 (left ".." "...")
406 (left "+" "-")
407 (left "*" "/" "%" "**")
408 (left "&&" "||")
409 (left "^" "&" "|")
410 (nonassoc "<=>")
411 (nonassoc ">" ">=" "<" "<=")
412 (nonassoc "==" "===" "!=")
413 (nonassoc "=~" "!~")
414 (left "<<" ">>")
415 (right "."))))))
416
417 (defun ruby-smie--bosp ()
418 (save-excursion (skip-chars-backward " \t")
419 (or (bolp) (memq (char-before) '(?\; ?=)))))
420
421 (defun ruby-smie--implicit-semi-p ()
422 (save-excursion
423 (skip-chars-backward " \t")
424 (not (or (bolp)
425 (memq (char-before) '(?\[ ?\())
426 (and (memq (char-before)
427 '(?\; ?- ?+ ?* ?/ ?: ?. ?, ?\\ ?& ?> ?< ?% ?~ ?^))
428 ;; Not a binary operator symbol.
429 (not (eq (char-before (1- (point))) ?:))
430 ;; Not the end of a regexp or a percent literal.
431 (not (memq (car (syntax-after (1- (point)))) '(7 15))))
432 (and (eq (char-before) ?\?)
433 (equal (save-excursion (ruby-smie--backward-token)) "?"))
434 (and (eq (char-before) ?=)
435 ;; Not a symbol :==, :!=, or a foo= method.
436 (string-match "\\`\\s." (save-excursion
437 (ruby-smie--backward-token))))
438 (and (eq (char-before) ?|)
439 (member (save-excursion (ruby-smie--backward-token))
440 '("|" "||")))
441 (and (eq (car (syntax-after (1- (point)))) 2)
442 (member (save-excursion (ruby-smie--backward-token))
443 '("iuwu-mod" "and" "or")))
444 (save-excursion
445 (forward-comment 1)
446 (eq (char-after) ?.))))))
447
448 (defun ruby-smie--redundant-do-p (&optional skip)
449 (save-excursion
450 (if skip (backward-word 1))
451 (member (nth 2 (smie-backward-sexp ";")) '("while" "until" "for"))))
452
453 (defun ruby-smie--opening-pipe-p ()
454 (save-excursion
455 (if (eq ?| (char-before)) (forward-char -1))
456 (skip-chars-backward " \t\n")
457 (or (eq ?\{ (char-before))
458 (looking-back "\\_<do" (- (point) 2)))))
459
460 (defun ruby-smie--closing-pipe-p ()
461 (save-excursion
462 (if (eq ?| (char-before)) (forward-char -1))
463 (and (re-search-backward "|" (line-beginning-position) t)
464 (ruby-smie--opening-pipe-p))))
465
466 (defun ruby-smie--args-separator-p (pos)
467 (and
468 (< pos (line-end-position))
469 (or (eq (char-syntax (preceding-char)) '?w)
470 ;; FIXME: Check that the preceding token is not a keyword.
471 ;; This isn't very important most of the time, though.
472 (and (memq (preceding-char) '(?! ??))
473 (eq (char-syntax (char-before (1- (point)))) '?w)))
474 (save-excursion
475 (goto-char pos)
476 (or (and (eq (char-syntax (char-after)) ?w)
477 (not (looking-at (regexp-opt '("unless" "if" "while" "until" "or"
478 "else" "elsif" "do" "end" "and")
479 'symbols))))
480 (memq (car (syntax-after pos)) '(7 15))
481 (looking-at "[([]\\|[-+!~]\\sw\\|:\\(?:\\sw\\|\\s.\\)")))))
482
483 (defun ruby-smie--at-dot-call ()
484 (and (eq ?w (char-syntax (following-char)))
485 (eq (char-before) ?.)
486 (not (eq (char-before (1- (point))) ?.))))
487
488 (defun ruby-smie--forward-token ()
489 (let ((pos (point)))
490 (skip-chars-forward " \t")
491 (cond
492 ((and (looking-at "\n") (looking-at "\\s\"")) ;A heredoc.
493 ;; Tokenize the whole heredoc as semicolon.
494 (goto-char (scan-sexps (point) 1))
495 ";")
496 ((and (looking-at "[\n#]")
497 (ruby-smie--implicit-semi-p)) ;Only add implicit ; when needed.
498 (if (eolp) (forward-char 1) (forward-comment 1))
499 ";")
500 (t
501 (forward-comment (point-max))
502 (cond
503 ((and (< pos (point))
504 (save-excursion
505 (ruby-smie--args-separator-p (prog1 (point) (goto-char pos)))))
506 " @ ")
507 ((looking-at ":\\s.+")
508 (goto-char (match-end 0)) (match-string 0)) ;bug#15208.
509 ((looking-at "\\s\"") "") ;A string.
510 (t
511 (let ((dot (ruby-smie--at-dot-call))
512 (tok (smie-default-forward-token)))
513 (when dot
514 (setq tok (concat "." tok)))
515 (cond
516 ((member tok '("unless" "if" "while" "until"))
517 (if (save-excursion (forward-word -1) (ruby-smie--bosp))
518 tok "iuwu-mod"))
519 ((string-match-p "\\`|[*&]?\\'" tok)
520 (forward-char (- 1 (length tok)))
521 (setq tok "|")
522 (cond
523 ((ruby-smie--opening-pipe-p) "opening-|")
524 ((ruby-smie--closing-pipe-p) "closing-|")
525 (t tok)))
526 ((and (equal tok "") (looking-at "\\\\\n"))
527 (goto-char (match-end 0)) (ruby-smie--forward-token))
528 ((equal tok "do")
529 (cond
530 ((not (ruby-smie--redundant-do-p 'skip)) tok)
531 ((> (save-excursion (forward-comment (point-max)) (point))
532 (line-end-position))
533 (ruby-smie--forward-token)) ;Fully redundant.
534 (t ";")))
535 (t tok)))))))))
536
537 (defun ruby-smie--backward-token ()
538 (let ((pos (point)))
539 (forward-comment (- (point)))
540 (cond
541 ((and (> pos (line-end-position)) (ruby-smie--implicit-semi-p))
542 (skip-chars-forward " \t") ";")
543 ((and (bolp) (not (bobp))) ;Presumably a heredoc.
544 ;; Tokenize the whole heredoc as semicolon.
545 (goto-char (scan-sexps (point) -1))
546 ";")
547 ((and (> pos (point)) (not (bolp))
548 (ruby-smie--args-separator-p pos))
549 ;; We have "ID SPC ID", which is a method call, but it binds less tightly
550 ;; than commas, since a method call can also be "ID ARG1, ARG2, ARG3".
551 ;; In some textbooks, "e1 @ e2" is used to mean "call e1 with arg e2".
552 " @ ")
553 (t
554 (let ((tok (smie-default-backward-token))
555 (dot (ruby-smie--at-dot-call)))
556 (when dot
557 (setq tok (concat "." tok)))
558 (when (and (eq ?: (char-before)) (string-match "\\`\\s." tok))
559 (forward-char -1) (setq tok (concat ":" tok))) ;; bug#15208.
560 (cond
561 ((member tok '("unless" "if" "while" "until"))
562 (if (ruby-smie--bosp)
563 tok "iuwu-mod"))
564 ((equal tok "|")
565 (cond
566 ((ruby-smie--opening-pipe-p) "opening-|")
567 ((ruby-smie--closing-pipe-p) "closing-|")
568 (t tok)))
569 ((string-match-p "\\`|[*&]\\'" tok)
570 (forward-char 1)
571 (substring tok 1))
572 ((and (equal tok "") (eq ?\\ (char-before)) (looking-at "\n"))
573 (forward-char -1) (ruby-smie--backward-token))
574 ((equal tok "do")
575 (cond
576 ((not (ruby-smie--redundant-do-p)) tok)
577 ((> (save-excursion (forward-word 1)
578 (forward-comment (point-max)) (point))
579 (line-end-position))
580 (ruby-smie--backward-token)) ;Fully redundant.
581 (t ";")))
582 (t tok)))))))
583
584 (defun ruby-smie--indent-to-stmt ()
585 (save-excursion
586 (smie-backward-sexp ";")
587 (cons 'column (smie-indent-virtual))))
588
589 (defun ruby-smie--indent-to-stmt-p (keyword)
590 (or (eq t ruby-align-to-stmt-keywords)
591 (memq (intern keyword) ruby-align-to-stmt-keywords)))
592
593 (defun ruby-smie-rules (kind token)
594 (pcase (cons kind token)
595 (`(:elem . basic) ruby-indent-level)
596 ;; "foo" "bar" is the concatenation of the two strings, so the second
597 ;; should be aligned with the first.
598 (`(:elem . args) (if (looking-at "\\s\"") 0))
599 ;; (`(:after . ",") (smie-rule-separator kind))
600 (`(:before . ";")
601 (cond
602 ((smie-rule-parent-p "def" "begin" "do" "class" "module" "for"
603 "while" "until" "unless"
604 "if" "then" "elsif" "else" "when"
605 "rescue" "ensure" "{")
606 (smie-rule-parent ruby-indent-level))
607 ;; For (invalid) code between switch and case.
608 ;; (if (smie-parent-p "switch") 4)
609 ))
610 (`(:before . ,(or `"(" `"[" `"{"))
611 (cond
612 ((and (equal token "{")
613 (not (smie-rule-prev-p "(" "{" "[" "," "=>" "=" "return" ";"))
614 (save-excursion
615 (forward-comment -1)
616 (not (eq (preceding-char) ?:))))
617 ;; Curly block opener.
618 (ruby-smie--indent-to-stmt))
619 ((smie-rule-hanging-p)
620 ;; Treat purely syntactic block-constructs as being part of their parent,
621 ;; when the opening token is hanging and the parent is not an
622 ;; open-paren.
623 (cond
624 ((eq (car (smie-indent--parent)) t) nil)
625 ;; When after `.', let's always de-indent,
626 ;; because when `.' is inside the line, the
627 ;; additional indentation from it looks out of place.
628 ((smie-rule-parent-p ".")
629 (let (smie--parent)
630 (save-excursion
631 ;; Traverse up the parents until the parent is "." at
632 ;; indentation, or any other token.
633 (while (and (progn
634 (goto-char (1- (cadr (smie-indent--parent))))
635 (not (ruby-smie--bosp)))
636 (progn
637 (setq smie--parent nil)
638 (smie-rule-parent-p "."))))
639 (smie-rule-parent))))
640 (t (smie-rule-parent))))))
641 (`(:after . ,(or `"(" "[" "{"))
642 ;; FIXME: Shouldn't this be the default behavior of
643 ;; `smie-indent-after-keyword'?
644 (save-excursion
645 (forward-char 1)
646 (skip-chars-forward " \t")
647 ;; `smie-rule-hanging-p' is not good enough here,
648 ;; because we want to reject hanging tokens at bol, too.
649 (unless (or (eolp) (forward-comment 1))
650 (cons 'column (current-column)))))
651 (`(:before . "do") (ruby-smie--indent-to-stmt))
652 (`(:before . ".")
653 (if (smie-rule-sibling-p)
654 (and ruby-align-chained-calls 0)
655 ruby-indent-level))
656 (`(:after . "=>") ruby-indent-level)
657 (`(:before . ,(or `"else" `"then" `"elsif" `"rescue" `"ensure"))
658 (smie-rule-parent))
659 (`(:before . "when")
660 ;; Align to the previous `when', but look up the virtual
661 ;; indentation of `case'.
662 (if (smie-rule-sibling-p) 0 (smie-rule-parent)))
663 (`(:after . ,(or "=" "iuwu-mod" "+" "-" "*" "/" "&&" "||" "%" "**" "^" "&"
664 "<=>" ">" "<" ">=" "<=" "==" "===" "!=" "<<" ">>"
665 "+=" "-=" "*=" "/=" "%=" "**=" "&=" "|=" "^=" "|"
666 "<<=" ">>=" "&&=" "||=" "and" "or"))
667 (and (smie-rule-parent-p ";" nil)
668 (smie-indent--hanging-p)
669 ruby-indent-level))
670 (`(:after . ,(or "?" ":")) ruby-indent-level)
671 (`(:before . ,(guard (memq (intern-soft token) ruby-alignable-keywords)))
672 (when (not (ruby--at-indentation-p))
673 (if (ruby-smie--indent-to-stmt-p token)
674 (ruby-smie--indent-to-stmt)
675 (cons 'column (current-column)))))
676 ))
677
678 (defun ruby--at-indentation-p (&optional point)
679 (save-excursion
680 (unless point (setq point (point)))
681 (forward-line 0)
682 (skip-chars-forward " \t")
683 (eq (point) point)))
684
685 (defun ruby-imenu-create-index-in-block (prefix beg end)
686 "Create an imenu index of methods inside a block."
687 (let ((index-alist '()) (case-fold-search nil)
688 name next pos decl sing)
689 (goto-char beg)
690 (while (re-search-forward "^\\s *\\(\\(class\\s +\\|\\(class\\s *<<\\s *\\)\\|module\\s +\\)\\([^\(<\n ]+\\)\\|\\(def\\|alias\\)\\s +\\([^\(\n ]+\\)\\)" end t)
691 (setq sing (match-beginning 3))
692 (setq decl (match-string 5))
693 (setq next (match-end 0))
694 (setq name (or (match-string 4) (match-string 6)))
695 (setq pos (match-beginning 0))
696 (cond
697 ((string= "alias" decl)
698 (if prefix (setq name (concat prefix name)))
699 (push (cons name pos) index-alist))
700 ((string= "def" decl)
701 (if prefix
702 (setq name
703 (cond
704 ((string-match "^self\." name)
705 (concat (substring prefix 0 -1) (substring name 4)))
706 (t (concat prefix name)))))
707 (push (cons name pos) index-alist)
708 (ruby-accurate-end-of-block end))
709 (t
710 (if (string= "self" name)
711 (if prefix (setq name (substring prefix 0 -1)))
712 (if prefix (setq name (concat (substring prefix 0 -1) "::" name)))
713 (push (cons name pos) index-alist))
714 (ruby-accurate-end-of-block end)
715 (setq beg (point))
716 (setq index-alist
717 (nconc (ruby-imenu-create-index-in-block
718 (concat name (if sing "." "#"))
719 next beg) index-alist))
720 (goto-char beg))))
721 index-alist))
722
723 (defun ruby-imenu-create-index ()
724 "Create an imenu index of all methods in the buffer."
725 (nreverse (ruby-imenu-create-index-in-block nil (point-min) nil)))
726
727 (defun ruby-accurate-end-of-block (&optional end)
728 "Jump to the end of the current block or END, whichever is closer."
729 (let (state
730 (end (or end (point-max))))
731 (if ruby-use-smie
732 (save-restriction
733 (back-to-indentation)
734 (narrow-to-region (point) end)
735 (smie-forward-sexp))
736 (while (and (setq state (apply 'ruby-parse-partial end state))
737 (>= (nth 2 state) 0) (< (point) end))))))
738
739 (defun ruby-mode-variables ()
740 "Set up initial buffer-local variables for Ruby mode."
741 (setq indent-tabs-mode ruby-indent-tabs-mode)
742 (if ruby-use-smie
743 (smie-setup ruby-smie-grammar #'ruby-smie-rules
744 :forward-token #'ruby-smie--forward-token
745 :backward-token #'ruby-smie--backward-token)
746 (setq-local indent-line-function 'ruby-indent-line))
747 (setq-local require-final-newline t)
748 (setq-local comment-start "# ")
749 (setq-local comment-end "")
750 (setq-local comment-column ruby-comment-column)
751 (setq-local comment-start-skip "#+ *")
752 (setq-local parse-sexp-ignore-comments t)
753 (setq-local parse-sexp-lookup-properties t)
754 (setq-local paragraph-start (concat "$\\|" page-delimiter))
755 (setq-local paragraph-separate paragraph-start)
756 (setq-local paragraph-ignore-fill-prefix t))
757
758 (defun ruby--insert-coding-comment (encoding)
759 "Insert a magic coding comment for ENCODING.
760 The style of the comment is controlled by `ruby-encoding-magic-comment-style'."
761 (let ((encoding-magic-comment-template
762 (pcase ruby-encoding-magic-comment-style
763 (`ruby "# coding: %s")
764 (`emacs "# -*- coding: %s -*-")
765 (`custom
766 ruby-custom-encoding-magic-comment-template))))
767 (insert
768 (format encoding-magic-comment-template encoding)
769 "\n")))
770
771 (defun ruby--detect-encoding ()
772 (if (eq ruby-insert-encoding-magic-comment 'always-utf8)
773 "utf-8"
774 (let ((coding-system
775 (or save-buffer-coding-system
776 buffer-file-coding-system)))
777 (if coding-system
778 (setq coding-system
779 (or (coding-system-get coding-system 'mime-charset)
780 (coding-system-change-eol-conversion coding-system nil))))
781 (if coding-system
782 (symbol-name
783 (if ruby-use-encoding-map
784 (let ((elt (assq coding-system ruby-encoding-map)))
785 (if elt (cdr elt) coding-system))
786 coding-system))
787 "ascii-8bit"))))
788
789 (defun ruby--encoding-comment-required-p ()
790 (or (eq ruby-insert-encoding-magic-comment 'always-utf8)
791 (re-search-forward "[^\0-\177]" nil t)))
792
793 (defun ruby-mode-set-encoding ()
794 "Insert a magic comment header with the proper encoding if necessary."
795 (save-excursion
796 (widen)
797 (goto-char (point-min))
798 (when (ruby--encoding-comment-required-p)
799 (goto-char (point-min))
800 (let ((coding-system (ruby--detect-encoding)))
801 (when coding-system
802 (if (looking-at "^#!") (beginning-of-line 2))
803 (cond ((looking-at "\\s *#\\s *.*\\(en\\)?coding\\s *:\\s *\\([-a-z0-9_]*\\)")
804 ;; update existing encoding comment if necessary
805 (unless (string= (match-string 2) coding-system)
806 (goto-char (match-beginning 2))
807 (delete-region (point) (match-end 2))
808 (insert coding-system)))
809 ((looking-at "\\s *#.*coding\\s *[:=]"))
810 (t (when ruby-insert-encoding-magic-comment
811 (ruby--insert-coding-comment coding-system))))
812 (when (buffer-modified-p)
813 (basic-save-buffer-1)))))))
814
815 (defvar ruby--electric-indent-chars '(?. ?\) ?} ?\]))
816
817 (defun ruby--electric-indent-p (char)
818 (cond
819 ((memq char ruby--electric-indent-chars)
820 ;; Reindent after typing a char affecting indentation.
821 (ruby--at-indentation-p (1- (point))))
822 ((memq (char-after) ruby--electric-indent-chars)
823 ;; Reindent after inserting something in front of the above.
824 (ruby--at-indentation-p (1- (point))))
825 ((or (and (>= char ?a) (<= char ?z)) (memq char '(?_ ?? ?! ?:)))
826 (let ((pt (point)))
827 (save-excursion
828 (skip-chars-backward "[:alpha:]:_?!")
829 (and (ruby--at-indentation-p)
830 (looking-at (regexp-opt (cons "end" ruby-block-mid-keywords)))
831 ;; Outdent after typing a keyword.
832 (or (eq (match-end 0) pt)
833 ;; Reindent if it wasn't a keyword after all.
834 (eq (match-end 0) (1- pt)))))))))
835
836 ;; FIXME: Remove this? It's unused here, but some redefinitions of
837 ;; `ruby-calculate-indent' in user init files still call it.
838 (defun ruby-current-indentation ()
839 "Return the indentation level of current line."
840 (save-excursion
841 (beginning-of-line)
842 (back-to-indentation)
843 (current-column)))
844
845 (defun ruby-indent-line (&optional ignored)
846 "Correct the indentation of the current Ruby line."
847 (interactive)
848 (ruby-indent-to (ruby-calculate-indent)))
849
850 (defun ruby-indent-to (column)
851 "Indent the current line to COLUMN."
852 (when column
853 (let (shift top beg)
854 (and (< column 0) (error "Invalid nesting"))
855 (setq shift (current-column))
856 (beginning-of-line)
857 (setq beg (point))
858 (back-to-indentation)
859 (setq top (current-column))
860 (skip-chars-backward " \t")
861 (if (>= shift top) (setq shift (- shift top))
862 (setq shift 0))
863 (if (and (bolp)
864 (= column top))
865 (move-to-column (+ column shift))
866 (move-to-column top)
867 (delete-region beg (point))
868 (beginning-of-line)
869 (indent-to column)
870 (move-to-column (+ column shift))))))
871
872 (defun ruby-special-char-p (&optional pos)
873 "Return t if the character before POS is a special character.
874 If omitted, POS defaults to the current point.
875 Special characters are `?', `$', `:' when preceded by whitespace,
876 and `\\' when preceded by `?'."
877 (setq pos (or pos (point)))
878 (let ((c (char-before pos)) (b (and (< (point-min) pos)
879 (char-before (1- pos)))))
880 (cond ((or (eq c ??) (eq c ?$)))
881 ((and (eq c ?:) (or (not b) (eq (char-syntax b) ? ))))
882 ((eq c ?\\) (eq b ??)))))
883
884 (defun ruby-singleton-class-p (&optional pos)
885 (save-excursion
886 (when pos (goto-char pos))
887 (forward-word -1)
888 (and (or (bolp) (not (eq (char-before (point)) ?_)))
889 (looking-at ruby-singleton-class-re))))
890
891 (defun ruby-expr-beg (&optional option)
892 "Check if point is possibly at the beginning of an expression.
893 OPTION specifies the type of the expression.
894 Can be one of `heredoc', `modifier', `expr-qstr', `expr-re'."
895 (save-excursion
896 (store-match-data nil)
897 (let ((space (skip-chars-backward " \t"))
898 (start (point)))
899 (cond
900 ((bolp) t)
901 ((progn
902 (forward-char -1)
903 (and (looking-at "\\?")
904 (or (eq (char-syntax (char-before (point))) ?w)
905 (ruby-special-char-p))))
906 nil)
907 ((looking-at ruby-operator-re))
908 ((eq option 'heredoc)
909 (and (< space 0) (not (ruby-singleton-class-p start))))
910 ((or (looking-at "[\\[({,;]")
911 (and (looking-at "[!?]")
912 (or (not (eq option 'modifier))
913 (bolp)
914 (save-excursion (forward-char -1) (looking-at "\\Sw$"))))
915 (and (looking-at ruby-symbol-re)
916 (skip-chars-backward ruby-symbol-chars)
917 (cond
918 ((looking-at (regexp-opt
919 (append ruby-block-beg-keywords
920 ruby-block-op-keywords
921 ruby-block-mid-keywords)
922 'words))
923 (goto-char (match-end 0))
924 (not (looking-at "\\s_")))
925 ((eq option 'expr-qstr)
926 (looking-at "[a-zA-Z][a-zA-z0-9_]* +%[^ \t]"))
927 ((eq option 'expr-re)
928 (looking-at "[a-zA-Z][a-zA-z0-9_]* +/[^ \t]"))
929 (t nil)))))))))
930
931 (defun ruby-forward-string (term &optional end no-error expand)
932 "Move forward across one balanced pair of string delimiters.
933 Skips escaped delimiters. If EXPAND is non-nil, also ignores
934 delimiters in interpolated strings.
935
936 TERM should be a string containing either a single, self-matching
937 delimiter (e.g. \"/\"), or a pair of matching delimiters with the
938 close delimiter first (e.g. \"][\").
939
940 When non-nil, search is bounded by position END.
941
942 Throws an error if a balanced match is not found, unless NO-ERROR
943 is non-nil, in which case nil will be returned.
944
945 This command assumes the character after point is an opening
946 delimiter."
947 (let ((n 1) (c (string-to-char term))
948 (re (concat "[^\\]\\(\\\\\\\\\\)*\\("
949 (if (string= term "^") ;[^] is not a valid regexp
950 "\\^"
951 (concat "[" term "]"))
952 (when expand "\\|\\(#{\\)")
953 "\\)")))
954 (while (and (re-search-forward re end no-error)
955 (if (match-beginning 3)
956 (ruby-forward-string "}{" end no-error nil)
957 (> (setq n (if (eq (char-before (point)) c)
958 (1- n) (1+ n))) 0)))
959 (forward-char -1))
960 (cond ((zerop n))
961 (no-error nil)
962 ((error "Unterminated string")))))
963
964 (defun ruby-deep-indent-paren-p (c)
965 "TODO: document."
966 (cond ((listp ruby-deep-indent-paren)
967 (let ((deep (assoc c ruby-deep-indent-paren)))
968 (cond (deep
969 (or (cdr deep) ruby-deep-indent-paren-style))
970 ((memq c ruby-deep-indent-paren)
971 ruby-deep-indent-paren-style))))
972 ((eq c ruby-deep-indent-paren) ruby-deep-indent-paren-style)
973 ((eq c ?\( ) ruby-deep-arglist)))
974
975 (defun ruby-parse-partial (&optional end in-string nest depth pcol indent)
976 "TODO: document throughout function body."
977 (or depth (setq depth 0))
978 (or indent (setq indent 0))
979 (when (re-search-forward ruby-delimiter end 'move)
980 (let ((pnt (point)) w re expand)
981 (goto-char (match-beginning 0))
982 (cond
983 ((and (memq (char-before) '(?@ ?$)) (looking-at "\\sw"))
984 (goto-char pnt))
985 ((looking-at "[\"`]") ;skip string
986 (cond
987 ((and (not (eobp))
988 (ruby-forward-string (buffer-substring (point) (1+ (point)))
989 end t t))
990 nil)
991 (t
992 (setq in-string (point))
993 (goto-char end))))
994 ((looking-at "'")
995 (cond
996 ((and (not (eobp))
997 (re-search-forward "[^\\]\\(\\\\\\\\\\)*'" end t))
998 nil)
999 (t
1000 (setq in-string (point))
1001 (goto-char end))))
1002 ((looking-at "/=")
1003 (goto-char pnt))
1004 ((looking-at "/")
1005 (cond
1006 ((and (not (eobp)) (ruby-expr-beg 'expr-re))
1007 (if (ruby-forward-string "/" end t t)
1008 nil
1009 (setq in-string (point))
1010 (goto-char end)))
1011 (t
1012 (goto-char pnt))))
1013 ((looking-at "%")
1014 (cond
1015 ((and (not (eobp))
1016 (ruby-expr-beg 'expr-qstr)
1017 (not (looking-at "%="))
1018 (looking-at "%[QqrxWw]?\\([^a-zA-Z0-9 \t\n]\\)"))
1019 (goto-char (match-beginning 1))
1020 (setq expand (not (memq (char-before) '(?q ?w))))
1021 (setq w (match-string 1))
1022 (cond
1023 ((string= w "[") (setq re "]["))
1024 ((string= w "{") (setq re "}{"))
1025 ((string= w "(") (setq re ")("))
1026 ((string= w "<") (setq re "><"))
1027 ((and expand (string= w "\\"))
1028 (setq w (concat "\\" w))))
1029 (unless (cond (re (ruby-forward-string re end t expand))
1030 (expand (ruby-forward-string w end t t))
1031 (t (re-search-forward
1032 (if (string= w "\\")
1033 "\\\\[^\\]*\\\\"
1034 (concat "[^\\]\\(\\\\\\\\\\)*" w))
1035 end t)))
1036 (setq in-string (point))
1037 (goto-char end)))
1038 (t
1039 (goto-char pnt))))
1040 ((looking-at "\\?") ;skip ?char
1041 (cond
1042 ((and (ruby-expr-beg)
1043 (looking-at "?\\(\\\\C-\\|\\\\M-\\)*\\\\?."))
1044 (goto-char (match-end 0)))
1045 (t
1046 (goto-char pnt))))
1047 ((looking-at "\\$") ;skip $char
1048 (goto-char pnt)
1049 (forward-char 1))
1050 ((looking-at "#") ;skip comment
1051 (forward-line 1)
1052 (goto-char (point))
1053 )
1054 ((looking-at "[\\[{(]")
1055 (let ((deep (ruby-deep-indent-paren-p (char-after))))
1056 (if (and deep (or (not (eq (char-after) ?\{)) (ruby-expr-beg)))
1057 (progn
1058 (and (eq deep 'space) (looking-at ".\\s +[^# \t\n]")
1059 (setq pnt (1- (match-end 0))))
1060 (setq nest (cons (cons (char-after (point)) pnt) nest))
1061 (setq pcol (cons (cons pnt depth) pcol))
1062 (setq depth 0))
1063 (setq nest (cons (cons (char-after (point)) pnt) nest))
1064 (setq depth (1+ depth))))
1065 (goto-char pnt)
1066 )
1067 ((looking-at "[])}]")
1068 (if (ruby-deep-indent-paren-p (matching-paren (char-after)))
1069 (setq depth (cdr (car pcol)) pcol (cdr pcol))
1070 (setq depth (1- depth)))
1071 (setq nest (cdr nest))
1072 (goto-char pnt))
1073 ((looking-at ruby-block-end-re)
1074 (if (or (and (not (bolp))
1075 (progn
1076 (forward-char -1)
1077 (setq w (char-after (point)))
1078 (or (eq ?_ w)
1079 (eq ?. w))))
1080 (progn
1081 (goto-char pnt)
1082 (setq w (char-after (point)))
1083 (or (eq ?_ w)
1084 (eq ?! w)
1085 (eq ?? w))))
1086 nil
1087 (setq nest (cdr nest))
1088 (setq depth (1- depth)))
1089 (goto-char pnt))
1090 ((looking-at "def\\s +[^(\n;]*")
1091 (if (or (bolp)
1092 (progn
1093 (forward-char -1)
1094 (not (eq ?_ (char-after (point))))))
1095 (progn
1096 (setq nest (cons (cons nil pnt) nest))
1097 (setq depth (1+ depth))))
1098 (goto-char (match-end 0)))
1099 ((looking-at (concat "\\_<\\(" ruby-block-beg-re "\\)\\_>"))
1100 (and
1101 (save-match-data
1102 (or (not (looking-at "do\\_>"))
1103 (save-excursion
1104 (back-to-indentation)
1105 (not (looking-at ruby-non-block-do-re)))))
1106 (or (bolp)
1107 (progn
1108 (forward-char -1)
1109 (setq w (char-after (point)))
1110 (not (or (eq ?_ w)
1111 (eq ?. w)))))
1112 (goto-char pnt)
1113 (not (eq ?! (char-after (point))))
1114 (skip-chars-forward " \t")
1115 (goto-char (match-beginning 0))
1116 (or (not (looking-at ruby-modifier-re))
1117 (ruby-expr-beg 'modifier))
1118 (goto-char pnt)
1119 (setq nest (cons (cons nil pnt) nest))
1120 (setq depth (1+ depth)))
1121 (goto-char pnt))
1122 ((looking-at ":\\(['\"]\\)")
1123 (goto-char (match-beginning 1))
1124 (ruby-forward-string (match-string 1) end t))
1125 ((looking-at ":\\([-,.+*/%&|^~<>]=?\\|===?\\|<=>\\|![~=]?\\)")
1126 (goto-char (match-end 0)))
1127 ((looking-at ":\\([a-zA-Z_][a-zA-Z_0-9]*[!?=]?\\)?")
1128 (goto-char (match-end 0)))
1129 ((or (looking-at "\\.\\.\\.?")
1130 (looking-at "\\.[0-9]+")
1131 (looking-at "\\.[a-zA-Z_0-9]+")
1132 (looking-at "\\."))
1133 (goto-char (match-end 0)))
1134 ((looking-at "^=begin")
1135 (if (re-search-forward "^=end" end t)
1136 (forward-line 1)
1137 (setq in-string (match-end 0))
1138 (goto-char end)))
1139 ((looking-at "<<")
1140 (cond
1141 ((and (ruby-expr-beg 'heredoc)
1142 (looking-at "<<\\(-\\)?\\(\\([\"'`]\\)\\([^\n]+?\\)\\3\\|\\(?:\\sw\\|\\s_\\)+\\)"))
1143 (setq re (regexp-quote (or (match-string 4) (match-string 2))))
1144 (if (match-beginning 1) (setq re (concat "\\s *" re)))
1145 (let* ((id-end (goto-char (match-end 0)))
1146 (line-end-position (point-at-eol))
1147 (state (list in-string nest depth pcol indent)))
1148 ;; parse the rest of the line
1149 (while (and (> line-end-position (point))
1150 (setq state (apply 'ruby-parse-partial
1151 line-end-position state))))
1152 (setq in-string (car state)
1153 nest (nth 1 state)
1154 depth (nth 2 state)
1155 pcol (nth 3 state)
1156 indent (nth 4 state))
1157 ;; skip heredoc section
1158 (if (re-search-forward (concat "^" re "$") end 'move)
1159 (forward-line 1)
1160 (setq in-string id-end)
1161 (goto-char end))))
1162 (t
1163 (goto-char pnt))))
1164 ((looking-at "^__END__$")
1165 (goto-char pnt))
1166 ((and (looking-at ruby-here-doc-beg-re)
1167 (boundp 'ruby-indent-point))
1168 (if (re-search-forward (ruby-here-doc-end-match)
1169 ruby-indent-point t)
1170 (forward-line 1)
1171 (setq in-string (match-end 0))
1172 (goto-char ruby-indent-point)))
1173 (t
1174 (error (format "Bad string %s"
1175 (buffer-substring (point) pnt)
1176 ))))))
1177 (list in-string nest depth pcol))
1178
1179 (defun ruby-parse-region (start end)
1180 "TODO: document."
1181 (let (state)
1182 (save-excursion
1183 (if start
1184 (goto-char start)
1185 (ruby-beginning-of-indent))
1186 (save-restriction
1187 (narrow-to-region (point) end)
1188 (while (and (> end (point))
1189 (setq state (apply 'ruby-parse-partial end state))))))
1190 (list (nth 0 state) ; in-string
1191 (car (nth 1 state)) ; nest
1192 (nth 2 state) ; depth
1193 (car (car (nth 3 state))) ; pcol
1194 ;(car (nth 5 state)) ; indent
1195 )))
1196
1197 (defun ruby-indent-size (pos nest)
1198 "Return the indentation level in spaces NEST levels deeper than POS."
1199 (+ pos (* (or nest 1) ruby-indent-level)))
1200
1201 (defun ruby-calculate-indent (&optional parse-start)
1202 "Return the proper indentation level of the current line."
1203 ;; TODO: Document body
1204 (save-excursion
1205 (beginning-of-line)
1206 (let ((ruby-indent-point (point))
1207 (case-fold-search nil)
1208 state eol begin op-end
1209 (paren (progn (skip-syntax-forward " ")
1210 (and (char-after) (matching-paren (char-after)))))
1211 (indent 0))
1212 (if parse-start
1213 (goto-char parse-start)
1214 (ruby-beginning-of-indent)
1215 (setq parse-start (point)))
1216 (back-to-indentation)
1217 (setq indent (current-column))
1218 (setq state (ruby-parse-region parse-start ruby-indent-point))
1219 (cond
1220 ((nth 0 state) ; within string
1221 (setq indent nil)) ; do nothing
1222 ((car (nth 1 state)) ; in paren
1223 (goto-char (setq begin (cdr (nth 1 state))))
1224 (let ((deep (ruby-deep-indent-paren-p (car (nth 1 state)))))
1225 (if deep
1226 (cond ((and (eq deep t) (eq (car (nth 1 state)) paren))
1227 (skip-syntax-backward " ")
1228 (setq indent (1- (current-column))))
1229 ((let ((s (ruby-parse-region (point) ruby-indent-point)))
1230 (and (nth 2 s) (> (nth 2 s) 0)
1231 (or (goto-char (cdr (nth 1 s))) t)))
1232 (forward-word -1)
1233 (setq indent (ruby-indent-size (current-column)
1234 (nth 2 state))))
1235 (t
1236 (setq indent (current-column))
1237 (cond ((eq deep 'space))
1238 (paren (setq indent (1- indent)))
1239 (t (setq indent (ruby-indent-size (1- indent) 1))))))
1240 (if (nth 3 state) (goto-char (nth 3 state))
1241 (goto-char parse-start) (back-to-indentation))
1242 (setq indent (ruby-indent-size (current-column) (nth 2 state))))
1243 (and (eq (car (nth 1 state)) paren)
1244 (ruby-deep-indent-paren-p (matching-paren paren))
1245 (search-backward (char-to-string paren))
1246 (setq indent (current-column)))))
1247 ((and (nth 2 state) (> (nth 2 state) 0)) ; in nest
1248 (if (null (cdr (nth 1 state)))
1249 (error "Invalid nesting"))
1250 (goto-char (cdr (nth 1 state)))
1251 (forward-word -1) ; skip back a keyword
1252 (setq begin (point))
1253 (cond
1254 ((looking-at "do\\>[^_]") ; iter block is a special case
1255 (if (nth 3 state) (goto-char (nth 3 state))
1256 (goto-char parse-start) (back-to-indentation))
1257 (setq indent (ruby-indent-size (current-column) (nth 2 state))))
1258 (t
1259 (setq indent (+ (current-column) ruby-indent-level)))))
1260
1261 ((and (nth 2 state) (< (nth 2 state) 0)) ; in negative nest
1262 (setq indent (ruby-indent-size (current-column) (nth 2 state)))))
1263 (when indent
1264 (goto-char ruby-indent-point)
1265 (end-of-line)
1266 (setq eol (point))
1267 (beginning-of-line)
1268 (cond
1269 ((and (not (ruby-deep-indent-paren-p paren))
1270 (re-search-forward ruby-negative eol t))
1271 (and (not (eq ?_ (char-after (match-end 0))))
1272 (setq indent (- indent ruby-indent-level))))
1273 ((and
1274 (save-excursion
1275 (beginning-of-line)
1276 (not (bobp)))
1277 (or (ruby-deep-indent-paren-p t)
1278 (null (car (nth 1 state)))))
1279 ;; goto beginning of non-empty no-comment line
1280 (let (end done)
1281 (while (not done)
1282 (skip-chars-backward " \t\n")
1283 (setq end (point))
1284 (beginning-of-line)
1285 (if (re-search-forward "^\\s *#" end t)
1286 (beginning-of-line)
1287 (setq done t))))
1288 (end-of-line)
1289 ;; skip the comment at the end
1290 (skip-chars-backward " \t")
1291 (let (end (pos (point)))
1292 (beginning-of-line)
1293 (while (and (re-search-forward "#" pos t)
1294 (setq end (1- (point)))
1295 (or (ruby-special-char-p end)
1296 (and (setq state (ruby-parse-region
1297 parse-start end))
1298 (nth 0 state))))
1299 (setq end nil))
1300 (goto-char (or end pos))
1301 (skip-chars-backward " \t")
1302 (setq begin (if (and end (nth 0 state)) pos (cdr (nth 1 state))))
1303 (setq state (ruby-parse-region parse-start (point))))
1304 (or (bobp) (forward-char -1))
1305 (and
1306 (or (and (looking-at ruby-symbol-re)
1307 (skip-chars-backward ruby-symbol-chars)
1308 (looking-at (concat "\\<\\(" ruby-block-hanging-re
1309 "\\)\\>"))
1310 (not (eq (point) (nth 3 state)))
1311 (save-excursion
1312 (goto-char (match-end 0))
1313 (not (looking-at "[a-z_]"))))
1314 (and (looking-at ruby-operator-re)
1315 (not (ruby-special-char-p))
1316 (save-excursion
1317 (forward-char -1)
1318 (or (not (looking-at ruby-operator-re))
1319 (not (eq (char-before) ?:))))
1320 ;; Operator at the end of line.
1321 (let ((c (char-after (point))))
1322 (and
1323 ;; (or (null begin)
1324 ;; (save-excursion
1325 ;; (goto-char begin)
1326 ;; (skip-chars-forward " \t")
1327 ;; (not (or (eolp) (looking-at "#")
1328 ;; (and (eq (car (nth 1 state)) ?{)
1329 ;; (looking-at "|"))))))
1330 ;; Not a regexp or percent literal.
1331 (null (nth 0 (ruby-parse-region (or begin parse-start)
1332 (point))))
1333 (or (not (eq ?| (char-after (point))))
1334 (save-excursion
1335 (or (eolp) (forward-char -1))
1336 (cond
1337 ((search-backward "|" nil t)
1338 (skip-chars-backward " \t\n")
1339 (and (not (eolp))
1340 (progn
1341 (forward-char -1)
1342 (not (looking-at "{")))
1343 (progn
1344 (forward-word -1)
1345 (not (looking-at "do\\>[^_]")))))
1346 (t t))))
1347 (not (eq ?, c))
1348 (setq op-end t)))))
1349 (setq indent
1350 (cond
1351 ((and
1352 (null op-end)
1353 (not (looking-at (concat "\\<\\(" ruby-block-hanging-re
1354 "\\)\\>")))
1355 (eq (ruby-deep-indent-paren-p t) 'space)
1356 (not (bobp)))
1357 (widen)
1358 (goto-char (or begin parse-start))
1359 (skip-syntax-forward " ")
1360 (current-column))
1361 ((car (nth 1 state)) indent)
1362 (t
1363 (+ indent ruby-indent-level))))))))
1364 (goto-char ruby-indent-point)
1365 (beginning-of-line)
1366 (skip-syntax-forward " ")
1367 (if (looking-at "\\.[^.]")
1368 (+ indent ruby-indent-level)
1369 indent))))
1370
1371 (defun ruby-beginning-of-defun (&optional arg)
1372 "Move backward to the beginning of the current defun.
1373 With ARG, move backward multiple defuns. Negative ARG means
1374 move forward."
1375 (interactive "p")
1376 (let (case-fold-search)
1377 (and (re-search-backward (concat "^\\s *" ruby-defun-beg-re "\\_>")
1378 nil t (or arg 1))
1379 (beginning-of-line))))
1380
1381 (defun ruby-end-of-defun ()
1382 "Move point to the end of the current defun.
1383 The defun begins at or after the point. This function is called
1384 by `end-of-defun'."
1385 (interactive "p")
1386 (ruby-forward-sexp)
1387 (let (case-fold-search)
1388 (when (looking-back (concat "^\\s *" ruby-block-end-re))
1389 (forward-line 1))))
1390
1391 (defun ruby-beginning-of-indent ()
1392 "Backtrack to a line which can be used as a reference for
1393 calculating indentation on the lines after it."
1394 (while (and (re-search-backward ruby-indent-beg-re nil 'move)
1395 (if (ruby-in-ppss-context-p 'anything)
1396 t
1397 ;; We can stop, then.
1398 (beginning-of-line)))))
1399
1400 (defun ruby-move-to-block (n)
1401 "Move to the beginning (N < 0) or the end (N > 0) of the
1402 current block, a sibling block, or an outer block. Do that (abs N) times."
1403 (back-to-indentation)
1404 (let ((signum (if (> n 0) 1 -1))
1405 (backward (< n 0))
1406 (depth (or (nth 2 (ruby-parse-region (point) (line-end-position))) 0))
1407 case-fold-search
1408 down done)
1409 (when (looking-at ruby-block-mid-re)
1410 (setq depth (+ depth signum)))
1411 (when (< (* depth signum) 0)
1412 ;; Moving end -> end or beginning -> beginning.
1413 (setq depth 0))
1414 (dotimes (_ (abs n))
1415 (setq done nil)
1416 (setq down (save-excursion
1417 (back-to-indentation)
1418 ;; There is a block start or block end keyword on this
1419 ;; line, don't need to look for another block.
1420 (and (re-search-forward
1421 (if backward ruby-block-end-re
1422 (concat "\\_<\\(" ruby-block-beg-re "\\)\\_>"))
1423 (line-end-position) t)
1424 (not (nth 8 (syntax-ppss))))))
1425 (while (and (not done) (not (if backward (bobp) (eobp))))
1426 (forward-line signum)
1427 (cond
1428 ;; Skip empty and commented out lines.
1429 ((looking-at "^\\s *$"))
1430 ((looking-at "^\\s *#"))
1431 ;; Skip block comments;
1432 ((and (not backward) (looking-at "^=begin\\>"))
1433 (re-search-forward "^=end\\>"))
1434 ((and backward (looking-at "^=end\\>"))
1435 (re-search-backward "^=begin\\>"))
1436 ;; Jump over a multiline literal.
1437 ((ruby-in-ppss-context-p 'string)
1438 (goto-char (nth 8 (syntax-ppss)))
1439 (unless backward
1440 (forward-sexp)
1441 (when (bolp) (forward-char -1)))) ; After a heredoc.
1442 (t
1443 (let ((state (ruby-parse-region (point) (line-end-position))))
1444 (unless (car state) ; Line ends with unfinished string.
1445 (setq depth (+ (nth 2 state) depth))))
1446 (cond
1447 ;; Increased depth, we found a block.
1448 ((> (* signum depth) 0)
1449 (setq down t))
1450 ;; We're at the same depth as when we started, and we've
1451 ;; encountered a block before. Stop.
1452 ((and down (zerop depth))
1453 (setq done t))
1454 ;; Lower depth, means outer block, can stop now.
1455 ((< (* signum depth) 0)
1456 (setq done t)))))))
1457 (back-to-indentation)))
1458
1459 (defun ruby-beginning-of-block (&optional arg)
1460 "Move backward to the beginning of the current block.
1461 With ARG, move up multiple blocks."
1462 (interactive "p")
1463 (ruby-move-to-block (- (or arg 1))))
1464
1465 (defun ruby-end-of-block (&optional arg)
1466 "Move forward to the end of the current block.
1467 With ARG, move out of multiple blocks."
1468 (interactive "p")
1469 (ruby-move-to-block (or arg 1)))
1470
1471 (defun ruby-forward-sexp (&optional arg)
1472 "Move forward across one balanced expression (sexp).
1473 With ARG, do it many times. Negative ARG means move backward."
1474 ;; TODO: Document body
1475 (interactive "p")
1476 (cond
1477 (ruby-use-smie (forward-sexp arg))
1478 ((and (numberp arg) (< arg 0)) (ruby-backward-sexp (- arg)))
1479 (t
1480 (let ((i (or arg 1)))
1481 (condition-case nil
1482 (while (> i 0)
1483 (skip-syntax-forward " ")
1484 (if (looking-at ",\\s *") (goto-char (match-end 0)))
1485 (cond ((looking-at "\\?\\(\\\\[CM]-\\)*\\\\?\\S ")
1486 (goto-char (match-end 0)))
1487 ((progn
1488 (skip-chars-forward ",.:;|&^~=!?\\+\\-\\*")
1489 (looking-at "\\s("))
1490 (goto-char (scan-sexps (point) 1)))
1491 ((and (looking-at (concat "\\<\\(" ruby-block-beg-re
1492 "\\)\\>"))
1493 (not (eq (char-before (point)) ?.))
1494 (not (eq (char-before (point)) ?:)))
1495 (ruby-end-of-block)
1496 (forward-word 1))
1497 ((looking-at "\\(\\$\\|@@?\\)?\\sw")
1498 (while (progn
1499 (while (progn (forward-word 1) (looking-at "_")))
1500 (cond ((looking-at "::") (forward-char 2) t)
1501 ((> (skip-chars-forward ".") 0))
1502 ((looking-at "\\?\\|!\\(=[~=>]\\|[^~=]\\)")
1503 (forward-char 1) nil)))))
1504 ((let (state expr)
1505 (while
1506 (progn
1507 (setq expr (or expr (ruby-expr-beg)
1508 (looking-at "%\\sw?\\Sw\\|[\"'`/]")))
1509 (nth 1 (setq state (apply #'ruby-parse-partial
1510 nil state))))
1511 (setq expr t)
1512 (skip-chars-forward "<"))
1513 (not expr))))
1514 (setq i (1- i)))
1515 ((error) (forward-word 1)))
1516 i))))
1517
1518 (defun ruby-backward-sexp (&optional arg)
1519 "Move backward across one balanced expression (sexp).
1520 With ARG, do it many times. Negative ARG means move forward."
1521 ;; TODO: Document body
1522 (interactive "p")
1523 (cond
1524 (ruby-use-smie (backward-sexp arg))
1525 ((and (numberp arg) (< arg 0)) (ruby-forward-sexp (- arg)))
1526 (t
1527 (let ((i (or arg 1)))
1528 (condition-case nil
1529 (while (> i 0)
1530 (skip-chars-backward " \t\n,.:;|&^~=!?\\+\\-\\*")
1531 (forward-char -1)
1532 (cond ((looking-at "\\s)")
1533 (goto-char (scan-sexps (1+ (point)) -1))
1534 (pcase (char-before)
1535 (`?% (forward-char -1))
1536 ((or `?q `?Q `?w `?W `?r `?x)
1537 (if (eq (char-before (1- (point))) ?%)
1538 (forward-char -2))))
1539 nil)
1540 ((looking-at "\\s\"\\|\\\\\\S_")
1541 (let ((c (char-to-string (char-before (match-end 0)))))
1542 (while (and (search-backward c)
1543 (eq (logand (skip-chars-backward "\\") 1)
1544 1))))
1545 nil)
1546 ((looking-at "\\s.\\|\\s\\")
1547 (if (ruby-special-char-p) (forward-char -1)))
1548 ((looking-at "\\s(") nil)
1549 (t
1550 (forward-char 1)
1551 (while (progn (forward-word -1)
1552 (pcase (char-before)
1553 (`?_ t)
1554 (`?. (forward-char -1) t)
1555 ((or `?$ `?@)
1556 (forward-char -1)
1557 (and (eq (char-before) (char-after))
1558 (forward-char -1)))
1559 (`?:
1560 (forward-char -1)
1561 (eq (char-before) :)))))
1562 (if (looking-at ruby-block-end-re)
1563 (ruby-beginning-of-block))
1564 nil))
1565 (setq i (1- i)))
1566 ((error)))
1567 i))))
1568
1569 (defun ruby-indent-exp (&optional ignored)
1570 "Indent each line in the balanced expression following the point."
1571 (interactive "*P")
1572 (let ((here (point-marker)) start top column (nest t))
1573 (set-marker-insertion-type here t)
1574 (unwind-protect
1575 (progn
1576 (beginning-of-line)
1577 (setq start (point) top (current-indentation))
1578 (while (and (not (eobp))
1579 (progn
1580 (setq column (ruby-calculate-indent start))
1581 (cond ((> column top)
1582 (setq nest t))
1583 ((and (= column top) nest)
1584 (setq nest nil) t))))
1585 (ruby-indent-to column)
1586 (beginning-of-line 2)))
1587 (goto-char here)
1588 (set-marker here nil))))
1589
1590 (defun ruby-add-log-current-method ()
1591 "Return the current method name as a string.
1592 This string includes all namespaces.
1593
1594 For example:
1595
1596 #exit
1597 String#gsub
1598 Net::HTTP#active?
1599 File.open
1600
1601 See `add-log-current-defun-function'."
1602 (condition-case nil
1603 (save-excursion
1604 (let* ((indent 0) mname mlist
1605 (start (point))
1606 (make-definition-re
1607 (lambda (re)
1608 (concat "^[ \t]*" re "[ \t]+"
1609 "\\("
1610 ;; \\. and :: for class methods
1611 "\\([A-Za-z_]" ruby-symbol-re "*\\|\\.\\|::" "\\)"
1612 "+\\)")))
1613 (definition-re (funcall make-definition-re ruby-defun-beg-re))
1614 (module-re (funcall make-definition-re "\\(class\\|module\\)")))
1615 ;; Get the current method definition (or class/module).
1616 (when (re-search-backward definition-re nil t)
1617 (goto-char (match-beginning 1))
1618 (if (not (string-equal "def" (match-string 1)))
1619 (setq mlist (list (match-string 2)))
1620 ;; We're inside the method. For classes and modules,
1621 ;; this check is skipped for performance.
1622 (when (ruby-block-contains-point start)
1623 (setq mname (match-string 2))))
1624 (setq indent (current-column))
1625 (beginning-of-line))
1626 ;; Walk up the class/module nesting.
1627 (while (and (> indent 0)
1628 (re-search-backward module-re nil t))
1629 (goto-char (match-beginning 1))
1630 (when (< (current-column) indent)
1631 (setq mlist (cons (match-string 2) mlist))
1632 (setq indent (current-column))
1633 (beginning-of-line)))
1634 ;; Process the method name.
1635 (when mname
1636 (let ((mn (split-string mname "\\.\\|::")))
1637 (if (cdr mn)
1638 (progn
1639 (unless (string-equal "self" (car mn)) ; def self.foo
1640 ;; def C.foo
1641 (let ((ml (nreverse mlist)))
1642 ;; If the method name references one of the
1643 ;; containing modules, drop the more nested ones.
1644 (while ml
1645 (if (string-equal (car ml) (car mn))
1646 (setq mlist (nreverse (cdr ml)) ml nil))
1647 (or (setq ml (cdr ml)) (nreverse mlist))))
1648 (if mlist
1649 (setcdr (last mlist) (butlast mn))
1650 (setq mlist (butlast mn))))
1651 (setq mname (concat "." (car (last mn)))))
1652 ;; See if the method is in singleton class context.
1653 (let ((in-singleton-class
1654 (when (re-search-forward ruby-singleton-class-re start t)
1655 (goto-char (match-beginning 0))
1656 ;; FIXME: Optimize it out, too?
1657 ;; This can be slow in a large file, but
1658 ;; unlike class/module declaration
1659 ;; indentations, method definitions can be
1660 ;; intermixed with these, and may or may not
1661 ;; be additionally indented after visibility
1662 ;; keywords.
1663 (ruby-block-contains-point start))))
1664 (setq mname (concat
1665 (if in-singleton-class "." "#")
1666 mname))))))
1667 ;; Generate the string.
1668 (if (consp mlist)
1669 (setq mlist (mapconcat (function identity) mlist "::")))
1670 (if mname
1671 (if mlist (concat mlist mname) mname)
1672 mlist)))))
1673
1674 (defun ruby-block-contains-point (pt)
1675 (save-excursion
1676 (save-match-data
1677 (ruby-forward-sexp)
1678 (> (point) pt))))
1679
1680 (defun ruby-brace-to-do-end (orig end)
1681 (let (beg-marker end-marker)
1682 (goto-char end)
1683 (when (eq (char-before) ?\})
1684 (delete-char -1)
1685 (when (save-excursion
1686 (skip-chars-backward " \t")
1687 (not (bolp)))
1688 (insert "\n"))
1689 (insert "end")
1690 (setq end-marker (point-marker))
1691 (when (and (not (eobp)) (eq (char-syntax (char-after)) ?w))
1692 (insert " "))
1693 (goto-char orig)
1694 (delete-char 1)
1695 (when (eq (char-syntax (char-before)) ?w)
1696 (insert " "))
1697 (insert "do")
1698 (setq beg-marker (point-marker))
1699 (when (looking-at "\\(\\s \\)*|")
1700 (unless (match-beginning 1)
1701 (insert " "))
1702 (goto-char (1+ (match-end 0)))
1703 (search-forward "|"))
1704 (unless (looking-at "\\s *$")
1705 (insert "\n"))
1706 (indent-region beg-marker end-marker)
1707 (goto-char beg-marker)
1708 t)))
1709
1710 (defun ruby-do-end-to-brace (orig end)
1711 (let (beg-marker end-marker beg-pos end-pos)
1712 (goto-char (- end 3))
1713 (when (looking-at ruby-block-end-re)
1714 (delete-char 3)
1715 (setq end-marker (point-marker))
1716 (insert "}")
1717 (goto-char orig)
1718 (delete-char 2)
1719 ;; Maybe this should be customizable, let's see if anyone asks.
1720 (insert "{ ")
1721 (setq beg-marker (point-marker))
1722 (when (looking-at "\\s +|")
1723 (delete-char (- (match-end 0) (match-beginning 0) 1))
1724 (forward-char)
1725 (re-search-forward "|" (line-end-position) t))
1726 (save-excursion
1727 (skip-chars-forward " \t\n\r")
1728 (setq beg-pos (point))
1729 (goto-char end-marker)
1730 (skip-chars-backward " \t\n\r")
1731 (setq end-pos (point)))
1732 (when (or
1733 (< end-pos beg-pos)
1734 (and (= (line-number-at-pos beg-pos) (line-number-at-pos end-pos))
1735 (< (+ (current-column) (- end-pos beg-pos) 2) fill-column)))
1736 (just-one-space -1)
1737 (goto-char end-marker)
1738 (just-one-space -1))
1739 (goto-char beg-marker)
1740 t)))
1741
1742 (defun ruby-toggle-block ()
1743 "Toggle block type from do-end to braces or back.
1744 The block must begin on the current line or above it and end after the point.
1745 If the result is do-end block, it will always be multiline."
1746 (interactive)
1747 (let ((start (point)) beg end)
1748 (end-of-line)
1749 (unless
1750 (if (and (re-search-backward "\\(?:[^#]\\)\\({\\)\\|\\(\\_<do\\_>\\)")
1751 (progn
1752 (goto-char (or (match-beginning 1) (match-beginning 2)))
1753 (setq beg (point))
1754 (save-match-data (ruby-forward-sexp))
1755 (setq end (point))
1756 (> end start)))
1757 (if (match-beginning 1)
1758 (ruby-brace-to-do-end beg end)
1759 (ruby-do-end-to-brace beg end)))
1760 (goto-char start))))
1761
1762 (eval-and-compile
1763 (defconst ruby-percent-literal-beg-re
1764 "\\(%\\)[qQrswWxIi]?\\([[:punct:]]\\)"
1765 "Regexp to match the beginning of percent literal.")
1766
1767 (defconst ruby-syntax-methods-before-regexp
1768 '("gsub" "gsub!" "sub" "sub!" "scan" "split" "split!" "index" "match"
1769 "assert_match" "Given" "Then" "When")
1770 "Methods that can take regexp as the first argument.
1771 It will be properly highlighted even when the call omits parens.")
1772
1773 (defvar ruby-syntax-before-regexp-re
1774 (concat
1775 ;; Special tokens that can't be followed by a division operator.
1776 "\\(^\\|[[=(,~;<>]"
1777 ;; Distinguish ternary operator tokens.
1778 ;; FIXME: They don't really have to be separated with spaces.
1779 "\\|[?:] "
1780 ;; Control flow keywords and operators following bol or whitespace.
1781 "\\|\\(?:^\\|\\s \\)"
1782 (regexp-opt '("if" "elsif" "unless" "while" "until" "when" "and"
1783 "or" "not" "&&" "||"))
1784 ;; Method name from the list.
1785 "\\|\\_<"
1786 (regexp-opt ruby-syntax-methods-before-regexp)
1787 "\\)\\s *")
1788 "Regexp to match text that can be followed by a regular expression."))
1789
1790 (defun ruby-syntax-propertize-function (start end)
1791 "Syntactic keywords for Ruby mode. See `syntax-propertize-function'."
1792 (let (case-fold-search)
1793 (goto-char start)
1794 (remove-text-properties start end '(ruby-expansion-match-data))
1795 (ruby-syntax-propertize-heredoc end)
1796 (ruby-syntax-enclosing-percent-literal end)
1797 (funcall
1798 (syntax-propertize-rules
1799 ;; $' $" $` .... are variables.
1800 ;; ?' ?" ?` are character literals (one-char strings in 1.9+).
1801 ("\\([?$]\\)[#\"'`]"
1802 (1 (unless (save-excursion
1803 ;; Not within a string.
1804 (nth 3 (syntax-ppss (match-beginning 0))))
1805 (string-to-syntax "\\"))))
1806 ;; Part of symbol when at the end of a method name.
1807 ("[!?]"
1808 (0 (unless (save-excursion
1809 (or (nth 8 (syntax-ppss (match-beginning 0)))
1810 (let (parse-sexp-lookup-properties)
1811 (zerop (skip-syntax-backward "w_")))
1812 (memq (preceding-char) '(?@ ?$))))
1813 (string-to-syntax "_"))))
1814 ;; Regular expressions. Start with matching unescaped slash.
1815 ("\\(?:\\=\\|[^\\]\\)\\(?:\\\\\\\\\\)*\\(/\\)"
1816 (1 (let ((state (save-excursion (syntax-ppss (match-beginning 1)))))
1817 (when (or
1818 ;; Beginning of a regexp.
1819 (and (null (nth 8 state))
1820 (save-excursion
1821 (forward-char -1)
1822 (looking-back ruby-syntax-before-regexp-re
1823 (point-at-bol))))
1824 ;; End of regexp. We don't match the whole
1825 ;; regexp at once because it can have
1826 ;; string interpolation inside, or span
1827 ;; several lines.
1828 (eq ?/ (nth 3 state)))
1829 (string-to-syntax "\"/")))))
1830 ;; Expression expansions in strings. We're handling them
1831 ;; here, so that the regexp rule never matches inside them.
1832 (ruby-expression-expansion-re
1833 (0 (ignore (ruby-syntax-propertize-expansion))))
1834 ("^=en\\(d\\)\\_>" (1 "!"))
1835 ("^\\(=\\)begin\\_>" (1 "!"))
1836 ;; Handle here documents.
1837 ((concat ruby-here-doc-beg-re ".*\\(\n\\)")
1838 (7 (unless (or (nth 8 (save-excursion
1839 (syntax-ppss (match-beginning 0))))
1840 (ruby-singleton-class-p (match-beginning 0)))
1841 (put-text-property (match-beginning 7) (match-end 7)
1842 'syntax-table (string-to-syntax "\""))
1843 (ruby-syntax-propertize-heredoc end))))
1844 ;; Handle percent literals: %w(), %q{}, etc.
1845 ((concat "\\(?:^\\|[[ \t\n<+(,=]\\)" ruby-percent-literal-beg-re)
1846 (1 (prog1 "|" (ruby-syntax-propertize-percent-literal end)))))
1847 (point) end)))
1848
1849 (defun ruby-syntax-propertize-heredoc (limit)
1850 (let ((ppss (syntax-ppss))
1851 (res '()))
1852 (when (eq ?\n (nth 3 ppss))
1853 (save-excursion
1854 (goto-char (nth 8 ppss))
1855 (beginning-of-line)
1856 (while (re-search-forward ruby-here-doc-beg-re
1857 (line-end-position) t)
1858 (unless (ruby-singleton-class-p (match-beginning 0))
1859 (push (concat (ruby-here-doc-end-match) "\n") res))))
1860 (save-excursion
1861 ;; With multiple openers on the same line, we don't know in which
1862 ;; part `start' is, so we have to go back to the beginning.
1863 (when (cdr res)
1864 (goto-char (nth 8 ppss))
1865 (setq res (nreverse res)))
1866 (while (and res (re-search-forward (pop res) limit 'move))
1867 (if (null res)
1868 (put-text-property (1- (point)) (point)
1869 'syntax-table (string-to-syntax "\""))))
1870 ;; End up at bol following the heredoc openers.
1871 ;; Propertize expression expansions from this point forward.
1872 ))))
1873
1874 (defun ruby-syntax-enclosing-percent-literal (limit)
1875 (let ((state (syntax-ppss))
1876 (start (point)))
1877 ;; When already inside percent literal, re-propertize it.
1878 (when (eq t (nth 3 state))
1879 (goto-char (nth 8 state))
1880 (when (looking-at ruby-percent-literal-beg-re)
1881 (ruby-syntax-propertize-percent-literal limit))
1882 (when (< (point) start) (goto-char start)))))
1883
1884 (defun ruby-syntax-propertize-percent-literal (limit)
1885 (goto-char (match-beginning 2))
1886 ;; Not inside a simple string or comment.
1887 (when (eq t (nth 3 (syntax-ppss)))
1888 (let* ((op (char-after))
1889 (ops (char-to-string op))
1890 (cl (or (cdr (aref (syntax-table) op))
1891 (cdr (assoc op '((?< . ?>))))))
1892 parse-sexp-lookup-properties)
1893 (save-excursion
1894 (condition-case nil
1895 (progn
1896 (if cl ; Paired delimiters.
1897 ;; Delimiter pairs of the same kind can be nested
1898 ;; inside the literal, as long as they are balanced.
1899 ;; Create syntax table that ignores other characters.
1900 (with-syntax-table (make-char-table 'syntax-table nil)
1901 (modify-syntax-entry op (concat "(" (char-to-string cl)))
1902 (modify-syntax-entry cl (concat ")" ops))
1903 (modify-syntax-entry ?\\ "\\")
1904 (save-restriction
1905 (narrow-to-region (point) limit)
1906 (forward-list))) ; skip to the paired character
1907 ;; Single character delimiter.
1908 (re-search-forward (concat "[^\\]\\(?:\\\\\\\\\\)*"
1909 (regexp-quote ops)) limit nil))
1910 ;; Found the closing delimiter.
1911 (put-text-property (1- (point)) (point) 'syntax-table
1912 (string-to-syntax "|")))
1913 ;; Unclosed literal, do nothing.
1914 ((scan-error search-failed)))))))
1915
1916 (defun ruby-syntax-propertize-expansion ()
1917 ;; Save the match data to a text property, for font-locking later.
1918 ;; Set the syntax of all double quotes and backticks to punctuation.
1919 (let* ((beg (match-beginning 2))
1920 (end (match-end 2))
1921 (state (and beg (save-excursion (syntax-ppss beg)))))
1922 (when (ruby-syntax-expansion-allowed-p state)
1923 (put-text-property beg (1+ beg) 'ruby-expansion-match-data
1924 (match-data))
1925 (goto-char beg)
1926 (while (re-search-forward "[\"`]" end 'move)
1927 (put-text-property (match-beginning 0) (match-end 0)
1928 'syntax-table (string-to-syntax "."))))))
1929
1930 (defun ruby-syntax-expansion-allowed-p (parse-state)
1931 "Return non-nil if expression expansion is allowed."
1932 (let ((term (nth 3 parse-state)))
1933 (cond
1934 ((memq term '(?\" ?` ?\n ?/)))
1935 ((eq term t)
1936 (save-match-data
1937 (save-excursion
1938 (goto-char (nth 8 parse-state))
1939 (looking-at "%\\(?:[QWrxI]\\|\\W\\)")))))))
1940
1941 (defun ruby-syntax-propertize-expansions (start end)
1942 (save-excursion
1943 (goto-char start)
1944 (while (re-search-forward ruby-expression-expansion-re end 'move)
1945 (ruby-syntax-propertize-expansion))))
1946
1947 (defun ruby-in-ppss-context-p (context &optional ppss)
1948 (let ((ppss (or ppss (syntax-ppss (point)))))
1949 (if (cond
1950 ((eq context 'anything)
1951 (or (nth 3 ppss)
1952 (nth 4 ppss)))
1953 ((eq context 'string)
1954 (nth 3 ppss))
1955 ((eq context 'heredoc)
1956 (eq ?\n (nth 3 ppss)))
1957 ((eq context 'non-heredoc)
1958 (and (ruby-in-ppss-context-p 'anything)
1959 (not (ruby-in-ppss-context-p 'heredoc))))
1960 ((eq context 'comment)
1961 (nth 4 ppss))
1962 (t
1963 (error (concat
1964 "Internal error on `ruby-in-ppss-context-p': "
1965 "context name `" (symbol-name context) "' is unknown"))))
1966 t)))
1967
1968 (defvar ruby-font-lock-syntax-table
1969 (let ((tbl (copy-syntax-table ruby-mode-syntax-table)))
1970 (modify-syntax-entry ?_ "w" tbl)
1971 tbl)
1972 "The syntax table to use for fontifying Ruby mode buffers.
1973 See `font-lock-syntax-table'.")
1974
1975 (defconst ruby-font-lock-keyword-beg-re "\\(?:^\\|[^.@$]\\|\\.\\.\\)")
1976
1977 (defconst ruby-font-lock-keywords
1978 `(;; Functions.
1979 ("^\\s *def\\s +\\(?:[^( \t\n.]*\\.\\)?\\([^( \t\n]+\\)"
1980 1 font-lock-function-name-face)
1981 ;; Keywords.
1982 (,(concat
1983 ruby-font-lock-keyword-beg-re
1984 (regexp-opt
1985 '("alias"
1986 "and"
1987 "begin"
1988 "break"
1989 "case"
1990 "class"
1991 "def"
1992 "defined?"
1993 "do"
1994 "elsif"
1995 "else"
1996 "fail"
1997 "ensure"
1998 "for"
1999 "end"
2000 "if"
2001 "in"
2002 "module"
2003 "next"
2004 "not"
2005 "or"
2006 "redo"
2007 "rescue"
2008 "retry"
2009 "return"
2010 "then"
2011 "super"
2012 "unless"
2013 "undef"
2014 "until"
2015 "when"
2016 "while"
2017 "yield")
2018 'symbols))
2019 (1 font-lock-keyword-face))
2020 ;; Core methods that have required arguments.
2021 (,(concat
2022 ruby-font-lock-keyword-beg-re
2023 (regexp-opt
2024 '( ;; built-in methods on Kernel
2025 "at_exit"
2026 "autoload"
2027 "autoload?"
2028 "catch"
2029 "eval"
2030 "exec"
2031 "fork"
2032 "format"
2033 "lambda"
2034 "load"
2035 "loop"
2036 "open"
2037 "p"
2038 "print"
2039 "printf"
2040 "proc"
2041 "putc"
2042 "puts"
2043 "require"
2044 "require_relative"
2045 "spawn"
2046 "sprintf"
2047 "syscall"
2048 "system"
2049 "trap"
2050 "warn"
2051 ;; keyword-like private methods on Module
2052 "alias_method"
2053 "attr"
2054 "attr_accessor"
2055 "attr_reader"
2056 "attr_writer"
2057 "define_method"
2058 "extend"
2059 "include"
2060 "module_function"
2061 "prepend"
2062 "private"
2063 "protected"
2064 "public"
2065 "refine"
2066 "using")
2067 'symbols))
2068 (1 (unless (looking-at " *\\(?:[]|,.)}]\\|$\\)")
2069 font-lock-builtin-face)))
2070 ;; Kernel methods that have no required arguments.
2071 (,(concat
2072 ruby-font-lock-keyword-beg-re
2073 (regexp-opt
2074 '("__callee__"
2075 "__dir__"
2076 "__method__"
2077 "abort"
2078 "at_exit"
2079 "binding"
2080 "block_given?"
2081 "caller"
2082 "exit"
2083 "exit!"
2084 "fail"
2085 "raise"
2086 "rand"
2087 "readline"
2088 "readlines"
2089 "sleep"
2090 "srand"
2091 "throw")
2092 'symbols))
2093 (1 font-lock-builtin-face))
2094 ;; Here-doc beginnings.
2095 (,ruby-here-doc-beg-re
2096 (0 (unless (ruby-singleton-class-p (match-beginning 0))
2097 'font-lock-string-face)))
2098 ;; Perl-ish keywords.
2099 "\\_<\\(?:BEGIN\\|END\\)\\_>\\|^__END__$"
2100 ;; Variables.
2101 (,(concat ruby-font-lock-keyword-beg-re
2102 "\\_<\\(nil\\|self\\|true\\|false\\)\\_>")
2103 1 font-lock-variable-name-face)
2104 ;; Keywords that evaluate to certain values.
2105 ("\\_<__\\(?:LINE\\|ENCODING\\|FILE\\)__\\_>"
2106 (0 font-lock-variable-name-face))
2107 ;; Symbols.
2108 ("\\(^\\|[^:]\\)\\(:\\([-+~]@?\\|[/%&|^`]\\|\\*\\*?\\|<\\(<\\|=>?\\)?\\|>[>=]?\\|===?\\|=~\\|![~=]?\\|\\[\\]=?\\|@?\\(\\w\\|_\\)+\\([!?=]\\|\\b_*\\)\\|#{[^}\n\\\\]*\\(\\\\.[^}\n\\\\]*\\)*}\\)\\)"
2109 2 font-lock-constant-face)
2110 ;; Variables.
2111 ("\\(\\$\\([^a-zA-Z0-9 \n]\\|[0-9]\\)\\)\\W"
2112 1 font-lock-variable-name-face)
2113 ("\\(\\$\\|@\\|@@\\)\\(\\w\\|_\\)+"
2114 0 font-lock-variable-name-face)
2115 ;; Constants.
2116 ("\\(?:\\_<\\|::\\)\\([A-Z]+\\(\\w\\|_\\)*\\)"
2117 1 (unless (eq ?\( (char-after)) font-lock-type-face))
2118 ("\\(^\\s *\\|[\[\{\(,]\\s *\\|\\sw\\s +\\)\\(\\(\\sw\\|_\\)+\\):[^:]"
2119 (2 font-lock-constant-face))
2120 ;; Conversion methods on Kernel.
2121 (,(concat ruby-font-lock-keyword-beg-re
2122 (regexp-opt '("Array" "Complex" "Float" "Hash"
2123 "Integer" "Rational" "String") 'symbols))
2124 (1 font-lock-builtin-face))
2125 ;; Expression expansion.
2126 (ruby-match-expression-expansion
2127 2 font-lock-variable-name-face t)
2128 ;; Negation char.
2129 ("[^[:alnum:]_]\\(!\\)[^=]"
2130 1 font-lock-negation-char-face)
2131 ;; Character literals.
2132 ;; FIXME: Support longer escape sequences.
2133 ("\\_<\\?\\\\?\\S " 0 font-lock-string-face)
2134 )
2135 "Additional expressions to highlight in Ruby mode.")
2136
2137 (defun ruby-match-expression-expansion (limit)
2138 (let* ((prop 'ruby-expansion-match-data)
2139 (pos (next-single-char-property-change (point) prop nil limit))
2140 value)
2141 (when (and pos (> pos (point)))
2142 (goto-char pos)
2143 (or (and (setq value (get-text-property pos prop))
2144 (progn (set-match-data value) t))
2145 (ruby-match-expression-expansion limit)))))
2146
2147 ;;;###autoload
2148 (define-derived-mode ruby-mode prog-mode "Ruby"
2149 "Major mode for editing Ruby code.
2150
2151 \\{ruby-mode-map}"
2152 (ruby-mode-variables)
2153
2154 (setq-local imenu-create-index-function 'ruby-imenu-create-index)
2155 (setq-local add-log-current-defun-function 'ruby-add-log-current-method)
2156 (setq-local beginning-of-defun-function 'ruby-beginning-of-defun)
2157 (setq-local end-of-defun-function 'ruby-end-of-defun)
2158
2159 (add-hook 'after-save-hook 'ruby-mode-set-encoding nil 'local)
2160 (add-hook 'electric-indent-functions 'ruby--electric-indent-p nil 'local)
2161
2162 (setq-local font-lock-defaults '((ruby-font-lock-keywords) nil nil))
2163 (setq-local font-lock-keywords ruby-font-lock-keywords)
2164 (setq-local font-lock-syntax-table ruby-font-lock-syntax-table)
2165
2166 (setq-local syntax-propertize-function #'ruby-syntax-propertize-function))
2167
2168 ;;; Invoke ruby-mode when appropriate
2169
2170 ;;;###autoload
2171 (add-to-list 'auto-mode-alist
2172 (cons (purecopy (concat "\\(?:\\."
2173 "rb\\|ru\\|rake\\|thor"
2174 "\\|jbuilder\\|gemspec\\|podspec"
2175 "\\|/"
2176 "\\(?:Gem\\|Rake\\|Cap\\|Thor"
2177 "Vagrant\\|Guard\\|Pod\\)file"
2178 "\\)\\'")) 'ruby-mode))
2179
2180 ;;;###autoload
2181 (dolist (name (list "ruby" "rbx" "jruby" "ruby1.9" "ruby1.8"))
2182 (add-to-list 'interpreter-mode-alist (cons (purecopy name) 'ruby-mode)))
2183
2184 (provide 'ruby-mode)
2185
2186 ;;; ruby-mode.el ends here