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