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.
42 (eval-when-compile (require 'cl
))
45 "Major mode for editing Ruby code."
49 (defconst ruby-block-beg-keywords
50 '("class" "module" "def" "if" "unless" "case" "while" "until" "for" "begin" "do")
51 "Keywords at the beginning of blocks.")
53 (defconst ruby-block-beg-re
54 (regexp-opt ruby-block-beg-keywords
)
55 "Regexp to match the beginning of blocks.")
57 (defconst ruby-non-block-do-re
58 (regexp-opt '("while" "until" "for" "rescue") 'symbols
)
59 "Regexp to match keywords that nest without blocks.")
61 (defconst ruby-indent-beg-re
62 (concat "^\\(\\s *" (regexp-opt '("class" "module" "def")) "\\|"
63 (regexp-opt '("if" "unless" "case" "while" "until" "for" "begin"))
65 "Regexp to match where the indentation gets deeper.")
67 (defconst ruby-modifier-beg-keywords
68 '("if" "unless" "while" "until")
69 "Modifiers that are the same as the beginning of blocks.")
71 (defconst ruby-modifier-beg-re
72 (regexp-opt ruby-modifier-beg-keywords
)
73 "Regexp to match modifiers same as the beginning of blocks.")
75 (defconst ruby-modifier-re
76 (regexp-opt (cons "rescue" ruby-modifier-beg-keywords
))
77 "Regexp to match modifiers.")
79 (defconst ruby-block-mid-keywords
80 '("then" "else" "elsif" "when" "rescue" "ensure")
81 "Keywords where the indentation gets shallower in middle of block statements.")
83 (defconst ruby-block-mid-re
84 (regexp-opt ruby-block-mid-keywords
)
85 "Regexp to match where the indentation gets shallower in middle of block statements.")
87 (defconst ruby-block-op-keywords
89 "Regexp to match boolean keywords.")
91 (defconst ruby-block-hanging-re
92 (regexp-opt (append ruby-modifier-beg-keywords ruby-block-op-keywords
))
93 "Regexp to match hanging block modifiers.")
95 (defconst ruby-block-end-re
"\\_<end\\_>")
97 (defconst ruby-defun-beg-re
98 '"\\(def\\|class\\|module\\)"
99 "Regexp to match the beginning of a defun, in the general sense.")
101 (defconst ruby-singleton-class-re
103 "Regexp to match the beginning of a singleton class context.")
106 (defconst ruby-here-doc-beg-re
107 "\\(<\\)<\\(-\\)?\\(\\([a-zA-Z0-9_]+\\)\\|[\"]\\([^\"]+\\)[\"]\\|[']\\([^']+\\)[']\\)"
108 "Regexp to match the beginning of a heredoc.")
110 (defconst ruby-expression-expansion-re
111 "\\(?:[^\\]\\|\\=\\)\\(\\\\\\\\\\)*\\(#\\({[^}\n\\\\]*\\(\\\\.[^}\n\\\\]*\\)*}\\|\\(\\$\\|@\\|@@\\)\\(\\w\\|_\\)+\\)\\)"))
113 (defun ruby-here-doc-end-match ()
114 "Return a regexp to find the end of a heredoc.
116 This should only be called after matching against `ruby-here-doc-beg-re'."
118 (if (match-string 2) "[ \t]*" nil
)
124 (defconst ruby-delimiter
125 (concat "[?$/%(){}#\"'`.:]\\|<<\\|\\[\\|\\]\\|\\_<\\("
127 "\\)\\_>\\|" ruby-block-end-re
128 "\\|^=begin\\|" ruby-here-doc-beg-re
))
130 (defconst ruby-negative
131 (concat "^[ \t]*\\(\\(" ruby-block-mid-re
"\\)\\>\\|"
132 ruby-block-end-re
"\\|}\\|\\]\\)")
133 "Regexp to match where the indentation gets shallower.")
135 (defconst ruby-operator-re
"[-,.+*/%&|^~=<>:]\\|\\\\$"
136 "Regexp to match operators.")
138 (defconst ruby-symbol-chars
"a-zA-Z0-9_"
139 "List of characters that symbol names may contain.")
141 (defconst ruby-symbol-re
(concat "[" ruby-symbol-chars
"]")
142 "Regexp to match symbols.")
144 (defvar ruby-use-smie t
)
146 (defvar ruby-mode-map
147 (let ((map (make-sparse-keymap)))
148 (unless ruby-use-smie
149 (define-key map
(kbd "M-C-b") 'ruby-backward-sexp
)
150 (define-key map
(kbd "M-C-f") 'ruby-forward-sexp
)
151 (define-key map
(kbd "M-C-q") 'ruby-indent-exp
))
153 (define-key map
(kbd "M-C-d") 'smie-down-list
))
154 (define-key map
(kbd "M-C-p") 'ruby-beginning-of-block
)
155 (define-key map
(kbd "M-C-n") 'ruby-end-of-block
)
156 (define-key map
(kbd "C-c {") 'ruby-toggle-block
)
158 "Keymap used in Ruby mode.")
165 ["Beginning of Block" ruby-beginning-of-block t
]
166 ["End of Block" ruby-end-of-block t
]
167 ["Toggle Block" ruby-toggle-block t
]
169 ["Backward Sexp" ruby-backward-sexp
170 :visible
(not ruby-use-smie
)]
171 ["Backward Sexp" backward-sexp
172 :visible ruby-use-smie
]
173 ["Forward Sexp" ruby-forward-sexp
174 :visible
(not ruby-use-smie
)]
175 ["Forward Sexp" forward-sexp
176 :visible ruby-use-smie
]
177 ["Indent Sexp" ruby-indent-exp
178 :visible
(not ruby-use-smie
)]
179 ["Indent Sexp" prog-indent-sexp
180 :visible ruby-use-smie
]))
182 (defvar ruby-mode-syntax-table
183 (let ((table (make-syntax-table)))
184 (modify-syntax-entry ?
\' "\"" table
)
185 (modify-syntax-entry ?
\" "\"" table
)
186 (modify-syntax-entry ?\
` "\"" table
)
187 (modify-syntax-entry ?
# "<" table
)
188 (modify-syntax-entry ?
\n ">" 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 (modify-syntax-entry ?\
} "){" table
)
209 (modify-syntax-entry ?\
[ "(]" table
)
210 (modify-syntax-entry ?\
] ")[" table
)
212 "Syntax table to use in Ruby mode.")
214 (defcustom ruby-indent-tabs-mode nil
215 "Indentation can insert tabs in Ruby mode if this is non-nil."
220 (defcustom ruby-indent-level
2
221 "Indentation of Ruby statements."
226 (defcustom ruby-comment-column
(default-value 'comment-column
)
227 "Indentation column of comments."
232 (defcustom ruby-deep-arglist t
233 "Deep indent lists in parenthesis when non-nil.
234 Also ignores spaces after parenthesis when 'space."
239 (defcustom ruby-deep-indent-paren
'(?\
( ?\
[ ?\
] t
)
240 "Deep indent lists in parenthesis when non-nil.
241 The value t means continuous line.
242 Also ignores spaces after parenthesis when 'space."
245 (defcustom ruby-deep-indent-paren-style
'space
246 "Default deep indent style."
247 :options
'(t nil space
) :group
'ruby
)
249 (defcustom ruby-encoding-map
250 '((us-ascii . nil
) ;; Do not put coding: us-ascii
251 (shift-jis . cp932
) ;; Emacs charset name of Shift_JIS
252 (shift_jis . cp932
) ;; MIME charset name of Shift_JIS
253 (japanese-cp932 . cp932
)) ;; Emacs charset name of CP932
254 "Alist to map encoding name from Emacs to Ruby.
255 Associating an encoding name with nil means it needs not be
256 explicitly declared in magic comment."
257 :type
'(repeat (cons (symbol :tag
"From") (symbol :tag
"To")))
260 (defcustom ruby-insert-encoding-magic-comment t
261 "Insert a magic Emacs 'coding' comment upon save if this is non-nil."
262 :type
'boolean
:group
'ruby
)
264 (defcustom ruby-use-encoding-map t
265 "Use `ruby-encoding-map' to set encoding magic comment if this is non-nil."
266 :type
'boolean
:group
'ruby
)
272 ;; Here's a simplified BNF grammar, for reference:
273 ;; http://www.cse.buffalo.edu/~regan/cse305/RubyBNF.pdf
274 (defconst ruby-smie-grammar
279 (insts (inst) (insts ";" insts
))
280 (inst (exp) (inst "iuwu-mod" exp
)
281 ;; Somewhat incorrect (both can be used multiple times),
282 ;; but avoids lots of conflicts:
283 (exp "and" exp
) (exp "or" exp
))
284 (exp (exp1) (exp "," exp
) (exp "=" exp
)
287 (exp1 (exp2) (exp2 "?" exp1
":" exp1
))
288 (exp2 ("def" insts
"end")
289 ("begin" insts-rescue-insts
"end")
291 ("class" insts
"end") ("module" insts
"end")
292 ("for" for-body
"end")
296 ("while" insts
"end")
297 ("until" insts
"end")
298 ("unless" insts
"end")
300 ("case" cases
"end"))
301 (formal-params ("opening-|" exp
"|"))
302 (for-body (for-head ";" insts
))
303 (for-head (id "in" exp
))
304 (cases (exp "then" insts
) ;; FIXME: Ruby also allows (exp ":" insts).
305 (cases "when" cases
) (insts "else" insts
))
306 (expseq (exp) );;(expseq "," expseq)
307 (hashvals (id "=>" exp1
) (hashvals "," hashvals
))
308 (insts-rescue-insts (insts)
309 (insts-rescue-insts "rescue" insts-rescue-insts
)
310 (insts-rescue-insts "ensure" insts-rescue-insts
))
311 (itheni (insts) (exp "then" insts
))
312 (ielsei (itheni) (itheni "else" insts
))
313 (if-body (ielsei) (if-body "elsif" if-body
)))
314 '((nonassoc "in") (assoc ";") (right " @ ")
315 (assoc ",") (right "=") (assoc "."))
318 '((assoc "rescue" "ensure"))
323 (right "+=" "-=" "*=" "/=" "%=" "**=" "&=" "|=" "^="
324 "<<=" ">>=" "&&=" "||=")
327 (left "*" "/" "%" "**")
328 ;; (left "|") ; FIXME: Conflicts with | after block parameters.
332 (nonassoc ">" ">=" "<" "<=")
333 (nonassoc "==" "===" "!=")
335 (left "<<" ">>"))))))
337 (defun ruby-smie--bosp ()
338 (save-excursion (skip-chars-backward " \t")
339 (or (bolp) (memq (char-before) '(?\
; ?=)))))
341 (defun ruby-smie--implicit-semi-p ()
343 (skip-chars-backward " \t")
345 (and (memq (char-before)
346 '(?\
; ?- ?+ ?* ?/ ?: ?. ?, ?\[ ?\( ?\{ ?\\ ?& ?> ?< ?% ?~ ?^))
347 ;; Make sure it's not the end of a regexp.
348 (not (eq (car (syntax-after (1- (point)))) 7)))
349 (and (eq (char-before) ?
\?)
350 (equal (save-excursion (ruby-smie--backward-token)) "?"))
351 (and (eq (char-before) ?
=)
352 (string-match "\\`\\s." (save-excursion
353 (ruby-smie--backward-token))))
354 (and (eq (car (syntax-after (1- (point)))) 2)
355 (member (save-excursion (ruby-smie--backward-token))
356 '("iuwu-mod" "and" "or")))
359 (eq (char-after) ?.
))))))
361 (defun ruby-smie--redundant-do-p (&optional skip
)
363 (if skip
(backward-word 1))
364 (member (nth 2 (smie-backward-sexp ";")) '("while" "until" "for"))))
366 (defun ruby-smie--opening-pipe-p ()
368 (if (eq ?|
(char-before)) (forward-char -
1))
369 (skip-chars-backward " \t\n")
370 (or (eq ?\
{ (char-before))
371 (looking-back "\\_<do" (- (point) 2)))))
373 (defun ruby-smie--args-separator-p (pos)
375 (< pos
(line-end-position))
376 (or (eq (char-syntax (preceding-char)) '?w
)
377 ;; FIXME: Check that the preceding token is not a keyword.
378 ;; This isn't very important most of the time, though.
379 (and (memq (preceding-char) '(?
! ??
))
380 (eq (char-syntax (char-before (1- (point)))) '?w
)))
383 (or (and (eq (char-syntax (char-after)) ?w
)
384 (not (looking-at (regexp-opt '("unless" "if" "while" "until"
385 "else" "elsif" "do" "end" "and" "or")
387 (memq (syntax-after pos
) '(7 15))
388 (looking-at "[([]\\|[-+!~:]\\sw")))))
390 (defun ruby-smie--at-dot-call ()
391 (and (eq ?w
(char-syntax (following-char)))
392 (eq (char-before) ?.
)
393 (not (eq (char-before (1- (point))) ?.
))))
395 (defun ruby-smie--forward-token ()
397 (skip-chars-forward " \t")
399 ((looking-at "\\s\"") ;A heredoc or a string.
400 (if (not (looking-at "\n"))
402 ;; Tokenize the whole heredoc as semicolon.
403 (goto-char (scan-sexps (point) 1))
405 ((and (looking-at "[\n#]")
406 (ruby-smie--implicit-semi-p)) ;Only add implicit ; when needed.
407 (if (eolp) (forward-char 1) (forward-comment 1))
410 (forward-comment (point-max))
412 ((looking-at ":\\s.+")
413 (goto-char (match-end 0)) (match-string 0)) ;; bug#15208.
414 ((and (< pos
(point))
416 (ruby-smie--args-separator-p (prog1 (point) (goto-char pos
)))))
419 (let ((dot (ruby-smie--at-dot-call))
420 (tok (smie-default-forward-token)))
422 (setq tok
(concat "." tok
)))
424 ((member tok
'("unless" "if" "while" "until"))
425 (if (save-excursion (forward-word -
1) (ruby-smie--bosp))
427 ((string-match "|[*&]?" tok
)
428 (forward-char (- 1 (length tok
)))
430 (if (ruby-smie--opening-pipe-p) "opening-|" tok
))
431 ((and (equal tok
"") (looking-at "\\\\\n"))
432 (goto-char (match-end 0)) (ruby-smie--forward-token))
435 ((not (ruby-smie--redundant-do-p 'skip
)) tok
)
436 ((> (save-excursion (forward-comment (point-max)) (point))
438 (ruby-smie--forward-token)) ;Fully redundant.
442 (defun ruby-smie--backward-token ()
444 (forward-comment (- (point)))
446 ((and (> pos
(line-end-position)) (ruby-smie--implicit-semi-p))
447 (skip-chars-forward " \t") ";")
448 ((and (bolp) (not (bobp))) ;Presumably a heredoc.
449 ;; Tokenize the whole heredoc as semicolon.
450 (goto-char (scan-sexps (point) -
1))
452 ((and (> pos
(point)) (not (bolp))
453 (ruby-smie--args-separator-p pos
))
454 ;; We have "ID SPC ID", which is a method call, but it binds less tightly
455 ;; than commas, since a method call can also be "ID ARG1, ARG2, ARG3".
456 ;; In some textbooks, "e1 @ e2" is used to mean "call e1 with arg e2".
459 (let ((tok (smie-default-backward-token))
460 (dot (ruby-smie--at-dot-call)))
462 (setq tok
(concat "." tok
)))
463 (when (and (eq ?
: (char-before)) (string-match "\\`\\s." tok
))
464 (forward-char -
1) (setq tok
(concat ":" tok
))) ;; bug#15208.
466 ((member tok
'("unless" "if" "while" "until"))
467 (if (ruby-smie--bosp)
470 (if (ruby-smie--opening-pipe-p) "opening-|" tok
))
471 ((string-match-p "|[*&]" tok
)
474 ((and (equal tok
"") (eq ?
\\ (char-before)) (looking-at "\n"))
475 (forward-char -
1) (ruby-smie--backward-token))
478 ((not (ruby-smie--redundant-do-p)) tok
)
479 ((> (save-excursion (forward-word 1)
480 (forward-comment (point-max)) (point))
482 (ruby-smie--backward-token)) ;Fully redundant.
486 (defun ruby-smie--indent-to-stmt ()
488 (smie-backward-sexp ";")
489 (cons 'column
(smie-indent-virtual))))
491 (defun ruby-smie-rules (kind token
)
492 (pcase (cons kind token
)
493 (`(:elem . basic
) ruby-indent-level
)
494 ;; "foo" "bar" is the concatenation of the two strings, so the second
495 ;; should be aligned with the first.
496 (`(:elem . args
) (if (looking-at "\\s\"") 0))
497 ;; (`(:after . ",") (smie-rule-separator kind))
500 ((smie-rule-parent-p "def" "begin" "do" "class" "module" "for"
501 "while" "until" "unless"
502 "if" "then" "elsif" "else" "when"
503 "rescue" "ensure" "{")
504 (smie-rule-parent ruby-indent-level
))
505 ;; For (invalid) code between switch and case.
506 ;; (if (smie-parent-p "switch") 4)
508 (`(:before .
,(or `"(" `"[" `"{"))
510 ((and (equal token
"{")
511 (not (smie-rule-prev-p "(" "{" "[" "," "=>" "=" "return" ";"))
514 (not (eq (preceding-char) ?
:))))
515 ;; Curly block opener.
516 (ruby-smie--indent-to-stmt))
517 ((smie-rule-hanging-p)
518 ;; Treat purely syntactic block-constructs as being part of their parent,
519 ;; when the opening statement is hanging.
520 (let ((state (smie-backward-sexp 'halfsexp
)))
521 (when (eq t
(car state
)) (goto-char (cadr state
))))
522 (cons 'column
(smie-indent-virtual)))))
523 (`(:after .
" @ ") (smie-rule-parent))
524 (`(:before .
"do") (ruby-smie--indent-to-stmt))
525 (`(,(or :before
:after
) .
".")
526 (unless (smie-rule-parent-p ".")
527 (smie-rule-parent ruby-indent-level
)))
528 (`(:before .
,(or `"else" `"then" `"elsif" `"rescue" `"ensure")) 0)
529 (`(:before .
,(or `"when"))
530 (if (not (smie-rule-sibling-p)) 0)) ;; ruby-indent-level
531 (`(:after .
,(or "=" "iuwu-mod" "+" "-" "*" "/" "&&" "||" "%" "**" "^" "&"
532 "<=>" ">" "<" ">=" "<=" "==" "===" "!=" "<<" ">>"
533 "+=" "-=" "*=" "/=" "%=" "**=" "&=" "|=" "^="
534 "<<=" ">>=" "&&=" "||=" "and" "or"))
535 (if (smie-rule-parent-p ";" nil
) ruby-indent-level
))
538 (defun ruby-imenu-create-index-in-block (prefix beg end
)
539 "Create an imenu index of methods inside a block."
540 (let ((index-alist '()) (case-fold-search nil
)
541 name next pos decl sing
)
543 (while (re-search-forward "^\\s *\\(\\(class\\s +\\|\\(class\\s *<<\\s *\\)\\|module\\s +\\)\\([^\(<\n ]+\\)\\|\\(def\\|alias\\)\\s +\\([^\(\n ]+\\)\\)" end t
)
544 (setq sing
(match-beginning 3))
545 (setq decl
(match-string 5))
546 (setq next
(match-end 0))
547 (setq name
(or (match-string 4) (match-string 6)))
548 (setq pos
(match-beginning 0))
550 ((string= "alias" decl
)
551 (if prefix
(setq name
(concat prefix name
)))
552 (push (cons name pos
) index-alist
))
553 ((string= "def" decl
)
557 ((string-match "^self\." name
)
558 (concat (substring prefix
0 -
1) (substring name
4)))
559 (t (concat prefix name
)))))
560 (push (cons name pos
) index-alist
)
561 (ruby-accurate-end-of-block end
))
563 (if (string= "self" name
)
564 (if prefix
(setq name
(substring prefix
0 -
1)))
565 (if prefix
(setq name
(concat (substring prefix
0 -
1) "::" name
)))
566 (push (cons name pos
) index-alist
))
567 (ruby-accurate-end-of-block end
)
570 (nconc (ruby-imenu-create-index-in-block
571 (concat name
(if sing
"." "#"))
572 next beg
) index-alist
))
576 (defun ruby-imenu-create-index ()
577 "Create an imenu index of all methods in the buffer."
578 (nreverse (ruby-imenu-create-index-in-block nil
(point-min) nil
)))
580 (defun ruby-accurate-end-of-block (&optional end
)
583 (end (or end
(point-max))))
584 (while (and (setq state
(apply 'ruby-parse-partial end state
))
585 (>= (nth 2 state
) 0) (< (point) end
)))))
587 (defun ruby-mode-variables ()
588 "Set up initial buffer-local variables for Ruby mode."
589 (setq indent-tabs-mode ruby-indent-tabs-mode
)
591 (smie-setup ruby-smie-grammar
#'ruby-smie-rules
592 :forward-token
#'ruby-smie--forward-token
593 :backward-token
#'ruby-smie--backward-token
)
594 (setq-local indent-line-function
'ruby-indent-line
))
595 (setq-local require-final-newline t
)
596 (setq-local comment-start
"# ")
597 (setq-local comment-end
"")
598 (setq-local comment-column ruby-comment-column
)
599 (setq-local comment-start-skip
"#+ *")
600 (setq-local parse-sexp-ignore-comments t
)
601 (setq-local parse-sexp-lookup-properties t
)
602 (setq-local paragraph-start
(concat "$\\|" page-delimiter
))
603 (setq-local paragraph-separate paragraph-start
)
604 (setq-local paragraph-ignore-fill-prefix t
))
606 (defun ruby-mode-set-encoding ()
607 "Insert a magic comment header with the proper encoding if necessary."
610 (goto-char (point-min))
611 (when (re-search-forward "[^\0-\177]" nil t
)
612 (goto-char (point-min))
614 (or save-buffer-coding-system
615 buffer-file-coding-system
)))
618 (or (coding-system-get coding-system
'mime-charset
)
619 (coding-system-change-eol-conversion coding-system nil
))))
623 (if ruby-use-encoding-map
624 (let ((elt (assq coding-system ruby-encoding-map
)))
625 (if elt
(cdr elt
) coding-system
))
629 (if (looking-at "^#!") (beginning-of-line 2))
630 (cond ((looking-at "\\s *#.*-\*-\\s *\\(en\\)?coding\\s *:\\s *\\([-a-z0-9_]*\\)\\s *\\(;\\|-\*-\\)")
631 (unless (string= (match-string 2) coding-system
)
632 (goto-char (match-beginning 2))
633 (delete-region (point) (match-end 2))
634 (and (looking-at "-\*-")
635 (let ((n (skip-chars-backward " ")))
636 (cond ((= n
0) (insert " ") (backward-char))
637 ((= n -
1) (insert " "))
639 (insert coding-system
)))
640 ((looking-at "\\s *#.*coding\\s *[:=]"))
641 (t (when ruby-insert-encoding-magic-comment
642 (insert "# -*- coding: " coding-system
" -*-\n"))))
643 (when (buffer-modified-p)
644 (basic-save-buffer-1)))))))
646 (defun ruby-current-indentation ()
647 "Return the indentation level of current line."
650 (back-to-indentation)
653 (defun ruby-indent-line (&optional ignored
)
654 "Correct the indentation of the current Ruby line."
656 (ruby-indent-to (ruby-calculate-indent)))
658 (defun ruby-indent-to (column)
659 "Indent the current line to COLUMN."
662 (and (< column
0) (error "Invalid nesting"))
663 (setq shift
(current-column))
666 (back-to-indentation)
667 (setq top
(current-column))
668 (skip-chars-backward " \t")
669 (if (>= shift top
) (setq shift
(- shift top
))
673 (move-to-column (+ column shift
))
675 (delete-region beg
(point))
678 (move-to-column (+ column shift
))))))
680 (defun ruby-special-char-p (&optional pos
)
681 "Return t if the character before POS is a special character.
682 If omitted, POS defaults to the current point.
683 Special characters are `?', `$', `:' when preceded by whitespace,
684 and `\\' when preceded by `?'."
685 (setq pos
(or pos
(point)))
686 (let ((c (char-before pos
)) (b (and (< (point-min) pos
)
687 (char-before (1- pos
)))))
688 (cond ((or (eq c ??
) (eq c ?$
)))
689 ((and (eq c ?
:) (or (not b
) (eq (char-syntax b
) ?
))))
690 ((eq c ?
\\) (eq b ??
)))))
692 (defun ruby-singleton-class-p (&optional pos
)
694 (when pos
(goto-char pos
))
696 (and (or (bolp) (not (eq (char-before (point)) ?_
)))
697 (looking-at ruby-singleton-class-re
))))
699 (defun ruby-expr-beg (&optional option
)
700 "Check if point is possibly at the beginning of an expression.
701 OPTION specifies the type of the expression.
702 Can be one of `heredoc', `modifier', `expr-qstr', `expr-re'."
704 (store-match-data nil
)
705 (let ((space (skip-chars-backward " \t"))
711 (and (looking-at "\\?")
712 (or (eq (char-syntax (char-before (point))) ?w
)
713 (ruby-special-char-p))))
715 ((looking-at ruby-operator-re
))
716 ((eq option
'heredoc
)
717 (and (< space
0) (not (ruby-singleton-class-p start
))))
718 ((or (looking-at "[\\[({,;]")
719 (and (looking-at "[!?]")
720 (or (not (eq option
'modifier
))
722 (save-excursion (forward-char -
1) (looking-at "\\Sw$"))))
723 (and (looking-at ruby-symbol-re
)
724 (skip-chars-backward ruby-symbol-chars
)
726 ((looking-at (regexp-opt
727 (append ruby-block-beg-keywords
728 ruby-block-op-keywords
729 ruby-block-mid-keywords
)
731 (goto-char (match-end 0))
732 (not (looking-at "\\s_\\|!")))
733 ((eq option
'expr-qstr
)
734 (looking-at "[a-zA-Z][a-zA-z0-9_]* +%[^ \t]"))
735 ((eq option
'expr-re
)
736 (looking-at "[a-zA-Z][a-zA-z0-9_]* +/[^ \t]"))
739 (defun ruby-forward-string (term &optional end no-error expand
)
741 (let ((n 1) (c (string-to-char term
))
743 (concat "[^\\]\\(\\\\\\\\\\)*\\([" term
"]\\|\\(#{\\)\\)")
744 (concat "[^\\]\\(\\\\\\\\\\)*[" term
"]"))))
745 (while (and (re-search-forward re end no-error
)
746 (if (match-beginning 3)
747 (ruby-forward-string "}{" end no-error nil
)
748 (> (setq n
(if (eq (char-before (point)) c
)
753 ((error "Unterminated string")))))
755 (defun ruby-deep-indent-paren-p (c)
757 (cond ((listp ruby-deep-indent-paren
)
758 (let ((deep (assoc c ruby-deep-indent-paren
)))
760 (or (cdr deep
) ruby-deep-indent-paren-style
))
761 ((memq c ruby-deep-indent-paren
)
762 ruby-deep-indent-paren-style
))))
763 ((eq c ruby-deep-indent-paren
) ruby-deep-indent-paren-style
)
764 ((eq c ?\
( ) ruby-deep-arglist
)))
766 (defun ruby-parse-partial (&optional end in-string nest depth pcol indent
)
767 "TODO: document throughout function body."
768 (or depth
(setq depth
0))
769 (or indent
(setq indent
0))
770 (when (re-search-forward ruby-delimiter end
'move
)
771 (let ((pnt (point)) w re expand
)
772 (goto-char (match-beginning 0))
774 ((and (memq (char-before) '(?
@ ?$
)) (looking-at "\\sw"))
776 ((looking-at "[\"`]") ;skip string
779 (ruby-forward-string (buffer-substring (point) (1+ (point))) end t t
))
782 (setq in-string
(point))
787 (re-search-forward "[^\\]\\(\\\\\\\\\\)*'" end t
))
790 (setq in-string
(point))
796 ((and (not (eobp)) (ruby-expr-beg 'expr-re
))
797 (if (ruby-forward-string "/" end t t
)
799 (setq in-string
(point))
806 (ruby-expr-beg 'expr-qstr
)
807 (not (looking-at "%="))
808 (looking-at "%[QqrxWw]?\\([^a-zA-Z0-9 \t\n]\\)"))
809 (goto-char (match-beginning 1))
810 (setq expand
(not (memq (char-before) '(?q ?w
))))
811 (setq w
(match-string 1))
813 ((string= w
"[") (setq re
"]["))
814 ((string= w
"{") (setq re
"}{"))
815 ((string= w
"(") (setq re
")("))
816 ((string= w
"<") (setq re
"><"))
817 ((and expand
(string= w
"\\"))
818 (setq w
(concat "\\" w
))))
819 (unless (cond (re (ruby-forward-string re end t expand
))
820 (expand (ruby-forward-string w end t t
))
821 (t (re-search-forward
824 (concat "[^\\]\\(\\\\\\\\\\)*" w
))
826 (setq in-string
(point))
830 ((looking-at "\\?") ;skip ?char
832 ((and (ruby-expr-beg)
833 (looking-at "?\\(\\\\C-\\|\\\\M-\\)*\\\\?."))
834 (goto-char (match-end 0)))
837 ((looking-at "\\$") ;skip $char
840 ((looking-at "#") ;skip comment
844 ((looking-at "[\\[{(]")
845 (let ((deep (ruby-deep-indent-paren-p (char-after))))
846 (if (and deep
(or (not (eq (char-after) ?\
{)) (ruby-expr-beg)))
848 (and (eq deep
'space
) (looking-at ".\\s +[^# \t\n]")
849 (setq pnt
(1- (match-end 0))))
850 (setq nest
(cons (cons (char-after (point)) pnt
) nest
))
851 (setq pcol
(cons (cons pnt depth
) pcol
))
853 (setq nest
(cons (cons (char-after (point)) pnt
) nest
))
854 (setq depth
(1+ depth
))))
857 ((looking-at "[])}]")
858 (if (ruby-deep-indent-paren-p (matching-paren (char-after)))
859 (setq depth
(cdr (car pcol
)) pcol
(cdr pcol
))
860 (setq depth
(1- depth
)))
861 (setq nest
(cdr nest
))
863 ((looking-at ruby-block-end-re
)
864 (if (or (and (not (bolp))
867 (setq w
(char-after (point)))
872 (setq w
(char-after (point)))
877 (setq nest
(cdr nest
))
878 (setq depth
(1- depth
)))
880 ((looking-at "def\\s +[^(\n;]*")
884 (not (eq ?_
(char-after (point))))))
886 (setq nest
(cons (cons nil pnt
) nest
))
887 (setq depth
(1+ depth
))))
888 (goto-char (match-end 0)))
889 ((looking-at (concat "\\_<\\(" ruby-block-beg-re
"\\)\\_>"))
892 (or (not (looking-at "do\\_>"))
894 (back-to-indentation)
895 (not (looking-at ruby-non-block-do-re
)))))
899 (setq w
(char-after (point)))
903 (not (eq ?
! (char-after (point))))
904 (skip-chars-forward " \t")
905 (goto-char (match-beginning 0))
906 (or (not (looking-at ruby-modifier-re
))
907 (ruby-expr-beg 'modifier
))
909 (setq nest
(cons (cons nil pnt
) nest
))
910 (setq depth
(1+ depth
)))
912 ((looking-at ":\\(['\"]\\)")
913 (goto-char (match-beginning 1))
914 (ruby-forward-string (match-string 1) end t
))
915 ((looking-at ":\\([-,.+*/%&|^~<>]=?\\|===?\\|<=>\\|![~=]?\\)")
916 (goto-char (match-end 0)))
917 ((looking-at ":\\([a-zA-Z_][a-zA-Z_0-9]*[!?=]?\\)?")
918 (goto-char (match-end 0)))
919 ((or (looking-at "\\.\\.\\.?")
920 (looking-at "\\.[0-9]+")
921 (looking-at "\\.[a-zA-Z_0-9]+")
923 (goto-char (match-end 0)))
924 ((looking-at "^=begin")
925 (if (re-search-forward "^=end" end t
)
927 (setq in-string
(match-end 0))
931 ((and (ruby-expr-beg 'heredoc
)
932 (looking-at "<<\\(-\\)?\\(\\([\"'`]\\)\\([^\n]+?\\)\\3\\|\\(?:\\sw\\|\\s_\\)+\\)"))
933 (setq re
(regexp-quote (or (match-string 4) (match-string 2))))
934 (if (match-beginning 1) (setq re
(concat "\\s *" re
)))
935 (let* ((id-end (goto-char (match-end 0)))
936 (line-end-position (point-at-eol))
937 (state (list in-string nest depth pcol indent
)))
938 ;; parse the rest of the line
939 (while (and (> line-end-position
(point))
940 (setq state
(apply 'ruby-parse-partial
941 line-end-position state
))))
942 (setq in-string
(car state
)
946 indent
(nth 4 state
))
947 ;; skip heredoc section
948 (if (re-search-forward (concat "^" re
"$") end
'move
)
950 (setq in-string id-end
)
954 ((looking-at "^__END__$")
956 ((and (looking-at ruby-here-doc-beg-re
)
957 (boundp 'ruby-indent-point
))
958 (if (re-search-forward (ruby-here-doc-end-match)
961 (setq in-string
(match-end 0))
962 (goto-char ruby-indent-point
)))
964 (error (format "Bad string %s"
965 (buffer-substring (point) pnt
)
967 (list in-string nest depth pcol
))
969 (defun ruby-parse-region (start end
)
975 (ruby-beginning-of-indent))
977 (narrow-to-region (point) end
)
978 (while (and (> end
(point))
979 (setq state
(apply 'ruby-parse-partial end state
))))))
980 (list (nth 0 state
) ; in-string
981 (car (nth 1 state
)) ; nest
982 (nth 2 state
) ; depth
983 (car (car (nth 3 state
))) ; pcol
984 ;(car (nth 5 state)) ; indent
987 (defun ruby-indent-size (pos nest
)
988 "Return the indentation level in spaces NEST levels deeper than POS."
989 (+ pos
(* (or nest
1) ruby-indent-level
)))
991 (defun ruby-calculate-indent (&optional parse-start
)
992 "Return the proper indentation level of the current line."
993 ;; TODO: Document body
996 (let ((ruby-indent-point (point))
997 (case-fold-search nil
)
998 state eol begin op-end
999 (paren (progn (skip-syntax-forward " ")
1000 (and (char-after) (matching-paren (char-after)))))
1003 (goto-char parse-start
)
1004 (ruby-beginning-of-indent)
1005 (setq parse-start
(point)))
1006 (back-to-indentation)
1007 (setq indent
(current-column))
1008 (setq state
(ruby-parse-region parse-start ruby-indent-point
))
1010 ((nth 0 state
) ; within string
1011 (setq indent nil
)) ; do nothing
1012 ((car (nth 1 state
)) ; in paren
1013 (goto-char (setq begin
(cdr (nth 1 state
))))
1014 (let ((deep (ruby-deep-indent-paren-p (car (nth 1 state
)))))
1016 (cond ((and (eq deep t
) (eq (car (nth 1 state
)) paren
))
1017 (skip-syntax-backward " ")
1018 (setq indent
(1- (current-column))))
1019 ((let ((s (ruby-parse-region (point) ruby-indent-point
)))
1020 (and (nth 2 s
) (> (nth 2 s
) 0)
1021 (or (goto-char (cdr (nth 1 s
))) t
)))
1023 (setq indent
(ruby-indent-size (current-column)
1026 (setq indent
(current-column))
1027 (cond ((eq deep
'space
))
1028 (paren (setq indent
(1- indent
)))
1029 (t (setq indent
(ruby-indent-size (1- indent
) 1))))))
1030 (if (nth 3 state
) (goto-char (nth 3 state
))
1031 (goto-char parse-start
) (back-to-indentation))
1032 (setq indent
(ruby-indent-size (current-column) (nth 2 state
))))
1033 (and (eq (car (nth 1 state
)) paren
)
1034 (ruby-deep-indent-paren-p (matching-paren paren
))
1035 (search-backward (char-to-string paren
))
1036 (setq indent
(current-column)))))
1037 ((and (nth 2 state
) (> (nth 2 state
) 0)) ; in nest
1038 (if (null (cdr (nth 1 state
)))
1039 (error "Invalid nesting"))
1040 (goto-char (cdr (nth 1 state
)))
1041 (forward-word -
1) ; skip back a keyword
1042 (setq begin
(point))
1044 ((looking-at "do\\>[^_]") ; iter block is a special case
1045 (if (nth 3 state
) (goto-char (nth 3 state
))
1046 (goto-char parse-start
) (back-to-indentation))
1047 (setq indent
(ruby-indent-size (current-column) (nth 2 state
))))
1049 (setq indent
(+ (current-column) ruby-indent-level
)))))
1051 ((and (nth 2 state
) (< (nth 2 state
) 0)) ; in negative nest
1052 (setq indent
(ruby-indent-size (current-column) (nth 2 state
)))))
1054 (goto-char ruby-indent-point
)
1059 ((and (not (ruby-deep-indent-paren-p paren
))
1060 (re-search-forward ruby-negative eol t
))
1061 (and (not (eq ?_
(char-after (match-end 0))))
1062 (setq indent
(- indent ruby-indent-level
))))
1067 (or (ruby-deep-indent-paren-p t
)
1068 (null (car (nth 1 state
)))))
1069 ;; goto beginning of non-empty no-comment line
1072 (skip-chars-backward " \t\n")
1075 (if (re-search-forward "^\\s *#" end t
)
1079 ;; skip the comment at the end
1080 (skip-chars-backward " \t")
1081 (let (end (pos (point)))
1083 (while (and (re-search-forward "#" pos t
)
1084 (setq end
(1- (point)))
1085 (or (ruby-special-char-p end
)
1086 (and (setq state
(ruby-parse-region parse-start end
))
1089 (goto-char (or end pos
))
1090 (skip-chars-backward " \t")
1091 (setq begin
(if (and end
(nth 0 state
)) pos
(cdr (nth 1 state
))))
1092 (setq state
(ruby-parse-region parse-start
(point))))
1093 (or (bobp) (forward-char -
1))
1095 (or (and (looking-at ruby-symbol-re
)
1096 (skip-chars-backward ruby-symbol-chars
)
1097 (looking-at (concat "\\<\\(" ruby-block-hanging-re
"\\)\\>"))
1098 (not (eq (point) (nth 3 state
)))
1100 (goto-char (match-end 0))
1101 (not (looking-at "[a-z_]"))))
1102 (and (looking-at ruby-operator-re
)
1103 (not (ruby-special-char-p))
1106 (or (not (looking-at ruby-operator-re
))
1107 (not (eq (char-before) ?
:))))
1108 ;; Operator at the end of line.
1109 (let ((c (char-after (point))))
1113 ;; (goto-char begin)
1114 ;; (skip-chars-forward " \t")
1115 ;; (not (or (eolp) (looking-at "#")
1116 ;; (and (eq (car (nth 1 state)) ?{)
1117 ;; (looking-at "|"))))))
1118 ;; Not a regexp or percent literal.
1119 (null (nth 0 (ruby-parse-region (or begin parse-start
)
1121 (or (not (eq ?|
(char-after (point))))
1123 (or (eolp) (forward-char -
1))
1125 ((search-backward "|" nil t
)
1126 (skip-chars-backward " \t\n")
1130 (not (looking-at "{")))
1133 (not (looking-at "do\\>[^_]")))))
1141 (not (looking-at (concat "\\<\\(" ruby-block-hanging-re
"\\)\\>")))
1142 (eq (ruby-deep-indent-paren-p t
) 'space
)
1145 (goto-char (or begin parse-start
))
1146 (skip-syntax-forward " ")
1148 ((car (nth 1 state
)) indent
)
1150 (+ indent ruby-indent-level
))))))))
1151 (goto-char ruby-indent-point
)
1153 (skip-syntax-forward " ")
1154 (if (looking-at "\\.[^.]")
1155 (+ indent ruby-indent-level
)
1158 (defun ruby-beginning-of-defun (&optional arg
)
1159 "Move backward to the beginning of the current defun.
1160 With ARG, move backward multiple defuns. Negative ARG means
1163 (let (case-fold-search)
1164 (and (re-search-backward (concat "^\\s *" ruby-defun-beg-re
"\\_>")
1166 (beginning-of-line))))
1168 (defun ruby-end-of-defun ()
1169 "Move point to the end of the current defun.
1170 The defun begins at or after the point. This function is called
1174 (let (case-fold-search)
1175 (when (looking-back (concat "^\\s *" ruby-block-end-re
))
1178 (defun ruby-beginning-of-indent ()
1179 "Backtrack to a line which can be used as a reference for
1180 calculating indentation on the lines after it."
1181 (while (and (re-search-backward ruby-indent-beg-re nil
'move
)
1182 (if (ruby-in-ppss-context-p 'anything
)
1184 ;; We can stop, then.
1185 (beginning-of-line)))))
1187 (defun ruby-move-to-block (n)
1188 "Move to the beginning (N < 0) or the end (N > 0) of the
1189 current block, a sibling block, or an outer block. Do that (abs N) times."
1190 (back-to-indentation)
1191 (let ((signum (if (> n
0) 1 -
1))
1193 (depth (or (nth 2 (ruby-parse-region (point) (line-end-position))) 0))
1196 (when (looking-at ruby-block-mid-re
)
1197 (setq depth
(+ depth signum
)))
1198 (when (< (* depth signum
) 0)
1199 ;; Moving end -> end or beginning -> beginning.
1201 (dotimes (_ (abs n
))
1203 (setq down
(save-excursion
1204 (back-to-indentation)
1205 ;; There is a block start or block end keyword on this
1206 ;; line, don't need to look for another block.
1207 (and (re-search-forward
1208 (if backward ruby-block-end-re
1209 (concat "\\_<\\(" ruby-block-beg-re
"\\)\\_>"))
1210 (line-end-position) t
)
1211 (not (nth 8 (syntax-ppss))))))
1212 (while (and (not done
) (not (if backward
(bobp) (eobp))))
1213 (forward-line signum
)
1215 ;; Skip empty and commented out lines.
1216 ((looking-at "^\\s *$"))
1217 ((looking-at "^\\s *#"))
1218 ;; Skip block comments;
1219 ((and (not backward
) (looking-at "^=begin\\>"))
1220 (re-search-forward "^=end\\>"))
1221 ((and backward
(looking-at "^=end\\>"))
1222 (re-search-backward "^=begin\\>"))
1223 ;; Jump over a multiline literal.
1224 ((ruby-in-ppss-context-p 'string
)
1225 (goto-char (nth 8 (syntax-ppss)))
1228 (when (bolp) (forward-char -
1)))) ; After a heredoc.
1230 (let ((state (ruby-parse-region (point) (line-end-position))))
1231 (unless (car state
) ; Line ends with unfinished string.
1232 (setq depth
(+ (nth 2 state
) depth
))))
1234 ;; Increased depth, we found a block.
1235 ((> (* signum depth
) 0)
1237 ;; We're at the same depth as when we started, and we've
1238 ;; encountered a block before. Stop.
1239 ((and down
(zerop depth
))
1241 ;; Lower depth, means outer block, can stop now.
1242 ((< (* signum depth
) 0)
1244 (back-to-indentation)))
1246 (defun ruby-beginning-of-block (&optional arg
)
1247 "Move backward to the beginning of the current block.
1248 With ARG, move up multiple blocks."
1250 (ruby-move-to-block (- (or arg
1))))
1252 (defun ruby-end-of-block (&optional arg
)
1253 "Move forward to the end of the current block.
1254 With ARG, move out of multiple blocks."
1256 (ruby-move-to-block (or arg
1)))
1258 (defun ruby-forward-sexp (&optional arg
)
1259 "Move forward across one balanced expression (sexp).
1260 With ARG, do it many times. Negative ARG means move backward."
1261 ;; TODO: Document body
1264 (ruby-use-smie (forward-sexp arg
))
1265 ((and (numberp arg
) (< arg
0)) (ruby-backward-sexp (- arg
)))
1267 (let ((i (or arg
1)))
1270 (skip-syntax-forward " ")
1271 (if (looking-at ",\\s *") (goto-char (match-end 0)))
1272 (cond ((looking-at "\\?\\(\\\\[CM]-\\)*\\\\?\\S ")
1273 (goto-char (match-end 0)))
1275 (skip-chars-forward ",.:;|&^~=!?\\+\\-\\*")
1276 (looking-at "\\s("))
1277 (goto-char (scan-sexps (point) 1)))
1278 ((and (looking-at (concat "\\<\\(" ruby-block-beg-re
"\\)\\>"))
1279 (not (eq (char-before (point)) ?.
))
1280 (not (eq (char-before (point)) ?
:)))
1283 ((looking-at "\\(\\$\\|@@?\\)?\\sw")
1285 (while (progn (forward-word 1) (looking-at "_")))
1286 (cond ((looking-at "::") (forward-char 2) t
)
1287 ((> (skip-chars-forward ".") 0))
1288 ((looking-at "\\?\\|!\\(=[~=>]\\|[^~=]\\)")
1289 (forward-char 1) nil
)))))
1293 (setq expr
(or expr
(ruby-expr-beg)
1294 (looking-at "%\\sw?\\Sw\\|[\"'`/]")))
1295 (nth 1 (setq state
(apply 'ruby-parse-partial nil state
))))
1297 (skip-chars-forward "<"))
1300 ((error) (forward-word 1)))
1303 (defun ruby-backward-sexp (&optional arg
)
1304 "Move backward across one balanced expression (sexp).
1305 With ARG, do it many times. Negative ARG means move forward."
1306 ;; TODO: Document body
1309 (ruby-use-smie (backward-sexp arg
))
1310 ((and (numberp arg
) (< arg
0)) (ruby-forward-sexp (- arg
)))
1312 (let ((i (or arg
1)))
1315 (skip-chars-backward " \t\n,.:;|&^~=!?\\+\\-\\*")
1317 (cond ((looking-at "\\s)")
1318 (goto-char (scan-sexps (1+ (point)) -
1))
1320 (?%
(forward-char -
1))
1321 ((?q ?Q ?w ?W ?r ?x
)
1322 (if (eq (char-before (1- (point))) ?%
) (forward-char -
2))))
1324 ((looking-at "\\s\"\\|\\\\\\S_")
1325 (let ((c (char-to-string (char-before (match-end 0)))))
1326 (while (and (search-backward c
)
1327 (eq (logand (skip-chars-backward "\\") 1)
1330 ((looking-at "\\s.\\|\\s\\")
1331 (if (ruby-special-char-p) (forward-char -
1)))
1332 ((looking-at "\\s(") nil
)
1335 (while (progn (forward-word -
1)
1338 (?.
(forward-char -
1) t
)
1341 (and (eq (char-before) (char-after)) (forward-char -
1)))
1344 (eq (char-before) :)))))
1345 (if (looking-at ruby-block-end-re
)
1346 (ruby-beginning-of-block))
1352 (defun ruby-indent-exp (&optional ignored
)
1353 "Indent each line in the balanced expression following the point."
1355 (let ((here (point-marker)) start top column
(nest t
))
1356 (set-marker-insertion-type here t
)
1360 (setq start
(point) top
(current-indentation))
1361 (while (and (not (eobp))
1363 (setq column
(ruby-calculate-indent start
))
1364 (cond ((> column top
)
1366 ((and (= column top
) nest
)
1367 (setq nest nil
) t
))))
1368 (ruby-indent-to column
)
1369 (beginning-of-line 2)))
1371 (set-marker here nil
))))
1373 (defun ruby-add-log-current-method ()
1374 "Return the current method name as a string.
1375 This string includes all namespaces.
1384 See `add-log-current-defun-function'."
1387 (let* ((indent 0) mname mlist
1391 (concat "^[ \t]*" re
"[ \t]+"
1393 ;; \\. and :: for class methods
1394 "\\([A-Za-z_]" ruby-symbol-re
"*\\|\\.\\|::" "\\)"
1396 (definition-re (funcall make-definition-re ruby-defun-beg-re
))
1397 (module-re (funcall make-definition-re
"\\(class\\|module\\)")))
1398 ;; Get the current method definition (or class/module).
1399 (when (re-search-backward definition-re nil t
)
1400 (goto-char (match-beginning 1))
1401 (if (not (string-equal "def" (match-string 1)))
1402 (setq mlist
(list (match-string 2)))
1403 ;; We're inside the method. For classes and modules,
1404 ;; this check is skipped for performance.
1405 (when (ruby-block-contains-point start
)
1406 (setq mname
(match-string 2))))
1407 (setq indent
(current-column))
1408 (beginning-of-line))
1409 ;; Walk up the class/module nesting.
1410 (while (and (> indent
0)
1411 (re-search-backward module-re nil t
))
1412 (goto-char (match-beginning 1))
1413 (when (< (current-column) indent
)
1414 (setq mlist
(cons (match-string 2) mlist
))
1415 (setq indent
(current-column))
1416 (beginning-of-line)))
1417 ;; Process the method name.
1419 (let ((mn (split-string mname
"\\.\\|::")))
1422 (unless (string-equal "self" (car mn
)) ; def self.foo
1424 (let ((ml (nreverse mlist
)))
1425 ;; If the method name references one of the
1426 ;; containing modules, drop the more nested ones.
1428 (if (string-equal (car ml
) (car mn
))
1429 (setq mlist
(nreverse (cdr ml
)) ml nil
))
1430 (or (setq ml
(cdr ml
)) (nreverse mlist
))))
1432 (setcdr (last mlist
) (butlast mn
))
1433 (setq mlist
(butlast mn
))))
1434 (setq mname
(concat "." (car (last mn
)))))
1435 ;; See if the method is in singleton class context.
1436 (let ((in-singleton-class
1437 (when (re-search-forward ruby-singleton-class-re start t
)
1438 (goto-char (match-beginning 0))
1439 ;; FIXME: Optimize it out, too?
1440 ;; This can be slow in a large file, but
1441 ;; unlike class/module declaration
1442 ;; indentations, method definitions can be
1443 ;; intermixed with these, and may or may not
1444 ;; be additionally indented after visibility
1446 (ruby-block-contains-point start
))))
1448 (if in-singleton-class
"." "#")
1450 ;; Generate the string.
1452 (setq mlist
(mapconcat (function identity
) mlist
"::")))
1454 (if mlist
(concat mlist mname
) mname
)
1457 (defun ruby-block-contains-point (pt)
1463 (defun ruby-brace-to-do-end (orig end
)
1464 (let (beg-marker end-marker
)
1466 (when (eq (char-before) ?\
})
1468 (when (save-excursion
1469 (skip-chars-backward " \t")
1473 (setq end-marker
(point-marker))
1474 (when (and (not (eobp)) (eq (char-syntax (char-after)) ?w
))
1478 (when (eq (char-syntax (char-before)) ?w
)
1481 (setq beg-marker
(point-marker))
1482 (when (looking-at "\\(\\s \\)*|")
1483 (unless (match-beginning 1)
1485 (goto-char (1+ (match-end 0)))
1486 (search-forward "|"))
1487 (unless (looking-at "\\s *$")
1489 (indent-region beg-marker end-marker
)
1490 (goto-char beg-marker
)
1493 (defun ruby-do-end-to-brace (orig end
)
1494 (let (beg-marker end-marker beg-pos end-pos
)
1495 (goto-char (- end
3))
1496 (when (looking-at ruby-block-end-re
)
1498 (setq end-marker
(point-marker))
1502 ;; Maybe this should be customizable, let's see if anyone asks.
1504 (setq beg-marker
(point-marker))
1505 (when (looking-at "\\s +|")
1506 (delete-char (- (match-end 0) (match-beginning 0) 1))
1508 (re-search-forward "|" (line-end-position) t
))
1510 (skip-chars-forward " \t\n\r")
1511 (setq beg-pos
(point))
1512 (goto-char end-marker
)
1513 (skip-chars-backward " \t\n\r")
1514 (setq end-pos
(point)))
1517 (and (= (line-number-at-pos beg-pos
) (line-number-at-pos end-pos
))
1518 (< (+ (current-column) (- end-pos beg-pos
) 2) fill-column
)))
1520 (goto-char end-marker
)
1521 (just-one-space -
1))
1522 (goto-char beg-marker
)
1525 (defun ruby-toggle-block ()
1526 "Toggle block type from do-end to braces or back.
1527 The block must begin on the current line or above it and end after the point.
1528 If the result is do-end block, it will always be multiline."
1530 (let ((start (point)) beg end
)
1533 (if (and (re-search-backward "\\({\\)\\|\\_<do\\(\\s \\|$\\||\\)")
1536 (save-match-data (ruby-forward-sexp))
1539 (if (match-beginning 1)
1540 (ruby-brace-to-do-end beg end
)
1541 (ruby-do-end-to-brace beg end
)))
1542 (goto-char start
))))
1545 (defconst ruby-percent-literal-beg-re
1546 "\\(%\\)[qQrswWxIi]?\\([[:punct:]]\\)"
1547 "Regexp to match the beginning of percent literal.")
1549 (defconst ruby-syntax-methods-before-regexp
1550 '("gsub" "gsub!" "sub" "sub!" "scan" "split" "split!" "index" "match"
1551 "assert_match" "Given" "Then" "When")
1552 "Methods that can take regexp as the first argument.
1553 It will be properly highlighted even when the call omits parens.")
1555 (defvar ruby-syntax-before-regexp-re
1557 ;; Special tokens that can't be followed by a division operator.
1559 ;; Distinguish ternary operator tokens.
1560 ;; FIXME: They don't really have to be separated with spaces.
1562 ;; Control flow keywords and operators following bol or whitespace.
1563 "\\|\\(?:^\\|\\s \\)"
1564 (regexp-opt '("if" "elsif" "unless" "while" "until" "when" "and"
1565 "or" "not" "&&" "||"))
1566 ;; Method name from the list.
1568 (regexp-opt ruby-syntax-methods-before-regexp
)
1570 "Regexp to match text that can be followed by a regular expression."))
1572 (defun ruby-syntax-propertize-function (start end
)
1573 "Syntactic keywords for Ruby mode. See `syntax-propertize-function'."
1574 (let (case-fold-search)
1576 (remove-text-properties start end
'(ruby-expansion-match-data))
1577 (ruby-syntax-propertize-heredoc end
)
1578 (ruby-syntax-enclosing-percent-literal end
)
1580 (syntax-propertize-rules
1581 ;; $' $" $` .... are variables.
1582 ;; ?' ?" ?` are character literals (one-char strings in 1.9+).
1583 ("\\([?$]\\)[#\"'`]"
1584 (1 (unless (save-excursion
1585 ;; Not within a string.
1586 (nth 3 (syntax-ppss (match-beginning 0))))
1587 (string-to-syntax "\\"))))
1588 ;; Regular expressions. Start with matching unescaped slash.
1589 ("\\(?:\\=\\|[^\\]\\)\\(?:\\\\\\\\\\)*\\(/\\)"
1590 (1 (let ((state (save-excursion (syntax-ppss (match-beginning 1)))))
1592 ;; Beginning of a regexp.
1593 (and (null (nth 8 state
))
1596 (looking-back ruby-syntax-before-regexp-re
1598 ;; End of regexp. We don't match the whole
1599 ;; regexp at once because it can have
1600 ;; string interpolation inside, or span
1602 (eq ?
/ (nth 3 state
)))
1603 (string-to-syntax "\"/")))))
1604 ;; Expression expansions in strings. We're handling them
1605 ;; here, so that the regexp rule never matches inside them.
1606 (ruby-expression-expansion-re
1607 (0 (ignore (ruby-syntax-propertize-expansion))))
1608 ("^=en\\(d\\)\\_>" (1 "!"))
1609 ("^\\(=\\)begin\\_>" (1 "!"))
1610 ;; Handle here documents.
1611 ((concat ruby-here-doc-beg-re
".*\\(\n\\)")
1612 (7 (unless (or (nth 8 (save-excursion
1613 (syntax-ppss (match-beginning 0))))
1614 (ruby-singleton-class-p (match-beginning 0)))
1615 (put-text-property (match-beginning 7) (match-end 7)
1616 'syntax-table
(string-to-syntax "\""))
1617 (ruby-syntax-propertize-heredoc end
))))
1618 ;; Handle percent literals: %w(), %q{}, etc.
1619 ((concat "\\(?:^\\|[[ \t\n<+(,=]\\)" ruby-percent-literal-beg-re
)
1620 (1 (prog1 "|" (ruby-syntax-propertize-percent-literal end
)))))
1623 (defun ruby-syntax-propertize-heredoc (limit)
1624 (let ((ppss (syntax-ppss))
1626 (when (eq ?
\n (nth 3 ppss
))
1628 (goto-char (nth 8 ppss
))
1630 (while (re-search-forward ruby-here-doc-beg-re
1631 (line-end-position) t
)
1632 (unless (ruby-singleton-class-p (match-beginning 0))
1633 (push (concat (ruby-here-doc-end-match) "\n") res
))))
1635 ;; With multiple openers on the same line, we don't know in which
1636 ;; part `start' is, so we have to go back to the beginning.
1638 (goto-char (nth 8 ppss
))
1639 (setq res
(nreverse res
)))
1640 (while (and res
(re-search-forward (pop res
) limit
'move
))
1642 (put-text-property (1- (point)) (point)
1643 'syntax-table
(string-to-syntax "\""))))
1644 ;; End up at bol following the heredoc openers.
1645 ;; Propertize expression expansions from this point forward.
1648 (defun ruby-syntax-enclosing-percent-literal (limit)
1649 (let ((state (syntax-ppss))
1651 ;; When already inside percent literal, re-propertize it.
1652 (when (eq t
(nth 3 state
))
1653 (goto-char (nth 8 state
))
1654 (when (looking-at ruby-percent-literal-beg-re
)
1655 (ruby-syntax-propertize-percent-literal limit
))
1656 (when (< (point) start
) (goto-char start
)))))
1658 (defun ruby-syntax-propertize-percent-literal (limit)
1659 (goto-char (match-beginning 2))
1660 ;; Not inside a simple string or comment.
1661 (when (eq t
(nth 3 (syntax-ppss)))
1662 (let* ((op (char-after))
1663 (ops (char-to-string op
))
1664 (cl (or (cdr (aref (syntax-table) op
))
1665 (cdr (assoc op
'((?
< . ?
>))))))
1666 parse-sexp-lookup-properties
)
1670 (if cl
; Paired delimiters.
1671 ;; Delimiter pairs of the same kind can be nested
1672 ;; inside the literal, as long as they are balanced.
1673 ;; Create syntax table that ignores other characters.
1674 (with-syntax-table (make-char-table 'syntax-table nil
)
1675 (modify-syntax-entry op
(concat "(" (char-to-string cl
)))
1676 (modify-syntax-entry cl
(concat ")" ops
))
1677 (modify-syntax-entry ?
\\ "\\")
1679 (narrow-to-region (point) limit
)
1680 (forward-list))) ; skip to the paired character
1681 ;; Single character delimiter.
1682 (re-search-forward (concat "[^\\]\\(?:\\\\\\\\\\)*"
1683 (regexp-quote ops
)) limit nil
))
1684 ;; Found the closing delimiter.
1685 (put-text-property (1- (point)) (point) 'syntax-table
1686 (string-to-syntax "|")))
1687 ;; Unclosed literal, do nothing.
1688 ((scan-error search-failed
)))))))
1690 (defun ruby-syntax-propertize-expansion ()
1691 ;; Save the match data to a text property, for font-locking later.
1692 ;; Set the syntax of all double quotes and backticks to punctuation.
1693 (let* ((beg (match-beginning 2))
1695 (state (and beg
(save-excursion (syntax-ppss beg
)))))
1696 (when (ruby-syntax-expansion-allowed-p state
)
1697 (put-text-property beg
(1+ beg
) 'ruby-expansion-match-data
1700 (while (re-search-forward "[\"`]" end
'move
)
1701 (put-text-property (match-beginning 0) (match-end 0)
1702 'syntax-table
(string-to-syntax "."))))))
1704 (defun ruby-syntax-expansion-allowed-p (parse-state)
1705 "Return non-nil if expression expansion is allowed."
1706 (let ((term (nth 3 parse-state
)))
1708 ((memq term
'(?
\" ?
` ?
\n ?
/)))
1712 (goto-char (nth 8 parse-state
))
1713 (looking-at "%\\(?:[QWrxI]\\|\\W\\)")))))))
1715 (defun ruby-syntax-propertize-expansions (start end
)
1718 (while (re-search-forward ruby-expression-expansion-re end
'move
)
1719 (ruby-syntax-propertize-expansion))))
1721 (defun ruby-in-ppss-context-p (context &optional ppss
)
1722 (let ((ppss (or ppss
(syntax-ppss (point)))))
1724 ((eq context
'anything
)
1727 ((eq context
'string
)
1729 ((eq context
'heredoc
)
1730 (eq ?
\n (nth 3 ppss
)))
1731 ((eq context
'non-heredoc
)
1732 (and (ruby-in-ppss-context-p 'anything
)
1733 (not (ruby-in-ppss-context-p 'heredoc
))))
1734 ((eq context
'comment
)
1738 "Internal error on `ruby-in-ppss-context-p': "
1739 "context name `" (symbol-name context
) "' is unknown"))))
1742 (defvar ruby-font-lock-syntax-table
1743 (let ((tbl (copy-syntax-table ruby-mode-syntax-table
)))
1744 (modify-syntax-entry ?_
"w" tbl
)
1746 "The syntax table to use for fontifying Ruby mode buffers.
1747 See `font-lock-syntax-table'.")
1749 (defconst ruby-font-lock-keyword-beg-re
"\\(?:^\\|[^.@$]\\|\\.\\.\\)")
1751 (defconst ruby-font-lock-keywords
1754 '("^\\s *def\\s +\\(?:[^( \t\n.]*\\.\\)?\\([^( \t\n]+\\)"
1755 1 font-lock-function-name-face
)
1758 ruby-font-lock-keyword-beg-re
1794 1 'font-lock-keyword-face
)
1795 ;; some core methods
1797 ruby-font-lock-keyword-beg-re
1799 '(;; built-in methods on Kernel
1843 ;; keyword-like private methods on Module
1860 1 'font-lock-builtin-face
)
1861 ;; here-doc beginnings
1862 `(,ruby-here-doc-beg-re
0 (unless (ruby-singleton-class-p (match-beginning 0))
1863 'font-lock-string-face
))
1864 ;; Perl-ish keywords
1865 "\\_<\\(?:BEGIN\\|END\\)\\_>\\|^__END__$"
1867 `(,(concat ruby-font-lock-keyword-beg-re
1868 "\\_<\\(nil\\|self\\|true\\|false\\)\\>")
1869 1 font-lock-variable-name-face
)
1870 ;; keywords that evaluate to certain values
1871 '("\\_<__\\(?:LINE\\|ENCODING\\|FILE\\)__\\_>" 0 font-lock-variable-name-face
)
1873 '("\\(^\\|[^:]\\)\\(:\\([-+~]@?\\|[/%&|^`]\\|\\*\\*?\\|<\\(<\\|=>?\\)?\\|>[>=]?\\|===?\\|=~\\|![~=]?\\|\\[\\]=?\\|@?\\(\\w\\|_\\)+\\([!?=]\\|\\b_*\\)\\|#{[^}\n\\\\]*\\(\\\\.[^}\n\\\\]*\\)*}\\)\\)"
1874 2 font-lock-constant-face
)
1876 '("\\(\\$\\([^a-zA-Z0-9 \n]\\|[0-9]\\)\\)\\W"
1877 1 font-lock-variable-name-face
)
1878 '("\\(\\$\\|@\\|@@\\)\\(\\w\\|_\\)+"
1879 0 font-lock-variable-name-face
)
1881 '("\\(?:\\_<\\|::\\)\\([A-Z]+\\(\\w\\|_\\)*\\)"
1882 1 (unless (eq ?\
( (char-after)) font-lock-type-face
))
1883 '("\\(^\\s *\\|[\[\{\(,]\\s *\\|\\sw\\s +\\)\\(\\(\\sw\\|_\\)+\\):[^:]" 2 font-lock-constant-face
)
1884 ;; conversion methods on Kernel
1885 (list (concat ruby-font-lock-keyword-beg-re
1886 (regexp-opt '("Array" "Complex" "Float" "Hash"
1887 "Integer" "Rational" "String") 'symbols
))
1888 1 font-lock-builtin-face
)
1889 ;; expression expansion
1890 '(ruby-match-expression-expansion
1891 2 font-lock-variable-name-face t
)
1893 '("[^[:alnum:]_]\\(!\\)[^=]"
1894 1 font-lock-negation-char-face
)
1895 ;; character literals
1896 ;; FIXME: Support longer escape sequences.
1897 '("\\_<\\?\\\\?\\S " 0 font-lock-string-face
)
1899 "Additional expressions to highlight in Ruby mode.")
1901 (defun ruby-match-expression-expansion (limit)
1902 (let* ((prop 'ruby-expansion-match-data
)
1903 (pos (next-single-char-property-change (point) prop nil limit
))
1905 (when (and pos
(> pos
(point)))
1907 (or (and (setq value
(get-text-property pos prop
))
1908 (progn (set-match-data value
) t
))
1909 (ruby-match-expression-expansion limit
)))))
1912 (define-derived-mode ruby-mode prog-mode
"Ruby"
1913 "Major mode for editing Ruby code.
1916 (ruby-mode-variables)
1918 (setq-local imenu-create-index-function
'ruby-imenu-create-index
)
1919 (setq-local add-log-current-defun-function
'ruby-add-log-current-method
)
1920 (setq-local beginning-of-defun-function
'ruby-beginning-of-defun
)
1921 (setq-local end-of-defun-function
'ruby-end-of-defun
)
1923 (add-hook 'after-save-hook
'ruby-mode-set-encoding nil
'local
)
1925 (setq-local electric-indent-chars
(append '(?\
{ ?\
}) electric-indent-chars
))
1927 (setq-local font-lock-defaults
'((ruby-font-lock-keywords) nil nil
))
1928 (setq-local font-lock-keywords ruby-font-lock-keywords
)
1929 (setq-local font-lock-syntax-table ruby-font-lock-syntax-table
)
1931 (setq-local syntax-propertize-function
#'ruby-syntax-propertize-function
))
1933 ;;; Invoke ruby-mode when appropriate
1936 (add-to-list 'auto-mode-alist
1937 (cons (purecopy (concat "\\(?:\\."
1938 "rb\\|ru\\|rake\\|thor"
1939 "\\|jbuilder\\|gemspec"
1941 "\\(?:Gem\\|Rake\\|Cap\\|Thor"
1942 "Vagrant\\|Guard\\)file"
1943 "\\)\\'")) 'ruby-mode
))
1946 (dolist (name (list "ruby" "rbx" "jruby" "ruby1.9" "ruby1.8"))
1947 (add-to-list 'interpreter-mode-alist
(cons (purecopy name
) 'ruby-mode
)))
1949 (provide 'ruby-mode
)
1951 ;;; ruby-mode.el ends here