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