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.")
140 (defconst ruby-symbol-re
(concat "[" ruby-symbol-chars
"]")
141 "Regexp to match symbols.")
143 (define-abbrev-table 'ruby-mode-abbrev-table
()
144 "Abbrev table in use in Ruby mode buffers.")
146 (defvar ruby-use-smie nil
)
148 (defvar ruby-mode-map
149 (let ((map (make-sparse-keymap)))
150 (unless ruby-use-smie
151 (define-key map
(kbd "M-C-b") 'ruby-backward-sexp
)
152 (define-key map
(kbd "M-C-f") 'ruby-forward-sexp
)
153 (define-key map
(kbd "M-C-q") 'ruby-indent-exp
))
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.")
160 (defvar ruby-mode-syntax-table
161 (let ((table (make-syntax-table)))
162 (modify-syntax-entry ?
\' "\"" table
)
163 (modify-syntax-entry ?
\" "\"" table
)
164 (modify-syntax-entry ?\
` "\"" table
)
165 (modify-syntax-entry ?
# "<" table
)
166 (modify-syntax-entry ?
\n ">" table
)
167 (modify-syntax-entry ?
\\ "\\" table
)
168 (modify-syntax-entry ?$
"." table
)
169 (modify-syntax-entry ??
"_" table
)
170 (modify-syntax-entry ?_
"_" table
)
171 (modify-syntax-entry ?
: "_" table
)
172 (modify-syntax-entry ?
< "." table
)
173 (modify-syntax-entry ?
> "." table
)
174 (modify-syntax-entry ?
& "." table
)
175 (modify-syntax-entry ?|
"." table
)
176 (modify-syntax-entry ?%
"." table
)
177 (modify-syntax-entry ?
= "." table
)
178 (modify-syntax-entry ?
/ "." table
)
179 (modify-syntax-entry ?
+ "." table
)
180 (modify-syntax-entry ?
* "." table
)
181 (modify-syntax-entry ?-
"." 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 ?\
} "){" table
)
187 (modify-syntax-entry ?\
[ "(]" table
)
188 (modify-syntax-entry ?\
] ")[" table
)
190 "Syntax table to use in Ruby mode.")
192 (defcustom ruby-indent-tabs-mode nil
193 "Indentation can insert tabs in Ruby mode if this is non-nil."
194 :type
'boolean
:group
'ruby
)
196 (defcustom ruby-indent-level
2
197 "Indentation of Ruby statements."
198 :type
'integer
:group
'ruby
)
200 (defcustom ruby-comment-column
32
201 "Indentation column of comments."
202 :type
'integer
:group
'ruby
)
204 (defcustom ruby-deep-arglist t
205 "Deep indent lists in parenthesis when non-nil.
206 Also ignores spaces after parenthesis when 'space."
209 (defcustom ruby-deep-indent-paren
'(?\
( ?\
[ ?\
] t
)
210 "Deep indent lists in parenthesis when non-nil.
211 The value t means continuous line.
212 Also ignores spaces after parenthesis when 'space."
215 (defcustom ruby-deep-indent-paren-style
'space
216 "Default deep indent style."
217 :options
'(t nil space
) :group
'ruby
)
219 (defcustom ruby-encoding-map
'((shift_jis . cp932
) (shift-jis . cp932
))
220 "Alist to map encoding name from Emacs to Ruby."
223 (defcustom ruby-insert-encoding-magic-comment t
224 "Insert a magic Emacs 'coding' comment upon save if this is non-nil."
225 :type
'boolean
:group
'ruby
)
227 (defcustom ruby-use-encoding-map t
228 "Use `ruby-encoding-map' to set encoding magic comment if this is non-nil."
229 :type
'boolean
:group
'ruby
)
231 ;; Safe file variables
232 (put 'ruby-indent-tabs-mode
'safe-local-variable
'booleanp
)
233 (put 'ruby-indent-level
'safe-local-variable
'integerp
)
234 (put 'ruby-comment-column
'safe-local-variable
'integerp
)
235 (put 'ruby-deep-arglist
'safe-local-variable
'booleanp
)
241 (defconst ruby-smie-grammar
242 ;; FIXME: Add support for Cucumber.
246 (insts (inst) (insts ";" insts
))
247 (inst (exp) (inst "iuwu-mod" exp
))
248 (exp (exp1) (exp "," exp
))
249 (exp1 (exp2) (exp2 "?" exp1
":" exp1
))
250 (exp2 ("def" insts
"end")
251 ("begin" insts-rescue-insts
"end")
253 ("class" insts
"end") ("module" insts
"end")
254 ("for" for-body
"end")
258 ("while" insts
"end")
259 ("until" insts
"end")
260 ("unless" insts
"end")
262 ("case" cases
"end"))
263 (formal-params ("opening-|" exp
"|"))
264 (for-body (for-head ";" insts
))
265 (for-head (id "in" exp
))
266 (cases (exp "then" insts
) ;; FIXME: Ruby also allows (exp ":" insts).
267 (cases "when" cases
) (insts "else" insts
))
268 (expseq (exp) );;(expseq "," expseq)
269 (hashvals (id "=>" exp1
) (hashvals "," hashvals
))
270 (insts-rescue-insts (insts)
271 (insts-rescue-insts "rescue" insts-rescue-insts
)
272 (insts-rescue-insts "ensure" insts-rescue-insts
))
273 (itheni (insts) (exp "then" insts
))
274 (ielsei (itheni) (itheni "else" insts
))
275 (if-body (ielsei) (if-body "elsif" if-body
)))
276 '((nonassoc "in") (assoc ";") (assoc ","))
279 '((assoc "rescue" "ensure"))
282 (defun ruby-smie--bosp ()
283 (save-excursion (skip-chars-backward " \t")
284 (or (bolp) (eq (char-before) ?\
;))))
286 (defun ruby-smie--implicit-semi-p ()
288 (skip-chars-backward " \t")
290 (and (memq (char-before) '(?\
; ?- ?+ ?* ?/ ?: ?.))
291 ;; Make sure it's not the end of a regexp.
292 (not (eq (car (syntax-after (1- (point)))) 7)))
293 (and (memq (char-before) '(?
\? ?
=))
294 (let ((tok (ruby-smie--backward-token)))
296 (string-match "\\`\\s." tok
))))))))
298 (defun ruby-smie--opening-pipe-p ()
300 (if (eq ?|
(char-before)) (forward-char -
1))
301 (skip-chars-backward " \t\n")
302 (or (eq ?\
{ (char-before))
303 (looking-back "\\_<do" (- (point) 2)))))
305 (defun ruby-smie--forward-token ()
306 (skip-chars-forward " \t")
307 (if (and (looking-at "[\n#]")
308 ;; Only add implicit ; when needed.
309 (ruby-smie--implicit-semi-p))
311 (if (eolp) (forward-char 1) (forward-comment 1))
313 (forward-comment (point-max))
314 (if (looking-at ":\\s.+")
315 (progn (goto-char (match-end 0)) (match-string 0)) ;; bug#15208.
316 (let ((tok (smie-default-forward-token)))
318 ((member tok
'("unless" "if" "while" "until"))
319 (if (save-excursion (forward-word -
1) (ruby-smie--bosp))
322 (if (ruby-smie--opening-pipe-p) "opening-|" tok
))
325 (defun ruby-smie--backward-token ()
327 (forward-comment (- (point)))
328 (if (and (> pos
(line-end-position))
329 (ruby-smie--implicit-semi-p))
330 (progn (skip-chars-forward " \t")
332 (let ((tok (smie-default-backward-token)))
333 (when (and (eq ?
: (char-before)) (string-match "\\`\\s." tok
))
334 (forward-char -
1) (setq tok
(concat ":" tok
))) ;; bug#15208.
336 ((member tok
'("unless" "if" "while" "until"))
337 (if (ruby-smie--bosp)
340 (if (ruby-smie--opening-pipe-p) "opening-|" tok
))
343 (defun ruby-smie-rules (kind token
)
344 (pcase (cons kind token
)
345 (`(:elem . basic
) ruby-indent-level
)
347 (if (smie-rule-parent-p "def" "begin" "do" "class" "module" "for"
348 "[" "{" "while" "until" "unless"
349 "if" "then" "elsif" "else" "when"
351 (smie-rule-parent ruby-indent-level
)
352 ;; For (invalid) code between switch and case.
353 ;; (if (smie-parent-p "switch") 4)
358 (forward-word 1) ;Skip "do"
359 (skip-chars-forward " \t")
360 (and (equal (save-excursion (ruby-smie--forward-token)) "opening-|")
361 (save-excursion (forward-sexp 1)
362 (skip-chars-forward " \t")
364 (looking-at comment-start-skip
)))))
365 ;; `(column . ,(smie-indent-virtual))
367 (`(:before .
,(or `"else" `"then" `"elsif" `"rescue")) 0)
368 (`(:before .
,(or `"when"))
369 (if (not (smie-rule-sibling-p)) 0)) ;; ruby-indent-level
370 ;; Hack attack: Since newlines are separators, don't try to align args that
371 ;; appear on a separate line.
372 (`(:list-intro .
";") t
)))
374 (defun ruby-imenu-create-index-in-block (prefix beg end
)
375 "Create an imenu index of methods inside a block."
376 (let ((index-alist '()) (case-fold-search nil
)
377 name next pos decl sing
)
379 (while (re-search-forward "^\\s *\\(\\(class\\s +\\|\\(class\\s *<<\\s *\\)\\|module\\s +\\)\\([^\(<\n ]+\\)\\|\\(def\\|alias\\)\\s +\\([^\(\n ]+\\)\\)" end t
)
380 (setq sing
(match-beginning 3))
381 (setq decl
(match-string 5))
382 (setq next
(match-end 0))
383 (setq name
(or (match-string 4) (match-string 6)))
384 (setq pos
(match-beginning 0))
386 ((string= "alias" decl
)
387 (if prefix
(setq name
(concat prefix name
)))
388 (push (cons name pos
) index-alist
))
389 ((string= "def" decl
)
393 ((string-match "^self\." name
)
394 (concat (substring prefix
0 -
1) (substring name
4)))
395 (t (concat prefix name
)))))
396 (push (cons name pos
) index-alist
)
397 (ruby-accurate-end-of-block end
))
399 (if (string= "self" name
)
400 (if prefix
(setq name
(substring prefix
0 -
1)))
401 (if prefix
(setq name
(concat (substring prefix
0 -
1) "::" name
)))
402 (push (cons name pos
) index-alist
))
403 (ruby-accurate-end-of-block end
)
406 (nconc (ruby-imenu-create-index-in-block
407 (concat name
(if sing
"." "#"))
408 next beg
) index-alist
))
412 (defun ruby-imenu-create-index ()
413 "Create an imenu index of all methods in the buffer."
414 (nreverse (ruby-imenu-create-index-in-block nil
(point-min) nil
)))
416 (defun ruby-accurate-end-of-block (&optional end
)
419 (end (or end
(point-max))))
420 (while (and (setq state
(apply 'ruby-parse-partial end state
))
421 (>= (nth 2 state
) 0) (< (point) end
)))))
423 (defun ruby-mode-variables ()
424 "Set up initial buffer-local variables for Ruby mode."
425 (set-syntax-table ruby-mode-syntax-table
)
426 (setq local-abbrev-table ruby-mode-abbrev-table
)
427 (setq indent-tabs-mode ruby-indent-tabs-mode
)
429 (smie-setup ruby-smie-grammar
#'ruby-smie-rules
430 :forward-token
#'ruby-smie--forward-token
431 :backward-token
#'ruby-smie--backward-token
)
432 (set (make-local-variable 'indent-line-function
) 'ruby-indent-line
))
433 (set (make-local-variable 'require-final-newline
) t
)
434 (set (make-local-variable 'comment-start
) "# ")
435 (set (make-local-variable 'comment-end
) "")
436 (set (make-local-variable 'comment-column
) ruby-comment-column
)
437 (set (make-local-variable 'comment-start-skip
) "#+ *")
438 (set (make-local-variable 'parse-sexp-ignore-comments
) t
)
439 (set (make-local-variable 'parse-sexp-lookup-properties
) t
)
440 (set (make-local-variable 'paragraph-start
) (concat "$\\|" page-delimiter
))
441 (set (make-local-variable 'paragraph-separate
) paragraph-start
)
442 (set (make-local-variable 'paragraph-ignore-fill-prefix
) t
))
444 (defun ruby-mode-set-encoding ()
445 "Insert a magic comment header with the proper encoding if necessary."
448 (goto-char (point-min))
449 (when (re-search-forward "[^\0-\177]" nil t
)
450 (goto-char (point-min))
452 (or coding-system-for-write
453 buffer-file-coding-system
)))
456 (or (coding-system-get coding-system
'mime-charset
)
457 (coding-system-change-eol-conversion coding-system nil
))))
461 (or (and ruby-use-encoding-map
462 (cdr (assq coding-system ruby-encoding-map
)))
465 (if (looking-at "^#!") (beginning-of-line 2))
466 (cond ((looking-at "\\s *#.*-\*-\\s *\\(en\\)?coding\\s *:\\s *\\([-a-z0-9_]*\\)\\s *\\(;\\|-\*-\\)")
467 (unless (string= (match-string 2) coding-system
)
468 (goto-char (match-beginning 2))
469 (delete-region (point) (match-end 2))
470 (and (looking-at "-\*-")
471 (let ((n (skip-chars-backward " ")))
472 (cond ((= n
0) (insert " ") (backward-char))
473 ((= n -
1) (insert " "))
475 (insert coding-system
)))
476 ((looking-at "\\s *#.*coding\\s *[:=]"))
477 (t (when ruby-insert-encoding-magic-comment
478 (insert "# -*- coding: " coding-system
" -*-\n"))))))))
480 (defun ruby-current-indentation ()
481 "Return the indentation level of current line."
484 (back-to-indentation)
487 (defun ruby-indent-line (&optional ignored
)
488 "Correct the indentation of the current Ruby line."
490 (ruby-indent-to (ruby-calculate-indent)))
492 (defun ruby-indent-to (column)
493 "Indent the current line to COLUMN."
496 (and (< column
0) (error "invalid nest"))
497 (setq shift
(current-column))
500 (back-to-indentation)
501 (setq top
(current-column))
502 (skip-chars-backward " \t")
503 (if (>= shift top
) (setq shift
(- shift top
))
507 (move-to-column (+ column shift
))
509 (delete-region beg
(point))
512 (move-to-column (+ column shift
))))))
514 (defun ruby-special-char-p (&optional pos
)
515 "Return t if the character before POS is a special character.
516 If omitted, POS defaults to the current point.
517 Special characters are `?', `$', `:' when preceded by whitespace,
518 and `\\' when preceded by `?'."
519 (setq pos
(or pos
(point)))
520 (let ((c (char-before pos
)) (b (and (< (point-min) pos
)
521 (char-before (1- pos
)))))
522 (cond ((or (eq c ??
) (eq c ?$
)))
523 ((and (eq c ?
:) (or (not b
) (eq (char-syntax b
) ?
))))
524 ((eq c ?
\\) (eq b ??
)))))
526 (defun ruby-singleton-class-p (&optional pos
)
528 (when pos
(goto-char pos
))
530 (and (or (bolp) (not (eq (char-before (point)) ?_
)))
531 (looking-at ruby-singleton-class-re
))))
533 (defun ruby-expr-beg (&optional option
)
534 "Check if point is possibly at the beginning of an expression.
535 OPTION specifies the type of the expression.
536 Can be one of `heredoc', `modifier', `expr-qstr', `expr-re'."
538 (store-match-data nil
)
539 (let ((space (skip-chars-backward " \t"))
545 (and (looking-at "\\?")
546 (or (eq (char-syntax (char-before (point))) ?w
)
547 (ruby-special-char-p))))
549 ((looking-at ruby-operator-re
))
550 ((eq option
'heredoc
)
551 (and (< space
0) (not (ruby-singleton-class-p start
))))
552 ((or (looking-at "[\\[({,;]")
553 (and (looking-at "[!?]")
554 (or (not (eq option
'modifier
))
556 (save-excursion (forward-char -
1) (looking-at "\\Sw$"))))
557 (and (looking-at ruby-symbol-re
)
558 (skip-chars-backward ruby-symbol-chars
)
560 ((looking-at (regexp-opt
561 (append ruby-block-beg-keywords
562 ruby-block-op-keywords
563 ruby-block-mid-keywords
)
565 (goto-char (match-end 0))
566 (not (looking-at "\\s_\\|!")))
567 ((eq option
'expr-qstr
)
568 (looking-at "[a-zA-Z][a-zA-z0-9_]* +%[^ \t]"))
569 ((eq option
'expr-re
)
570 (looking-at "[a-zA-Z][a-zA-z0-9_]* +/[^ \t]"))
573 (defun ruby-forward-string (term &optional end no-error expand
)
575 (let ((n 1) (c (string-to-char term
))
577 (concat "[^\\]\\(\\\\\\\\\\)*\\([" term
"]\\|\\(#{\\)\\)")
578 (concat "[^\\]\\(\\\\\\\\\\)*[" term
"]"))))
579 (while (and (re-search-forward re end no-error
)
580 (if (match-beginning 3)
581 (ruby-forward-string "}{" end no-error nil
)
582 (> (setq n
(if (eq (char-before (point)) c
)
587 ((error "unterminated string")))))
589 (defun ruby-deep-indent-paren-p (c)
591 (cond ((listp ruby-deep-indent-paren
)
592 (let ((deep (assoc c ruby-deep-indent-paren
)))
594 (or (cdr deep
) ruby-deep-indent-paren-style
))
595 ((memq c ruby-deep-indent-paren
)
596 ruby-deep-indent-paren-style
))))
597 ((eq c ruby-deep-indent-paren
) ruby-deep-indent-paren-style
)
598 ((eq c ?\
( ) ruby-deep-arglist
)))
600 (defun ruby-parse-partial (&optional end in-string nest depth pcol indent
)
601 "TODO: document throughout function body."
602 (or depth
(setq depth
0))
603 (or indent
(setq indent
0))
604 (when (re-search-forward ruby-delimiter end
'move
)
605 (let ((pnt (point)) w re expand
)
606 (goto-char (match-beginning 0))
608 ((and (memq (char-before) '(?
@ ?$
)) (looking-at "\\sw"))
610 ((looking-at "[\"`]") ;skip string
613 (ruby-forward-string (buffer-substring (point) (1+ (point))) end t t
))
616 (setq in-string
(point))
621 (re-search-forward "[^\\]\\(\\\\\\\\\\)*'" end t
))
624 (setq in-string
(point))
630 ((and (not (eobp)) (ruby-expr-beg 'expr-re
))
631 (if (ruby-forward-string "/" end t t
)
633 (setq in-string
(point))
640 (ruby-expr-beg 'expr-qstr
)
641 (not (looking-at "%="))
642 (looking-at "%[QqrxWw]?\\([^a-zA-Z0-9 \t\n]\\)"))
643 (goto-char (match-beginning 1))
644 (setq expand
(not (memq (char-before) '(?q ?w
))))
645 (setq w
(match-string 1))
647 ((string= w
"[") (setq re
"]["))
648 ((string= w
"{") (setq re
"}{"))
649 ((string= w
"(") (setq re
")("))
650 ((string= w
"<") (setq re
"><"))
651 ((and expand
(string= w
"\\"))
652 (setq w
(concat "\\" w
))))
653 (unless (cond (re (ruby-forward-string re end t expand
))
654 (expand (ruby-forward-string w end t t
))
655 (t (re-search-forward
658 (concat "[^\\]\\(\\\\\\\\\\)*" w
))
660 (setq in-string
(point))
664 ((looking-at "\\?") ;skip ?char
666 ((and (ruby-expr-beg)
667 (looking-at "?\\(\\\\C-\\|\\\\M-\\)*\\\\?."))
668 (goto-char (match-end 0)))
671 ((looking-at "\\$") ;skip $char
674 ((looking-at "#") ;skip comment
678 ((looking-at "[\\[{(]")
679 (let ((deep (ruby-deep-indent-paren-p (char-after))))
680 (if (and deep
(or (not (eq (char-after) ?\
{)) (ruby-expr-beg)))
682 (and (eq deep
'space
) (looking-at ".\\s +[^# \t\n]")
683 (setq pnt
(1- (match-end 0))))
684 (setq nest
(cons (cons (char-after (point)) pnt
) nest
))
685 (setq pcol
(cons (cons pnt depth
) pcol
))
687 (setq nest
(cons (cons (char-after (point)) pnt
) nest
))
688 (setq depth
(1+ depth
))))
691 ((looking-at "[])}]")
692 (if (ruby-deep-indent-paren-p (matching-paren (char-after)))
693 (setq depth
(cdr (car pcol
)) pcol
(cdr pcol
))
694 (setq depth
(1- depth
)))
695 (setq nest
(cdr nest
))
697 ((looking-at ruby-block-end-re
)
698 (if (or (and (not (bolp))
701 (setq w
(char-after (point)))
706 (setq w
(char-after (point)))
711 (setq nest
(cdr nest
))
712 (setq depth
(1- depth
)))
714 ((looking-at "def\\s +[^(\n;]*")
718 (not (eq ?_
(char-after (point))))))
720 (setq nest
(cons (cons nil pnt
) nest
))
721 (setq depth
(1+ depth
))))
722 (goto-char (match-end 0)))
723 ((looking-at (concat "\\_<\\(" ruby-block-beg-re
"\\)\\_>"))
726 (or (not (looking-at "do\\_>"))
728 (back-to-indentation)
729 (not (looking-at ruby-non-block-do-re
)))))
733 (setq w
(char-after (point)))
737 (not (eq ?
! (char-after (point))))
738 (skip-chars-forward " \t")
739 (goto-char (match-beginning 0))
740 (or (not (looking-at ruby-modifier-re
))
741 (ruby-expr-beg 'modifier
))
743 (setq nest
(cons (cons nil pnt
) nest
))
744 (setq depth
(1+ depth
)))
746 ((looking-at ":\\(['\"]\\)")
747 (goto-char (match-beginning 1))
748 (ruby-forward-string (match-string 1) end t
))
749 ((looking-at ":\\([-,.+*/%&|^~<>]=?\\|===?\\|<=>\\|![~=]?\\)")
750 (goto-char (match-end 0)))
751 ((looking-at ":\\([a-zA-Z_][a-zA-Z_0-9]*[!?=]?\\)?")
752 (goto-char (match-end 0)))
753 ((or (looking-at "\\.\\.\\.?")
754 (looking-at "\\.[0-9]+")
755 (looking-at "\\.[a-zA-Z_0-9]+")
757 (goto-char (match-end 0)))
758 ((looking-at "^=begin")
759 (if (re-search-forward "^=end" end t
)
761 (setq in-string
(match-end 0))
765 ((and (ruby-expr-beg 'heredoc
)
766 (looking-at "<<\\(-\\)?\\(\\([\"'`]\\)\\([^\n]+?\\)\\3\\|\\(?:\\sw\\|\\s_\\)+\\)"))
767 (setq re
(regexp-quote (or (match-string 4) (match-string 2))))
768 (if (match-beginning 1) (setq re
(concat "\\s *" re
)))
769 (let* ((id-end (goto-char (match-end 0)))
770 (line-end-position (point-at-eol))
771 (state (list in-string nest depth pcol indent
)))
772 ;; parse the rest of the line
773 (while (and (> line-end-position
(point))
774 (setq state
(apply 'ruby-parse-partial
775 line-end-position state
))))
776 (setq in-string
(car state
)
780 indent
(nth 4 state
))
781 ;; skip heredoc section
782 (if (re-search-forward (concat "^" re
"$") end
'move
)
784 (setq in-string id-end
)
788 ((looking-at "^__END__$")
790 ((and (looking-at ruby-here-doc-beg-re
)
791 (boundp 'ruby-indent-point
))
792 (if (re-search-forward (ruby-here-doc-end-match)
795 (setq in-string
(match-end 0))
796 (goto-char ruby-indent-point
)))
798 (error (format "bad string %s"
799 (buffer-substring (point) pnt
)
801 (list in-string nest depth pcol
))
803 (defun ruby-parse-region (start end
)
809 (ruby-beginning-of-indent))
811 (narrow-to-region (point) end
)
812 (while (and (> end
(point))
813 (setq state
(apply 'ruby-parse-partial end state
))))))
814 (list (nth 0 state
) ; in-string
815 (car (nth 1 state
)) ; nest
816 (nth 2 state
) ; depth
817 (car (car (nth 3 state
))) ; pcol
818 ;(car (nth 5 state)) ; indent
821 (defun ruby-indent-size (pos nest
)
822 "Return the indentation level in spaces NEST levels deeper than POS."
823 (+ pos
(* (or nest
1) ruby-indent-level
)))
825 (defun ruby-calculate-indent (&optional parse-start
)
826 "Return the proper indentation level of the current line."
827 ;; TODO: Document body
830 (let ((ruby-indent-point (point))
831 (case-fold-search nil
)
832 state eol begin op-end
833 (paren (progn (skip-syntax-forward " ")
834 (and (char-after) (matching-paren (char-after)))))
837 (goto-char parse-start
)
838 (ruby-beginning-of-indent)
839 (setq parse-start
(point)))
840 (back-to-indentation)
841 (setq indent
(current-column))
842 (setq state
(ruby-parse-region parse-start ruby-indent-point
))
844 ((nth 0 state
) ; within string
845 (setq indent nil
)) ; do nothing
846 ((car (nth 1 state
)) ; in paren
847 (goto-char (setq begin
(cdr (nth 1 state
))))
848 (let ((deep (ruby-deep-indent-paren-p (car (nth 1 state
)))))
850 (cond ((and (eq deep t
) (eq (car (nth 1 state
)) paren
))
851 (skip-syntax-backward " ")
852 (setq indent
(1- (current-column))))
853 ((let ((s (ruby-parse-region (point) ruby-indent-point
)))
854 (and (nth 2 s
) (> (nth 2 s
) 0)
855 (or (goto-char (cdr (nth 1 s
))) t
)))
857 (setq indent
(ruby-indent-size (current-column)
860 (setq indent
(current-column))
861 (cond ((eq deep
'space
))
862 (paren (setq indent
(1- indent
)))
863 (t (setq indent
(ruby-indent-size (1- indent
) 1))))))
864 (if (nth 3 state
) (goto-char (nth 3 state
))
865 (goto-char parse-start
) (back-to-indentation))
866 (setq indent
(ruby-indent-size (current-column) (nth 2 state
))))
867 (and (eq (car (nth 1 state
)) paren
)
868 (ruby-deep-indent-paren-p (matching-paren paren
))
869 (search-backward (char-to-string paren
))
870 (setq indent
(current-column)))))
871 ((and (nth 2 state
) (> (nth 2 state
) 0)) ; in nest
872 (if (null (cdr (nth 1 state
)))
873 (error "invalid nest"))
874 (goto-char (cdr (nth 1 state
)))
875 (forward-word -
1) ; skip back a keyword
878 ((looking-at "do\\>[^_]") ; iter block is a special case
879 (if (nth 3 state
) (goto-char (nth 3 state
))
880 (goto-char parse-start
) (back-to-indentation))
881 (setq indent
(ruby-indent-size (current-column) (nth 2 state
))))
883 (setq indent
(+ (current-column) ruby-indent-level
)))))
885 ((and (nth 2 state
) (< (nth 2 state
) 0)) ; in negative nest
886 (setq indent
(ruby-indent-size (current-column) (nth 2 state
)))))
888 (goto-char ruby-indent-point
)
893 ((and (not (ruby-deep-indent-paren-p paren
))
894 (re-search-forward ruby-negative eol t
))
895 (and (not (eq ?_
(char-after (match-end 0))))
896 (setq indent
(- indent ruby-indent-level
))))
901 (or (ruby-deep-indent-paren-p t
)
902 (null (car (nth 1 state
)))))
903 ;; goto beginning of non-empty no-comment line
906 (skip-chars-backward " \t\n")
909 (if (re-search-forward "^\\s *#" end t
)
913 ;; skip the comment at the end
914 (skip-chars-backward " \t")
915 (let (end (pos (point)))
917 (while (and (re-search-forward "#" pos t
)
918 (setq end
(1- (point)))
919 (or (ruby-special-char-p end
)
920 (and (setq state
(ruby-parse-region parse-start end
))
923 (goto-char (or end pos
))
924 (skip-chars-backward " \t")
925 (setq begin
(if (and end
(nth 0 state
)) pos
(cdr (nth 1 state
))))
926 (setq state
(ruby-parse-region parse-start
(point))))
927 (or (bobp) (forward-char -
1))
929 (or (and (looking-at ruby-symbol-re
)
930 (skip-chars-backward ruby-symbol-chars
)
931 (looking-at (concat "\\<\\(" ruby-block-hanging-re
"\\)\\>"))
932 (not (eq (point) (nth 3 state
)))
934 (goto-char (match-end 0))
935 (not (looking-at "[a-z_]"))))
936 (and (looking-at ruby-operator-re
)
937 (not (ruby-special-char-p))
938 ;; Operator at the end of line.
939 (let ((c (char-after (point))))
944 ;; (skip-chars-forward " \t")
945 ;; (not (or (eolp) (looking-at "#")
946 ;; (and (eq (car (nth 1 state)) ?{)
947 ;; (looking-at "|"))))))
948 ;; Not a regexp or percent literal.
949 (null (nth 0 (ruby-parse-region (or begin parse-start
)
951 (or (not (eq ?|
(char-after (point))))
953 (or (eolp) (forward-char -
1))
955 ((search-backward "|" nil t
)
956 (skip-chars-backward " \t\n")
960 (not (looking-at "{")))
963 (not (looking-at "do\\>[^_]")))))
971 (not (looking-at (concat "\\<\\(" ruby-block-hanging-re
"\\)\\>")))
972 (eq (ruby-deep-indent-paren-p t
) 'space
)
975 (goto-char (or begin parse-start
))
976 (skip-syntax-forward " ")
978 ((car (nth 1 state
)) indent
)
980 (+ indent ruby-indent-level
))))))))
981 (goto-char ruby-indent-point
)
983 (skip-syntax-forward " ")
984 (if (looking-at "\\.[^.]")
985 (+ indent ruby-indent-level
)
988 (defun ruby-beginning-of-defun (&optional arg
)
989 "Move backward to the beginning of the current defun.
990 With ARG, move backward multiple defuns. Negative ARG means
993 (let (case-fold-search)
994 (and (re-search-backward (concat "^\\s *" ruby-defun-beg-re
"\\_>")
996 (beginning-of-line))))
998 (defun ruby-end-of-defun ()
999 "Move point to the end of the current defun.
1000 The defun begins at or after the point. This function is called
1004 (let (case-fold-search)
1005 (when (looking-back (concat "^\\s *" ruby-block-end-re
))
1008 (defun ruby-beginning-of-indent ()
1009 "Backtrack to a line which can be used as a reference for
1010 calculating indentation on the lines after it."
1011 (while (and (re-search-backward ruby-indent-beg-re nil
'move
)
1012 (if (ruby-in-ppss-context-p 'anything
)
1014 ;; We can stop, then.
1015 (beginning-of-line)))))
1017 (defun ruby-move-to-block (n)
1018 "Move to the beginning (N < 0) or the end (N > 0) of the
1019 current block, a sibling block, or an outer block. Do that (abs N) times."
1020 (back-to-indentation)
1021 (let ((signum (if (> n
0) 1 -
1))
1023 (depth (or (nth 2 (ruby-parse-region (point) (line-end-position))) 0))
1026 (when (looking-at ruby-block-mid-re
)
1027 (setq depth
(+ depth signum
)))
1028 (when (< (* depth signum
) 0)
1029 ;; Moving end -> end or beginning -> beginning.
1031 (dotimes (_ (abs n
))
1033 (setq down
(save-excursion
1034 (back-to-indentation)
1035 ;; There is a block start or block end keyword on this
1036 ;; line, don't need to look for another block.
1037 (and (re-search-forward
1038 (if backward ruby-block-end-re
1039 (concat "\\_<\\(" ruby-block-beg-re
"\\)\\_>"))
1040 (line-end-position) t
)
1041 (not (nth 8 (syntax-ppss))))))
1042 (while (and (not done
) (not (if backward
(bobp) (eobp))))
1043 (forward-line signum
)
1045 ;; Skip empty and commented out lines.
1046 ((looking-at "^\\s *$"))
1047 ((looking-at "^\\s *#"))
1048 ;; Skip block comments;
1049 ((and (not backward
) (looking-at "^=begin\\>"))
1050 (re-search-forward "^=end\\>"))
1051 ((and backward
(looking-at "^=end\\>"))
1052 (re-search-backward "^=begin\\>"))
1053 ;; Jump over a multiline literal.
1054 ((ruby-in-ppss-context-p 'string
)
1055 (goto-char (nth 8 (syntax-ppss)))
1058 (when (bolp) (forward-char -
1)))) ; After a heredoc.
1060 (let ((state (ruby-parse-region (point) (line-end-position))))
1061 (unless (car state
) ; Line ends with unfinished string.
1062 (setq depth
(+ (nth 2 state
) depth
))))
1064 ;; Increased depth, we found a block.
1065 ((> (* signum depth
) 0)
1067 ;; We're at the same depth as when we started, and we've
1068 ;; encountered a block before. Stop.
1069 ((and down
(zerop depth
))
1071 ;; Lower depth, means outer block, can stop now.
1072 ((< (* signum depth
) 0)
1074 (back-to-indentation)))
1076 (defun ruby-beginning-of-block (&optional arg
)
1077 "Move backward to the beginning of the current block.
1078 With ARG, move up multiple blocks."
1080 (ruby-move-to-block (- (or arg
1))))
1082 (defun ruby-end-of-block (&optional arg
)
1083 "Move forward to the end of the current block.
1084 With ARG, move out of multiple blocks."
1086 (ruby-move-to-block (or arg
1)))
1088 (defun ruby-forward-sexp (&optional arg
)
1089 "Move forward across one balanced expression (sexp).
1090 With ARG, do it many times. Negative ARG means move backward."
1091 ;; TODO: Document body
1093 (if (and (numberp arg
) (< arg
0))
1094 (ruby-backward-sexp (- arg
))
1095 (let ((i (or arg
1)))
1098 (skip-syntax-forward " ")
1099 (if (looking-at ",\\s *") (goto-char (match-end 0)))
1100 (cond ((looking-at "\\?\\(\\\\[CM]-\\)*\\\\?\\S ")
1101 (goto-char (match-end 0)))
1103 (skip-chars-forward ",.:;|&^~=!?\\+\\-\\*")
1104 (looking-at "\\s("))
1105 (goto-char (scan-sexps (point) 1)))
1106 ((and (looking-at (concat "\\<\\(" ruby-block-beg-re
"\\)\\>"))
1107 (not (eq (char-before (point)) ?.
))
1108 (not (eq (char-before (point)) ?
:)))
1111 ((looking-at "\\(\\$\\|@@?\\)?\\sw")
1113 (while (progn (forward-word 1) (looking-at "_")))
1114 (cond ((looking-at "::") (forward-char 2) t
)
1115 ((> (skip-chars-forward ".") 0))
1116 ((looking-at "\\?\\|!\\(=[~=>]\\|[^~=]\\)")
1117 (forward-char 1) nil
)))))
1121 (setq expr
(or expr
(ruby-expr-beg)
1122 (looking-at "%\\sw?\\Sw\\|[\"'`/]")))
1123 (nth 1 (setq state
(apply 'ruby-parse-partial nil state
))))
1125 (skip-chars-forward "<"))
1128 ((error) (forward-word 1)))
1131 (defun ruby-backward-sexp (&optional arg
)
1132 "Move backward across one balanced expression (sexp).
1133 With ARG, do it many times. Negative ARG means move forward."
1134 ;; TODO: Document body
1136 (if (and (numberp arg
) (< arg
0))
1137 (ruby-forward-sexp (- arg
))
1138 (let ((i (or arg
1)))
1141 (skip-chars-backward " \t\n,.:;|&^~=!?\\+\\-\\*")
1143 (cond ((looking-at "\\s)")
1144 (goto-char (scan-sexps (1+ (point)) -
1))
1146 (?%
(forward-char -
1))
1147 ((?q ?Q ?w ?W ?r ?x
)
1148 (if (eq (char-before (1- (point))) ?%
) (forward-char -
2))))
1150 ((looking-at "\\s\"\\|\\\\\\S_")
1151 (let ((c (char-to-string (char-before (match-end 0)))))
1152 (while (and (search-backward c
)
1153 (eq (logand (skip-chars-backward "\\") 1)
1156 ((looking-at "\\s.\\|\\s\\")
1157 (if (ruby-special-char-p) (forward-char -
1)))
1158 ((looking-at "\\s(") nil
)
1161 (while (progn (forward-word -
1)
1164 (?.
(forward-char -
1) t
)
1167 (and (eq (char-before) (char-after)) (forward-char -
1)))
1170 (eq (char-before) :)))))
1171 (if (looking-at ruby-block-end-re
)
1172 (ruby-beginning-of-block))
1178 (defun ruby-indent-exp (&optional ignored
)
1179 "Indent each line in the balanced expression following the point."
1181 (let ((here (point-marker)) start top column
(nest t
))
1182 (set-marker-insertion-type here t
)
1186 (setq start
(point) top
(current-indentation))
1187 (while (and (not (eobp))
1189 (setq column
(ruby-calculate-indent start
))
1190 (cond ((> column top
)
1192 ((and (= column top
) nest
)
1193 (setq nest nil
) t
))))
1194 (ruby-indent-to column
)
1195 (beginning-of-line 2)))
1197 (set-marker here nil
))))
1199 (defun ruby-add-log-current-method ()
1200 "Return the current method name as a string.
1201 This string includes all namespaces.
1210 See `add-log-current-defun-function'."
1213 (let* ((indent 0) mname mlist
1217 (concat "^[ \t]*" re
"[ \t]+"
1219 ;; \\. and :: for class methods
1220 "\\([A-Za-z_]" ruby-symbol-re
"*\\|\\.\\|::" "\\)"
1222 (definition-re (funcall make-definition-re ruby-defun-beg-re
))
1223 (module-re (funcall make-definition-re
"\\(class\\|module\\)")))
1224 ;; Get the current method definition (or class/module).
1225 (when (re-search-backward definition-re nil t
)
1226 (goto-char (match-beginning 1))
1227 (if (not (string-equal "def" (match-string 1)))
1228 (setq mlist
(list (match-string 2)))
1229 ;; We're inside the method. For classes and modules,
1230 ;; this check is skipped for performance.
1231 (when (ruby-block-contains-point start
)
1232 (setq mname
(match-string 2))))
1233 (setq indent
(current-column))
1234 (beginning-of-line))
1235 ;; Walk up the class/module nesting.
1236 (while (and (> indent
0)
1237 (re-search-backward module-re nil t
))
1238 (goto-char (match-beginning 1))
1239 (when (< (current-column) indent
)
1240 (setq mlist
(cons (match-string 2) mlist
))
1241 (setq indent
(current-column))
1242 (beginning-of-line)))
1243 ;; Process the method name.
1245 (let ((mn (split-string mname
"\\.\\|::")))
1248 (unless (string-equal "self" (car mn
)) ; def self.foo
1250 (let ((ml (nreverse mlist
)))
1251 ;; If the method name references one of the
1252 ;; containing modules, drop the more nested ones.
1254 (if (string-equal (car ml
) (car mn
))
1255 (setq mlist
(nreverse (cdr ml
)) ml nil
))
1256 (or (setq ml
(cdr ml
)) (nreverse mlist
))))
1258 (setcdr (last mlist
) (butlast mn
))
1259 (setq mlist
(butlast mn
))))
1260 (setq mname
(concat "." (car (last mn
)))))
1261 ;; See if the method is in singleton class context.
1262 (let ((in-singleton-class
1263 (when (re-search-forward ruby-singleton-class-re start t
)
1264 (goto-char (match-beginning 0))
1265 ;; FIXME: Optimize it out, too?
1266 ;; This can be slow in a large file, but
1267 ;; unlike class/module declaration
1268 ;; indentations, method definitions can be
1269 ;; intermixed with these, and may or may not
1270 ;; be additionally indented after visibility
1272 (ruby-block-contains-point start
))))
1274 (if in-singleton-class
"." "#")
1276 ;; Generate the string.
1278 (setq mlist
(mapconcat (function identity
) mlist
"::")))
1280 (if mlist
(concat mlist mname
) mname
)
1283 (defun ruby-block-contains-point (pt)
1289 (defun ruby-brace-to-do-end (orig end
)
1290 (let (beg-marker end-marker
)
1292 (when (eq (char-before) ?\
})
1294 (when (save-excursion
1295 (skip-chars-backward " \t")
1299 (setq end-marker
(point-marker))
1300 (when (and (not (eobp)) (eq (char-syntax (char-after)) ?w
))
1304 (when (eq (char-syntax (char-before)) ?w
)
1307 (setq beg-marker
(point-marker))
1308 (when (looking-at "\\(\\s \\)*|")
1309 (unless (match-beginning 1)
1311 (goto-char (1+ (match-end 0)))
1312 (search-forward "|"))
1313 (unless (looking-at "\\s *$")
1315 (indent-region beg-marker end-marker
)
1316 (goto-char beg-marker
)
1319 (defun ruby-do-end-to-brace (orig end
)
1320 (let (beg-marker end-marker beg-pos end-pos
)
1321 (goto-char (- end
3))
1322 (when (looking-at ruby-block-end-re
)
1324 (setq end-marker
(point-marker))
1329 (setq beg-marker
(point-marker))
1330 (when (looking-at "\\s +|")
1331 (delete-char (- (match-end 0) (match-beginning 0) 1))
1333 (re-search-forward "|" (line-end-position) t
))
1335 (skip-chars-forward " \t\n\r")
1336 (setq beg-pos
(point))
1337 (goto-char end-marker
)
1338 (skip-chars-backward " \t\n\r")
1339 (setq end-pos
(point)))
1342 (and (= (line-number-at-pos beg-pos
) (line-number-at-pos end-pos
))
1343 (< (+ (current-column) (- end-pos beg-pos
) 2) fill-column
)))
1345 (goto-char end-marker
)
1346 (just-one-space -
1))
1347 (goto-char beg-marker
)
1350 (defun ruby-toggle-block ()
1351 "Toggle block type from do-end to braces or back.
1352 The block must begin on the current line or above it and end after the point.
1353 If the result is do-end block, it will always be multiline."
1355 (let ((start (point)) beg end
)
1358 (if (and (re-search-backward "\\({\\)\\|\\_<do\\(\\s \\|$\\||\\)")
1361 (save-match-data (ruby-forward-sexp))
1364 (if (match-beginning 1)
1365 (ruby-brace-to-do-end beg end
)
1366 (ruby-do-end-to-brace beg end
)))
1367 (goto-char start
))))
1369 (declare-function ruby-syntax-propertize-heredoc
"ruby-mode" (limit))
1370 (declare-function ruby-syntax-enclosing-percent-literal
"ruby-mode" (limit))
1371 (declare-function ruby-syntax-propertize-percent-literal
"ruby-mode" (limit))
1372 ;; Unusual code layout confuses the byte-compiler.
1373 (declare-function ruby-syntax-propertize-expansion
"ruby-mode" ())
1374 (declare-function ruby-syntax-expansion-allowed-p
"ruby-mode" (parse-state))
1376 (if (eval-when-compile (fboundp #'syntax-propertize-rules
))
1377 ;; New code that works independently from font-lock.
1380 (defconst ruby-percent-literal-beg-re
1381 "\\(%\\)[qQrswWxIi]?\\([[:punct:]]\\)"
1382 "Regexp to match the beginning of percent literal.")
1384 (defconst ruby-syntax-methods-before-regexp
1385 '("gsub" "gsub!" "sub" "sub!" "scan" "split" "split!" "index" "match"
1386 "assert_match" "Given" "Then" "When")
1387 "Methods that can take regexp as the first argument.
1388 It will be properly highlighted even when the call omits parens.")
1390 (defvar ruby-syntax-before-regexp-re
1392 ;; Special tokens that can't be followed by a division operator.
1394 ;; Distinguish ternary operator tokens.
1395 ;; FIXME: They don't really have to be separated with spaces.
1397 ;; Control flow keywords and operators following bol or whitespace.
1398 "\\|\\(?:^\\|\\s \\)"
1399 (regexp-opt '("if" "elsif" "unless" "while" "until" "when" "and"
1400 "or" "not" "&&" "||"))
1401 ;; Method name from the list.
1403 (regexp-opt ruby-syntax-methods-before-regexp
)
1405 "Regexp to match text that can be followed by a regular expression."))
1407 (defun ruby-syntax-propertize-function (start end
)
1408 "Syntactic keywords for Ruby mode. See `syntax-propertize-function'."
1409 (let (case-fold-search)
1411 (remove-text-properties start end
'(ruby-expansion-match-data))
1412 (ruby-syntax-propertize-heredoc end
)
1413 (ruby-syntax-enclosing-percent-literal end
)
1415 (syntax-propertize-rules
1416 ;; $' $" $` .... are variables.
1417 ;; ?' ?" ?` are character literals (one-char strings in 1.9+).
1418 ("\\([?$]\\)[#\"'`]"
1419 (1 (unless (save-excursion
1420 ;; Not within a string.
1421 (nth 3 (syntax-ppss (match-beginning 0))))
1422 (string-to-syntax "\\"))))
1423 ;; Regular expressions. Start with matching unescaped slash.
1424 ("\\(?:\\=\\|[^\\]\\)\\(?:\\\\\\\\\\)*\\(/\\)"
1425 (1 (let ((state (save-excursion (syntax-ppss (match-beginning 1)))))
1427 ;; Beginning of a regexp.
1428 (and (null (nth 8 state
))
1431 (looking-back ruby-syntax-before-regexp-re
1433 ;; End of regexp. We don't match the whole
1434 ;; regexp at once because it can have
1435 ;; string interpolation inside, or span
1437 (eq ?
/ (nth 3 state
)))
1438 (string-to-syntax "\"/")))))
1439 ;; Expression expansions in strings. We're handling them
1440 ;; here, so that the regexp rule never matches inside them.
1441 (ruby-expression-expansion-re
1442 (0 (ignore (ruby-syntax-propertize-expansion))))
1443 ("^=en\\(d\\)\\_>" (1 "!"))
1444 ("^\\(=\\)begin\\_>" (1 "!"))
1445 ;; Handle here documents.
1446 ((concat ruby-here-doc-beg-re
".*\\(\n\\)")
1447 (7 (unless (or (nth 8 (save-excursion
1448 (syntax-ppss (match-beginning 0))))
1449 (ruby-singleton-class-p (match-beginning 0)))
1450 (put-text-property (match-beginning 7) (match-end 7)
1451 'syntax-table
(string-to-syntax "\""))
1452 (ruby-syntax-propertize-heredoc end
))))
1453 ;; Handle percent literals: %w(), %q{}, etc.
1454 ((concat "\\(?:^\\|[[ \t\n<+(,=]\\)" ruby-percent-literal-beg-re
)
1455 (1 (prog1 "|" (ruby-syntax-propertize-percent-literal end
)))))
1458 (defun ruby-syntax-propertize-heredoc (limit)
1459 (let ((ppss (syntax-ppss))
1461 (when (eq ?
\n (nth 3 ppss
))
1463 (goto-char (nth 8 ppss
))
1465 (while (re-search-forward ruby-here-doc-beg-re
1466 (line-end-position) t
)
1467 (unless (ruby-singleton-class-p (match-beginning 0))
1468 (push (concat (ruby-here-doc-end-match) "\n") res
))))
1470 ;; With multiple openers on the same line, we don't know in which
1471 ;; part `start' is, so we have to go back to the beginning.
1473 (goto-char (nth 8 ppss
))
1474 (setq res
(nreverse res
)))
1475 (while (and res
(re-search-forward (pop res
) limit
'move
))
1477 (put-text-property (1- (point)) (point)
1478 'syntax-table
(string-to-syntax "\""))))
1479 ;; End up at bol following the heredoc openers.
1480 ;; Propertize expression expansions from this point forward.
1483 (defun ruby-syntax-enclosing-percent-literal (limit)
1484 (let ((state (syntax-ppss))
1486 ;; When already inside percent literal, re-propertize it.
1487 (when (eq t
(nth 3 state
))
1488 (goto-char (nth 8 state
))
1489 (when (looking-at ruby-percent-literal-beg-re
)
1490 (ruby-syntax-propertize-percent-literal limit
))
1491 (when (< (point) start
) (goto-char start
)))))
1493 (defun ruby-syntax-propertize-percent-literal (limit)
1494 (goto-char (match-beginning 2))
1495 ;; Not inside a simple string or comment.
1496 (when (eq t
(nth 3 (syntax-ppss)))
1497 (let* ((op (char-after))
1498 (ops (char-to-string op
))
1499 (cl (or (cdr (aref (syntax-table) op
))
1500 (cdr (assoc op
'((?
< . ?
>))))))
1501 parse-sexp-lookup-properties
)
1505 (if cl
; Paired delimiters.
1506 ;; Delimiter pairs of the same kind can be nested
1507 ;; inside the literal, as long as they are balanced.
1508 ;; Create syntax table that ignores other characters.
1509 (with-syntax-table (make-char-table 'syntax-table nil
)
1510 (modify-syntax-entry op
(concat "(" (char-to-string cl
)))
1511 (modify-syntax-entry cl
(concat ")" ops
))
1512 (modify-syntax-entry ?
\\ "\\")
1514 (narrow-to-region (point) limit
)
1515 (forward-list))) ; skip to the paired character
1516 ;; Single character delimiter.
1517 (re-search-forward (concat "[^\\]\\(?:\\\\\\\\\\)*"
1518 (regexp-quote ops
)) limit nil
))
1519 ;; Found the closing delimiter.
1520 (put-text-property (1- (point)) (point) 'syntax-table
1521 (string-to-syntax "|")))
1522 ;; Unclosed literal, do nothing.
1523 ((scan-error search-failed
)))))))
1525 (defun ruby-syntax-propertize-expansion ()
1526 ;; Save the match data to a text property, for font-locking later.
1527 ;; Set the syntax of all double quotes and backticks to punctuation.
1528 (let* ((beg (match-beginning 2))
1530 (state (and beg
(save-excursion (syntax-ppss beg
)))))
1531 (when (ruby-syntax-expansion-allowed-p state
)
1532 (put-text-property beg
(1+ beg
) 'ruby-expansion-match-data
1535 (while (re-search-forward "[\"`]" end
'move
)
1536 (put-text-property (match-beginning 0) (match-end 0)
1537 'syntax-table
(string-to-syntax "."))))))
1539 (defun ruby-syntax-expansion-allowed-p (parse-state)
1540 "Return non-nil if expression expansion is allowed."
1541 (let ((term (nth 3 parse-state
)))
1543 ((memq term
'(?
\" ?
` ?
\n ?
/)))
1547 (goto-char (nth 8 parse-state
))
1548 (looking-at "%\\(?:[QWrxI]\\|\\W\\)")))))))
1550 (defun ruby-syntax-propertize-expansions (start end
)
1553 (while (re-search-forward ruby-expression-expansion-re end
'move
)
1554 (ruby-syntax-propertize-expansion))))
1557 ;; For Emacsen where syntax-propertize-rules is not (yet) available,
1558 ;; fallback on the old font-lock-syntactic-keywords stuff.
1560 (defconst ruby-here-doc-end-re
1561 "^\\([ \t]+\\)?\\(.*\\)\\(\n\\)"
1562 "Regexp to match the end of heredocs.
1564 This will actually match any line with one or more characters.
1565 It's useful in that it divides up the match string so that
1566 `ruby-here-doc-beg-match' can search for the beginning of the heredoc.")
1568 (defun ruby-here-doc-beg-match ()
1569 "Return a regexp to find the beginning of a heredoc.
1571 This should only be called after matching against `ruby-here-doc-end-re'."
1572 (let ((contents (concat
1573 (regexp-quote (concat (match-string 2) (match-string 3)))
1574 (if (string= (match-string 3) "_") "\\B" "\\b"))))
1576 (let ((match (match-string 1)))
1577 (if (and match
(> (length match
) 0))
1578 (concat "\\(?:-\\([\"']?\\)\\|\\([\"']\\)"
1579 (match-string 1) "\\)"
1580 contents
"\\(\\1\\|\\2\\)")
1581 (concat "-?\\([\"']\\|\\)" contents
"\\1"))))))
1583 (defconst ruby-font-lock-syntactic-keywords
1585 ;; the last $', $", $` in the respective string is not variable
1586 ;; the last ?', ?", ?` in the respective string is not ascii code
1587 ("\\(^\\|[\[ \t\n<+\(,=]\\)\\(['\"`]\\)\\(\\\\.\\|\\2\\|[^'\"`\n\\\\]\\)*?\\\\?[?$]\\(\\2\\)"
1590 ;; $' $" $` .... are variables
1591 ;; ?' ?" ?` are ascii codes
1592 ("\\(^\\|[^\\\\]\\)\\(\\\\\\\\\\)*[?$]\\([#\"'`]\\)" 3 (1 . nil
))
1594 ("\\(^\\|[[=(,~?:;<>]\\|\\(^\\|\\s \\)\\(if\\|elsif\\|unless\\|while\\|until\\|when\\|and\\|or\\|&&\\|||\\)\\|g?sub!?\\|scan\\|split!?\\)\\s *\\(/\\)[^/\n\\\\]*\\(\\\\.[^/\n\\\\]*\\)*\\(/\\)"
1597 ("^=en\\(d\\)\\_>" 1 "!")
1599 ("\\(^\\|[[ \t\n<+(,=]\\)\\(%[xrqQwW]?\\([^<[{(a-zA-Z0-9 \n]\\)[^\n\\\\]*\\(\\\\.[^\n\\\\]*\\)*\\(\\3\\)\\)"
1602 ("^\\(=\\)begin\\_>" 1 (ruby-comment-beg-syntax))
1603 ;; Currently, the following case is highlighted incorrectly:
1612 ;; This is because all here-doc beginnings are highlighted before any endings,
1613 ;; so although <<BAR is properly marked as a beginning, when we get to <<BAZ
1614 ;; it thinks <<BAR is part of a string so it's marked as well.
1616 ;; This may be fixable by modifying ruby-in-here-doc-p to use
1617 ;; ruby-in-non-here-doc-string-p rather than syntax-ppss-context,
1618 ;; but I don't want to try that until we've got unit tests set up
1619 ;; to make sure I don't break anything else.
1620 (,(concat ruby-here-doc-beg-re
".*\\(\n\\)")
1621 ,(+ 1 (regexp-opt-depth ruby-here-doc-beg-re
))
1622 (ruby-here-doc-beg-syntax))
1623 (,ruby-here-doc-end-re
3 (ruby-here-doc-end-syntax)))
1624 "Syntactic keywords for Ruby mode. See `font-lock-syntactic-keywords'.")
1626 (defun ruby-comment-beg-syntax ()
1627 "Return the syntax cell for a the first character of a =begin.
1628 See the definition of `ruby-font-lock-syntactic-keywords'.
1630 This returns a comment-delimiter cell as long as the =begin
1631 isn't in a string or another comment."
1632 (when (not (nth 3 (syntax-ppss)))
1633 (string-to-syntax "!")))
1635 (defun ruby-in-here-doc-p ()
1636 "Return whether or not the point is in a heredoc."
1638 (let ((old-point (point)) (case-fold-search nil
))
1641 (while (and (re-search-backward ruby-here-doc-beg-re nil t
)
1642 (not (ruby-singleton-class-p)))
1643 (if (not (or (ruby-in-ppss-context-p 'anything
)
1644 (ruby-here-doc-find-end old-point
)))
1645 (throw 'found-beg t
)))))))
1647 (defun ruby-here-doc-find-end (&optional limit
)
1648 "Expects the point to be on a line with one or more heredoc openers.
1649 Returns the buffer position at which all heredocs on the line
1650 are terminated, or nil if they aren't terminated before the
1651 buffer position `limit' or the end of the buffer."
1655 (let ((eol (point-at-eol))
1656 (case-fold-search nil
)
1657 ;; Fake match data such that (match-end 0) is at eol
1658 (end-match-data (progn (looking-at ".*$") (match-data)))
1659 beg-match-data end-re
)
1660 (while (re-search-forward ruby-here-doc-beg-re eol t
)
1661 (setq beg-match-data
(match-data))
1662 (setq end-re
(ruby-here-doc-end-match))
1664 (set-match-data end-match-data
)
1665 (goto-char (match-end 0))
1666 (unless (re-search-forward end-re limit t
) (throw 'done nil
))
1667 (setq end-match-data
(match-data))
1669 (set-match-data beg-match-data
)
1670 (goto-char (match-end 0)))
1671 (set-match-data end-match-data
)
1672 (goto-char (match-end 0))
1675 (defun ruby-here-doc-beg-syntax ()
1676 "Return the syntax cell for a line that may begin a heredoc.
1677 See the definition of `ruby-font-lock-syntactic-keywords'.
1679 This sets the syntax cell for the newline ending the line
1680 containing the heredoc beginning so that cases where multiple
1681 heredocs are started on one line are handled correctly."
1683 (goto-char (match-beginning 0))
1684 (unless (or (ruby-in-ppss-context-p 'non-heredoc
)
1685 (ruby-in-here-doc-p))
1686 (string-to-syntax "\""))))
1688 (defun ruby-here-doc-end-syntax ()
1689 "Return the syntax cell for a line that may end a heredoc.
1690 See the definition of `ruby-font-lock-syntactic-keywords'."
1691 (let ((pss (syntax-ppss)) (case-fold-search nil
))
1692 ;; If we aren't in a string, we definitely aren't ending a heredoc,
1693 ;; so we can just give up.
1694 ;; This means we aren't doing a full-document search
1695 ;; every time we enter a character.
1696 (when (ruby-in-ppss-context-p 'heredoc pss
)
1698 (goto-char (nth 8 pss
)) ; Go to the beginning of heredoc.
1699 (let ((eol (point)))
1701 (if (and (re-search-forward (ruby-here-doc-beg-match) eol t
) ; If there is a heredoc that matches this line...
1702 (not (ruby-in-ppss-context-p 'anything
)) ; And that's not inside a heredoc/string/comment...
1703 (progn (goto-char (match-end 0)) ; And it's the last heredoc on its line...
1704 (not (re-search-forward ruby-here-doc-beg-re eol t
))))
1705 (string-to-syntax "\"")))))))
1707 (unless (functionp 'syntax-ppss
)
1708 (defun syntax-ppss (&optional pos
)
1709 (parse-partial-sexp (point-min) (or pos
(point)))))
1712 (defun ruby-in-ppss-context-p (context &optional ppss
)
1713 (let ((ppss (or ppss
(syntax-ppss (point)))))
1715 ((eq context
'anything
)
1718 ((eq context
'string
)
1720 ((eq context
'heredoc
)
1721 (eq ?
\n (nth 3 ppss
)))
1722 ((eq context
'non-heredoc
)
1723 (and (ruby-in-ppss-context-p 'anything
)
1724 (not (ruby-in-ppss-context-p 'heredoc
))))
1725 ((eq context
'comment
)
1729 "Internal error on `ruby-in-ppss-context-p': "
1730 "context name `" (symbol-name context
) "' is unknown"))))
1733 (if (featurep 'xemacs
)
1734 (put 'ruby-mode
'font-lock-defaults
1735 '((ruby-font-lock-keywords)
1738 (font-lock-syntactic-keywords
1739 . ruby-font-lock-syntactic-keywords
))))
1741 (defvar ruby-font-lock-syntax-table
1742 (let ((tbl (copy-syntax-table ruby-mode-syntax-table
)))
1743 (modify-syntax-entry ?_
"w" tbl
)
1745 "The syntax table to use for fontifying Ruby mode buffers.
1746 See `font-lock-syntax-table'.")
1748 (defconst ruby-font-lock-keyword-beg-re
"\\(?:^\\|[^.@$]\\|\\.\\.\\)")
1750 (defconst ruby-font-lock-keywords
1753 '("^\\s *def\\s +\\(?:[^( \t\n.]*\\.\\)?\\([^( \t\n]+\\)"
1754 1 font-lock-function-name-face
)
1757 ruby-font-lock-keyword-beg-re
1793 1 'font-lock-keyword-face
)
1794 ;; some core methods
1796 ruby-font-lock-keyword-beg-re
1798 '(;; built-in methods on Kernel
1842 ;; keyword-like private methods on Module
1859 1 'font-lock-builtin-face
)
1860 ;; Perl-ish keywords
1861 "\\_<\\(?:BEGIN\\|END\\)\\_>\\|^__END__$"
1862 ;; here-doc beginnings
1863 `(,ruby-here-doc-beg-re
0 (unless (ruby-singleton-class-p (match-beginning 0))
1864 'font-lock-string-face
))
1866 `(,(concat ruby-font-lock-keyword-beg-re
1867 "\\_<\\(nil\\|self\\|true\\|false\\)\\>")
1868 1 font-lock-variable-name-face
)
1869 ;; keywords that evaluate to certain values
1870 '("\\_<__\\(?:LINE\\|ENCODING\\|FILE\\)__\\_>" 0 font-lock-variable-name-face
)
1872 '("\\(^\\|[^:]\\)\\(:\\([-+~]@?\\|[/%&|^`]\\|\\*\\*?\\|<\\(<\\|=>?\\)?\\|>[>=]?\\|===?\\|=~\\|![~=]?\\|\\[\\]=?\\|@?\\(\\w\\|_\\)+\\([!?=]\\|\\b_*\\)\\|#{[^}\n\\\\]*\\(\\\\.[^}\n\\\\]*\\)*}\\)\\)"
1873 2 font-lock-constant-face
)
1875 '("\\(\\$\\([^a-zA-Z0-9 \n]\\|[0-9]\\)\\)\\W"
1876 1 font-lock-variable-name-face
)
1877 '("\\(\\$\\|@\\|@@\\)\\(\\w\\|_\\)+"
1878 0 font-lock-variable-name-face
)
1880 '("\\(?:\\_<\\|::\\)\\([A-Z]+\\(\\w\\|_\\)*\\)"
1881 1 (unless (eq ?\
( (char-after)) font-lock-type-face
))
1882 '("\\(^\\s *\\|[\[\{\(,]\\s *\\|\\sw\\s +\\)\\(\\(\\sw\\|_\\)+\\):[^:]" 2 font-lock-constant-face
)
1883 ;; conversion methods on Kernel
1884 (list (concat ruby-font-lock-keyword-beg-re
1885 (regexp-opt '("Array" "Complex" "Float" "Hash"
1886 "Integer" "Rational" "String") 'symbols
))
1887 1 font-lock-builtin-face
)
1888 ;; expression expansion
1889 '(ruby-match-expression-expansion
1890 2 font-lock-variable-name-face t
)
1892 '("[^[:alnum:]_]\\(!\\)[^=]"
1893 1 font-lock-negation-char-face
)
1894 ;; character literals
1895 ;; FIXME: Support longer escape sequences.
1896 '("\\_<\\?\\\\?\\S " 0 font-lock-string-face
)
1898 "Additional expressions to highlight in Ruby mode.")
1900 (defun ruby-match-expression-expansion (limit)
1901 (let* ((prop 'ruby-expansion-match-data
)
1902 (pos (next-single-char-property-change (point) prop nil limit
))
1904 (when (and pos
(> pos
(point)))
1906 (or (and (setq value
(get-text-property pos prop
))
1907 (progn (set-match-data value
) t
))
1908 (ruby-match-expression-expansion limit
)))))
1911 (define-derived-mode ruby-mode prog-mode
"Ruby"
1912 "Major mode for editing Ruby scripts.
1913 \\[ruby-indent-line] properly indents subexpressions of multi-line
1914 class, module, def, if, while, for, do, and case statements, taking
1915 nesting into account.
1917 The variable `ruby-indent-level' controls the amount of indentation.
1920 (ruby-mode-variables)
1922 (set (make-local-variable 'imenu-create-index-function
)
1923 'ruby-imenu-create-index
)
1924 (set (make-local-variable 'add-log-current-defun-function
)
1925 'ruby-add-log-current-method
)
1926 (set (make-local-variable 'beginning-of-defun-function
)
1927 'ruby-beginning-of-defun
)
1928 (set (make-local-variable 'end-of-defun-function
)
1932 (cond ((boundp 'before-save-hook
) 'before-save-hook
)
1933 ((boundp 'write-contents-functions
) 'write-contents-functions
)
1934 ((boundp 'write-contents-hooks
) 'write-contents-hooks
))
1935 'ruby-mode-set-encoding nil
'local
)
1937 (set (make-local-variable 'electric-indent-chars
)
1938 (append '(?\
{ ?\
}) electric-indent-chars
))
1940 (set (make-local-variable 'font-lock-defaults
)
1941 '((ruby-font-lock-keywords) nil nil
))
1942 (set (make-local-variable 'font-lock-keywords
)
1943 ruby-font-lock-keywords
)
1944 (set (make-local-variable 'font-lock-syntax-table
)
1945 ruby-font-lock-syntax-table
)
1947 (if (eval-when-compile (fboundp 'syntax-propertize-rules
))
1948 (set (make-local-variable 'syntax-propertize-function
)
1949 #'ruby-syntax-propertize-function
)
1950 (set (make-local-variable 'font-lock-syntactic-keywords
)
1951 ruby-font-lock-syntactic-keywords
)))
1953 ;;; Invoke ruby-mode when appropriate
1956 (add-to-list 'auto-mode-alist
1957 (cons (purecopy (concat "\\(?:\\."
1958 "rb\\|ru\\|rake\\|thor"
1959 "\\|jbuilder\\|gemspec"
1961 "\\(?:Gem\\|Rake\\|Cap\\|Thor"
1962 "Vagrant\\|Guard\\)file"
1963 "\\)\\'")) 'ruby-mode
))
1966 (dolist (name (list "ruby" "rbx" "jruby" "ruby1.9" "ruby1.8"))
1967 (add-to-list 'interpreter-mode-alist
(cons (purecopy name
) 'ruby-mode
)))
1969 (provide 'ruby-mode
)
1971 ;;; ruby-mode.el ends here