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