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