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