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