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