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")
257 ("while" insts
"end")
258 ("until" insts
"end")
259 ("unless" insts
"end")
261 ("case" cases
"end"))
262 (for-body (for-head ";" insts
))
263 (for-head (id "in" exp
))
264 (cases (exp "then" insts
) ;; FIXME: Ruby also allows (exp ":" insts).
265 (cases "when" cases
) (insts "else" insts
))
266 (expseq (exp) );;(expseq "," expseq)
267 (hashvals (id "=>" exp1
) (hashvals "," hashvals
))
268 (insts-rescue-insts (insts)
269 (insts-rescue-insts "rescue" insts-rescue-insts
)
270 (insts-rescue-insts "ensure" insts-rescue-insts
))
271 (itheni (insts) (exp "then" insts
))
272 (ielsei (itheni) (itheni "else" insts
))
273 (if-body (ielsei) (if-body "elsif" if-body
)))
274 '((nonassoc "in") (assoc ";") (assoc ","))
277 '((assoc "rescue" "ensure"))
280 (defun ruby-smie--bosp ()
281 (save-excursion (skip-chars-backward " \t")
282 (or (bolp) (eq (char-before) ?\
;))))
284 (defun ruby-smie--implicit-semi-p ()
286 (skip-chars-backward " \t")
288 (memq (char-before) '(?\
; ?- ?+ ?* ?/ ?:))
289 (and (memq (char-before) '(?
\? ?
=))
290 (not (memq (char-syntax (char-before (1- (point))))
293 (defun ruby-smie--forward-token ()
294 (skip-chars-forward " \t")
295 (if (and (looking-at "[\n#]")
296 ;; Only add implicit ; when needed.
297 (ruby-smie--implicit-semi-p))
299 (if (eolp) (forward-char 1) (forward-comment 1))
301 (forward-comment (point-max))
302 (let ((tok (smie-default-forward-token)))
304 ((member tok
'("unless" "if" "while" "until"))
305 (if (save-excursion (forward-word -
1) (ruby-smie--bosp))
309 (defun ruby-smie--backward-token ()
311 (forward-comment (- (point)))
312 (if (and (> pos
(line-end-position))
313 (ruby-smie--implicit-semi-p))
314 (progn (skip-chars-forward " \t")
316 (let ((tok (smie-default-backward-token)))
318 ((member tok
'("unless" "if" "while" "until"))
319 (if (ruby-smie--bosp)
323 (defun ruby-smie-rules (kind token
)
324 (pcase (cons kind token
)
325 (`(:elem . basic
) ruby-indent-level
)
327 (if (smie-rule-parent-p "def" "begin" "do" "class" "module" "for"
328 "[" "{" "while" "until" "unless"
329 "if" "then" "elsif" "else" "when"
331 (smie-rule-parent ruby-indent-level
)
332 ;; For (invalid) code between switch and case.
333 ;; (if (smie-parent-p "switch") 4)
335 (`(:before .
,(or `"else" `"then" `"elsif")) 0)
336 (`(:before .
,(or `"when"))
337 (if (not (smie-rule-sibling-p)) 0)) ;; ruby-indent-level
338 ;; Hack attack: Since newlines are separators, don't try to align args that
339 ;; appear on a separate line.
340 (`(:list-intro .
";") t
)))
342 (defun ruby-imenu-create-index-in-block (prefix beg end
)
343 "Create an imenu index of methods inside a block."
344 (let ((index-alist '()) (case-fold-search nil
)
345 name next pos decl sing
)
347 (while (re-search-forward "^\\s *\\(\\(class\\s +\\|\\(class\\s *<<\\s *\\)\\|module\\s +\\)\\([^\(<\n ]+\\)\\|\\(def\\|alias\\)\\s +\\([^\(\n ]+\\)\\)" end t
)
348 (setq sing
(match-beginning 3))
349 (setq decl
(match-string 5))
350 (setq next
(match-end 0))
351 (setq name
(or (match-string 4) (match-string 6)))
352 (setq pos
(match-beginning 0))
354 ((string= "alias" decl
)
355 (if prefix
(setq name
(concat prefix name
)))
356 (push (cons name pos
) index-alist
))
357 ((string= "def" decl
)
361 ((string-match "^self\." name
)
362 (concat (substring prefix
0 -
1) (substring name
4)))
363 (t (concat prefix name
)))))
364 (push (cons name pos
) index-alist
)
365 (ruby-accurate-end-of-block end
))
367 (if (string= "self" name
)
368 (if prefix
(setq name
(substring prefix
0 -
1)))
369 (if prefix
(setq name
(concat (substring prefix
0 -
1) "::" name
)))
370 (push (cons name pos
) index-alist
))
371 (ruby-accurate-end-of-block end
)
374 (nconc (ruby-imenu-create-index-in-block
375 (concat name
(if sing
"." "#"))
376 next beg
) index-alist
))
380 (defun ruby-imenu-create-index ()
381 "Create an imenu index of all methods in the buffer."
382 (nreverse (ruby-imenu-create-index-in-block nil
(point-min) nil
)))
384 (defun ruby-accurate-end-of-block (&optional end
)
387 (end (or end
(point-max))))
388 (while (and (setq state
(apply 'ruby-parse-partial end state
))
389 (>= (nth 2 state
) 0) (< (point) end
)))))
391 (defun ruby-mode-variables ()
392 "Set up initial buffer-local variables for Ruby mode."
393 (set-syntax-table ruby-mode-syntax-table
)
394 (setq local-abbrev-table ruby-mode-abbrev-table
)
395 (setq indent-tabs-mode ruby-indent-tabs-mode
)
397 (smie-setup ruby-smie-grammar
#'ruby-smie-rules
398 :forward-token
#'ruby-smie--forward-token
399 :backward-token
#'ruby-smie--backward-token
)
400 (set (make-local-variable 'indent-line-function
) 'ruby-indent-line
))
401 (set (make-local-variable 'require-final-newline
) t
)
402 (set (make-local-variable 'comment-start
) "# ")
403 (set (make-local-variable 'comment-end
) "")
404 (set (make-local-variable 'comment-column
) ruby-comment-column
)
405 (set (make-local-variable 'comment-start-skip
) "#+ *")
406 (set (make-local-variable 'parse-sexp-ignore-comments
) t
)
407 (set (make-local-variable 'parse-sexp-lookup-properties
) t
)
408 (set (make-local-variable 'paragraph-start
) (concat "$\\|" page-delimiter
))
409 (set (make-local-variable 'paragraph-separate
) paragraph-start
)
410 (set (make-local-variable 'paragraph-ignore-fill-prefix
) t
))
412 (defun ruby-mode-set-encoding ()
413 "Insert a magic comment header with the proper encoding if necessary."
416 (goto-char (point-min))
417 (when (re-search-forward "[^\0-\177]" nil t
)
418 (goto-char (point-min))
420 (or coding-system-for-write
421 buffer-file-coding-system
)))
424 (or (coding-system-get coding-system
'mime-charset
)
425 (coding-system-change-eol-conversion coding-system nil
))))
429 (or (and ruby-use-encoding-map
430 (cdr (assq coding-system ruby-encoding-map
)))
433 (if (looking-at "^#!") (beginning-of-line 2))
434 (cond ((looking-at "\\s *#.*-\*-\\s *\\(en\\)?coding\\s *:\\s *\\([-a-z0-9_]*\\)\\s *\\(;\\|-\*-\\)")
435 (unless (string= (match-string 2) coding-system
)
436 (goto-char (match-beginning 2))
437 (delete-region (point) (match-end 2))
438 (and (looking-at "-\*-")
439 (let ((n (skip-chars-backward " ")))
440 (cond ((= n
0) (insert " ") (backward-char))
441 ((= n -
1) (insert " "))
443 (insert coding-system
)))
444 ((looking-at "\\s *#.*coding\\s *[:=]"))
445 (t (when ruby-insert-encoding-magic-comment
446 (insert "# -*- coding: " coding-system
" -*-\n"))))))))
448 (defun ruby-current-indentation ()
449 "Return the indentation level of current line."
452 (back-to-indentation)
455 (defun ruby-indent-line (&optional ignored
)
456 "Correct the indentation of the current Ruby line."
458 (ruby-indent-to (ruby-calculate-indent)))
460 (defun ruby-indent-to (column)
461 "Indent the current line to COLUMN."
464 (and (< column
0) (error "invalid nest"))
465 (setq shift
(current-column))
468 (back-to-indentation)
469 (setq top
(current-column))
470 (skip-chars-backward " \t")
471 (if (>= shift top
) (setq shift
(- shift top
))
475 (move-to-column (+ column shift
))
477 (delete-region beg
(point))
480 (move-to-column (+ column shift
))))))
482 (defun ruby-special-char-p (&optional pos
)
483 "Return t if the character before POS is a special character.
484 If omitted, POS defaults to the current point.
485 Special characters are `?', `$', `:' when preceded by whitespace,
486 and `\\' when preceded by `?'."
487 (setq pos
(or pos
(point)))
488 (let ((c (char-before pos
)) (b (and (< (point-min) pos
)
489 (char-before (1- pos
)))))
490 (cond ((or (eq c ??
) (eq c ?$
)))
491 ((and (eq c ?
:) (or (not b
) (eq (char-syntax b
) ?
))))
492 ((eq c ?
\\) (eq b ??
)))))
494 (defun ruby-singleton-class-p (&optional pos
)
496 (when pos
(goto-char pos
))
498 (and (or (bolp) (not (eq (char-before (point)) ?_
)))
499 (looking-at ruby-singleton-class-re
))))
501 (defun ruby-expr-beg (&optional option
)
502 "Check if point is possibly at the beginning of an expression.
503 OPTION specifies the type of the expression.
504 Can be one of `heredoc', `modifier', `expr-qstr', `expr-re'."
506 (store-match-data nil
)
507 (let ((space (skip-chars-backward " \t"))
513 (and (looking-at "\\?")
514 (or (eq (char-syntax (char-before (point))) ?w
)
515 (ruby-special-char-p))))
517 ((looking-at ruby-operator-re
))
518 ((eq option
'heredoc
)
519 (and (< space
0) (not (ruby-singleton-class-p start
))))
520 ((or (looking-at "[\\[({,;]")
521 (and (looking-at "[!?]")
522 (or (not (eq option
'modifier
))
524 (save-excursion (forward-char -
1) (looking-at "\\Sw$"))))
525 (and (looking-at ruby-symbol-re
)
526 (skip-chars-backward ruby-symbol-chars
)
528 ((looking-at (regexp-opt
529 (append ruby-block-beg-keywords
530 ruby-block-op-keywords
531 ruby-block-mid-keywords
)
533 (goto-char (match-end 0))
534 (not (looking-at "\\s_\\|!")))
535 ((eq option
'expr-qstr
)
536 (looking-at "[a-zA-Z][a-zA-z0-9_]* +%[^ \t]"))
537 ((eq option
'expr-re
)
538 (looking-at "[a-zA-Z][a-zA-z0-9_]* +/[^ \t]"))
541 (defun ruby-forward-string (term &optional end no-error expand
)
543 (let ((n 1) (c (string-to-char term
))
545 (concat "[^\\]\\(\\\\\\\\\\)*\\([" term
"]\\|\\(#{\\)\\)")
546 (concat "[^\\]\\(\\\\\\\\\\)*[" term
"]"))))
547 (while (and (re-search-forward re end no-error
)
548 (if (match-beginning 3)
549 (ruby-forward-string "}{" end no-error nil
)
550 (> (setq n
(if (eq (char-before (point)) c
)
555 ((error "unterminated string")))))
557 (defun ruby-deep-indent-paren-p (c)
559 (cond ((listp ruby-deep-indent-paren
)
560 (let ((deep (assoc c ruby-deep-indent-paren
)))
562 (or (cdr deep
) ruby-deep-indent-paren-style
))
563 ((memq c ruby-deep-indent-paren
)
564 ruby-deep-indent-paren-style
))))
565 ((eq c ruby-deep-indent-paren
) ruby-deep-indent-paren-style
)
566 ((eq c ?\
( ) ruby-deep-arglist
)))
568 (defun ruby-parse-partial (&optional end in-string nest depth pcol indent
)
569 "TODO: document throughout function body."
570 (or depth
(setq depth
0))
571 (or indent
(setq indent
0))
572 (when (re-search-forward ruby-delimiter end
'move
)
573 (let ((pnt (point)) w re expand
)
574 (goto-char (match-beginning 0))
576 ((and (memq (char-before) '(?
@ ?$
)) (looking-at "\\sw"))
578 ((looking-at "[\"`]") ;skip string
581 (ruby-forward-string (buffer-substring (point) (1+ (point))) end t t
))
584 (setq in-string
(point))
589 (re-search-forward "[^\\]\\(\\\\\\\\\\)*'" end t
))
592 (setq in-string
(point))
598 ((and (not (eobp)) (ruby-expr-beg 'expr-re
))
599 (if (ruby-forward-string "/" end t t
)
601 (setq in-string
(point))
608 (ruby-expr-beg 'expr-qstr
)
609 (not (looking-at "%="))
610 (looking-at "%[QqrxWw]?\\([^a-zA-Z0-9 \t\n]\\)"))
611 (goto-char (match-beginning 1))
612 (setq expand
(not (memq (char-before) '(?q ?w
))))
613 (setq w
(match-string 1))
615 ((string= w
"[") (setq re
"]["))
616 ((string= w
"{") (setq re
"}{"))
617 ((string= w
"(") (setq re
")("))
618 ((string= w
"<") (setq re
"><"))
619 ((and expand
(string= w
"\\"))
620 (setq w
(concat "\\" w
))))
621 (unless (cond (re (ruby-forward-string re end t expand
))
622 (expand (ruby-forward-string w end t t
))
623 (t (re-search-forward
626 (concat "[^\\]\\(\\\\\\\\\\)*" w
))
628 (setq in-string
(point))
632 ((looking-at "\\?") ;skip ?char
634 ((and (ruby-expr-beg)
635 (looking-at "?\\(\\\\C-\\|\\\\M-\\)*\\\\?."))
636 (goto-char (match-end 0)))
639 ((looking-at "\\$") ;skip $char
642 ((looking-at "#") ;skip comment
646 ((looking-at "[\\[{(]")
647 (let ((deep (ruby-deep-indent-paren-p (char-after))))
648 (if (and deep
(or (not (eq (char-after) ?\
{)) (ruby-expr-beg)))
650 (and (eq deep
'space
) (looking-at ".\\s +[^# \t\n]")
651 (setq pnt
(1- (match-end 0))))
652 (setq nest
(cons (cons (char-after (point)) pnt
) nest
))
653 (setq pcol
(cons (cons pnt depth
) pcol
))
655 (setq nest
(cons (cons (char-after (point)) pnt
) nest
))
656 (setq depth
(1+ depth
))))
659 ((looking-at "[])}]")
660 (if (ruby-deep-indent-paren-p (matching-paren (char-after)))
661 (setq depth
(cdr (car pcol
)) pcol
(cdr pcol
))
662 (setq depth
(1- depth
)))
663 (setq nest
(cdr nest
))
665 ((looking-at ruby-block-end-re
)
666 (if (or (and (not (bolp))
669 (setq w
(char-after (point)))
674 (setq w
(char-after (point)))
679 (setq nest
(cdr nest
))
680 (setq depth
(1- depth
)))
682 ((looking-at "def\\s +[^(\n;]*")
686 (not (eq ?_
(char-after (point))))))
688 (setq nest
(cons (cons nil pnt
) nest
))
689 (setq depth
(1+ depth
))))
690 (goto-char (match-end 0)))
691 ((looking-at (concat "\\_<\\(" ruby-block-beg-re
"\\)\\_>"))
694 (or (not (looking-at "do\\_>"))
696 (back-to-indentation)
697 (not (looking-at ruby-non-block-do-re
)))))
701 (setq w
(char-after (point)))
705 (not (eq ?
! (char-after (point))))
706 (skip-chars-forward " \t")
707 (goto-char (match-beginning 0))
708 (or (not (looking-at ruby-modifier-re
))
709 (ruby-expr-beg 'modifier
))
711 (setq nest
(cons (cons nil pnt
) nest
))
712 (setq depth
(1+ depth
)))
714 ((looking-at ":\\(['\"]\\)")
715 (goto-char (match-beginning 1))
716 (ruby-forward-string (match-string 1) end t
))
717 ((looking-at ":\\([-,.+*/%&|^~<>]=?\\|===?\\|<=>\\|![~=]?\\)")
718 (goto-char (match-end 0)))
719 ((looking-at ":\\([a-zA-Z_][a-zA-Z_0-9]*[!?=]?\\)?")
720 (goto-char (match-end 0)))
721 ((or (looking-at "\\.\\.\\.?")
722 (looking-at "\\.[0-9]+")
723 (looking-at "\\.[a-zA-Z_0-9]+")
725 (goto-char (match-end 0)))
726 ((looking-at "^=begin")
727 (if (re-search-forward "^=end" end t
)
729 (setq in-string
(match-end 0))
733 ((and (ruby-expr-beg 'heredoc
)
734 (looking-at "<<\\(-\\)?\\(\\([\"'`]\\)\\([^\n]+?\\)\\3\\|\\(?:\\sw\\|\\s_\\)+\\)"))
735 (setq re
(regexp-quote (or (match-string 4) (match-string 2))))
736 (if (match-beginning 1) (setq re
(concat "\\s *" re
)))
737 (let* ((id-end (goto-char (match-end 0)))
738 (line-end-position (point-at-eol))
739 (state (list in-string nest depth pcol indent
)))
740 ;; parse the rest of the line
741 (while (and (> line-end-position
(point))
742 (setq state
(apply 'ruby-parse-partial
743 line-end-position state
))))
744 (setq in-string
(car state
)
748 indent
(nth 4 state
))
749 ;; skip heredoc section
750 (if (re-search-forward (concat "^" re
"$") end
'move
)
752 (setq in-string id-end
)
756 ((looking-at "^__END__$")
758 ((and (looking-at ruby-here-doc-beg-re
)
759 (boundp 'ruby-indent-point
))
760 (if (re-search-forward (ruby-here-doc-end-match)
763 (setq in-string
(match-end 0))
764 (goto-char ruby-indent-point
)))
766 (error (format "bad string %s"
767 (buffer-substring (point) pnt
)
769 (list in-string nest depth pcol
))
771 (defun ruby-parse-region (start end
)
777 (ruby-beginning-of-indent))
779 (narrow-to-region (point) end
)
780 (while (and (> end
(point))
781 (setq state
(apply 'ruby-parse-partial end state
))))))
782 (list (nth 0 state
) ; in-string
783 (car (nth 1 state
)) ; nest
784 (nth 2 state
) ; depth
785 (car (car (nth 3 state
))) ; pcol
786 ;(car (nth 5 state)) ; indent
789 (defun ruby-indent-size (pos nest
)
790 "Return the indentation level in spaces NEST levels deeper than POS."
791 (+ pos
(* (or nest
1) ruby-indent-level
)))
793 (defun ruby-calculate-indent (&optional parse-start
)
794 "Return the proper indentation level of the current line."
795 ;; TODO: Document body
798 (let ((ruby-indent-point (point))
799 (case-fold-search nil
)
800 state eol begin op-end
801 (paren (progn (skip-syntax-forward " ")
802 (and (char-after) (matching-paren (char-after)))))
805 (goto-char parse-start
)
806 (ruby-beginning-of-indent)
807 (setq parse-start
(point)))
808 (back-to-indentation)
809 (setq indent
(current-column))
810 (setq state
(ruby-parse-region parse-start ruby-indent-point
))
812 ((nth 0 state
) ; within string
813 (setq indent nil
)) ; do nothing
814 ((car (nth 1 state
)) ; in paren
815 (goto-char (setq begin
(cdr (nth 1 state
))))
816 (let ((deep (ruby-deep-indent-paren-p (car (nth 1 state
)))))
818 (cond ((and (eq deep t
) (eq (car (nth 1 state
)) paren
))
819 (skip-syntax-backward " ")
820 (setq indent
(1- (current-column))))
821 ((let ((s (ruby-parse-region (point) ruby-indent-point
)))
822 (and (nth 2 s
) (> (nth 2 s
) 0)
823 (or (goto-char (cdr (nth 1 s
))) t
)))
825 (setq indent
(ruby-indent-size (current-column)
828 (setq indent
(current-column))
829 (cond ((eq deep
'space
))
830 (paren (setq indent
(1- indent
)))
831 (t (setq indent
(ruby-indent-size (1- indent
) 1))))))
832 (if (nth 3 state
) (goto-char (nth 3 state
))
833 (goto-char parse-start
) (back-to-indentation))
834 (setq indent
(ruby-indent-size (current-column) (nth 2 state
))))
835 (and (eq (car (nth 1 state
)) paren
)
836 (ruby-deep-indent-paren-p (matching-paren paren
))
837 (search-backward (char-to-string paren
))
838 (setq indent
(current-column)))))
839 ((and (nth 2 state
) (> (nth 2 state
) 0)) ; in nest
840 (if (null (cdr (nth 1 state
)))
841 (error "invalid nest"))
842 (goto-char (cdr (nth 1 state
)))
843 (forward-word -
1) ; skip back a keyword
846 ((looking-at "do\\>[^_]") ; iter block is a special case
847 (if (nth 3 state
) (goto-char (nth 3 state
))
848 (goto-char parse-start
) (back-to-indentation))
849 (setq indent
(ruby-indent-size (current-column) (nth 2 state
))))
851 (setq indent
(+ (current-column) ruby-indent-level
)))))
853 ((and (nth 2 state
) (< (nth 2 state
) 0)) ; in negative nest
854 (setq indent
(ruby-indent-size (current-column) (nth 2 state
)))))
856 (goto-char ruby-indent-point
)
861 ((and (not (ruby-deep-indent-paren-p paren
))
862 (re-search-forward ruby-negative eol t
))
863 (and (not (eq ?_
(char-after (match-end 0))))
864 (setq indent
(- indent ruby-indent-level
))))
869 (or (ruby-deep-indent-paren-p t
)
870 (null (car (nth 1 state
)))))
871 ;; goto beginning of non-empty no-comment line
874 (skip-chars-backward " \t\n")
877 (if (re-search-forward "^\\s *#" end t
)
881 ;; skip the comment at the end
882 (skip-chars-backward " \t")
883 (let (end (pos (point)))
885 (while (and (re-search-forward "#" pos t
)
886 (setq end
(1- (point)))
887 (or (ruby-special-char-p end
)
888 (and (setq state
(ruby-parse-region parse-start end
))
891 (goto-char (or end pos
))
892 (skip-chars-backward " \t")
893 (setq begin
(if (and end
(nth 0 state
)) pos
(cdr (nth 1 state
))))
894 (setq state
(ruby-parse-region parse-start
(point))))
895 (or (bobp) (forward-char -
1))
897 (or (and (looking-at ruby-symbol-re
)
898 (skip-chars-backward ruby-symbol-chars
)
899 (looking-at (concat "\\<\\(" ruby-block-hanging-re
"\\)\\>"))
900 (not (eq (point) (nth 3 state
)))
902 (goto-char (match-end 0))
903 (not (looking-at "[a-z_]"))))
904 (and (looking-at ruby-operator-re
)
905 (not (ruby-special-char-p))
906 ;; Operator at the end of line.
907 (let ((c (char-after (point))))
912 ;; (skip-chars-forward " \t")
913 ;; (not (or (eolp) (looking-at "#")
914 ;; (and (eq (car (nth 1 state)) ?{)
915 ;; (looking-at "|"))))))
916 ;; Not a regexp or percent literal.
917 (null (nth 0 (ruby-parse-region (or begin parse-start
)
919 (or (not (eq ?|
(char-after (point))))
921 (or (eolp) (forward-char -
1))
923 ((search-backward "|" nil t
)
924 (skip-chars-backward " \t\n")
928 (not (looking-at "{")))
931 (not (looking-at "do\\>[^_]")))))
939 (not (looking-at (concat "\\<\\(" ruby-block-hanging-re
"\\)\\>")))
940 (eq (ruby-deep-indent-paren-p t
) 'space
)
943 (goto-char (or begin parse-start
))
944 (skip-syntax-forward " ")
946 ((car (nth 1 state
)) indent
)
948 (+ indent ruby-indent-level
))))))))
949 (goto-char ruby-indent-point
)
951 (skip-syntax-forward " ")
952 (if (looking-at "\\.[^.]")
953 (+ indent ruby-indent-level
)
956 (defun ruby-beginning-of-defun (&optional arg
)
957 "Move backward to the beginning of the current defun.
958 With ARG, move backward multiple defuns. Negative ARG means
961 (let (case-fold-search)
962 (and (re-search-backward (concat "^\\s *" ruby-defun-beg-re
"\\_>")
964 (beginning-of-line))))
966 (defun ruby-end-of-defun ()
967 "Move point to the end of the current defun.
968 The defun begins at or after the point. This function is called
972 (let (case-fold-search)
973 (when (looking-back (concat "^\\s *" ruby-block-end-re
))
976 (defun ruby-beginning-of-indent ()
977 "Backtrack to a line which can be used as a reference for
978 calculating indentation on the lines after it."
979 (while (and (re-search-backward ruby-indent-beg-re nil
'move
)
980 (if (ruby-in-ppss-context-p 'anything
)
982 ;; We can stop, then.
983 (beginning-of-line)))))
985 (defun ruby-move-to-block (n)
986 "Move to the beginning (N < 0) or the end (N > 0) of the
987 current block, a sibling block, or an outer block. Do that (abs N) times."
988 (back-to-indentation)
989 (let ((signum (if (> n
0) 1 -
1))
991 (depth (or (nth 2 (ruby-parse-region (point) (line-end-position))) 0))
994 (when (looking-at ruby-block-mid-re
)
995 (setq depth
(+ depth signum
)))
996 (when (< (* depth signum
) 0)
997 ;; Moving end -> end or beginning -> beginning.
1001 (setq down
(save-excursion
1002 (back-to-indentation)
1003 ;; There is a block start or block end keyword on this
1004 ;; line, don't need to look for another block.
1005 (and (re-search-forward
1006 (if backward ruby-block-end-re
1007 (concat "\\_<\\(" ruby-block-beg-re
"\\)\\_>"))
1008 (line-end-position) t
)
1009 (not (nth 8 (syntax-ppss))))))
1010 (while (and (not done
) (not (if backward
(bobp) (eobp))))
1011 (forward-line signum
)
1013 ;; Skip empty and commented out lines.
1014 ((looking-at "^\\s *$"))
1015 ((looking-at "^\\s *#"))
1016 ;; Skip block comments;
1017 ((and (not backward
) (looking-at "^=begin\\>"))
1018 (re-search-forward "^=end\\>"))
1019 ((and backward
(looking-at "^=end\\>"))
1020 (re-search-backward "^=begin\\>"))
1021 ;; Jump over a multiline literal.
1022 ((ruby-in-ppss-context-p 'string
)
1023 (goto-char (nth 8 (syntax-ppss)))
1026 (when (bolp) (forward-char -
1)))) ; After a heredoc.
1028 (let ((state (ruby-parse-region (point) (line-end-position))))
1029 (unless (car state
) ; Line ends with unfinished string.
1030 (setq depth
(+ (nth 2 state
) depth
))))
1032 ;; Increased depth, we found a block.
1033 ((> (* signum depth
) 0)
1035 ;; We're at the same depth as when we started, and we've
1036 ;; encountered a block before. Stop.
1037 ((and down
(zerop depth
))
1039 ;; Lower depth, means outer block, can stop now.
1040 ((< (* signum depth
) 0)
1042 (back-to-indentation)))
1044 (defun ruby-beginning-of-block (&optional arg
)
1045 "Move backward to the beginning of the current block.
1046 With ARG, move up multiple blocks."
1048 (ruby-move-to-block (- (or arg
1))))
1050 (defun ruby-end-of-block (&optional arg
)
1051 "Move forward to the end of the current block.
1052 With ARG, move out of multiple blocks."
1054 (ruby-move-to-block (or arg
1)))
1056 (defun ruby-forward-sexp (&optional arg
)
1057 "Move forward across one balanced expression (sexp).
1058 With ARG, do it many times. Negative ARG means move backward."
1059 ;; TODO: Document body
1061 (if (and (numberp arg
) (< arg
0))
1062 (ruby-backward-sexp (- arg
))
1063 (let ((i (or arg
1)))
1066 (skip-syntax-forward " ")
1067 (if (looking-at ",\\s *") (goto-char (match-end 0)))
1068 (cond ((looking-at "\\?\\(\\\\[CM]-\\)*\\\\?\\S ")
1069 (goto-char (match-end 0)))
1071 (skip-chars-forward ",.:;|&^~=!?\\+\\-\\*")
1072 (looking-at "\\s("))
1073 (goto-char (scan-sexps (point) 1)))
1074 ((and (looking-at (concat "\\<\\(" ruby-block-beg-re
"\\)\\>"))
1075 (not (eq (char-before (point)) ?.
))
1076 (not (eq (char-before (point)) ?
:)))
1079 ((looking-at "\\(\\$\\|@@?\\)?\\sw")
1081 (while (progn (forward-word 1) (looking-at "_")))
1082 (cond ((looking-at "::") (forward-char 2) t
)
1083 ((> (skip-chars-forward ".") 0))
1084 ((looking-at "\\?\\|!\\(=[~=>]\\|[^~=]\\)")
1085 (forward-char 1) nil
)))))
1089 (setq expr
(or expr
(ruby-expr-beg)
1090 (looking-at "%\\sw?\\Sw\\|[\"'`/]")))
1091 (nth 1 (setq state
(apply 'ruby-parse-partial nil state
))))
1093 (skip-chars-forward "<"))
1096 ((error) (forward-word 1)))
1099 (defun ruby-backward-sexp (&optional arg
)
1100 "Move backward across one balanced expression (sexp).
1101 With ARG, do it many times. Negative ARG means move forward."
1102 ;; TODO: Document body
1104 (if (and (numberp arg
) (< arg
0))
1105 (ruby-forward-sexp (- arg
))
1106 (let ((i (or arg
1)))
1109 (skip-chars-backward " \t\n,.:;|&^~=!?\\+\\-\\*")
1111 (cond ((looking-at "\\s)")
1112 (goto-char (scan-sexps (1+ (point)) -
1))
1114 (?%
(forward-char -
1))
1115 ((?q ?Q ?w ?W ?r ?x
)
1116 (if (eq (char-before (1- (point))) ?%
) (forward-char -
2))))
1118 ((looking-at "\\s\"\\|\\\\\\S_")
1119 (let ((c (char-to-string (char-before (match-end 0)))))
1120 (while (and (search-backward c
)
1121 (eq (logand (skip-chars-backward "\\") 1)
1124 ((looking-at "\\s.\\|\\s\\")
1125 (if (ruby-special-char-p) (forward-char -
1)))
1126 ((looking-at "\\s(") nil
)
1129 (while (progn (forward-word -
1)
1132 (?.
(forward-char -
1) t
)
1135 (and (eq (char-before) (char-after)) (forward-char -
1)))
1138 (eq (char-before) :)))))
1139 (if (looking-at ruby-block-end-re
)
1140 (ruby-beginning-of-block))
1146 (defun ruby-indent-exp (&optional ignored
)
1147 "Indent each line in the balanced expression following the point."
1149 (let ((here (point-marker)) start top column
(nest t
))
1150 (set-marker-insertion-type here t
)
1154 (setq start
(point) top
(current-indentation))
1155 (while (and (not (eobp))
1157 (setq column
(ruby-calculate-indent start
))
1158 (cond ((> column top
)
1160 ((and (= column top
) nest
)
1161 (setq nest nil
) t
))))
1162 (ruby-indent-to column
)
1163 (beginning-of-line 2)))
1165 (set-marker here nil
))))
1167 (defun ruby-add-log-current-method ()
1168 "Return the current method name as a string.
1169 This string includes all namespaces.
1178 See `add-log-current-defun-function'."
1181 (let* ((indent 0) mname mlist
1185 (concat "^[ \t]*" re
"[ \t]+"
1187 ;; \\. and :: for class methods
1188 "\\([A-Za-z_]" ruby-symbol-re
"*\\|\\.\\|::" "\\)"
1190 (definition-re (funcall make-definition-re ruby-defun-beg-re
))
1191 (module-re (funcall make-definition-re
"\\(class\\|module\\)")))
1192 ;; Get the current method definition (or class/module).
1193 (when (re-search-backward definition-re nil t
)
1194 (goto-char (match-beginning 1))
1195 (if (not (string-equal "def" (match-string 1)))
1196 (setq mlist
(list (match-string 2)))
1197 ;; We're inside the method. For classes and modules,
1198 ;; this check is skipped for performance.
1199 (when (ruby-block-contains-point start
)
1200 (setq mname
(match-string 2))))
1201 (setq indent
(current-column))
1202 (beginning-of-line))
1203 ;; Walk up the class/module nesting.
1204 (while (and (> indent
0)
1205 (re-search-backward module-re nil t
))
1206 (goto-char (match-beginning 1))
1207 (when (< (current-column) indent
)
1208 (setq mlist
(cons (match-string 2) mlist
))
1209 (setq indent
(current-column))
1210 (beginning-of-line)))
1211 ;; Process the method name.
1213 (let ((mn (split-string mname
"\\.\\|::")))
1216 (unless (string-equal "self" (car mn
)) ; def self.foo
1218 (let ((ml (nreverse mlist
)))
1219 ;; If the method name references one of the
1220 ;; containing modules, drop the more nested ones.
1222 (if (string-equal (car ml
) (car mn
))
1223 (setq mlist
(nreverse (cdr ml
)) ml nil
))
1224 (or (setq ml
(cdr ml
)) (nreverse mlist
))))
1226 (setcdr (last mlist
) (butlast mn
))
1227 (setq mlist
(butlast mn
))))
1228 (setq mname
(concat "." (car (last mn
)))))
1229 ;; See if the method is in singleton class context.
1230 (let ((in-singleton-class
1231 (when (re-search-forward ruby-singleton-class-re start t
)
1232 (goto-char (match-beginning 0))
1233 ;; FIXME: Optimize it out, too?
1234 ;; This can be slow in a large file, but
1235 ;; unlike class/module declaration
1236 ;; indentations, method definitions can be
1237 ;; intermixed with these, and may or may not
1238 ;; be additionally indented after visibility
1240 (ruby-block-contains-point start
))))
1242 (if in-singleton-class
"." "#")
1244 ;; Generate the string.
1246 (setq mlist
(mapconcat (function identity
) mlist
"::")))
1248 (if mlist
(concat mlist mname
) mname
)
1251 (defun ruby-block-contains-point (pt)
1257 (defun ruby-brace-to-do-end (orig end
)
1258 (let (beg-marker end-marker
)
1260 (when (eq (char-before) ?\
})
1262 (when (save-excursion
1263 (skip-chars-backward " \t")
1267 (setq end-marker
(point-marker))
1268 (when (and (not (eobp)) (eq (char-syntax (char-after)) ?w
))
1272 (when (eq (char-syntax (char-before)) ?w
)
1275 (setq beg-marker
(point-marker))
1276 (when (looking-at "\\(\\s \\)*|")
1277 (unless (match-beginning 1)
1279 (goto-char (1+ (match-end 0)))
1280 (search-forward "|"))
1281 (unless (looking-at "\\s *$")
1283 (indent-region beg-marker end-marker
)
1284 (goto-char beg-marker
)
1287 (defun ruby-do-end-to-brace (orig end
)
1288 (let (beg-marker end-marker beg-pos end-pos
)
1289 (goto-char (- end
3))
1290 (when (looking-at ruby-block-end-re
)
1292 (setq end-marker
(point-marker))
1297 (setq beg-marker
(point-marker))
1298 (when (looking-at "\\s +|")
1299 (delete-char (- (match-end 0) (match-beginning 0) 1))
1301 (re-search-forward "|" (line-end-position) t
))
1303 (skip-chars-forward " \t\n\r")
1304 (setq beg-pos
(point))
1305 (goto-char end-marker
)
1306 (skip-chars-backward " \t\n\r")
1307 (setq end-pos
(point)))
1310 (and (= (line-number-at-pos beg-pos
) (line-number-at-pos end-pos
))
1311 (< (+ (current-column) (- end-pos beg-pos
) 2) fill-column
)))
1313 (goto-char end-marker
)
1314 (just-one-space -
1))
1315 (goto-char beg-marker
)
1318 (defun ruby-toggle-block ()
1319 "Toggle block type from do-end to braces or back.
1320 The block must begin on the current line or above it and end after the point.
1321 If the result is do-end block, it will always be multiline."
1323 (let ((start (point)) beg end
)
1326 (if (and (re-search-backward "\\({\\)\\|\\_<do\\(\\s \\|$\\||\\)")
1329 (save-match-data (ruby-forward-sexp))
1332 (if (match-beginning 1)
1333 (ruby-brace-to-do-end beg end
)
1334 (ruby-do-end-to-brace beg end
)))
1335 (goto-char start
))))
1337 (declare-function ruby-syntax-propertize-heredoc
"ruby-mode" (limit))
1338 (declare-function ruby-syntax-enclosing-percent-literal
"ruby-mode" (limit))
1339 (declare-function ruby-syntax-propertize-percent-literal
"ruby-mode" (limit))
1340 ;; Unusual code layout confuses the byte-compiler.
1341 (declare-function ruby-syntax-propertize-expansion
"ruby-mode" ())
1342 (declare-function ruby-syntax-expansion-allowed-p
"ruby-mode" (parse-state))
1344 (if (eval-when-compile (fboundp #'syntax-propertize-rules
))
1345 ;; New code that works independently from font-lock.
1348 (defconst ruby-percent-literal-beg-re
1349 "\\(%\\)[qQrswWxIi]?\\([[:punct:]]\\)"
1350 "Regexp to match the beginning of percent literal.")
1352 (defconst ruby-syntax-methods-before-regexp
1353 '("gsub" "gsub!" "sub" "sub!" "scan" "split" "split!" "index" "match"
1354 "assert_match" "Given" "Then" "When")
1355 "Methods that can take regexp as the first argument.
1356 It will be properly highlighted even when the call omits parens.")
1358 (defvar ruby-syntax-before-regexp-re
1360 ;; Special tokens that can't be followed by a division operator.
1362 ;; Distinguish ternary operator tokens.
1363 ;; FIXME: They don't really have to be separated with spaces.
1365 ;; Control flow keywords and operators following bol or whitespace.
1366 "\\|\\(?:^\\|\\s \\)"
1367 (regexp-opt '("if" "elsif" "unless" "while" "until" "when" "and"
1368 "or" "not" "&&" "||"))
1369 ;; Method name from the list.
1371 (regexp-opt ruby-syntax-methods-before-regexp
)
1373 "Regexp to match text that can be followed by a regular expression."))
1375 (defun ruby-syntax-propertize-function (start end
)
1376 "Syntactic keywords for Ruby mode. See `syntax-propertize-function'."
1377 (let (case-fold-search)
1379 (remove-text-properties start end
'(ruby-expansion-match-data))
1380 (ruby-syntax-propertize-heredoc end
)
1381 (ruby-syntax-enclosing-percent-literal end
)
1383 (syntax-propertize-rules
1384 ;; $' $" $` .... are variables.
1385 ;; ?' ?" ?` are character literals (one-char strings in 1.9+).
1386 ("\\([?$]\\)[#\"'`]"
1387 (1 (unless (save-excursion
1388 ;; Not within a string.
1389 (nth 3 (syntax-ppss (match-beginning 0))))
1390 (string-to-syntax "\\"))))
1391 ;; Regular expressions. Start with matching unescaped slash.
1392 ("\\(?:\\=\\|[^\\]\\)\\(?:\\\\\\\\\\)*\\(/\\)"
1393 (1 (let ((state (save-excursion (syntax-ppss (match-beginning 1)))))
1395 ;; Beginning of a regexp.
1396 (and (null (nth 8 state
))
1399 (looking-back ruby-syntax-before-regexp-re
1401 ;; End of regexp. We don't match the whole
1402 ;; regexp at once because it can have
1403 ;; string interpolation inside, or span
1405 (eq ?
/ (nth 3 state
)))
1406 (string-to-syntax "\"/")))))
1407 ;; Expression expansions in strings. We're handling them
1408 ;; here, so that the regexp rule never matches inside them.
1409 (ruby-expression-expansion-re
1410 (0 (ignore (ruby-syntax-propertize-expansion))))
1411 ("^=en\\(d\\)\\_>" (1 "!"))
1412 ("^\\(=\\)begin\\_>" (1 "!"))
1413 ;; Handle here documents.
1414 ((concat ruby-here-doc-beg-re
".*\\(\n\\)")
1415 (7 (unless (or (nth 8 (save-excursion
1416 (syntax-ppss (match-beginning 0))))
1417 (ruby-singleton-class-p (match-beginning 0)))
1418 (put-text-property (match-beginning 7) (match-end 7)
1419 'syntax-table
(string-to-syntax "\""))
1420 (ruby-syntax-propertize-heredoc end
))))
1421 ;; Handle percent literals: %w(), %q{}, etc.
1422 ((concat "\\(?:^\\|[[ \t\n<+(,=]\\)" ruby-percent-literal-beg-re
)
1423 (1 (prog1 "|" (ruby-syntax-propertize-percent-literal end
)))))
1426 (defun ruby-syntax-propertize-heredoc (limit)
1427 (let ((ppss (syntax-ppss))
1429 (when (eq ?
\n (nth 3 ppss
))
1431 (goto-char (nth 8 ppss
))
1433 (while (re-search-forward ruby-here-doc-beg-re
1434 (line-end-position) t
)
1435 (unless (ruby-singleton-class-p (match-beginning 0))
1436 (push (concat (ruby-here-doc-end-match) "\n") res
))))
1438 ;; With multiple openers on the same line, we don't know in which
1439 ;; part `start' is, so we have to go back to the beginning.
1441 (goto-char (nth 8 ppss
))
1442 (setq res
(nreverse res
)))
1443 (while (and res
(re-search-forward (pop res
) limit
'move
))
1445 (put-text-property (1- (point)) (point)
1446 'syntax-table
(string-to-syntax "\""))))
1447 ;; End up at bol following the heredoc openers.
1448 ;; Propertize expression expansions from this point forward.
1451 (defun ruby-syntax-enclosing-percent-literal (limit)
1452 (let ((state (syntax-ppss))
1454 ;; When already inside percent literal, re-propertize it.
1455 (when (eq t
(nth 3 state
))
1456 (goto-char (nth 8 state
))
1457 (when (looking-at ruby-percent-literal-beg-re
)
1458 (ruby-syntax-propertize-percent-literal limit
))
1459 (when (< (point) start
) (goto-char start
)))))
1461 (defun ruby-syntax-propertize-percent-literal (limit)
1462 (goto-char (match-beginning 2))
1463 ;; Not inside a simple string or comment.
1464 (when (eq t
(nth 3 (syntax-ppss)))
1465 (let* ((op (char-after))
1466 (ops (char-to-string op
))
1467 (cl (or (cdr (aref (syntax-table) op
))
1468 (cdr (assoc op
'((?
< . ?
>))))))
1469 parse-sexp-lookup-properties
)
1473 (if cl
; Paired delimiters.
1474 ;; Delimiter pairs of the same kind can be nested
1475 ;; inside the literal, as long as they are balanced.
1476 ;; Create syntax table that ignores other characters.
1477 (with-syntax-table (make-char-table 'syntax-table nil
)
1478 (modify-syntax-entry op
(concat "(" (char-to-string cl
)))
1479 (modify-syntax-entry cl
(concat ")" ops
))
1480 (modify-syntax-entry ?
\\ "\\")
1482 (narrow-to-region (point) limit
)
1483 (forward-list))) ; skip to the paired character
1484 ;; Single character delimiter.
1485 (re-search-forward (concat "[^\\]\\(?:\\\\\\\\\\)*"
1486 (regexp-quote ops
)) limit nil
))
1487 ;; Found the closing delimiter.
1488 (put-text-property (1- (point)) (point) 'syntax-table
1489 (string-to-syntax "|")))
1490 ;; Unclosed literal, do nothing.
1491 ((scan-error search-failed
)))))))
1493 (defun ruby-syntax-propertize-expansion ()
1494 ;; Save the match data to a text property, for font-locking later.
1495 ;; Set the syntax of all double quotes and backticks to punctuation.
1496 (let* ((beg (match-beginning 2))
1498 (state (and beg
(save-excursion (syntax-ppss beg
)))))
1499 (when (ruby-syntax-expansion-allowed-p state
)
1500 (put-text-property beg
(1+ beg
) 'ruby-expansion-match-data
1503 (while (re-search-forward "[\"`]" end
'move
)
1504 (put-text-property (match-beginning 0) (match-end 0)
1505 'syntax-table
(string-to-syntax "."))))))
1507 (defun ruby-syntax-expansion-allowed-p (parse-state)
1508 "Return non-nil if expression expansion is allowed."
1509 (let ((term (nth 3 parse-state
)))
1511 ((memq term
'(?
\" ?
` ?
\n ?
/)))
1515 (goto-char (nth 8 parse-state
))
1516 (looking-at "%\\(?:[QWrxI]\\|\\W\\)")))))))
1518 (defun ruby-syntax-propertize-expansions (start end
)
1521 (while (re-search-forward ruby-expression-expansion-re end
'move
)
1522 (ruby-syntax-propertize-expansion))))
1525 ;; For Emacsen where syntax-propertize-rules is not (yet) available,
1526 ;; fallback on the old font-lock-syntactic-keywords stuff.
1528 (defconst ruby-here-doc-end-re
1529 "^\\([ \t]+\\)?\\(.*\\)\\(\n\\)"
1530 "Regexp to match the end of heredocs.
1532 This will actually match any line with one or more characters.
1533 It's useful in that it divides up the match string so that
1534 `ruby-here-doc-beg-match' can search for the beginning of the heredoc.")
1536 (defun ruby-here-doc-beg-match ()
1537 "Return a regexp to find the beginning of a heredoc.
1539 This should only be called after matching against `ruby-here-doc-end-re'."
1540 (let ((contents (concat
1541 (regexp-quote (concat (match-string 2) (match-string 3)))
1542 (if (string= (match-string 3) "_") "\\B" "\\b"))))
1544 (let ((match (match-string 1)))
1545 (if (and match
(> (length match
) 0))
1546 (concat "\\(?:-\\([\"']?\\)\\|\\([\"']\\)"
1547 (match-string 1) "\\)"
1548 contents
"\\(\\1\\|\\2\\)")
1549 (concat "-?\\([\"']\\|\\)" contents
"\\1"))))))
1551 (defconst ruby-font-lock-syntactic-keywords
1553 ;; the last $', $", $` in the respective string is not variable
1554 ;; the last ?', ?", ?` in the respective string is not ascii code
1555 ("\\(^\\|[\[ \t\n<+\(,=]\\)\\(['\"`]\\)\\(\\\\.\\|\\2\\|[^'\"`\n\\\\]\\)*?\\\\?[?$]\\(\\2\\)"
1558 ;; $' $" $` .... are variables
1559 ;; ?' ?" ?` are ascii codes
1560 ("\\(^\\|[^\\\\]\\)\\(\\\\\\\\\\)*[?$]\\([#\"'`]\\)" 3 (1 . nil
))
1562 ("\\(^\\|[[=(,~?:;<>]\\|\\(^\\|\\s \\)\\(if\\|elsif\\|unless\\|while\\|until\\|when\\|and\\|or\\|&&\\|||\\)\\|g?sub!?\\|scan\\|split!?\\)\\s *\\(/\\)[^/\n\\\\]*\\(\\\\.[^/\n\\\\]*\\)*\\(/\\)"
1565 ("^=en\\(d\\)\\_>" 1 "!")
1567 ("\\(^\\|[[ \t\n<+(,=]\\)\\(%[xrqQwW]?\\([^<[{(a-zA-Z0-9 \n]\\)[^\n\\\\]*\\(\\\\.[^\n\\\\]*\\)*\\(\\3\\)\\)"
1570 ("^\\(=\\)begin\\_>" 1 (ruby-comment-beg-syntax))
1571 ;; Currently, the following case is highlighted incorrectly:
1580 ;; This is because all here-doc beginnings are highlighted before any endings,
1581 ;; so although <<BAR is properly marked as a beginning, when we get to <<BAZ
1582 ;; it thinks <<BAR is part of a string so it's marked as well.
1584 ;; This may be fixable by modifying ruby-in-here-doc-p to use
1585 ;; ruby-in-non-here-doc-string-p rather than syntax-ppss-context,
1586 ;; but I don't want to try that until we've got unit tests set up
1587 ;; to make sure I don't break anything else.
1588 (,(concat ruby-here-doc-beg-re
".*\\(\n\\)")
1589 ,(+ 1 (regexp-opt-depth ruby-here-doc-beg-re
))
1590 (ruby-here-doc-beg-syntax))
1591 (,ruby-here-doc-end-re
3 (ruby-here-doc-end-syntax)))
1592 "Syntactic keywords for Ruby mode. See `font-lock-syntactic-keywords'.")
1594 (defun ruby-comment-beg-syntax ()
1595 "Return the syntax cell for a the first character of a =begin.
1596 See the definition of `ruby-font-lock-syntactic-keywords'.
1598 This returns a comment-delimiter cell as long as the =begin
1599 isn't in a string or another comment."
1600 (when (not (nth 3 (syntax-ppss)))
1601 (string-to-syntax "!")))
1603 (defun ruby-in-here-doc-p ()
1604 "Return whether or not the point is in a heredoc."
1606 (let ((old-point (point)) (case-fold-search nil
))
1609 (while (and (re-search-backward ruby-here-doc-beg-re nil t
)
1610 (not (ruby-singleton-class-p)))
1611 (if (not (or (ruby-in-ppss-context-p 'anything
)
1612 (ruby-here-doc-find-end old-point
)))
1613 (throw 'found-beg t
)))))))
1615 (defun ruby-here-doc-find-end (&optional limit
)
1616 "Expects the point to be on a line with one or more heredoc openers.
1617 Returns the buffer position at which all heredocs on the line
1618 are terminated, or nil if they aren't terminated before the
1619 buffer position `limit' or the end of the buffer."
1623 (let ((eol (point-at-eol))
1624 (case-fold-search nil
)
1625 ;; Fake match data such that (match-end 0) is at eol
1626 (end-match-data (progn (looking-at ".*$") (match-data)))
1627 beg-match-data end-re
)
1628 (while (re-search-forward ruby-here-doc-beg-re eol t
)
1629 (setq beg-match-data
(match-data))
1630 (setq end-re
(ruby-here-doc-end-match))
1632 (set-match-data end-match-data
)
1633 (goto-char (match-end 0))
1634 (unless (re-search-forward end-re limit t
) (throw 'done nil
))
1635 (setq end-match-data
(match-data))
1637 (set-match-data beg-match-data
)
1638 (goto-char (match-end 0)))
1639 (set-match-data end-match-data
)
1640 (goto-char (match-end 0))
1643 (defun ruby-here-doc-beg-syntax ()
1644 "Return the syntax cell for a line that may begin a heredoc.
1645 See the definition of `ruby-font-lock-syntactic-keywords'.
1647 This sets the syntax cell for the newline ending the line
1648 containing the heredoc beginning so that cases where multiple
1649 heredocs are started on one line are handled correctly."
1651 (goto-char (match-beginning 0))
1652 (unless (or (ruby-in-ppss-context-p 'non-heredoc
)
1653 (ruby-in-here-doc-p))
1654 (string-to-syntax "\""))))
1656 (defun ruby-here-doc-end-syntax ()
1657 "Return the syntax cell for a line that may end a heredoc.
1658 See the definition of `ruby-font-lock-syntactic-keywords'."
1659 (let ((pss (syntax-ppss)) (case-fold-search nil
))
1660 ;; If we aren't in a string, we definitely aren't ending a heredoc,
1661 ;; so we can just give up.
1662 ;; This means we aren't doing a full-document search
1663 ;; every time we enter a character.
1664 (when (ruby-in-ppss-context-p 'heredoc pss
)
1666 (goto-char (nth 8 pss
)) ; Go to the beginning of heredoc.
1667 (let ((eol (point)))
1669 (if (and (re-search-forward (ruby-here-doc-beg-match) eol t
) ; If there is a heredoc that matches this line...
1670 (not (ruby-in-ppss-context-p 'anything
)) ; And that's not inside a heredoc/string/comment...
1671 (progn (goto-char (match-end 0)) ; And it's the last heredoc on its line...
1672 (not (re-search-forward ruby-here-doc-beg-re eol t
))))
1673 (string-to-syntax "\"")))))))
1675 (unless (functionp 'syntax-ppss
)
1676 (defun syntax-ppss (&optional pos
)
1677 (parse-partial-sexp (point-min) (or pos
(point)))))
1680 (defun ruby-in-ppss-context-p (context &optional ppss
)
1681 (let ((ppss (or ppss
(syntax-ppss (point)))))
1683 ((eq context
'anything
)
1686 ((eq context
'string
)
1688 ((eq context
'heredoc
)
1689 (eq ?
\n (nth 3 ppss
)))
1690 ((eq context
'non-heredoc
)
1691 (and (ruby-in-ppss-context-p 'anything
)
1692 (not (ruby-in-ppss-context-p 'heredoc
))))
1693 ((eq context
'comment
)
1697 "Internal error on `ruby-in-ppss-context-p': "
1698 "context name `" (symbol-name context
) "' is unknown"))))
1701 (if (featurep 'xemacs
)
1702 (put 'ruby-mode
'font-lock-defaults
1703 '((ruby-font-lock-keywords)
1706 (font-lock-syntactic-keywords
1707 . ruby-font-lock-syntactic-keywords
))))
1709 (defvar ruby-font-lock-syntax-table
1710 (let ((tbl (copy-syntax-table ruby-mode-syntax-table
)))
1711 (modify-syntax-entry ?_
"w" tbl
)
1713 "The syntax table to use for fontifying Ruby mode buffers.
1714 See `font-lock-syntax-table'.")
1716 (defconst ruby-font-lock-keyword-beg-re
"\\(?:^\\|[^.@$]\\|\\.\\.\\)")
1718 (defconst ruby-font-lock-keywords
1721 '("^\\s *def\\s +\\(?:[^( \t\n.]*\\.\\)?\\([^( \t\n]+\\)"
1722 1 font-lock-function-name-face
)
1725 ruby-font-lock-keyword-beg-re
1761 1 'font-lock-keyword-face
)
1762 ;; some core methods
1764 ruby-font-lock-keyword-beg-re
1766 '(;; built-in methods on Kernel
1810 ;; keyword-like private methods on Module
1827 1 'font-lock-builtin-face
)
1828 ;; Perl-ish keywords
1829 "\\_<\\(?:BEGIN\\|END\\)\\_>\\|^__END__$"
1830 ;; here-doc beginnings
1831 `(,ruby-here-doc-beg-re
0 (unless (ruby-singleton-class-p (match-beginning 0))
1832 'font-lock-string-face
))
1834 `(,(concat ruby-font-lock-keyword-beg-re
1835 "\\_<\\(nil\\|self\\|true\\|false\\)\\>")
1836 1 font-lock-variable-name-face
)
1837 ;; keywords that evaluate to certain values
1838 '("\\_<__\\(?:LINE\\|ENCODING\\|FILE\\)__\\_>" 0 font-lock-variable-name-face
)
1840 '("\\(^\\|[^:]\\)\\(:\\([-+~]@?\\|[/%&|^`]\\|\\*\\*?\\|<\\(<\\|=>?\\)?\\|>[>=]?\\|===?\\|=~\\|![~=]?\\|\\[\\]=?\\|@?\\(\\w\\|_\\)+\\([!?=]\\|\\b_*\\)\\|#{[^}\n\\\\]*\\(\\\\.[^}\n\\\\]*\\)*}\\)\\)"
1841 2 font-lock-constant-face
)
1843 '("\\(\\$\\([^a-zA-Z0-9 \n]\\|[0-9]\\)\\)\\W"
1844 1 font-lock-variable-name-face
)
1845 '("\\(\\$\\|@\\|@@\\)\\(\\w\\|_\\)+"
1846 0 font-lock-variable-name-face
)
1848 '("\\(?:\\_<\\|::\\)\\([A-Z]+\\(\\w\\|_\\)*\\)"
1849 1 (unless (eq ?\
( (char-after)) font-lock-type-face
))
1850 '("\\(^\\s *\\|[\[\{\(,]\\s *\\|\\sw\\s +\\)\\(\\(\\sw\\|_\\)+\\):[^:]" 2 font-lock-constant-face
)
1851 ;; conversion methods on Kernel
1852 (list (concat ruby-font-lock-keyword-beg-re
1853 (regexp-opt '("Array" "Complex" "Float" "Hash"
1854 "Integer" "Rational" "String") 'symbols
))
1855 1 font-lock-builtin-face
)
1856 ;; expression expansion
1857 '(ruby-match-expression-expansion
1858 2 font-lock-variable-name-face t
)
1860 '("[^[:alnum:]_]\\(!\\)[^=]"
1861 1 font-lock-negation-char-face
)
1862 ;; character literals
1863 ;; FIXME: Support longer escape sequences.
1864 '("\\_<\\?\\\\?\\S " 0 font-lock-string-face
)
1866 "Additional expressions to highlight in Ruby mode.")
1868 (defun ruby-match-expression-expansion (limit)
1869 (let* ((prop 'ruby-expansion-match-data
)
1870 (pos (next-single-char-property-change (point) prop nil limit
))
1872 (when (and pos
(> pos
(point)))
1874 (or (and (setq value
(get-text-property pos prop
))
1875 (progn (set-match-data value
) t
))
1876 (ruby-match-expression-expansion limit
)))))
1879 (define-derived-mode ruby-mode prog-mode
"Ruby"
1880 "Major mode for editing Ruby scripts.
1881 \\[ruby-indent-line] properly indents subexpressions of multi-line
1882 class, module, def, if, while, for, do, and case statements, taking
1883 nesting into account.
1885 The variable `ruby-indent-level' controls the amount of indentation.
1888 (ruby-mode-variables)
1890 (set (make-local-variable 'imenu-create-index-function
)
1891 'ruby-imenu-create-index
)
1892 (set (make-local-variable 'add-log-current-defun-function
)
1893 'ruby-add-log-current-method
)
1894 (set (make-local-variable 'beginning-of-defun-function
)
1895 'ruby-beginning-of-defun
)
1896 (set (make-local-variable 'end-of-defun-function
)
1900 (cond ((boundp 'before-save-hook
) 'before-save-hook
)
1901 ((boundp 'write-contents-functions
) 'write-contents-functions
)
1902 ((boundp 'write-contents-hooks
) 'write-contents-hooks
))
1903 'ruby-mode-set-encoding nil
'local
)
1905 (set (make-local-variable 'electric-indent-chars
)
1906 (append '(?\
{ ?\
}) electric-indent-chars
))
1908 (set (make-local-variable 'font-lock-defaults
)
1909 '((ruby-font-lock-keywords) nil nil
))
1910 (set (make-local-variable 'font-lock-keywords
)
1911 ruby-font-lock-keywords
)
1912 (set (make-local-variable 'font-lock-syntax-table
)
1913 ruby-font-lock-syntax-table
)
1915 (if (eval-when-compile (fboundp 'syntax-propertize-rules
))
1916 (set (make-local-variable 'syntax-propertize-function
)
1917 #'ruby-syntax-propertize-function
)
1918 (set (make-local-variable 'font-lock-syntactic-keywords
)
1919 ruby-font-lock-syntactic-keywords
)))
1921 ;;; Invoke ruby-mode when appropriate
1924 (add-to-list 'auto-mode-alist
1925 (cons (purecopy (concat "\\(?:\\."
1926 "rb\\|ru\\|rake\\|thor"
1927 "\\|jbuilder\\|gemspec"
1929 "\\(?:Gem\\|Rake\\|Cap\\|Thor"
1930 "Vagrant\\|Guard\\)file"
1931 "\\)\\'")) 'ruby-mode
))
1934 (dolist (name (list "ruby" "rbx" "jruby" "ruby1.9" "ruby1.8"))
1935 (add-to-list 'interpreter-mode-alist
(cons (purecopy name
) 'ruby-mode
)))
1937 (provide 'ruby-mode
)
1939 ;;; ruby-mode.el ends here