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)
208 (modify-syntax-entry ?\] ")[" table)
210 "Syntax table to use in Ruby mode.")
212 (defcustom ruby-indent-tabs-mode nil
213 "Indentation can insert tabs in Ruby mode if this is non-nil."
218 (defcustom ruby-indent-level 2
219 "Indentation of Ruby statements."
224 (defcustom ruby-comment-column (default-value 'comment-column)
225 "Indentation column of comments."
230 (defcustom ruby-deep-arglist t
231 "Deep indent lists in parenthesis when non-nil.
232 Also ignores spaces after parenthesis when 'space."
237 (defcustom ruby-deep-indent-paren '(?\( ?\[ ?\] t)
238 "Deep indent lists in parenthesis when non-nil.
239 The value t means continuous line.
240 Also ignores spaces after parenthesis when 'space."
243 (defcustom ruby-deep-indent-paren-style 'space
244 "Default deep indent style."
245 :options '(t nil space) :group 'ruby)
247 (defcustom ruby-encoding-map
248 '((us-ascii . nil) ;; Do not put coding: us-ascii
249 (shift-jis . cp932) ;; Emacs charset name of Shift_JIS
250 (shift_jis . cp932) ;; MIME charset name of Shift_JIS
251 (japanese-cp932 . cp932)) ;; Emacs charset name of CP932
252 "Alist to map encoding name from Emacs to Ruby.
253 Associating an encoding name with nil means it needs not be
254 explicitly declared in magic comment."
255 :type '(repeat (cons (symbol :tag "From") (symbol :tag "To")))
258 (defcustom ruby-insert-encoding-magic-comment t
259 "Insert a magic Emacs 'coding' comment upon save if this is non-nil."
260 :type 'boolean :group 'ruby)
262 (defcustom ruby-encoding-magic-comment-style 'ruby
263 "The style of the magic encoding comment to use."
265 (const :tag "Emacs Style" emacs)
266 (const :tag "Ruby Style" ruby)
267 (const :tag "Custom Style" custom))
270 (defcustom ruby-custom-encoding-magic-comment-template "# coding: %s"
271 "The encoding comment template to be used when
272 `ruby-encoding-magic-comment-style' is set to `custom'."
276 (defcustom ruby-use-encoding-map t
277 "Use `ruby-encoding-map' to set encoding magic comment if this is non-nil."
278 :type 'boolean :group 'ruby)
284 ;; Here's a simplified BNF grammar, for reference:
285 ;; http://www.cse.buffalo.edu/~regan/cse305/RubyBNF.pdf
286 (defconst ruby-smie-grammar
291 (insts (inst) (insts ";" insts))
292 (inst (exp) (inst "iuwu-mod" exp)
293 ;; Somewhat incorrect (both can be used multiple times),
294 ;; but avoids lots of conflicts:
295 (exp "and" exp) (exp "or" exp))
296 (exp (exp1) (exp "," exp) (exp "=" exp)
299 (exp1 (exp2) (exp2 "?" exp1 ":" exp1))
300 (exp2 ("def" insts "end")
301 ("begin" insts-rescue-insts "end")
303 ("class" insts "end") ("module" insts "end")
304 ("for" for-body "end")
308 ("while" insts "end")
309 ("until" insts "end")
310 ("unless" insts "end")
312 ("case" cases "end"))
313 (formal-params ("opening-|" exp "closing-|"))
314 (for-body (for-head ";" insts))
315 (for-head (id "in" exp))
316 (cases (exp "then" insts)
317 (cases "when" cases) (insts "else" insts))
318 (expseq (exp) );;(expseq "," expseq)
319 (hashvals (id "=>" exp1) (hashvals "," hashvals))
320 (insts-rescue-insts (insts)
321 (insts-rescue-insts "rescue" insts-rescue-insts)
322 (insts-rescue-insts "ensure" insts-rescue-insts))
323 (itheni (insts) (exp "then" insts))
324 (ielsei (itheni) (itheni "else" insts))
325 (if-body (ielsei) (if-body "elsif" if-body)))
326 '((nonassoc "in") (assoc ";") (right " @ ")
327 (assoc ",") (right "=") (assoc "."))
330 '((assoc "rescue" "ensure"))
335 (right "+=" "-=" "*=" "/=" "%=" "**=" "&=" "|=" "^="
336 "<<=" ">>=" "&&=" "||=")
339 (left "*" "/" "%" "**")
343 (nonassoc ">" ">=" "<" "<=")
344 (nonassoc "==" "===" "!=")
346 (left "<<" ">>"))))))
348 (defun ruby-smie--bosp ()
349 (save-excursion (skip-chars-backward " \t")
350 (or (bolp) (memq (char-before) '(?\; ?=)))))
352 (defun ruby-smie--implicit-semi-p ()
354 (skip-chars-backward " \t")
356 (and (memq (char-before)
357 '(?\; ?- ?+ ?* ?/ ?: ?. ?, ?\[ ?\( ?\{ ?\\ ?& ?> ?< ?%
359 ;; Make sure it's not the end of a regexp.
360 (not (eq (car (syntax-after (1- (point)))) 7)))
361 (and (eq (char-before) ?\?)
362 (equal (save-excursion (ruby-smie--backward-token)) "?"))
363 (and (eq (char-before) ?=)
364 (string-match "\\`\\s." (save-excursion
365 (ruby-smie--backward-token))))
366 (and (eq (char-before) ?|)
367 (member (save-excursion (ruby-smie--backward-token))
369 (and (eq (car (syntax-after (1- (point)))) 2)
370 (member (save-excursion (ruby-smie--backward-token))
371 '("iuwu-mod" "and" "or")))
374 (eq (char-after) ?.))))))
376 (defun ruby-smie--redundant-do-p (&optional skip)
378 (if skip (backward-word 1))
379 (member (nth 2 (smie-backward-sexp ";")) '("while" "until" "for"))))
381 (defun ruby-smie--opening-pipe-p ()
383 (if (eq ?| (char-before)) (forward-char -1))
384 (skip-chars-backward " \t\n")
385 (or (eq ?\{ (char-before))
386 (looking-back "\\_<do" (- (point) 2)))))
388 (defun ruby-smie--closing-pipe-p ()
390 (if (eq ?| (char-before)) (forward-char -1))
391 (and (re-search-backward "|" (line-beginning-position) t)
392 (ruby-smie--opening-pipe-p))))
394 (defun ruby-smie--args-separator-p (pos)
396 (< pos (line-end-position))
397 (or (eq (char-syntax (preceding-char)) '?w)
398 ;; FIXME: Check that the preceding token is not a keyword.
399 ;; This isn't very important most of the time, though.
400 (and (memq (preceding-char) '(?! ??))
401 (eq (char-syntax (char-before (1- (point)))) '?w)))
404 (or (and (eq (char-syntax (char-after)) ?w)
405 (not (looking-at (regexp-opt '("unless" "if" "while" "until" "or"
406 "else" "elsif" "do" "end" "and")
408 (memq (syntax-after pos) '(7 15))
409 (looking-at "[([]\\|[-+!~:]\\sw")))))
411 (defun ruby-smie--at-dot-call ()
412 (and (eq ?w (char-syntax (following-char)))
413 (eq (char-before) ?.)
414 (not (eq (char-before (1- (point))) ?.))))
416 (defun ruby-smie--forward-token ()
418 (skip-chars-forward " \t")
420 ((looking-at "\\s\"") ;A heredoc or a string.
421 (if (not (looking-at "\n"))
423 ;; Tokenize the whole heredoc as semicolon.
424 (goto-char (scan-sexps (point) 1))
426 ((and (looking-at "[\n#]")
427 (ruby-smie--implicit-semi-p)) ;Only add implicit ; when needed.
428 (if (eolp) (forward-char 1) (forward-comment 1))
431 (forward-comment (point-max))
433 ((looking-at ":\\s.+")
434 (goto-char (match-end 0)) (match-string 0)) ;; bug#15208.
435 ((and (< pos (point))
437 (ruby-smie--args-separator-p (prog1 (point) (goto-char pos)))))
440 (let ((dot (ruby-smie--at-dot-call))
441 (tok (smie-default-forward-token)))
443 (setq tok (concat "." tok)))
445 ((member tok '("unless" "if" "while" "until"))
446 (if (save-excursion (forward-word -1) (ruby-smie--bosp))
448 ((string-match-p "\\`|[*&]?\\'" tok)
449 (forward-char (- 1 (length tok)))
452 ((ruby-smie--opening-pipe-p) "opening-|")
453 ((ruby-smie--closing-pipe-p) "closing-|")
455 ((and (equal tok "") (looking-at "\\\\\n"))
456 (goto-char (match-end 0)) (ruby-smie--forward-token))
459 ((not (ruby-smie--redundant-do-p 'skip)) tok)
460 ((> (save-excursion (forward-comment (point-max)) (point))
462 (ruby-smie--forward-token)) ;Fully redundant.
466 (defun ruby-smie--backward-token ()
468 (forward-comment (- (point)))
470 ((and (> pos (line-end-position)) (ruby-smie--implicit-semi-p))
471 (skip-chars-forward " \t") ";")
472 ((and (bolp) (not (bobp))) ;Presumably a heredoc.
473 ;; Tokenize the whole heredoc as semicolon.
474 (goto-char (scan-sexps (point) -1))
476 ((and (> pos (point)) (not (bolp))
477 (ruby-smie--args-separator-p pos))
478 ;; We have "ID SPC ID", which is a method call, but it binds less tightly
479 ;; than commas, since a method call can also be "ID ARG1, ARG2, ARG3".
480 ;; In some textbooks, "e1 @ e2" is used to mean "call e1 with arg e2".
483 (let ((tok (smie-default-backward-token))
484 (dot (ruby-smie--at-dot-call)))
486 (setq tok (concat "." tok)))
487 (when (and (eq ?: (char-before)) (string-match "\\`\\s." tok))
488 (forward-char -1) (setq tok (concat ":" tok))) ;; bug#15208.
490 ((member tok '("unless" "if" "while" "until"))
491 (if (ruby-smie--bosp)
495 ((ruby-smie--opening-pipe-p) "opening-|")
496 ((ruby-smie--closing-pipe-p) "closing-|")
498 ((string-match-p "\\`|[*&]\\'" tok)
501 ((and (equal tok "") (eq ?\\ (char-before)) (looking-at "\n"))
502 (forward-char -1) (ruby-smie--backward-token))
505 ((not (ruby-smie--redundant-do-p)) tok)
506 ((> (save-excursion (forward-word 1)
507 (forward-comment (point-max)) (point))
509 (ruby-smie--backward-token)) ;Fully redundant.
513 (defun ruby-smie--indent-to-stmt ()
515 (smie-backward-sexp ";")
516 (cons 'column (smie-indent-virtual))))
518 (defun ruby-smie-rules (kind token)
519 (pcase (cons kind token)
520 (`(:elem . basic) ruby-indent-level)
521 ;; "foo" "bar" is the concatenation of the two strings, so the second
522 ;; should be aligned with the first.
523 (`(:elem . args) (if (looking-at "\\s\"") 0))
524 ;; (`(:after . ",") (smie-rule-separator kind))
527 ((smie-rule-parent-p "def" "begin" "do" "class" "module" "for"
528 "while" "until" "unless"
529 "if" "then" "elsif" "else" "when"
530 "rescue" "ensure" "{")
531 (smie-rule-parent ruby-indent-level))
532 ;; For (invalid) code between switch and case.
533 ;; (if (smie-parent-p "switch") 4)
535 (`(:before . ,(or `"(" `"[" `"{"))
537 ((and (equal token "{")
538 (not (smie-rule-prev-p "(" "{" "[" "," "=>" "=" "return" ";"))
541 (not (eq (preceding-char) ?:))))
542 ;; Curly block opener.
543 (ruby-smie--indent-to-stmt))
544 ((smie-rule-hanging-p)
545 ;; Treat purely syntactic block-constructs as being part of their parent,
546 ;; when the opening statement is hanging.
547 (let ((state (smie-backward-sexp 'halfsexp)))
548 (when (eq t (car state)) (goto-char (cadr state))))
549 (cons 'column (smie-indent-virtual)))))
550 (`(:after . " @ ") (smie-rule-parent))
551 (`(:before . "do") (ruby-smie--indent-to-stmt))
552 (`(,(or :before :after) . ".")
553 (unless (smie-rule-parent-p ".")
554 (smie-rule-parent ruby-indent-level)))
555 (`(:before . ,(or `"else" `"then" `"elsif" `"rescue" `"ensure")) 0)
556 (`(:before . ,(or `"when"))
557 (if (not (smie-rule-sibling-p)) 0)) ;; ruby-indent-level
558 (`(:after . ,(or "=" "iuwu-mod" "+" "-" "*" "/" "&&" "||" "%" "**" "^" "&"
559 "<=>" ">" "<" ">=" "<=" "==" "===" "!=" "<<" ">>"
560 "+=" "-=" "*=" "/=" "%=" "**=" "&=" "|=" "^=" "|"
561 "<<=" ">>=" "&&=" "||=" "and" "or"))
562 (if (smie-rule-parent-p ";" nil) ruby-indent-level))
563 (`(:before . "begin")
564 (unless (save-excursion (skip-chars-backward " \t") (bolp))
568 (defun ruby-imenu-create-index-in-block (prefix beg end)
569 "Create an imenu index of methods inside a block."
570 (let ((index-alist '()) (case-fold-search nil)
571 name next pos decl sing)
573 (while (re-search-forward "^\\s *\\(\\(class\\s +\\|\\(class\\s *<<\\s *\\)\\|module\\s +\\)\\([^\(<\n ]+\\)\\|\\(def\\|alias\\)\\s +\\([^\(\n ]+\\)\\)" end t)
574 (setq sing (match-beginning 3))
575 (setq decl (match-string 5))
576 (setq next (match-end 0))
577 (setq name (or (match-string 4) (match-string 6)))
578 (setq pos (match-beginning 0))
580 ((string= "alias" decl)
581 (if prefix (setq name (concat prefix name)))
582 (push (cons name pos) index-alist))
583 ((string= "def" decl)
587 ((string-match "^self\." name)
588 (concat (substring prefix 0 -1) (substring name 4)))
589 (t (concat prefix name)))))
590 (push (cons name pos) index-alist)
591 (ruby-accurate-end-of-block end))
593 (if (string= "self" name)
594 (if prefix (setq name (substring prefix 0 -1)))
595 (if prefix (setq name (concat (substring prefix 0 -1) "::" name)))
596 (push (cons name pos) index-alist))
597 (ruby-accurate-end-of-block end)
600 (nconc (ruby-imenu-create-index-in-block
601 (concat name (if sing "." "#"))
602 next beg) index-alist))
606 (defun ruby-imenu-create-index ()
607 "Create an imenu index of all methods in the buffer."
608 (nreverse (ruby-imenu-create-index-in-block nil (point-min) nil)))
610 (defun ruby-accurate-end-of-block (&optional end)
613 (end (or end (point-max))))
614 (while (and (setq state (apply 'ruby-parse-partial end state))
615 (>= (nth 2 state) 0) (< (point) end)))))
617 (defun ruby-mode-variables ()
618 "Set up initial buffer-local variables for Ruby mode."
619 (setq indent-tabs-mode ruby-indent-tabs-mode)
621 (smie-setup ruby-smie-grammar #'ruby-smie-rules
622 :forward-token #'ruby-smie--forward-token
623 :backward-token #'ruby-smie--backward-token)
624 (setq-local indent-line-function 'ruby-indent-line))
625 (setq-local require-final-newline t)
626 (setq-local comment-start "# ")
627 (setq-local comment-end "")
628 (setq-local comment-column ruby-comment-column)
629 (setq-local comment-start-skip "#+ *")
630 (setq-local parse-sexp-ignore-comments t)
631 (setq-local parse-sexp-lookup-properties t)
632 (setq-local paragraph-start (concat "$\\|" page-delimiter))
633 (setq-local paragraph-separate paragraph-start)
634 (setq-local paragraph-ignore-fill-prefix t))
636 (defun ruby-mode-set-encoding ()
637 "Insert a magic comment header with the proper encoding if necessary."
640 (goto-char (point-min))
641 (when (re-search-forward "[^\0-\177]" nil t)
642 (goto-char (point-min))
644 (or save-buffer-coding-system
645 buffer-file-coding-system)))
648 (or (coding-system-get coding-system 'mime-charset)
649 (coding-system-change-eol-conversion coding-system nil))))
653 (if ruby-use-encoding-map
654 (let ((elt (assq coding-system ruby-encoding-map)))
655 (if elt (cdr elt) coding-system))
659 (if (looking-at "^#!") (beginning-of-line 2))
660 (cond ((looking-at "\\s *#.*-\*-\\s *\\(en\\)?coding\\s *:\\s *\\([-a-z0-9_]*\\)\\s *\\(;\\|-\*-\\)")
661 (unless (string= (match-string 2) coding-system)
662 (goto-char (match-beginning 2))
663 (delete-region (point) (match-end 2))
664 (and (looking-at "-\*-")
665 (let ((n (skip-chars-backward " ")))
666 (cond ((= n 0) (insert " ") (backward-char))
667 ((= n -1) (insert " "))
669 (insert coding-system)))
670 ((looking-at "\\s *#.*coding\\s *[:=]"))
671 (t (when ruby-insert-encoding-magic-comment
672 (let ((encoding-magic-comment-template
673 (pcase ruby-encoding-magic-comment-style
674 (`ruby "# coding: %s")
675 (`emacs "# -*- coding: %s -*-")
677 ruby-custom-encoding-magic-comment-template))))
679 (format encoding-magic-comment-template coding-system)
681 (when (buffer-modified-p)
682 (basic-save-buffer-1)))))))
684 (defun ruby-current-indentation ()
685 "Return the indentation level of current line."
688 (back-to-indentation)
691 (defun ruby-indent-line (&optional ignored)
692 "Correct the indentation of the current Ruby line."
694 (ruby-indent-to (ruby-calculate-indent)))
696 (defun ruby-indent-to (column)
697 "Indent the current line to COLUMN."
700 (and (< column 0) (error "Invalid nesting"))
701 (setq shift (current-column))
704 (back-to-indentation)
705 (setq top (current-column))
706 (skip-chars-backward " \t")
707 (if (>= shift top) (setq shift (- shift top))
711 (move-to-column (+ column shift))
713 (delete-region beg (point))
716 (move-to-column (+ column shift))))))
718 (defun ruby-special-char-p (&optional pos)
719 "Return t if the character before POS is a special character.
720 If omitted, POS defaults to the current point.
721 Special characters are `?', `$', `:' when preceded by whitespace,
722 and `\\' when preceded by `?'."
723 (setq pos (or pos (point)))
724 (let ((c (char-before pos)) (b (and (< (point-min) pos)
725 (char-before (1- pos)))))
726 (cond ((or (eq c ??) (eq c ?$)))
727 ((and (eq c ?:) (or (not b) (eq (char-syntax b) ? ))))
728 ((eq c ?\\) (eq b ??)))))
730 (defun ruby-singleton-class-p (&optional pos)
732 (when pos (goto-char pos))
734 (and (or (bolp) (not (eq (char-before (point)) ?_)))
735 (looking-at ruby-singleton-class-re))))
737 (defun ruby-expr-beg (&optional option)
738 "Check if point is possibly at the beginning of an expression.
739 OPTION specifies the type of the expression.
740 Can be one of `heredoc', `modifier', `expr-qstr', `expr-re'."
742 (store-match-data nil)
743 (let ((space (skip-chars-backward " \t"))
749 (and (looking-at "\\?")
750 (or (eq (char-syntax (char-before (point))) ?w)
751 (ruby-special-char-p))))
753 ((looking-at ruby-operator-re))
754 ((eq option 'heredoc)
755 (and (< space 0) (not (ruby-singleton-class-p start))))
756 ((or (looking-at "[\\[({,;]")
757 (and (looking-at "[!?]")
758 (or (not (eq option 'modifier))
760 (save-excursion (forward-char -1) (looking-at "\\Sw$"))))
761 (and (looking-at ruby-symbol-re)
762 (skip-chars-backward ruby-symbol-chars)
764 ((looking-at (regexp-opt
765 (append ruby-block-beg-keywords
766 ruby-block-op-keywords
767 ruby-block-mid-keywords)
769 (goto-char (match-end 0))
770 (not (looking-at "\\s_\\|!")))
771 ((eq option 'expr-qstr)
772 (looking-at "[a-zA-Z][a-zA-z0-9_]* +%[^ \t]"))
773 ((eq option 'expr-re)
774 (looking-at "[a-zA-Z][a-zA-z0-9_]* +/[^ \t]"))
777 (defun ruby-forward-string (term &optional end no-error expand)
779 (let ((n 1) (c (string-to-char term))
781 (concat "[^\\]\\(\\\\\\\\\\)*\\([" term "]\\|\\(#{\\)\\)")
782 (concat "[^\\]\\(\\\\\\\\\\)*[" term "]"))))
783 (while (and (re-search-forward re end no-error)
784 (if (match-beginning 3)
785 (ruby-forward-string "}{" end no-error nil)
786 (> (setq n (if (eq (char-before (point)) c)
791 ((error "Unterminated string")))))
793 (defun ruby-deep-indent-paren-p (c)
795 (cond ((listp ruby-deep-indent-paren)
796 (let ((deep (assoc c ruby-deep-indent-paren)))
798 (or (cdr deep) ruby-deep-indent-paren-style))
799 ((memq c ruby-deep-indent-paren)
800 ruby-deep-indent-paren-style))))
801 ((eq c ruby-deep-indent-paren) ruby-deep-indent-paren-style)
802 ((eq c ?\( ) ruby-deep-arglist)))
804 (defun ruby-parse-partial (&optional end in-string nest depth pcol indent)
805 "TODO: document throughout function body."
806 (or depth (setq depth 0))
807 (or indent (setq indent 0))
808 (when (re-search-forward ruby-delimiter end 'move)
809 (let ((pnt (point)) w re expand)
810 (goto-char (match-beginning 0))
812 ((and (memq (char-before) '(?@ ?$)) (looking-at "\\sw"))
814 ((looking-at "[\"`]") ;skip string
817 (ruby-forward-string (buffer-substring (point) (1+ (point)))
821 (setq in-string (point))
826 (re-search-forward "[^\\]\\(\\\\\\\\\\)*'" end t))
829 (setq in-string (point))
835 ((and (not (eobp)) (ruby-expr-beg 'expr-re))
836 (if (ruby-forward-string "/" end t t)
838 (setq in-string (point))
845 (ruby-expr-beg 'expr-qstr)
846 (not (looking-at "%="))
847 (looking-at "%[QqrxWw]?\\([^a-zA-Z0-9 \t\n]\\)"))
848 (goto-char (match-beginning 1))
849 (setq expand (not (memq (char-before) '(?q ?w))))
850 (setq w (match-string 1))
852 ((string= w "[") (setq re "]["))
853 ((string= w "{") (setq re "}{"))
854 ((string= w "(") (setq re ")("))
855 ((string= w "<") (setq re "><"))
856 ((and expand (string= w "\\"))
857 (setq w (concat "\\" w))))
858 (unless (cond (re (ruby-forward-string re end t expand))
859 (expand (ruby-forward-string w end t t))
860 (t (re-search-forward
863 (concat "[^\\]\\(\\\\\\\\\\)*" w))
865 (setq in-string (point))
869 ((looking-at "\\?") ;skip ?char
871 ((and (ruby-expr-beg)
872 (looking-at "?\\(\\\\C-\\|\\\\M-\\)*\\\\?."))
873 (goto-char (match-end 0)))
876 ((looking-at "\\$") ;skip $char
879 ((looking-at "#") ;skip comment
883 ((looking-at "[\\[{(]")
884 (let ((deep (ruby-deep-indent-paren-p (char-after))))
885 (if (and deep (or (not (eq (char-after) ?\{)) (ruby-expr-beg)))
887 (and (eq deep 'space) (looking-at ".\\s +[^# \t\n]")
888 (setq pnt (1- (match-end 0))))
889 (setq nest (cons (cons (char-after (point)) pnt) nest))
890 (setq pcol (cons (cons pnt depth) pcol))
892 (setq nest (cons (cons (char-after (point)) pnt) nest))
893 (setq depth (1+ depth))))
896 ((looking-at "[])}]")
897 (if (ruby-deep-indent-paren-p (matching-paren (char-after)))
898 (setq depth (cdr (car pcol)) pcol (cdr pcol))
899 (setq depth (1- depth)))
900 (setq nest (cdr nest))
902 ((looking-at ruby-block-end-re)
903 (if (or (and (not (bolp))
906 (setq w (char-after (point)))
911 (setq w (char-after (point)))
916 (setq nest (cdr nest))
917 (setq depth (1- depth)))
919 ((looking-at "def\\s +[^(\n;]*")
923 (not (eq ?_ (char-after (point))))))
925 (setq nest (cons (cons nil pnt) nest))
926 (setq depth (1+ depth))))
927 (goto-char (match-end 0)))
928 ((looking-at (concat "\\_<\\(" ruby-block-beg-re "\\)\\_>"))
931 (or (not (looking-at "do\\_>"))
933 (back-to-indentation)
934 (not (looking-at ruby-non-block-do-re)))))
938 (setq w (char-after (point)))
942 (not (eq ?! (char-after (point))))
943 (skip-chars-forward " \t")
944 (goto-char (match-beginning 0))
945 (or (not (looking-at ruby-modifier-re))
946 (ruby-expr-beg 'modifier))
948 (setq nest (cons (cons nil pnt) nest))
949 (setq depth (1+ depth)))
951 ((looking-at ":\\(['\"]\\)")
952 (goto-char (match-beginning 1))
953 (ruby-forward-string (match-string 1) end t))
954 ((looking-at ":\\([-,.+*/%&|^~<>]=?\\|===?\\|<=>\\|![~=]?\\)")
955 (goto-char (match-end 0)))
956 ((looking-at ":\\([a-zA-Z_][a-zA-Z_0-9]*[!?=]?\\)?")
957 (goto-char (match-end 0)))
958 ((or (looking-at "\\.\\.\\.?")
959 (looking-at "\\.[0-9]+")
960 (looking-at "\\.[a-zA-Z_0-9]+")
962 (goto-char (match-end 0)))
963 ((looking-at "^=begin")
964 (if (re-search-forward "^=end" end t)
966 (setq in-string (match-end 0))
970 ((and (ruby-expr-beg 'heredoc)
971 (looking-at "<<\\(-\\)?\\(\\([\"'`]\\)\\([^\n]+?\\)\\3\\|\\(?:\\sw\\|\\s_\\)+\\)"))
972 (setq re (regexp-quote (or (match-string 4) (match-string 2))))
973 (if (match-beginning 1) (setq re (concat "\\s *" re)))
974 (let* ((id-end (goto-char (match-end 0)))
975 (line-end-position (point-at-eol))
976 (state (list in-string nest depth pcol indent)))
977 ;; parse the rest of the line
978 (while (and (> line-end-position (point))
979 (setq state (apply 'ruby-parse-partial
980 line-end-position state))))
981 (setq in-string (car state)
985 indent (nth 4 state))
986 ;; skip heredoc section
987 (if (re-search-forward (concat "^" re "$") end 'move)
989 (setq in-string id-end)
993 ((looking-at "^__END__$")
995 ((and (looking-at ruby-here-doc-beg-re)
996 (boundp 'ruby-indent-point))
997 (if (re-search-forward (ruby-here-doc-end-match)
1000 (setq in-string (match-end 0))
1001 (goto-char ruby-indent-point)))
1003 (error (format "Bad string %s"
1004 (buffer-substring (point) pnt)
1006 (list in-string nest depth pcol))
1008 (defun ruby-parse-region (start end)
1014 (ruby-beginning-of-indent))
1016 (narrow-to-region (point) end)
1017 (while (and (> end (point))
1018 (setq state (apply 'ruby-parse-partial end state))))))
1019 (list (nth 0 state) ; in-string
1020 (car (nth 1 state)) ; nest
1021 (nth 2 state) ; depth
1022 (car (car (nth 3 state))) ; pcol
1023 ;(car (nth 5 state)) ; indent
1026 (defun ruby-indent-size (pos nest)
1027 "Return the indentation level in spaces NEST levels deeper than POS."
1028 (+ pos (* (or nest 1) ruby-indent-level)))
1030 (defun ruby-calculate-indent (&optional parse-start)
1031 "Return the proper indentation level of the current line."
1032 ;; TODO: Document body
1035 (let ((ruby-indent-point (point))
1036 (case-fold-search nil)
1037 state eol begin op-end
1038 (paren (progn (skip-syntax-forward " ")
1039 (and (char-after) (matching-paren (char-after)))))
1042 (goto-char parse-start)
1043 (ruby-beginning-of-indent)
1044 (setq parse-start (point)))
1045 (back-to-indentation)
1046 (setq indent (current-column))
1047 (setq state (ruby-parse-region parse-start ruby-indent-point))
1049 ((nth 0 state) ; within string
1050 (setq indent nil)) ; do nothing
1051 ((car (nth 1 state)) ; in paren
1052 (goto-char (setq begin (cdr (nth 1 state))))
1053 (let ((deep (ruby-deep-indent-paren-p (car (nth 1 state)))))
1055 (cond ((and (eq deep t) (eq (car (nth 1 state)) paren))
1056 (skip-syntax-backward " ")
1057 (setq indent (1- (current-column))))
1058 ((let ((s (ruby-parse-region (point) ruby-indent-point)))
1059 (and (nth 2 s) (> (nth 2 s) 0)
1060 (or (goto-char (cdr (nth 1 s))) t)))
1062 (setq indent (ruby-indent-size (current-column)
1065 (setq indent (current-column))
1066 (cond ((eq deep 'space))
1067 (paren (setq indent (1- indent)))
1068 (t (setq indent (ruby-indent-size (1- indent) 1))))))
1069 (if (nth 3 state) (goto-char (nth 3 state))
1070 (goto-char parse-start) (back-to-indentation))
1071 (setq indent (ruby-indent-size (current-column) (nth 2 state))))
1072 (and (eq (car (nth 1 state)) paren)
1073 (ruby-deep-indent-paren-p (matching-paren paren))
1074 (search-backward (char-to-string paren))
1075 (setq indent (current-column)))))
1076 ((and (nth 2 state) (> (nth 2 state) 0)) ; in nest
1077 (if (null (cdr (nth 1 state)))
1078 (error "Invalid nesting"))
1079 (goto-char (cdr (nth 1 state)))
1080 (forward-word -1) ; skip back a keyword
1081 (setq begin (point))
1083 ((looking-at "do\\>[^_]") ; iter block is a special case
1084 (if (nth 3 state) (goto-char (nth 3 state))
1085 (goto-char parse-start) (back-to-indentation))
1086 (setq indent (ruby-indent-size (current-column) (nth 2 state))))
1088 (setq indent (+ (current-column) ruby-indent-level)))))
1090 ((and (nth 2 state) (< (nth 2 state) 0)) ; in negative nest
1091 (setq indent (ruby-indent-size (current-column) (nth 2 state)))))
1093 (goto-char ruby-indent-point)
1098 ((and (not (ruby-deep-indent-paren-p paren))
1099 (re-search-forward ruby-negative eol t))
1100 (and (not (eq ?_ (char-after (match-end 0))))
1101 (setq indent (- indent ruby-indent-level))))
1106 (or (ruby-deep-indent-paren-p t)
1107 (null (car (nth 1 state)))))
1108 ;; goto beginning of non-empty no-comment line
1111 (skip-chars-backward " \t\n")
1114 (if (re-search-forward "^\\s *#" end t)
1118 ;; skip the comment at the end
1119 (skip-chars-backward " \t")
1120 (let (end (pos (point)))
1122 (while (and (re-search-forward "#" pos t)
1123 (setq end (1- (point)))
1124 (or (ruby-special-char-p end)
1125 (and (setq state (ruby-parse-region
1129 (goto-char (or end pos))
1130 (skip-chars-backward " \t")
1131 (setq begin (if (and end (nth 0 state)) pos (cdr (nth 1 state))))
1132 (setq state (ruby-parse-region parse-start (point))))
1133 (or (bobp) (forward-char -1))
1135 (or (and (looking-at ruby-symbol-re)
1136 (skip-chars-backward ruby-symbol-chars)
1137 (looking-at (concat "\\<\\(" ruby-block-hanging-re
1139 (not (eq (point) (nth 3 state)))
1141 (goto-char (match-end 0))
1142 (not (looking-at "[a-z_]"))))
1143 (and (looking-at ruby-operator-re)
1144 (not (ruby-special-char-p))
1147 (or (not (looking-at ruby-operator-re))
1148 (not (eq (char-before) ?:))))
1149 ;; Operator at the end of line.
1150 (let ((c (char-after (point))))
1154 ;; (goto-char begin)
1155 ;; (skip-chars-forward " \t")
1156 ;; (not (or (eolp) (looking-at "#")
1157 ;; (and (eq (car (nth 1 state)) ?{)
1158 ;; (looking-at "|"))))))
1159 ;; Not a regexp or percent literal.
1160 (null (nth 0 (ruby-parse-region (or begin parse-start)
1162 (or (not (eq ?| (char-after (point))))
1164 (or (eolp) (forward-char -1))
1166 ((search-backward "|" nil t)
1167 (skip-chars-backward " \t\n")
1171 (not (looking-at "{")))
1174 (not (looking-at "do\\>[^_]")))))
1182 (not (looking-at (concat "\\<\\(" ruby-block-hanging-re
1184 (eq (ruby-deep-indent-paren-p t) 'space)
1187 (goto-char (or begin parse-start))
1188 (skip-syntax-forward " ")
1190 ((car (nth 1 state)) indent)
1192 (+ indent ruby-indent-level))))))))
1193 (goto-char ruby-indent-point)
1195 (skip-syntax-forward " ")
1196 (if (looking-at "\\.[^.]")
1197 (+ indent ruby-indent-level)
1200 (defun ruby-beginning-of-defun (&optional arg)
1201 "Move backward to the beginning of the current defun.
1202 With ARG, move backward multiple defuns. Negative ARG means
1205 (let (case-fold-search)
1206 (and (re-search-backward (concat "^\\s *" ruby-defun-beg-re "\\_>")
1208 (beginning-of-line))))
1210 (defun ruby-end-of-defun ()
1211 "Move point to the end of the current defun.
1212 The defun begins at or after the point. This function is called
1216 (let (case-fold-search)
1217 (when (looking-back (concat "^\\s *" ruby-block-end-re))
1220 (defun ruby-beginning-of-indent ()
1221 "Backtrack to a line which can be used as a reference for
1222 calculating indentation on the lines after it."
1223 (while (and (re-search-backward ruby-indent-beg-re nil 'move)
1224 (if (ruby-in-ppss-context-p 'anything)
1226 ;; We can stop, then.
1227 (beginning-of-line)))))
1229 (defun ruby-move-to-block (n)
1230 "Move to the beginning (N < 0) or the end (N > 0) of the
1231 current block, a sibling block, or an outer block. Do that (abs N) times."
1232 (back-to-indentation)
1233 (let ((signum (if (> n 0) 1 -1))
1235 (depth (or (nth 2 (ruby-parse-region (point) (line-end-position))) 0))
1238 (when (looking-at ruby-block-mid-re)
1239 (setq depth (+ depth signum)))
1240 (when (< (* depth signum) 0)
1241 ;; Moving end -> end or beginning -> beginning.
1243 (dotimes (_ (abs n))
1245 (setq down (save-excursion
1246 (back-to-indentation)
1247 ;; There is a block start or block end keyword on this
1248 ;; line, don't need to look for another block.
1249 (and (re-search-forward
1250 (if backward ruby-block-end-re
1251 (concat "\\_<\\(" ruby-block-beg-re "\\)\\_>"))
1252 (line-end-position) t)
1253 (not (nth 8 (syntax-ppss))))))
1254 (while (and (not done) (not (if backward (bobp) (eobp))))
1255 (forward-line signum)
1257 ;; Skip empty and commented out lines.
1258 ((looking-at "^\\s *$"))
1259 ((looking-at "^\\s *#"))
1260 ;; Skip block comments;
1261 ((and (not backward) (looking-at "^=begin\\>"))
1262 (re-search-forward "^=end\\>"))
1263 ((and backward (looking-at "^=end\\>"))
1264 (re-search-backward "^=begin\\>"))
1265 ;; Jump over a multiline literal.
1266 ((ruby-in-ppss-context-p 'string)
1267 (goto-char (nth 8 (syntax-ppss)))
1270 (when (bolp) (forward-char -1)))) ; After a heredoc.
1272 (let ((state (ruby-parse-region (point) (line-end-position))))
1273 (unless (car state) ; Line ends with unfinished string.
1274 (setq depth (+ (nth 2 state) depth))))
1276 ;; Increased depth, we found a block.
1277 ((> (* signum depth) 0)
1279 ;; We're at the same depth as when we started, and we've
1280 ;; encountered a block before. Stop.
1281 ((and down (zerop depth))
1283 ;; Lower depth, means outer block, can stop now.
1284 ((< (* signum depth) 0)
1286 (back-to-indentation)))
1288 (defun ruby-beginning-of-block (&optional arg)
1289 "Move backward to the beginning of the current block.
1290 With ARG, move up multiple blocks."
1292 (ruby-move-to-block (- (or arg 1))))
1294 (defun ruby-end-of-block (&optional arg)
1295 "Move forward to the end of the current block.
1296 With ARG, move out of multiple blocks."
1298 (ruby-move-to-block (or arg 1)))
1300 (defun ruby-forward-sexp (&optional arg)
1301 "Move forward across one balanced expression (sexp).
1302 With ARG, do it many times. Negative ARG means move backward."
1303 ;; TODO: Document body
1306 (ruby-use-smie (forward-sexp arg))
1307 ((and (numberp arg) (< arg 0)) (ruby-backward-sexp (- arg)))
1309 (let ((i (or arg 1)))
1312 (skip-syntax-forward " ")
1313 (if (looking-at ",\\s *") (goto-char (match-end 0)))
1314 (cond ((looking-at "\\?\\(\\\\[CM]-\\)*\\\\?\\S ")
1315 (goto-char (match-end 0)))
1317 (skip-chars-forward ",.:;|&^~=!?\\+\\-\\*")
1318 (looking-at "\\s("))
1319 (goto-char (scan-sexps (point) 1)))
1320 ((and (looking-at (concat "\\<\\(" ruby-block-beg-re
1322 (not (eq (char-before (point)) ?.))
1323 (not (eq (char-before (point)) ?:)))
1326 ((looking-at "\\(\\$\\|@@?\\)?\\sw")
1328 (while (progn (forward-word 1) (looking-at "_")))
1329 (cond ((looking-at "::") (forward-char 2) t)
1330 ((> (skip-chars-forward ".") 0))
1331 ((looking-at "\\?\\|!\\(=[~=>]\\|[^~=]\\)")
1332 (forward-char 1) nil)))))
1336 (setq expr (or expr (ruby-expr-beg)
1337 (looking-at "%\\sw?\\Sw\\|[\"'`/]")))
1338 (nth 1 (setq state (apply #'ruby-parse-partial
1341 (skip-chars-forward "<"))
1344 ((error) (forward-word 1)))
1347 (defun ruby-backward-sexp (&optional arg)
1348 "Move backward across one balanced expression (sexp).
1349 With ARG, do it many times. Negative ARG means move forward."
1350 ;; TODO: Document body
1353 (ruby-use-smie (backward-sexp arg))
1354 ((and (numberp arg) (< arg 0)) (ruby-forward-sexp (- arg)))
1356 (let ((i (or arg 1)))
1359 (skip-chars-backward " \t\n,.:;|&^~=!?\\+\\-\\*")
1361 (cond ((looking-at "\\s)")
1362 (goto-char (scan-sexps (1+ (point)) -1))
1363 (pcase (char-before)
1364 (`?% (forward-char -1))
1365 ((or `?q `?Q `?w `?W `?r `?x)
1366 (if (eq (char-before (1- (point))) ?%)
1367 (forward-char -2))))
1369 ((looking-at "\\s\"\\|\\\\\\S_")
1370 (let ((c (char-to-string (char-before (match-end 0)))))
1371 (while (and (search-backward c)
1372 (eq (logand (skip-chars-backward "\\") 1)
1375 ((looking-at "\\s.\\|\\s\\")
1376 (if (ruby-special-char-p) (forward-char -1)))
1377 ((looking-at "\\s(") nil)
1380 (while (progn (forward-word -1)
1381 (pcase (char-before)
1383 (`?. (forward-char -1) t)
1386 (and (eq (char-before) (char-after))
1390 (eq (char-before) :)))))
1391 (if (looking-at ruby-block-end-re)
1392 (ruby-beginning-of-block))
1398 (defun ruby-indent-exp (&optional ignored)
1399 "Indent each line in the balanced expression following the point."
1401 (let ((here (point-marker)) start top column (nest t))
1402 (set-marker-insertion-type here t)
1406 (setq start (point) top (current-indentation))
1407 (while (and (not (eobp))
1409 (setq column (ruby-calculate-indent start))
1410 (cond ((> column top)
1412 ((and (= column top) nest)
1413 (setq nest nil) t))))
1414 (ruby-indent-to column)
1415 (beginning-of-line 2)))
1417 (set-marker here nil))))
1419 (defun ruby-add-log-current-method ()
1420 "Return the current method name as a string.
1421 This string includes all namespaces.
1430 See `add-log-current-defun-function'."
1433 (let* ((indent 0) mname mlist
1437 (concat "^[ \t]*" re "[ \t]+"
1439 ;; \\. and :: for class methods
1440 "\\([A-Za-z_]" ruby-symbol-re "*\\|\\.\\|::" "\\)"
1442 (definition-re (funcall make-definition-re ruby-defun-beg-re))
1443 (module-re (funcall make-definition-re "\\(class\\|module\\)")))
1444 ;; Get the current method definition (or class/module).
1445 (when (re-search-backward definition-re nil t)
1446 (goto-char (match-beginning 1))
1447 (if (not (string-equal "def" (match-string 1)))
1448 (setq mlist (list (match-string 2)))
1449 ;; We're inside the method. For classes and modules,
1450 ;; this check is skipped for performance.
1451 (when (ruby-block-contains-point start)
1452 (setq mname (match-string 2))))
1453 (setq indent (current-column))
1454 (beginning-of-line))
1455 ;; Walk up the class/module nesting.
1456 (while (and (> indent 0)
1457 (re-search-backward module-re nil t))
1458 (goto-char (match-beginning 1))
1459 (when (< (current-column) indent)
1460 (setq mlist (cons (match-string 2) mlist))
1461 (setq indent (current-column))
1462 (beginning-of-line)))
1463 ;; Process the method name.
1465 (let ((mn (split-string mname "\\.\\|::")))
1468 (unless (string-equal "self" (car mn)) ; def self.foo
1470 (let ((ml (nreverse mlist)))
1471 ;; If the method name references one of the
1472 ;; containing modules, drop the more nested ones.
1474 (if (string-equal (car ml) (car mn))
1475 (setq mlist (nreverse (cdr ml)) ml nil))
1476 (or (setq ml (cdr ml)) (nreverse mlist))))
1478 (setcdr (last mlist) (butlast mn))
1479 (setq mlist (butlast mn))))
1480 (setq mname (concat "." (car (last mn)))))
1481 ;; See if the method is in singleton class context.
1482 (let ((in-singleton-class
1483 (when (re-search-forward ruby-singleton-class-re start t)
1484 (goto-char (match-beginning 0))
1485 ;; FIXME: Optimize it out, too?
1486 ;; This can be slow in a large file, but
1487 ;; unlike class/module declaration
1488 ;; indentations, method definitions can be
1489 ;; intermixed with these, and may or may not
1490 ;; be additionally indented after visibility
1492 (ruby-block-contains-point start))))
1494 (if in-singleton-class "." "#")
1496 ;; Generate the string.
1498 (setq mlist (mapconcat (function identity) mlist "::")))
1500 (if mlist (concat mlist mname) mname)
1503 (defun ruby-block-contains-point (pt)
1509 (defun ruby-brace-to-do-end (orig end)
1510 (let (beg-marker end-marker)
1512 (when (eq (char-before) ?\})
1514 (when (save-excursion
1515 (skip-chars-backward " \t")
1519 (setq end-marker (point-marker))
1520 (when (and (not (eobp)) (eq (char-syntax (char-after)) ?w))
1524 (when (eq (char-syntax (char-before)) ?w)
1527 (setq beg-marker (point-marker))
1528 (when (looking-at "\\(\\s \\)*|")
1529 (unless (match-beginning 1)
1531 (goto-char (1+ (match-end 0)))
1532 (search-forward "|"))
1533 (unless (looking-at "\\s *$")
1535 (indent-region beg-marker end-marker)
1536 (goto-char beg-marker)
1539 (defun ruby-do-end-to-brace (orig end)
1540 (let (beg-marker end-marker beg-pos end-pos)
1541 (goto-char (- end 3))
1542 (when (looking-at ruby-block-end-re)
1544 (setq end-marker (point-marker))
1548 ;; Maybe this should be customizable, let's see if anyone asks.
1550 (setq beg-marker (point-marker))
1551 (when (looking-at "\\s +|")
1552 (delete-char (- (match-end 0) (match-beginning 0) 1))
1554 (re-search-forward "|" (line-end-position) t))
1556 (skip-chars-forward " \t\n\r")
1557 (setq beg-pos (point))
1558 (goto-char end-marker)
1559 (skip-chars-backward " \t\n\r")
1560 (setq end-pos (point)))
1563 (and (= (line-number-at-pos beg-pos) (line-number-at-pos end-pos))
1564 (< (+ (current-column) (- end-pos beg-pos) 2) fill-column)))
1566 (goto-char end-marker)
1567 (just-one-space -1))
1568 (goto-char beg-marker)
1571 (defun ruby-toggle-block ()
1572 "Toggle block type from do-end to braces or back.
1573 The block must begin on the current line or above it and end after the point.
1574 If the result is do-end block, it will always be multiline."
1576 (let ((start (point)) beg end)
1579 (if (and (re-search-backward "\\({\\)\\|\\_<do\\(\\s \\|$\\||\\)")
1582 (save-match-data (ruby-forward-sexp))
1585 (if (match-beginning 1)
1586 (ruby-brace-to-do-end beg end)
1587 (ruby-do-end-to-brace beg end)))
1588 (goto-char start))))
1591 (defconst ruby-percent-literal-beg-re
1592 "\\(%\\)[qQrswWxIi]?\\([[:punct:]]\\)"
1593 "Regexp to match the beginning of percent literal.")
1595 (defconst ruby-syntax-methods-before-regexp
1596 '("gsub" "gsub!" "sub" "sub!" "scan" "split" "split!" "index" "match"
1597 "assert_match" "Given" "Then" "When")
1598 "Methods that can take regexp as the first argument.
1599 It will be properly highlighted even when the call omits parens.")
1601 (defvar ruby-syntax-before-regexp-re
1603 ;; Special tokens that can't be followed by a division operator.
1605 ;; Distinguish ternary operator tokens.
1606 ;; FIXME: They don't really have to be separated with spaces.
1608 ;; Control flow keywords and operators following bol or whitespace.
1609 "\\|\\(?:^\\|\\s \\)"
1610 (regexp-opt '("if" "elsif" "unless" "while" "until" "when" "and"
1611 "or" "not" "&&" "||"))
1612 ;; Method name from the list.
1614 (regexp-opt ruby-syntax-methods-before-regexp)
1616 "Regexp to match text that can be followed by a regular expression."))
1618 (defun ruby-syntax-propertize-function (start end)
1619 "Syntactic keywords for Ruby mode. See `syntax-propertize-function'."
1620 (let (case-fold-search)
1622 (remove-text-properties start end '(ruby-expansion-match-data))
1623 (ruby-syntax-propertize-heredoc end)
1624 (ruby-syntax-enclosing-percent-literal end)
1626 (syntax-propertize-rules
1627 ;; $' $" $` .... are variables.
1628 ;; ?' ?" ?` are character literals (one-char strings in 1.9+).
1629 ("\\([?$]\\)[#\"'`]"
1630 (1 (unless (save-excursion
1631 ;; Not within a string.
1632 (nth 3 (syntax-ppss (match-beginning 0))))
1633 (string-to-syntax "\\"))))
1634 ;; Regular expressions. Start with matching unescaped slash.
1635 ("\\(?:\\=\\|[^\\]\\)\\(?:\\\\\\\\\\)*\\(/\\)"
1636 (1 (let ((state (save-excursion (syntax-ppss (match-beginning 1)))))
1638 ;; Beginning of a regexp.
1639 (and (null (nth 8 state))
1642 (looking-back ruby-syntax-before-regexp-re
1644 ;; End of regexp. We don't match the whole
1645 ;; regexp at once because it can have
1646 ;; string interpolation inside, or span
1648 (eq ?/ (nth 3 state)))
1649 (string-to-syntax "\"/")))))
1650 ;; Expression expansions in strings. We're handling them
1651 ;; here, so that the regexp rule never matches inside them.
1652 (ruby-expression-expansion-re
1653 (0 (ignore (ruby-syntax-propertize-expansion))))
1654 ("^=en\\(d\\)\\_>" (1 "!"))
1655 ("^\\(=\\)begin\\_>" (1 "!"))
1656 ;; Handle here documents.
1657 ((concat ruby-here-doc-beg-re ".*\\(\n\\)")
1658 (7 (unless (or (nth 8 (save-excursion
1659 (syntax-ppss (match-beginning 0))))
1660 (ruby-singleton-class-p (match-beginning 0)))
1661 (put-text-property (match-beginning 7) (match-end 7)
1662 'syntax-table (string-to-syntax "\""))
1663 (ruby-syntax-propertize-heredoc end))))
1664 ;; Handle percent literals: %w(), %q{}, etc.
1665 ((concat "\\(?:^\\|[[ \t\n<+(,=]\\)" ruby-percent-literal-beg-re)
1666 (1 (prog1 "|" (ruby-syntax-propertize-percent-literal end)))))
1669 (defun ruby-syntax-propertize-heredoc (limit)
1670 (let ((ppss (syntax-ppss))
1672 (when (eq ?\n (nth 3 ppss))
1674 (goto-char (nth 8 ppss))
1676 (while (re-search-forward ruby-here-doc-beg-re
1677 (line-end-position) t)
1678 (unless (ruby-singleton-class-p (match-beginning 0))
1679 (push (concat (ruby-here-doc-end-match) "\n") res))))
1681 ;; With multiple openers on the same line, we don't know in which
1682 ;; part `start' is, so we have to go back to the beginning.
1684 (goto-char (nth 8 ppss))
1685 (setq res (nreverse res)))
1686 (while (and res (re-search-forward (pop res) limit 'move))
1688 (put-text-property (1- (point)) (point)
1689 'syntax-table (string-to-syntax "\""))))
1690 ;; End up at bol following the heredoc openers.
1691 ;; Propertize expression expansions from this point forward.
1694 (defun ruby-syntax-enclosing-percent-literal (limit)
1695 (let ((state (syntax-ppss))
1697 ;; When already inside percent literal, re-propertize it.
1698 (when (eq t (nth 3 state))
1699 (goto-char (nth 8 state))
1700 (when (looking-at ruby-percent-literal-beg-re)
1701 (ruby-syntax-propertize-percent-literal limit))
1702 (when (< (point) start) (goto-char start)))))
1704 (defun ruby-syntax-propertize-percent-literal (limit)
1705 (goto-char (match-beginning 2))
1706 ;; Not inside a simple string or comment.
1707 (when (eq t (nth 3 (syntax-ppss)))
1708 (let* ((op (char-after))
1709 (ops (char-to-string op))
1710 (cl (or (cdr (aref (syntax-table) op))
1711 (cdr (assoc op '((?< . ?>))))))
1712 parse-sexp-lookup-properties)
1716 (if cl ; Paired delimiters.
1717 ;; Delimiter pairs of the same kind can be nested
1718 ;; inside the literal, as long as they are balanced.
1719 ;; Create syntax table that ignores other characters.
1720 (with-syntax-table (make-char-table 'syntax-table nil)
1721 (modify-syntax-entry op (concat "(" (char-to-string cl)))
1722 (modify-syntax-entry cl (concat ")" ops))
1723 (modify-syntax-entry ?\\ "\\")
1725 (narrow-to-region (point) limit)
1726 (forward-list))) ; skip to the paired character
1727 ;; Single character delimiter.
1728 (re-search-forward (concat "[^\\]\\(?:\\\\\\\\\\)*"
1729 (regexp-quote ops)) limit nil))
1730 ;; Found the closing delimiter.
1731 (put-text-property (1- (point)) (point) 'syntax-table
1732 (string-to-syntax "|")))
1733 ;; Unclosed literal, do nothing.
1734 ((scan-error search-failed)))))))
1736 (defun ruby-syntax-propertize-expansion ()
1737 ;; Save the match data to a text property, for font-locking later.
1738 ;; Set the syntax of all double quotes and backticks to punctuation.
1739 (let* ((beg (match-beginning 2))
1741 (state (and beg (save-excursion (syntax-ppss beg)))))
1742 (when (ruby-syntax-expansion-allowed-p state)
1743 (put-text-property beg (1+ beg) 'ruby-expansion-match-data
1746 (while (re-search-forward "[\"`]" end 'move)
1747 (put-text-property (match-beginning 0) (match-end 0)
1748 'syntax-table (string-to-syntax "."))))))
1750 (defun ruby-syntax-expansion-allowed-p (parse-state)
1751 "Return non-nil if expression expansion is allowed."
1752 (let ((term (nth 3 parse-state)))
1754 ((memq term '(?\" ?` ?\n ?/)))
1758 (goto-char (nth 8 parse-state))
1759 (looking-at "%\\(?:[QWrxI]\\|\\W\\)")))))))
1761 (defun ruby-syntax-propertize-expansions (start end)
1764 (while (re-search-forward ruby-expression-expansion-re end 'move)
1765 (ruby-syntax-propertize-expansion))))
1767 (defun ruby-in-ppss-context-p (context &optional ppss)
1768 (let ((ppss (or ppss (syntax-ppss (point)))))
1770 ((eq context 'anything)
1773 ((eq context 'string)
1775 ((eq context 'heredoc)
1776 (eq ?\n (nth 3 ppss)))
1777 ((eq context 'non-heredoc)
1778 (and (ruby-in-ppss-context-p 'anything)
1779 (not (ruby-in-ppss-context-p 'heredoc))))
1780 ((eq context 'comment)
1784 "Internal error on `ruby-in-ppss-context-p': "
1785 "context name `" (symbol-name context) "' is unknown"))))
1788 (defvar ruby-font-lock-syntax-table
1789 (let ((tbl (copy-syntax-table ruby-mode-syntax-table)))
1790 (modify-syntax-entry ?_ "w" tbl)
1792 "The syntax table to use for fontifying Ruby mode buffers.
1793 See `font-lock-syntax-table'.")
1795 (defconst ruby-font-lock-keyword-beg-re "\\(?:^\\|[^.@$]\\|\\.\\.\\)")
1797 (defconst ruby-font-lock-keywords
1799 ("^\\s *def\\s +\\(?:[^( \t\n.]*\\.\\)?\\([^( \t\n]+\\)"
1800 1 font-lock-function-name-face)
1803 ruby-font-lock-keyword-beg-re
1839 (1 font-lock-keyword-face))
1840 ;; Some core methods.
1842 ruby-font-lock-keyword-beg-re
1844 '( ;; built-in methods on Kernel
1888 ;; keyword-like private methods on Module
1905 (1 font-lock-builtin-face))
1906 ;; Here-doc beginnings.
1907 (,ruby-here-doc-beg-re
1908 (0 (unless (ruby-singleton-class-p (match-beginning 0))
1909 'font-lock-string-face)))
1910 ;; Perl-ish keywords.
1911 "\\_<\\(?:BEGIN\\|END\\)\\_>\\|^__END__$"
1913 (,(concat ruby-font-lock-keyword-beg-re
1914 "\\_<\\(nil\\|self\\|true\\|false\\)\\>")
1915 1 font-lock-variable-name-face)
1916 ;; Keywords that evaluate to certain values.
1917 ("\\_<__\\(?:LINE\\|ENCODING\\|FILE\\)__\\_>"
1918 (0 font-lock-variable-name-face))
1920 ("\\(^\\|[^:]\\)\\(:\\([-+~]@?\\|[/%&|^`]\\|\\*\\*?\\|<\\(<\\|=>?\\)?\\|>[>=]?\\|===?\\|=~\\|![~=]?\\|\\[\\]=?\\|@?\\(\\w\\|_\\)+\\([!?=]\\|\\b_*\\)\\|#{[^}\n\\\\]*\\(\\\\.[^}\n\\\\]*\\)*}\\)\\)"
1921 2 font-lock-constant-face)
1923 ("\\(\\$\\([^a-zA-Z0-9 \n]\\|[0-9]\\)\\)\\W"
1924 1 font-lock-variable-name-face)
1925 ("\\(\\$\\|@\\|@@\\)\\(\\w\\|_\\)+"
1926 0 font-lock-variable-name-face)
1928 ("\\(?:\\_<\\|::\\)\\([A-Z]+\\(\\w\\|_\\)*\\)"
1929 1 (unless (eq ?\( (char-after)) font-lock-type-face))
1930 ("\\(^\\s *\\|[\[\{\(,]\\s *\\|\\sw\\s +\\)\\(\\(\\sw\\|_\\)+\\):[^:]"
1931 (2 font-lock-constant-face))
1932 ;; Conversion methods on Kernel.
1933 (,(concat ruby-font-lock-keyword-beg-re
1934 (regexp-opt '("Array" "Complex" "Float" "Hash"
1935 "Integer" "Rational" "String") 'symbols))
1936 (1 font-lock-builtin-face))
1937 ;; Expression expansion.
1938 (ruby-match-expression-expansion
1939 2 font-lock-variable-name-face t)
1941 ("[^[:alnum:]_]\\(!\\)[^=]"
1942 1 font-lock-negation-char-face)
1943 ;; Character literals.
1944 ;; FIXME: Support longer escape sequences.
1945 ("\\_<\\?\\\\?\\S " 0 font-lock-string-face)
1947 "Additional expressions to highlight in Ruby mode.")
1949 (defun ruby-match-expression-expansion (limit)
1950 (let* ((prop 'ruby-expansion-match-data)
1951 (pos (next-single-char-property-change (point) prop nil limit))
1953 (when (and pos (> pos (point)))
1955 (or (and (setq value (get-text-property pos prop))
1956 (progn (set-match-data value) t))
1957 (ruby-match-expression-expansion limit)))))
1960 (define-derived-mode ruby-mode prog-mode "Ruby"
1961 "Major mode for editing Ruby code.
1964 (ruby-mode-variables)
1966 (setq-local imenu-create-index-function 'ruby-imenu-create-index)
1967 (setq-local add-log-current-defun-function 'ruby-add-log-current-method)
1968 (setq-local beginning-of-defun-function 'ruby-beginning-of-defun)
1969 (setq-local end-of-defun-function 'ruby-end-of-defun)
1971 (add-hook 'after-save-hook 'ruby-mode-set-encoding nil 'local)
1973 (setq-local electric-indent-chars (append '(?\{ ?\}) electric-indent-chars))
1975 (setq-local font-lock-defaults '((ruby-font-lock-keywords) nil nil))
1976 (setq-local font-lock-keywords ruby-font-lock-keywords)
1977 (setq-local font-lock-syntax-table ruby-font-lock-syntax-table)
1979 (setq-local syntax-propertize-function #'ruby-syntax-propertize-function))
1981 ;;; Invoke ruby-mode when appropriate
1984 (add-to-list 'auto-mode-alist
1985 (cons (purecopy (concat "\\(?:\\."
1986 "rb\\|ru\\|rake\\|thor"
1987 "\\|jbuilder\\|gemspec"
1989 "\\(?:Gem\\|Rake\\|Cap\\|Thor"
1990 "Vagrant\\|Guard\\)file"
1991 "\\)\\'")) 'ruby-mode))
1994 (dolist (name (list "ruby" "rbx" "jruby" "ruby1.9" "ruby1.8"))
1995 (add-to-list 'interpreter-mode-alist (cons (purecopy name) 'ruby-mode)))
1997 (provide 'ruby-mode)
1999 ;;; ruby-mode.el ends here