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