1 ;;; ruby-mode.el --- Major mode for editing Ruby files
3 ;; Copyright (C) 1994-2013 Free Software Foundation, Inc.
5 ;; Authors: Yukihiro Matsumoto
7 ;; URL: http://www.emacswiki.org/cgi-bin/wiki/RubyMode
8 ;; Created: Fri Feb 4 14:49:13 JST 1994
9 ;; Keywords: languages ruby
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/>.
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.
43 "Major mode for editing Ruby code."
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"))
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
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
101 "Regexp to match the beginning of a singleton class context.")
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'."
116 (if (match-string 2) "[ \t]*" nil
)
122 (defconst ruby-delimiter
123 (concat "[?$/%(){}#\"'`.:]\\|<<\\|\\[\\|\\]\\|\\_<\\("
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
))
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
)
156 "Keymap used in Ruby mode.")
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
]
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
)
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."
217 (defcustom ruby-indent-level
2
218 "Indentation of Ruby statements."
223 (defcustom ruby-comment-column
(default-value 'comment-column
)
224 "Indentation column of comments."
229 (defcustom ruby-deep-arglist t
230 "Deep indent lists in parenthesis when non-nil.
231 Also ignores spaces after parenthesis when 'space."
236 (defcustom ruby-deep-indent-paren
'(?\
( ?\
[ ?\
] t
)
237 "Deep indent lists in parenthesis when non-nil.
238 The value t means continuous line.
239 Also ignores spaces after parenthesis when 'space."
242 (defcustom ruby-deep-indent-paren-style
'space
243 "Default deep indent style."
244 :options
'(t nil space
) :group
'ruby
)
246 (defcustom ruby-encoding-map
247 '((us-ascii . nil
) ;; Do not put coding: us-ascii
248 (shift-jis . cp932
) ;; Emacs charset name of Shift_JIS
249 (shift_jis . cp932
) ;; MIME charset name of Shift_JIS
250 (japanese-cp932 . cp932
)) ;; Emacs charset name of CP932
251 "Alist to map encoding name from Emacs to Ruby.
252 Associating an encoding name with nil means it needs not be
253 explicitly declared in magic comment."
254 :type
'(repeat (cons (symbol :tag
"From") (symbol :tag
"To")))
257 (defcustom ruby-insert-encoding-magic-comment t
258 "Insert a magic Ruby encoding comment upon save if this is non-nil.
259 The encoding will be auto-detected. The format of the encoding comment
260 is customizable via `ruby-encoding-magic-comment-style'.
262 When set to `always-utf8' an utf-8 comment will always be added,
263 even if it's not required."
264 :type
'boolean
:group
'ruby
)
266 (defcustom ruby-encoding-magic-comment-style
'ruby
267 "The style of the magic encoding comment to use."
269 (const :tag
"Emacs Style" emacs
)
270 (const :tag
"Ruby Style" ruby
)
271 (const :tag
"Custom Style" custom
))
275 (defcustom ruby-custom-encoding-magic-comment-template
"# encoding: %s"
276 "A custom encoding comment template.
277 It is used when `ruby-encoding-magic-comment-style' is set to `custom'."
282 (defcustom ruby-use-encoding-map t
283 "Use `ruby-encoding-map' to set encoding magic comment if this is non-nil."
284 :type
'boolean
:group
'ruby
)
290 ;; Here's a simplified BNF grammar, for reference:
291 ;; http://www.cse.buffalo.edu/~regan/cse305/RubyBNF.pdf
292 (defconst ruby-smie-grammar
297 (insts (inst) (insts ";" insts
))
298 (inst (exp) (inst "iuwu-mod" exp
)
299 ;; Somewhat incorrect (both can be used multiple times),
300 ;; but avoids lots of conflicts:
301 (exp "and" exp
) (exp "or" exp
))
302 (exp (exp1) (exp "," exp
) (exp "=" exp
)
305 (exp1 (exp2) (exp2 "?" exp1
":" exp1
))
306 (exp2 ("def" insts
"end")
307 ("begin" insts-rescue-insts
"end")
309 ("class" insts
"end") ("module" insts
"end")
310 ("for" for-body
"end")
314 ("while" insts
"end")
315 ("until" insts
"end")
316 ("unless" insts
"end")
318 ("case" cases
"end"))
319 (formal-params ("opening-|" exp
"closing-|"))
320 (for-body (for-head ";" insts
))
321 (for-head (id "in" exp
))
322 (cases (exp "then" insts
)
323 (cases "when" cases
) (insts "else" insts
))
324 (expseq (exp) );;(expseq "," expseq)
325 (hashvals (id "=>" exp1
) (hashvals "," hashvals
))
326 (insts-rescue-insts (insts)
327 (insts-rescue-insts "rescue" insts-rescue-insts
)
328 (insts-rescue-insts "ensure" insts-rescue-insts
))
329 (itheni (insts) (exp "then" insts
))
330 (ielsei (itheni) (itheni "else" insts
))
331 (if-body (ielsei) (if-body "elsif" if-body
)))
332 '((nonassoc "in") (assoc ";") (right " @ ")
333 (assoc ",") (right "=") (assoc "."))
336 '((assoc "rescue" "ensure"))
341 (right "+=" "-=" "*=" "/=" "%=" "**=" "&=" "|=" "^="
342 "<<=" ">>=" "&&=" "||=")
345 (left "*" "/" "%" "**")
349 (nonassoc ">" ">=" "<" "<=")
350 (nonassoc "==" "===" "!=")
352 (left "<<" ">>"))))))
354 (defun ruby-smie--bosp ()
355 (save-excursion (skip-chars-backward " \t")
356 (or (bolp) (memq (char-before) '(?\
; ?=)))))
358 (defun ruby-smie--implicit-semi-p ()
360 (skip-chars-backward " \t")
362 (and (memq (char-before)
363 '(?\
; ?- ?+ ?* ?/ ?: ?. ?, ?\[ ?\( ?\{ ?\\ ?& ?> ?< ?%
365 ;; Not the end of a regexp or a percent literal.
366 (not (memq (car (syntax-after (1- (point)))) '(7 15))))
367 (and (eq (char-before) ?
\?)
368 (equal (save-excursion (ruby-smie--backward-token)) "?"))
369 (and (eq (char-before) ?
=)
370 (string-match "\\`\\s." (save-excursion
371 (ruby-smie--backward-token))))
372 (and (eq (char-before) ?|
)
373 (member (save-excursion (ruby-smie--backward-token))
375 (and (eq (car (syntax-after (1- (point)))) 2)
376 (member (save-excursion (ruby-smie--backward-token))
377 '("iuwu-mod" "and" "or")))
380 (eq (char-after) ?.
))))))
382 (defun ruby-smie--redundant-do-p (&optional skip
)
384 (if skip
(backward-word 1))
385 (member (nth 2 (smie-backward-sexp ";")) '("while" "until" "for"))))
387 (defun ruby-smie--opening-pipe-p ()
389 (if (eq ?|
(char-before)) (forward-char -
1))
390 (skip-chars-backward " \t\n")
391 (or (eq ?\
{ (char-before))
392 (looking-back "\\_<do" (- (point) 2)))))
394 (defun ruby-smie--closing-pipe-p ()
396 (if (eq ?|
(char-before)) (forward-char -
1))
397 (and (re-search-backward "|" (line-beginning-position) t
)
398 (ruby-smie--opening-pipe-p))))
400 (defun ruby-smie--args-separator-p (pos)
402 (< pos
(line-end-position))
403 (or (eq (char-syntax (preceding-char)) '?w
)
404 ;; FIXME: Check that the preceding token is not a keyword.
405 ;; This isn't very important most of the time, though.
406 (and (memq (preceding-char) '(?
! ??
))
407 (eq (char-syntax (char-before (1- (point)))) '?w
)))
410 (or (and (eq (char-syntax (char-after)) ?w
)
411 (not (looking-at (regexp-opt '("unless" "if" "while" "until" "or"
412 "else" "elsif" "do" "end" "and")
414 (memq (syntax-after pos
) '(7 15))
415 (looking-at "[([]\\|[-+!~:]\\sw")))))
417 (defun ruby-smie--at-dot-call ()
418 (and (eq ?w
(char-syntax (following-char)))
419 (eq (char-before) ?.
)
420 (not (eq (char-before (1- (point))) ?.
))))
422 (defun ruby-smie--forward-token ()
424 (skip-chars-forward " \t")
426 ((looking-at "\\s\"") ;A heredoc or a string.
427 (if (not (looking-at "\n"))
429 ;; Tokenize the whole heredoc as semicolon.
430 (goto-char (scan-sexps (point) 1))
432 ((and (looking-at "[\n#]")
433 (ruby-smie--implicit-semi-p)) ;Only add implicit ; when needed.
434 (if (eolp) (forward-char 1) (forward-comment 1))
437 (forward-comment (point-max))
439 ((looking-at ":\\s.+")
440 (goto-char (match-end 0)) (match-string 0)) ;; bug#15208.
441 ((and (< pos
(point))
443 (ruby-smie--args-separator-p (prog1 (point) (goto-char pos
)))))
446 (let ((dot (ruby-smie--at-dot-call))
447 (tok (smie-default-forward-token)))
449 (setq tok
(concat "." tok
)))
451 ((member tok
'("unless" "if" "while" "until"))
452 (if (save-excursion (forward-word -
1) (ruby-smie--bosp))
454 ((string-match-p "\\`|[*&]?\\'" tok
)
455 (forward-char (- 1 (length tok
)))
458 ((ruby-smie--opening-pipe-p) "opening-|")
459 ((ruby-smie--closing-pipe-p) "closing-|")
461 ((and (equal tok
"") (looking-at "\\\\\n"))
462 (goto-char (match-end 0)) (ruby-smie--forward-token))
465 ((not (ruby-smie--redundant-do-p 'skip
)) tok
)
466 ((> (save-excursion (forward-comment (point-max)) (point))
468 (ruby-smie--forward-token)) ;Fully redundant.
472 (defun ruby-smie--backward-token ()
474 (forward-comment (- (point)))
476 ((and (> pos
(line-end-position)) (ruby-smie--implicit-semi-p))
477 (skip-chars-forward " \t") ";")
478 ((and (bolp) (not (bobp))) ;Presumably a heredoc.
479 ;; Tokenize the whole heredoc as semicolon.
480 (goto-char (scan-sexps (point) -
1))
482 ((and (> pos
(point)) (not (bolp))
483 (ruby-smie--args-separator-p pos
))
484 ;; We have "ID SPC ID", which is a method call, but it binds less tightly
485 ;; than commas, since a method call can also be "ID ARG1, ARG2, ARG3".
486 ;; In some textbooks, "e1 @ e2" is used to mean "call e1 with arg e2".
489 (let ((tok (smie-default-backward-token))
490 (dot (ruby-smie--at-dot-call)))
492 (setq tok
(concat "." tok
)))
493 (when (and (eq ?
: (char-before)) (string-match "\\`\\s." tok
))
494 (forward-char -
1) (setq tok
(concat ":" tok
))) ;; bug#15208.
496 ((member tok
'("unless" "if" "while" "until"))
497 (if (ruby-smie--bosp)
501 ((ruby-smie--opening-pipe-p) "opening-|")
502 ((ruby-smie--closing-pipe-p) "closing-|")
504 ((string-match-p "\\`|[*&]\\'" tok
)
507 ((and (equal tok
"") (eq ?
\\ (char-before)) (looking-at "\n"))
508 (forward-char -
1) (ruby-smie--backward-token))
511 ((not (ruby-smie--redundant-do-p)) tok
)
512 ((> (save-excursion (forward-word 1)
513 (forward-comment (point-max)) (point))
515 (ruby-smie--backward-token)) ;Fully redundant.
519 (defun ruby-smie--indent-to-stmt ()
521 (smie-backward-sexp ";")
522 (cons 'column
(smie-indent-virtual))))
524 (defun ruby-smie-rules (kind token
)
525 (pcase (cons kind token
)
526 (`(:elem . basic
) ruby-indent-level
)
527 ;; "foo" "bar" is the concatenation of the two strings, so the second
528 ;; should be aligned with the first.
529 (`(:elem . args
) (if (looking-at "\\s\"") 0))
530 ;; (`(:after . ",") (smie-rule-separator kind))
533 ((smie-rule-parent-p "def" "begin" "do" "class" "module" "for"
534 "while" "until" "unless"
535 "if" "then" "elsif" "else" "when"
536 "rescue" "ensure" "{")
537 (smie-rule-parent ruby-indent-level
))
538 ;; For (invalid) code between switch and case.
539 ;; (if (smie-parent-p "switch") 4)
541 (`(:before .
,(or `"(" `"[" `"{"))
543 ((and (equal token
"{")
544 (not (smie-rule-prev-p "(" "{" "[" "," "=>" "=" "return" ";"))
547 (not (eq (preceding-char) ?
:))))
548 ;; Curly block opener.
549 (ruby-smie--indent-to-stmt))
550 ((smie-rule-hanging-p)
551 ;; Treat purely syntactic block-constructs as being part of their parent,
552 ;; when the opening statement is hanging.
553 (let ((state (smie-backward-sexp 'halfsexp
)))
554 (when (eq t
(car state
)) (goto-char (cadr state
))))
555 (cons 'column
(smie-indent-virtual)))))
556 (`(:after .
" @ ") (smie-rule-parent))
557 (`(:before .
"do") (ruby-smie--indent-to-stmt))
558 (`(,(or :before
:after
) .
".")
559 (unless (smie-rule-parent-p ".")
560 (smie-rule-parent ruby-indent-level
)))
561 (`(:before .
,(or `"else" `"then" `"elsif" `"rescue" `"ensure")) 0)
562 (`(:before .
,(or `"when"))
563 (if (not (smie-rule-sibling-p)) 0)) ;; ruby-indent-level
564 (`(:after .
,(or "=" "iuwu-mod" "+" "-" "*" "/" "&&" "||" "%" "**" "^" "&"
565 "<=>" ">" "<" ">=" "<=" "==" "===" "!=" "<<" ">>"
566 "+=" "-=" "*=" "/=" "%=" "**=" "&=" "|=" "^=" "|"
567 "<<=" ">>=" "&&=" "||=" "and" "or"))
568 (if (smie-rule-parent-p ";" nil
) ruby-indent-level
))
569 (`(:before .
"begin")
570 (unless (save-excursion (skip-chars-backward " \t") (bolp))
574 (defun ruby-imenu-create-index-in-block (prefix beg end
)
575 "Create an imenu index of methods inside a block."
576 (let ((index-alist '()) (case-fold-search nil
)
577 name next pos decl sing
)
579 (while (re-search-forward "^\\s *\\(\\(class\\s +\\|\\(class\\s *<<\\s *\\)\\|module\\s +\\)\\([^\(<\n ]+\\)\\|\\(def\\|alias\\)\\s +\\([^\(\n ]+\\)\\)" end t
)
580 (setq sing
(match-beginning 3))
581 (setq decl
(match-string 5))
582 (setq next
(match-end 0))
583 (setq name
(or (match-string 4) (match-string 6)))
584 (setq pos
(match-beginning 0))
586 ((string= "alias" decl
)
587 (if prefix
(setq name
(concat prefix name
)))
588 (push (cons name pos
) index-alist
))
589 ((string= "def" decl
)
593 ((string-match "^self\." name
)
594 (concat (substring prefix
0 -
1) (substring name
4)))
595 (t (concat prefix name
)))))
596 (push (cons name pos
) index-alist
)
597 (ruby-accurate-end-of-block end
))
599 (if (string= "self" name
)
600 (if prefix
(setq name
(substring prefix
0 -
1)))
601 (if prefix
(setq name
(concat (substring prefix
0 -
1) "::" name
)))
602 (push (cons name pos
) index-alist
))
603 (ruby-accurate-end-of-block end
)
606 (nconc (ruby-imenu-create-index-in-block
607 (concat name
(if sing
"." "#"))
608 next beg
) index-alist
))
612 (defun ruby-imenu-create-index ()
613 "Create an imenu index of all methods in the buffer."
614 (nreverse (ruby-imenu-create-index-in-block nil
(point-min) nil
)))
616 (defun ruby-accurate-end-of-block (&optional end
)
617 "Jump to the end of the current block or END, whichever is closer."
619 (end (or end
(point-max))))
622 (back-to-indentation)
623 (narrow-to-region (point) end
)
625 (while (and (setq state
(apply 'ruby-parse-partial end state
))
626 (>= (nth 2 state
) 0) (< (point) end
))))))
628 (defun ruby-mode-variables ()
629 "Set up initial buffer-local variables for Ruby mode."
630 (setq indent-tabs-mode ruby-indent-tabs-mode
)
632 (smie-setup ruby-smie-grammar
#'ruby-smie-rules
633 :forward-token
#'ruby-smie--forward-token
634 :backward-token
#'ruby-smie--backward-token
)
635 (setq-local indent-line-function
'ruby-indent-line
))
636 (setq-local require-final-newline t
)
637 (setq-local comment-start
"# ")
638 (setq-local comment-end
"")
639 (setq-local comment-column ruby-comment-column
)
640 (setq-local comment-start-skip
"#+ *")
641 (setq-local parse-sexp-ignore-comments t
)
642 (setq-local parse-sexp-lookup-properties t
)
643 (setq-local paragraph-start
(concat "$\\|" page-delimiter
))
644 (setq-local paragraph-separate paragraph-start
)
645 (setq-local paragraph-ignore-fill-prefix t
))
647 (defun ruby--insert-coding-comment (encoding)
648 "Insert a magic coding comment for ENCODING.
649 The style of the comment is controlled by `ruby-encoding-magic-comment-style'."
650 (let ((encoding-magic-comment-template
651 (pcase ruby-encoding-magic-comment-style
652 (`ruby
"# coding: %s")
653 (`emacs
"# -*- coding: %s -*-")
655 ruby-custom-encoding-magic-comment-template
))))
657 (format encoding-magic-comment-template encoding
)
660 (defun ruby--detect-encoding ()
661 (if (eq ruby-insert-encoding-magic-comment
'always-utf8
)
664 (or save-buffer-coding-system
665 buffer-file-coding-system
)))
668 (or (coding-system-get coding-system
'mime-charset
)
669 (coding-system-change-eol-conversion coding-system nil
))))
672 (if ruby-use-encoding-map
673 (let ((elt (assq coding-system ruby-encoding-map
)))
674 (if elt
(cdr elt
) coding-system
))
678 (defun ruby--encoding-comment-required-p ()
679 (or (eq ruby-insert-encoding-magic-comment
'always-utf8
)
680 (re-search-forward "[^\0-\177]" nil t
)))
682 (defun ruby-mode-set-encoding ()
683 "Insert a magic comment header with the proper encoding if necessary."
686 (goto-char (point-min))
687 (when (ruby--encoding-comment-required-p)
688 (goto-char (point-min))
689 (let ((coding-system (ruby--detect-encoding)))
691 (if (looking-at "^#!") (beginning-of-line 2))
692 (cond ((looking-at "\\s *#\\s *.*\\(en\\)?coding\\s *:\\s *\\([-a-z0-9_]*\\)")
693 ;; update existing encoding comment if necessary
694 (unless (string= (match-string 2) coding-system
)
695 (goto-char (match-beginning 2))
696 (delete-region (point) (match-end 2))
697 (insert coding-system
)))
698 ((looking-at "\\s *#.*coding\\s *[:=]"))
699 (t (when ruby-insert-encoding-magic-comment
700 (ruby--insert-coding-comment coding-system
))))
701 (when (buffer-modified-p)
702 (basic-save-buffer-1)))))))
704 (defun ruby-current-indentation ()
705 "Return the indentation level of current line."
708 (back-to-indentation)
711 (defun ruby-indent-line (&optional ignored
)
712 "Correct the indentation of the current Ruby line."
714 (ruby-indent-to (ruby-calculate-indent)))
716 (defun ruby-indent-to (column)
717 "Indent the current line to COLUMN."
720 (and (< column
0) (error "Invalid nesting"))
721 (setq shift
(current-column))
724 (back-to-indentation)
725 (setq top
(current-column))
726 (skip-chars-backward " \t")
727 (if (>= shift top
) (setq shift
(- shift top
))
731 (move-to-column (+ column shift
))
733 (delete-region beg
(point))
736 (move-to-column (+ column shift
))))))
738 (defun ruby-special-char-p (&optional pos
)
739 "Return t if the character before POS is a special character.
740 If omitted, POS defaults to the current point.
741 Special characters are `?', `$', `:' when preceded by whitespace,
742 and `\\' when preceded by `?'."
743 (setq pos
(or pos
(point)))
744 (let ((c (char-before pos
)) (b (and (< (point-min) pos
)
745 (char-before (1- pos
)))))
746 (cond ((or (eq c ??
) (eq c ?$
)))
747 ((and (eq c ?
:) (or (not b
) (eq (char-syntax b
) ?
))))
748 ((eq c ?
\\) (eq b ??
)))))
750 (defun ruby-singleton-class-p (&optional pos
)
752 (when pos
(goto-char pos
))
754 (and (or (bolp) (not (eq (char-before (point)) ?_
)))
755 (looking-at ruby-singleton-class-re
))))
757 (defun ruby-expr-beg (&optional option
)
758 "Check if point is possibly at the beginning of an expression.
759 OPTION specifies the type of the expression.
760 Can be one of `heredoc', `modifier', `expr-qstr', `expr-re'."
762 (store-match-data nil
)
763 (let ((space (skip-chars-backward " \t"))
769 (and (looking-at "\\?")
770 (or (eq (char-syntax (char-before (point))) ?w
)
771 (ruby-special-char-p))))
773 ((looking-at ruby-operator-re
))
774 ((eq option
'heredoc
)
775 (and (< space
0) (not (ruby-singleton-class-p start
))))
776 ((or (looking-at "[\\[({,;]")
777 (and (looking-at "[!?]")
778 (or (not (eq option
'modifier
))
780 (save-excursion (forward-char -
1) (looking-at "\\Sw$"))))
781 (and (looking-at ruby-symbol-re
)
782 (skip-chars-backward ruby-symbol-chars
)
784 ((looking-at (regexp-opt
785 (append ruby-block-beg-keywords
786 ruby-block-op-keywords
787 ruby-block-mid-keywords
)
789 (goto-char (match-end 0))
790 (not (looking-at "\\s_")))
791 ((eq option
'expr-qstr
)
792 (looking-at "[a-zA-Z][a-zA-z0-9_]* +%[^ \t]"))
793 ((eq option
'expr-re
)
794 (looking-at "[a-zA-Z][a-zA-z0-9_]* +/[^ \t]"))
797 (defun ruby-forward-string (term &optional end no-error expand
)
798 "Move forward across one balanced pair of string delimiters.
799 Skips escaped delimiters. If EXPAND is non-nil, also ignores
800 delimiters in interpolated strings.
802 TERM should be a string containing either a single, self-matching
803 delimiter (e.g. \"/\"), or a pair of matching delimiters with the
804 close delimiter first (e.g. \"][\").
806 When non-nil, search is bounded by position END.
808 Throws an error if a balanced match is not found, unless NO-ERROR
809 is non-nil, in which case nil will be returned.
811 This command assumes the character after point is an opening
813 (let ((n 1) (c (string-to-char term
))
814 (re (concat "[^\\]\\(\\\\\\\\\\)*\\("
815 (if (string= term
"^") ;[^] is not a valid regexp
817 (concat "[" term
"]"))
818 (when expand
"\\|\\(#{\\)")
820 (while (and (re-search-forward re end no-error
)
821 (if (match-beginning 3)
822 (ruby-forward-string "}{" end no-error nil
)
823 (> (setq n
(if (eq (char-before (point)) c
)
828 ((error "Unterminated string")))))
830 (defun ruby-deep-indent-paren-p (c)
832 (cond ((listp ruby-deep-indent-paren
)
833 (let ((deep (assoc c ruby-deep-indent-paren
)))
835 (or (cdr deep
) ruby-deep-indent-paren-style
))
836 ((memq c ruby-deep-indent-paren
)
837 ruby-deep-indent-paren-style
))))
838 ((eq c ruby-deep-indent-paren
) ruby-deep-indent-paren-style
)
839 ((eq c ?\
( ) ruby-deep-arglist
)))
841 (defun ruby-parse-partial (&optional end in-string nest depth pcol indent
)
842 "TODO: document throughout function body."
843 (or depth
(setq depth
0))
844 (or indent
(setq indent
0))
845 (when (re-search-forward ruby-delimiter end
'move
)
846 (let ((pnt (point)) w re expand
)
847 (goto-char (match-beginning 0))
849 ((and (memq (char-before) '(?
@ ?$
)) (looking-at "\\sw"))
851 ((looking-at "[\"`]") ;skip string
854 (ruby-forward-string (buffer-substring (point) (1+ (point)))
858 (setq in-string
(point))
863 (re-search-forward "[^\\]\\(\\\\\\\\\\)*'" end t
))
866 (setq in-string
(point))
872 ((and (not (eobp)) (ruby-expr-beg 'expr-re
))
873 (if (ruby-forward-string "/" end t t
)
875 (setq in-string
(point))
882 (ruby-expr-beg 'expr-qstr
)
883 (not (looking-at "%="))
884 (looking-at "%[QqrxWw]?\\([^a-zA-Z0-9 \t\n]\\)"))
885 (goto-char (match-beginning 1))
886 (setq expand
(not (memq (char-before) '(?q ?w
))))
887 (setq w
(match-string 1))
889 ((string= w
"[") (setq re
"]["))
890 ((string= w
"{") (setq re
"}{"))
891 ((string= w
"(") (setq re
")("))
892 ((string= w
"<") (setq re
"><"))
893 ((and expand
(string= w
"\\"))
894 (setq w
(concat "\\" w
))))
895 (unless (cond (re (ruby-forward-string re end t expand
))
896 (expand (ruby-forward-string w end t t
))
897 (t (re-search-forward
900 (concat "[^\\]\\(\\\\\\\\\\)*" w
))
902 (setq in-string
(point))
906 ((looking-at "\\?") ;skip ?char
908 ((and (ruby-expr-beg)
909 (looking-at "?\\(\\\\C-\\|\\\\M-\\)*\\\\?."))
910 (goto-char (match-end 0)))
913 ((looking-at "\\$") ;skip $char
916 ((looking-at "#") ;skip comment
920 ((looking-at "[\\[{(]")
921 (let ((deep (ruby-deep-indent-paren-p (char-after))))
922 (if (and deep
(or (not (eq (char-after) ?\
{)) (ruby-expr-beg)))
924 (and (eq deep
'space
) (looking-at ".\\s +[^# \t\n]")
925 (setq pnt
(1- (match-end 0))))
926 (setq nest
(cons (cons (char-after (point)) pnt
) nest
))
927 (setq pcol
(cons (cons pnt depth
) pcol
))
929 (setq nest
(cons (cons (char-after (point)) pnt
) nest
))
930 (setq depth
(1+ depth
))))
933 ((looking-at "[])}]")
934 (if (ruby-deep-indent-paren-p (matching-paren (char-after)))
935 (setq depth
(cdr (car pcol
)) pcol
(cdr pcol
))
936 (setq depth
(1- depth
)))
937 (setq nest
(cdr nest
))
939 ((looking-at ruby-block-end-re
)
940 (if (or (and (not (bolp))
943 (setq w
(char-after (point)))
948 (setq w
(char-after (point)))
953 (setq nest
(cdr nest
))
954 (setq depth
(1- depth
)))
956 ((looking-at "def\\s +[^(\n;]*")
960 (not (eq ?_
(char-after (point))))))
962 (setq nest
(cons (cons nil pnt
) nest
))
963 (setq depth
(1+ depth
))))
964 (goto-char (match-end 0)))
965 ((looking-at (concat "\\_<\\(" ruby-block-beg-re
"\\)\\_>"))
968 (or (not (looking-at "do\\_>"))
970 (back-to-indentation)
971 (not (looking-at ruby-non-block-do-re
)))))
975 (setq w
(char-after (point)))
979 (not (eq ?
! (char-after (point))))
980 (skip-chars-forward " \t")
981 (goto-char (match-beginning 0))
982 (or (not (looking-at ruby-modifier-re
))
983 (ruby-expr-beg 'modifier
))
985 (setq nest
(cons (cons nil pnt
) nest
))
986 (setq depth
(1+ depth
)))
988 ((looking-at ":\\(['\"]\\)")
989 (goto-char (match-beginning 1))
990 (ruby-forward-string (match-string 1) end t
))
991 ((looking-at ":\\([-,.+*/%&|^~<>]=?\\|===?\\|<=>\\|![~=]?\\)")
992 (goto-char (match-end 0)))
993 ((looking-at ":\\([a-zA-Z_][a-zA-Z_0-9]*[!?=]?\\)?")
994 (goto-char (match-end 0)))
995 ((or (looking-at "\\.\\.\\.?")
996 (looking-at "\\.[0-9]+")
997 (looking-at "\\.[a-zA-Z_0-9]+")
999 (goto-char (match-end 0)))
1000 ((looking-at "^=begin")
1001 (if (re-search-forward "^=end" end t
)
1003 (setq in-string
(match-end 0))
1007 ((and (ruby-expr-beg 'heredoc
)
1008 (looking-at "<<\\(-\\)?\\(\\([\"'`]\\)\\([^\n]+?\\)\\3\\|\\(?:\\sw\\|\\s_\\)+\\)"))
1009 (setq re
(regexp-quote (or (match-string 4) (match-string 2))))
1010 (if (match-beginning 1) (setq re
(concat "\\s *" re
)))
1011 (let* ((id-end (goto-char (match-end 0)))
1012 (line-end-position (point-at-eol))
1013 (state (list in-string nest depth pcol indent
)))
1014 ;; parse the rest of the line
1015 (while (and (> line-end-position
(point))
1016 (setq state
(apply 'ruby-parse-partial
1017 line-end-position state
))))
1018 (setq in-string
(car state
)
1022 indent
(nth 4 state
))
1023 ;; skip heredoc section
1024 (if (re-search-forward (concat "^" re
"$") end
'move
)
1026 (setq in-string id-end
)
1030 ((looking-at "^__END__$")
1032 ((and (looking-at ruby-here-doc-beg-re
)
1033 (boundp 'ruby-indent-point
))
1034 (if (re-search-forward (ruby-here-doc-end-match)
1035 ruby-indent-point t
)
1037 (setq in-string
(match-end 0))
1038 (goto-char ruby-indent-point
)))
1040 (error (format "Bad string %s"
1041 (buffer-substring (point) pnt
)
1043 (list in-string nest depth pcol
))
1045 (defun ruby-parse-region (start end
)
1051 (ruby-beginning-of-indent))
1053 (narrow-to-region (point) end
)
1054 (while (and (> end
(point))
1055 (setq state
(apply 'ruby-parse-partial end state
))))))
1056 (list (nth 0 state
) ; in-string
1057 (car (nth 1 state
)) ; nest
1058 (nth 2 state
) ; depth
1059 (car (car (nth 3 state
))) ; pcol
1060 ;(car (nth 5 state)) ; indent
1063 (defun ruby-indent-size (pos nest
)
1064 "Return the indentation level in spaces NEST levels deeper than POS."
1065 (+ pos
(* (or nest
1) ruby-indent-level
)))
1067 (defun ruby-calculate-indent (&optional parse-start
)
1068 "Return the proper indentation level of the current line."
1069 ;; TODO: Document body
1072 (let ((ruby-indent-point (point))
1073 (case-fold-search nil
)
1074 state eol begin op-end
1075 (paren (progn (skip-syntax-forward " ")
1076 (and (char-after) (matching-paren (char-after)))))
1079 (goto-char parse-start
)
1080 (ruby-beginning-of-indent)
1081 (setq parse-start
(point)))
1082 (back-to-indentation)
1083 (setq indent
(current-column))
1084 (setq state
(ruby-parse-region parse-start ruby-indent-point
))
1086 ((nth 0 state
) ; within string
1087 (setq indent nil
)) ; do nothing
1088 ((car (nth 1 state
)) ; in paren
1089 (goto-char (setq begin
(cdr (nth 1 state
))))
1090 (let ((deep (ruby-deep-indent-paren-p (car (nth 1 state
)))))
1092 (cond ((and (eq deep t
) (eq (car (nth 1 state
)) paren
))
1093 (skip-syntax-backward " ")
1094 (setq indent
(1- (current-column))))
1095 ((let ((s (ruby-parse-region (point) ruby-indent-point
)))
1096 (and (nth 2 s
) (> (nth 2 s
) 0)
1097 (or (goto-char (cdr (nth 1 s
))) t
)))
1099 (setq indent
(ruby-indent-size (current-column)
1102 (setq indent
(current-column))
1103 (cond ((eq deep
'space
))
1104 (paren (setq indent
(1- indent
)))
1105 (t (setq indent
(ruby-indent-size (1- indent
) 1))))))
1106 (if (nth 3 state
) (goto-char (nth 3 state
))
1107 (goto-char parse-start
) (back-to-indentation))
1108 (setq indent
(ruby-indent-size (current-column) (nth 2 state
))))
1109 (and (eq (car (nth 1 state
)) paren
)
1110 (ruby-deep-indent-paren-p (matching-paren paren
))
1111 (search-backward (char-to-string paren
))
1112 (setq indent
(current-column)))))
1113 ((and (nth 2 state
) (> (nth 2 state
) 0)) ; in nest
1114 (if (null (cdr (nth 1 state
)))
1115 (error "Invalid nesting"))
1116 (goto-char (cdr (nth 1 state
)))
1117 (forward-word -
1) ; skip back a keyword
1118 (setq begin
(point))
1120 ((looking-at "do\\>[^_]") ; iter block is a special case
1121 (if (nth 3 state
) (goto-char (nth 3 state
))
1122 (goto-char parse-start
) (back-to-indentation))
1123 (setq indent
(ruby-indent-size (current-column) (nth 2 state
))))
1125 (setq indent
(+ (current-column) ruby-indent-level
)))))
1127 ((and (nth 2 state
) (< (nth 2 state
) 0)) ; in negative nest
1128 (setq indent
(ruby-indent-size (current-column) (nth 2 state
)))))
1130 (goto-char ruby-indent-point
)
1135 ((and (not (ruby-deep-indent-paren-p paren
))
1136 (re-search-forward ruby-negative eol t
))
1137 (and (not (eq ?_
(char-after (match-end 0))))
1138 (setq indent
(- indent ruby-indent-level
))))
1143 (or (ruby-deep-indent-paren-p t
)
1144 (null (car (nth 1 state
)))))
1145 ;; goto beginning of non-empty no-comment line
1148 (skip-chars-backward " \t\n")
1151 (if (re-search-forward "^\\s *#" end t
)
1155 ;; skip the comment at the end
1156 (skip-chars-backward " \t")
1157 (let (end (pos (point)))
1159 (while (and (re-search-forward "#" pos t
)
1160 (setq end
(1- (point)))
1161 (or (ruby-special-char-p end
)
1162 (and (setq state
(ruby-parse-region
1166 (goto-char (or end pos
))
1167 (skip-chars-backward " \t")
1168 (setq begin
(if (and end
(nth 0 state
)) pos
(cdr (nth 1 state
))))
1169 (setq state
(ruby-parse-region parse-start
(point))))
1170 (or (bobp) (forward-char -
1))
1172 (or (and (looking-at ruby-symbol-re
)
1173 (skip-chars-backward ruby-symbol-chars
)
1174 (looking-at (concat "\\<\\(" ruby-block-hanging-re
1176 (not (eq (point) (nth 3 state
)))
1178 (goto-char (match-end 0))
1179 (not (looking-at "[a-z_]"))))
1180 (and (looking-at ruby-operator-re
)
1181 (not (ruby-special-char-p))
1184 (or (not (looking-at ruby-operator-re
))
1185 (not (eq (char-before) ?
:))))
1186 ;; Operator at the end of line.
1187 (let ((c (char-after (point))))
1191 ;; (goto-char begin)
1192 ;; (skip-chars-forward " \t")
1193 ;; (not (or (eolp) (looking-at "#")
1194 ;; (and (eq (car (nth 1 state)) ?{)
1195 ;; (looking-at "|"))))))
1196 ;; Not a regexp or percent literal.
1197 (null (nth 0 (ruby-parse-region (or begin parse-start
)
1199 (or (not (eq ?|
(char-after (point))))
1201 (or (eolp) (forward-char -
1))
1203 ((search-backward "|" nil t
)
1204 (skip-chars-backward " \t\n")
1208 (not (looking-at "{")))
1211 (not (looking-at "do\\>[^_]")))))
1219 (not (looking-at (concat "\\<\\(" ruby-block-hanging-re
1221 (eq (ruby-deep-indent-paren-p t
) 'space
)
1224 (goto-char (or begin parse-start
))
1225 (skip-syntax-forward " ")
1227 ((car (nth 1 state
)) indent
)
1229 (+ indent ruby-indent-level
))))))))
1230 (goto-char ruby-indent-point
)
1232 (skip-syntax-forward " ")
1233 (if (looking-at "\\.[^.]")
1234 (+ indent ruby-indent-level
)
1237 (defun ruby-beginning-of-defun (&optional arg
)
1238 "Move backward to the beginning of the current defun.
1239 With ARG, move backward multiple defuns. Negative ARG means
1242 (let (case-fold-search)
1243 (and (re-search-backward (concat "^\\s *" ruby-defun-beg-re
"\\_>")
1245 (beginning-of-line))))
1247 (defun ruby-end-of-defun ()
1248 "Move point to the end of the current defun.
1249 The defun begins at or after the point. This function is called
1253 (let (case-fold-search)
1254 (when (looking-back (concat "^\\s *" ruby-block-end-re
))
1257 (defun ruby-beginning-of-indent ()
1258 "Backtrack to a line which can be used as a reference for
1259 calculating indentation on the lines after it."
1260 (while (and (re-search-backward ruby-indent-beg-re nil
'move
)
1261 (if (ruby-in-ppss-context-p 'anything
)
1263 ;; We can stop, then.
1264 (beginning-of-line)))))
1266 (defun ruby-move-to-block (n)
1267 "Move to the beginning (N < 0) or the end (N > 0) of the
1268 current block, a sibling block, or an outer block. Do that (abs N) times."
1269 (back-to-indentation)
1270 (let ((signum (if (> n
0) 1 -
1))
1272 (depth (or (nth 2 (ruby-parse-region (point) (line-end-position))) 0))
1275 (when (looking-at ruby-block-mid-re
)
1276 (setq depth
(+ depth signum
)))
1277 (when (< (* depth signum
) 0)
1278 ;; Moving end -> end or beginning -> beginning.
1280 (dotimes (_ (abs n
))
1282 (setq down
(save-excursion
1283 (back-to-indentation)
1284 ;; There is a block start or block end keyword on this
1285 ;; line, don't need to look for another block.
1286 (and (re-search-forward
1287 (if backward ruby-block-end-re
1288 (concat "\\_<\\(" ruby-block-beg-re
"\\)\\_>"))
1289 (line-end-position) t
)
1290 (not (nth 8 (syntax-ppss))))))
1291 (while (and (not done
) (not (if backward
(bobp) (eobp))))
1292 (forward-line signum
)
1294 ;; Skip empty and commented out lines.
1295 ((looking-at "^\\s *$"))
1296 ((looking-at "^\\s *#"))
1297 ;; Skip block comments;
1298 ((and (not backward
) (looking-at "^=begin\\>"))
1299 (re-search-forward "^=end\\>"))
1300 ((and backward
(looking-at "^=end\\>"))
1301 (re-search-backward "^=begin\\>"))
1302 ;; Jump over a multiline literal.
1303 ((ruby-in-ppss-context-p 'string
)
1304 (goto-char (nth 8 (syntax-ppss)))
1307 (when (bolp) (forward-char -
1)))) ; After a heredoc.
1309 (let ((state (ruby-parse-region (point) (line-end-position))))
1310 (unless (car state
) ; Line ends with unfinished string.
1311 (setq depth
(+ (nth 2 state
) depth
))))
1313 ;; Increased depth, we found a block.
1314 ((> (* signum depth
) 0)
1316 ;; We're at the same depth as when we started, and we've
1317 ;; encountered a block before. Stop.
1318 ((and down
(zerop depth
))
1320 ;; Lower depth, means outer block, can stop now.
1321 ((< (* signum depth
) 0)
1323 (back-to-indentation)))
1325 (defun ruby-beginning-of-block (&optional arg
)
1326 "Move backward to the beginning of the current block.
1327 With ARG, move up multiple blocks."
1329 (ruby-move-to-block (- (or arg
1))))
1331 (defun ruby-end-of-block (&optional arg
)
1332 "Move forward to the end of the current block.
1333 With ARG, move out of multiple blocks."
1335 (ruby-move-to-block (or arg
1)))
1337 (defun ruby-forward-sexp (&optional arg
)
1338 "Move forward across one balanced expression (sexp).
1339 With ARG, do it many times. Negative ARG means move backward."
1340 ;; TODO: Document body
1343 (ruby-use-smie (forward-sexp arg
))
1344 ((and (numberp arg
) (< arg
0)) (ruby-backward-sexp (- arg
)))
1346 (let ((i (or arg
1)))
1349 (skip-syntax-forward " ")
1350 (if (looking-at ",\\s *") (goto-char (match-end 0)))
1351 (cond ((looking-at "\\?\\(\\\\[CM]-\\)*\\\\?\\S ")
1352 (goto-char (match-end 0)))
1354 (skip-chars-forward ",.:;|&^~=!?\\+\\-\\*")
1355 (looking-at "\\s("))
1356 (goto-char (scan-sexps (point) 1)))
1357 ((and (looking-at (concat "\\<\\(" ruby-block-beg-re
1359 (not (eq (char-before (point)) ?.
))
1360 (not (eq (char-before (point)) ?
:)))
1363 ((looking-at "\\(\\$\\|@@?\\)?\\sw")
1365 (while (progn (forward-word 1) (looking-at "_")))
1366 (cond ((looking-at "::") (forward-char 2) t
)
1367 ((> (skip-chars-forward ".") 0))
1368 ((looking-at "\\?\\|!\\(=[~=>]\\|[^~=]\\)")
1369 (forward-char 1) nil
)))))
1373 (setq expr
(or expr
(ruby-expr-beg)
1374 (looking-at "%\\sw?\\Sw\\|[\"'`/]")))
1375 (nth 1 (setq state
(apply #'ruby-parse-partial
1378 (skip-chars-forward "<"))
1381 ((error) (forward-word 1)))
1384 (defun ruby-backward-sexp (&optional arg
)
1385 "Move backward across one balanced expression (sexp).
1386 With ARG, do it many times. Negative ARG means move forward."
1387 ;; TODO: Document body
1390 (ruby-use-smie (backward-sexp arg
))
1391 ((and (numberp arg
) (< arg
0)) (ruby-forward-sexp (- arg
)))
1393 (let ((i (or arg
1)))
1396 (skip-chars-backward " \t\n,.:;|&^~=!?\\+\\-\\*")
1398 (cond ((looking-at "\\s)")
1399 (goto-char (scan-sexps (1+ (point)) -
1))
1400 (pcase (char-before)
1401 (`?%
(forward-char -
1))
1402 ((or `?q
`?Q
`?w
`?W
`?r
`?x
)
1403 (if (eq (char-before (1- (point))) ?%
)
1404 (forward-char -
2))))
1406 ((looking-at "\\s\"\\|\\\\\\S_")
1407 (let ((c (char-to-string (char-before (match-end 0)))))
1408 (while (and (search-backward c
)
1409 (eq (logand (skip-chars-backward "\\") 1)
1412 ((looking-at "\\s.\\|\\s\\")
1413 (if (ruby-special-char-p) (forward-char -
1)))
1414 ((looking-at "\\s(") nil
)
1417 (while (progn (forward-word -
1)
1418 (pcase (char-before)
1420 (`?.
(forward-char -
1) t
)
1423 (and (eq (char-before) (char-after))
1427 (eq (char-before) :)))))
1428 (if (looking-at ruby-block-end-re
)
1429 (ruby-beginning-of-block))
1435 (defun ruby-indent-exp (&optional ignored
)
1436 "Indent each line in the balanced expression following the point."
1438 (let ((here (point-marker)) start top column
(nest t
))
1439 (set-marker-insertion-type here t
)
1443 (setq start
(point) top
(current-indentation))
1444 (while (and (not (eobp))
1446 (setq column
(ruby-calculate-indent start
))
1447 (cond ((> column top
)
1449 ((and (= column top
) nest
)
1450 (setq nest nil
) t
))))
1451 (ruby-indent-to column
)
1452 (beginning-of-line 2)))
1454 (set-marker here nil
))))
1456 (defun ruby-add-log-current-method ()
1457 "Return the current method name as a string.
1458 This string includes all namespaces.
1467 See `add-log-current-defun-function'."
1470 (let* ((indent 0) mname mlist
1474 (concat "^[ \t]*" re
"[ \t]+"
1476 ;; \\. and :: for class methods
1477 "\\([A-Za-z_]" ruby-symbol-re
"*\\|\\.\\|::" "\\)"
1479 (definition-re (funcall make-definition-re ruby-defun-beg-re
))
1480 (module-re (funcall make-definition-re
"\\(class\\|module\\)")))
1481 ;; Get the current method definition (or class/module).
1482 (when (re-search-backward definition-re nil t
)
1483 (goto-char (match-beginning 1))
1484 (if (not (string-equal "def" (match-string 1)))
1485 (setq mlist
(list (match-string 2)))
1486 ;; We're inside the method. For classes and modules,
1487 ;; this check is skipped for performance.
1488 (when (ruby-block-contains-point start
)
1489 (setq mname
(match-string 2))))
1490 (setq indent
(current-column))
1491 (beginning-of-line))
1492 ;; Walk up the class/module nesting.
1493 (while (and (> indent
0)
1494 (re-search-backward module-re nil t
))
1495 (goto-char (match-beginning 1))
1496 (when (< (current-column) indent
)
1497 (setq mlist
(cons (match-string 2) mlist
))
1498 (setq indent
(current-column))
1499 (beginning-of-line)))
1500 ;; Process the method name.
1502 (let ((mn (split-string mname
"\\.\\|::")))
1505 (unless (string-equal "self" (car mn
)) ; def self.foo
1507 (let ((ml (nreverse mlist
)))
1508 ;; If the method name references one of the
1509 ;; containing modules, drop the more nested ones.
1511 (if (string-equal (car ml
) (car mn
))
1512 (setq mlist
(nreverse (cdr ml
)) ml nil
))
1513 (or (setq ml
(cdr ml
)) (nreverse mlist
))))
1515 (setcdr (last mlist
) (butlast mn
))
1516 (setq mlist
(butlast mn
))))
1517 (setq mname
(concat "." (car (last mn
)))))
1518 ;; See if the method is in singleton class context.
1519 (let ((in-singleton-class
1520 (when (re-search-forward ruby-singleton-class-re start t
)
1521 (goto-char (match-beginning 0))
1522 ;; FIXME: Optimize it out, too?
1523 ;; This can be slow in a large file, but
1524 ;; unlike class/module declaration
1525 ;; indentations, method definitions can be
1526 ;; intermixed with these, and may or may not
1527 ;; be additionally indented after visibility
1529 (ruby-block-contains-point start
))))
1531 (if in-singleton-class
"." "#")
1533 ;; Generate the string.
1535 (setq mlist
(mapconcat (function identity
) mlist
"::")))
1537 (if mlist
(concat mlist mname
) mname
)
1540 (defun ruby-block-contains-point (pt)
1546 (defun ruby-brace-to-do-end (orig end
)
1547 (let (beg-marker end-marker
)
1549 (when (eq (char-before) ?\
})
1551 (when (save-excursion
1552 (skip-chars-backward " \t")
1556 (setq end-marker
(point-marker))
1557 (when (and (not (eobp)) (eq (char-syntax (char-after)) ?w
))
1561 (when (eq (char-syntax (char-before)) ?w
)
1564 (setq beg-marker
(point-marker))
1565 (when (looking-at "\\(\\s \\)*|")
1566 (unless (match-beginning 1)
1568 (goto-char (1+ (match-end 0)))
1569 (search-forward "|"))
1570 (unless (looking-at "\\s *$")
1572 (indent-region beg-marker end-marker
)
1573 (goto-char beg-marker
)
1576 (defun ruby-do-end-to-brace (orig end
)
1577 (let (beg-marker end-marker beg-pos end-pos
)
1578 (goto-char (- end
3))
1579 (when (looking-at ruby-block-end-re
)
1581 (setq end-marker
(point-marker))
1585 ;; Maybe this should be customizable, let's see if anyone asks.
1587 (setq beg-marker
(point-marker))
1588 (when (looking-at "\\s +|")
1589 (delete-char (- (match-end 0) (match-beginning 0) 1))
1591 (re-search-forward "|" (line-end-position) t
))
1593 (skip-chars-forward " \t\n\r")
1594 (setq beg-pos
(point))
1595 (goto-char end-marker
)
1596 (skip-chars-backward " \t\n\r")
1597 (setq end-pos
(point)))
1600 (and (= (line-number-at-pos beg-pos
) (line-number-at-pos end-pos
))
1601 (< (+ (current-column) (- end-pos beg-pos
) 2) fill-column
)))
1603 (goto-char end-marker
)
1604 (just-one-space -
1))
1605 (goto-char beg-marker
)
1608 (defun ruby-toggle-block ()
1609 "Toggle block type from do-end to braces or back.
1610 The block must begin on the current line or above it and end after the point.
1611 If the result is do-end block, it will always be multiline."
1613 (let ((start (point)) beg end
)
1616 (if (and (re-search-backward "\\(?:[^#]\\)\\({\\)\\|\\(\\_<do\\_>\\)")
1618 (goto-char (or (match-beginning 1) (match-beginning 2)))
1620 (save-match-data (ruby-forward-sexp))
1623 (if (match-beginning 1)
1624 (ruby-brace-to-do-end beg end
)
1625 (ruby-do-end-to-brace beg end
)))
1626 (goto-char start
))))
1629 (defconst ruby-percent-literal-beg-re
1630 "\\(%\\)[qQrswWxIi]?\\([[:punct:]]\\)"
1631 "Regexp to match the beginning of percent literal.")
1633 (defconst ruby-syntax-methods-before-regexp
1634 '("gsub" "gsub!" "sub" "sub!" "scan" "split" "split!" "index" "match"
1635 "assert_match" "Given" "Then" "When")
1636 "Methods that can take regexp as the first argument.
1637 It will be properly highlighted even when the call omits parens.")
1639 (defvar ruby-syntax-before-regexp-re
1641 ;; Special tokens that can't be followed by a division operator.
1643 ;; Distinguish ternary operator tokens.
1644 ;; FIXME: They don't really have to be separated with spaces.
1646 ;; Control flow keywords and operators following bol or whitespace.
1647 "\\|\\(?:^\\|\\s \\)"
1648 (regexp-opt '("if" "elsif" "unless" "while" "until" "when" "and"
1649 "or" "not" "&&" "||"))
1650 ;; Method name from the list.
1652 (regexp-opt ruby-syntax-methods-before-regexp
)
1654 "Regexp to match text that can be followed by a regular expression."))
1656 (defun ruby-syntax-propertize-function (start end
)
1657 "Syntactic keywords for Ruby mode. See `syntax-propertize-function'."
1658 (let (case-fold-search)
1660 (remove-text-properties start end
'(ruby-expansion-match-data))
1661 (ruby-syntax-propertize-heredoc end
)
1662 (ruby-syntax-enclosing-percent-literal end
)
1664 (syntax-propertize-rules
1665 ;; $' $" $` .... are variables.
1666 ;; ?' ?" ?` are character literals (one-char strings in 1.9+).
1667 ("\\([?$]\\)[#\"'`]"
1668 (1 (unless (save-excursion
1669 ;; Not within a string.
1670 (nth 3 (syntax-ppss (match-beginning 0))))
1671 (string-to-syntax "\\"))))
1672 ;; Part of symbol when at the end of a method name.
1674 (0 (unless (save-excursion
1675 (or (nth 8 (syntax-ppss (match-beginning 0)))
1676 (let (parse-sexp-lookup-properties)
1677 (zerop (skip-syntax-backward "w_")))
1678 (memq (preceding-char) '(?
@ ?$
))))
1679 (string-to-syntax "_"))))
1680 ;; Regular expressions. Start with matching unescaped slash.
1681 ("\\(?:\\=\\|[^\\]\\)\\(?:\\\\\\\\\\)*\\(/\\)"
1682 (1 (let ((state (save-excursion (syntax-ppss (match-beginning 1)))))
1684 ;; Beginning of a regexp.
1685 (and (null (nth 8 state
))
1688 (looking-back ruby-syntax-before-regexp-re
1690 ;; End of regexp. We don't match the whole
1691 ;; regexp at once because it can have
1692 ;; string interpolation inside, or span
1694 (eq ?
/ (nth 3 state
)))
1695 (string-to-syntax "\"/")))))
1696 ;; Expression expansions in strings. We're handling them
1697 ;; here, so that the regexp rule never matches inside them.
1698 (ruby-expression-expansion-re
1699 (0 (ignore (ruby-syntax-propertize-expansion))))
1700 ("^=en\\(d\\)\\_>" (1 "!"))
1701 ("^\\(=\\)begin\\_>" (1 "!"))
1702 ;; Handle here documents.
1703 ((concat ruby-here-doc-beg-re
".*\\(\n\\)")
1704 (7 (unless (or (nth 8 (save-excursion
1705 (syntax-ppss (match-beginning 0))))
1706 (ruby-singleton-class-p (match-beginning 0)))
1707 (put-text-property (match-beginning 7) (match-end 7)
1708 'syntax-table
(string-to-syntax "\""))
1709 (ruby-syntax-propertize-heredoc end
))))
1710 ;; Handle percent literals: %w(), %q{}, etc.
1711 ((concat "\\(?:^\\|[[ \t\n<+(,=]\\)" ruby-percent-literal-beg-re
)
1712 (1 (prog1 "|" (ruby-syntax-propertize-percent-literal end
)))))
1715 (defun ruby-syntax-propertize-heredoc (limit)
1716 (let ((ppss (syntax-ppss))
1718 (when (eq ?
\n (nth 3 ppss
))
1720 (goto-char (nth 8 ppss
))
1722 (while (re-search-forward ruby-here-doc-beg-re
1723 (line-end-position) t
)
1724 (unless (ruby-singleton-class-p (match-beginning 0))
1725 (push (concat (ruby-here-doc-end-match) "\n") res
))))
1727 ;; With multiple openers on the same line, we don't know in which
1728 ;; part `start' is, so we have to go back to the beginning.
1730 (goto-char (nth 8 ppss
))
1731 (setq res
(nreverse res
)))
1732 (while (and res
(re-search-forward (pop res
) limit
'move
))
1734 (put-text-property (1- (point)) (point)
1735 'syntax-table
(string-to-syntax "\""))))
1736 ;; End up at bol following the heredoc openers.
1737 ;; Propertize expression expansions from this point forward.
1740 (defun ruby-syntax-enclosing-percent-literal (limit)
1741 (let ((state (syntax-ppss))
1743 ;; When already inside percent literal, re-propertize it.
1744 (when (eq t
(nth 3 state
))
1745 (goto-char (nth 8 state
))
1746 (when (looking-at ruby-percent-literal-beg-re
)
1747 (ruby-syntax-propertize-percent-literal limit
))
1748 (when (< (point) start
) (goto-char start
)))))
1750 (defun ruby-syntax-propertize-percent-literal (limit)
1751 (goto-char (match-beginning 2))
1752 ;; Not inside a simple string or comment.
1753 (when (eq t
(nth 3 (syntax-ppss)))
1754 (let* ((op (char-after))
1755 (ops (char-to-string op
))
1756 (cl (or (cdr (aref (syntax-table) op
))
1757 (cdr (assoc op
'((?
< . ?
>))))))
1758 parse-sexp-lookup-properties
)
1762 (if cl
; Paired delimiters.
1763 ;; Delimiter pairs of the same kind can be nested
1764 ;; inside the literal, as long as they are balanced.
1765 ;; Create syntax table that ignores other characters.
1766 (with-syntax-table (make-char-table 'syntax-table nil
)
1767 (modify-syntax-entry op
(concat "(" (char-to-string cl
)))
1768 (modify-syntax-entry cl
(concat ")" ops
))
1769 (modify-syntax-entry ?
\\ "\\")
1771 (narrow-to-region (point) limit
)
1772 (forward-list))) ; skip to the paired character
1773 ;; Single character delimiter.
1774 (re-search-forward (concat "[^\\]\\(?:\\\\\\\\\\)*"
1775 (regexp-quote ops
)) limit nil
))
1776 ;; Found the closing delimiter.
1777 (put-text-property (1- (point)) (point) 'syntax-table
1778 (string-to-syntax "|")))
1779 ;; Unclosed literal, do nothing.
1780 ((scan-error search-failed
)))))))
1782 (defun ruby-syntax-propertize-expansion ()
1783 ;; Save the match data to a text property, for font-locking later.
1784 ;; Set the syntax of all double quotes and backticks to punctuation.
1785 (let* ((beg (match-beginning 2))
1787 (state (and beg
(save-excursion (syntax-ppss beg
)))))
1788 (when (ruby-syntax-expansion-allowed-p state
)
1789 (put-text-property beg
(1+ beg
) 'ruby-expansion-match-data
1792 (while (re-search-forward "[\"`]" end
'move
)
1793 (put-text-property (match-beginning 0) (match-end 0)
1794 'syntax-table
(string-to-syntax "."))))))
1796 (defun ruby-syntax-expansion-allowed-p (parse-state)
1797 "Return non-nil if expression expansion is allowed."
1798 (let ((term (nth 3 parse-state
)))
1800 ((memq term
'(?
\" ?
` ?
\n ?
/)))
1804 (goto-char (nth 8 parse-state
))
1805 (looking-at "%\\(?:[QWrxI]\\|\\W\\)")))))))
1807 (defun ruby-syntax-propertize-expansions (start end
)
1810 (while (re-search-forward ruby-expression-expansion-re end
'move
)
1811 (ruby-syntax-propertize-expansion))))
1813 (defun ruby-in-ppss-context-p (context &optional ppss
)
1814 (let ((ppss (or ppss
(syntax-ppss (point)))))
1816 ((eq context
'anything
)
1819 ((eq context
'string
)
1821 ((eq context
'heredoc
)
1822 (eq ?
\n (nth 3 ppss
)))
1823 ((eq context
'non-heredoc
)
1824 (and (ruby-in-ppss-context-p 'anything
)
1825 (not (ruby-in-ppss-context-p 'heredoc
))))
1826 ((eq context
'comment
)
1830 "Internal error on `ruby-in-ppss-context-p': "
1831 "context name `" (symbol-name context
) "' is unknown"))))
1834 (defvar ruby-font-lock-syntax-table
1835 (let ((tbl (copy-syntax-table ruby-mode-syntax-table
)))
1836 (modify-syntax-entry ?_
"w" tbl
)
1838 "The syntax table to use for fontifying Ruby mode buffers.
1839 See `font-lock-syntax-table'.")
1841 (defconst ruby-font-lock-keyword-beg-re
"\\(?:^\\|[^.@$]\\|\\.\\.\\)")
1843 (defconst ruby-font-lock-keywords
1845 ("^\\s *def\\s +\\(?:[^( \t\n.]*\\.\\)?\\([^( \t\n]+\\)"
1846 1 font-lock-function-name-face
)
1849 ruby-font-lock-keyword-beg-re
1885 (1 font-lock-keyword-face
))
1886 ;; Some core methods.
1888 ruby-font-lock-keyword-beg-re
1890 '( ;; built-in methods on Kernel
1934 ;; keyword-like private methods on Module
1951 (1 font-lock-builtin-face
))
1952 ;; Here-doc beginnings.
1953 (,ruby-here-doc-beg-re
1954 (0 (unless (ruby-singleton-class-p (match-beginning 0))
1955 'font-lock-string-face
)))
1956 ;; Perl-ish keywords.
1957 "\\_<\\(?:BEGIN\\|END\\)\\_>\\|^__END__$"
1959 (,(concat ruby-font-lock-keyword-beg-re
1960 "\\_<\\(nil\\|self\\|true\\|false\\)\\_>")
1961 1 font-lock-variable-name-face
)
1962 ;; Keywords that evaluate to certain values.
1963 ("\\_<__\\(?:LINE\\|ENCODING\\|FILE\\)__\\_>"
1964 (0 font-lock-variable-name-face
))
1966 ("\\(^\\|[^:]\\)\\(:\\([-+~]@?\\|[/%&|^`]\\|\\*\\*?\\|<\\(<\\|=>?\\)?\\|>[>=]?\\|===?\\|=~\\|![~=]?\\|\\[\\]=?\\|@?\\(\\w\\|_\\)+\\([!?=]\\|\\b_*\\)\\|#{[^}\n\\\\]*\\(\\\\.[^}\n\\\\]*\\)*}\\)\\)"
1967 2 font-lock-constant-face
)
1969 ("\\(\\$\\([^a-zA-Z0-9 \n]\\|[0-9]\\)\\)\\W"
1970 1 font-lock-variable-name-face
)
1971 ("\\(\\$\\|@\\|@@\\)\\(\\w\\|_\\)+"
1972 0 font-lock-variable-name-face
)
1974 ("\\(?:\\_<\\|::\\)\\([A-Z]+\\(\\w\\|_\\)*\\)"
1975 1 (unless (eq ?\
( (char-after)) font-lock-type-face
))
1976 ("\\(^\\s *\\|[\[\{\(,]\\s *\\|\\sw\\s +\\)\\(\\(\\sw\\|_\\)+\\):[^:]"
1977 (2 font-lock-constant-face
))
1978 ;; Conversion methods on Kernel.
1979 (,(concat ruby-font-lock-keyword-beg-re
1980 (regexp-opt '("Array" "Complex" "Float" "Hash"
1981 "Integer" "Rational" "String") 'symbols
))
1982 (1 font-lock-builtin-face
))
1983 ;; Expression expansion.
1984 (ruby-match-expression-expansion
1985 2 font-lock-variable-name-face t
)
1987 ("[^[:alnum:]_]\\(!\\)[^=]"
1988 1 font-lock-negation-char-face
)
1989 ;; Character literals.
1990 ;; FIXME: Support longer escape sequences.
1991 ("\\_<\\?\\\\?\\S " 0 font-lock-string-face
)
1993 "Additional expressions to highlight in Ruby mode.")
1995 (defun ruby-match-expression-expansion (limit)
1996 (let* ((prop 'ruby-expansion-match-data
)
1997 (pos (next-single-char-property-change (point) prop nil limit
))
1999 (when (and pos
(> pos
(point)))
2001 (or (and (setq value
(get-text-property pos prop
))
2002 (progn (set-match-data value
) t
))
2003 (ruby-match-expression-expansion limit
)))))
2006 (define-derived-mode ruby-mode prog-mode
"Ruby"
2007 "Major mode for editing Ruby code.
2010 (ruby-mode-variables)
2012 (setq-local imenu-create-index-function
'ruby-imenu-create-index
)
2013 (setq-local add-log-current-defun-function
'ruby-add-log-current-method
)
2014 (setq-local beginning-of-defun-function
'ruby-beginning-of-defun
)
2015 (setq-local end-of-defun-function
'ruby-end-of-defun
)
2017 (add-hook 'after-save-hook
'ruby-mode-set-encoding nil
'local
)
2019 (setq-local electric-indent-chars
(append '(?\
{ ?\
}) electric-indent-chars
))
2021 (setq-local font-lock-defaults
'((ruby-font-lock-keywords) nil nil
))
2022 (setq-local font-lock-keywords ruby-font-lock-keywords
)
2023 (setq-local font-lock-syntax-table ruby-font-lock-syntax-table
)
2025 (setq-local syntax-propertize-function
#'ruby-syntax-propertize-function
))
2027 ;;; Invoke ruby-mode when appropriate
2030 (add-to-list 'auto-mode-alist
2031 (cons (purecopy (concat "\\(?:\\."
2032 "rb\\|ru\\|rake\\|thor"
2033 "\\|jbuilder\\|gemspec"
2035 "\\(?:Gem\\|Rake\\|Cap\\|Thor"
2036 "Vagrant\\|Guard\\)file"
2037 "\\)\\'")) 'ruby-mode
))
2040 (dolist (name (list "ruby" "rbx" "jruby" "ruby1.9" "ruby1.8"))
2041 (add-to-list 'interpreter-mode-alist
(cons (purecopy name
) 'ruby-mode
)))
2043 (provide 'ruby-mode
)
2045 ;;; ruby-mode.el ends here