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