Update copyright notices for 2013.
[emacs.git] / lisp / progmodes / ruby-mode.el
blobe48ee8e92d3765352943a1d3ae9707578a50189e
1 ;;; ruby-mode.el --- Major mode for editing Ruby files
3 ;; Copyright (C) 1994-2013 Free Software Foundation, Inc.
5 ;; Authors: Yukihiro Matsumoto
6 ;; Nobuyoshi Nakada
7 ;; URL: http://www.emacswiki.org/cgi-bin/wiki/RubyMode
8 ;; Created: Fri Feb 4 14:49:13 JST 1994
9 ;; Keywords: languages ruby
10 ;; Version: 1.2
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/>.
27 ;;; Commentary:
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.
40 ;;; Code:
42 (eval-when-compile (require 'cl))
44 (defgroup ruby nil
45 "Major mode for editing Ruby code."
46 :prefix "ruby-"
47 :group 'languages)
49 (defconst ruby-keyword-end-re
50 (if (string-match "\\_>" "ruby")
51 "\\_>"
52 "\\>"))
54 (defconst ruby-block-beg-keywords
55 '("class" "module" "def" "if" "unless" "case" "while" "until" "for" "begin" "do")
56 "Keywords at the beginning of blocks.")
58 (defconst ruby-block-beg-re
59 (regexp-opt ruby-block-beg-keywords)
60 "Regexp to match the beginning of blocks.")
62 (defconst ruby-non-block-do-re
63 (concat (regexp-opt '("while" "until" "for" "rescue") t) ruby-keyword-end-re)
64 "Regexp to match keywords that nest without blocks.")
66 (defconst ruby-indent-beg-re
67 (concat "^\\(\\s *" (regexp-opt '("class" "module" "def")) "\\|"
68 (regexp-opt '("if" "unless" "case" "while" "until" "for" "begin"))
69 "\\)\\_>")
70 "Regexp to match where the indentation gets deeper.")
72 (defconst ruby-modifier-beg-keywords
73 '("if" "unless" "while" "until")
74 "Modifiers that are the same as the beginning of blocks.")
76 (defconst ruby-modifier-beg-re
77 (regexp-opt ruby-modifier-beg-keywords)
78 "Regexp to match modifiers same as the beginning of blocks.")
80 (defconst ruby-modifier-re
81 (regexp-opt (cons "rescue" ruby-modifier-beg-keywords))
82 "Regexp to match modifiers.")
84 (defconst ruby-block-mid-keywords
85 '("then" "else" "elsif" "when" "rescue" "ensure")
86 "Keywords where the indentation gets shallower in middle of block statements.")
88 (defconst ruby-block-mid-re
89 (regexp-opt ruby-block-mid-keywords)
90 "Regexp to match where the indentation gets shallower in middle of block statements.")
92 (defconst ruby-block-op-keywords
93 '("and" "or" "not")
94 "Regexp to match boolean keywords.")
96 (defconst ruby-block-hanging-re
97 (regexp-opt (append ruby-modifier-beg-keywords ruby-block-op-keywords))
98 "Regexp to match hanging block modifiers.")
100 (defconst ruby-block-end-re "\\_<end\\_>")
102 (defconst ruby-defun-beg-re
103 '"\\(def\\|class\\|module\\)"
104 "Regexp to match the beginning of a defun, in the general sense.")
106 (eval-and-compile
107 (defconst ruby-here-doc-beg-re
108 "\\(<\\)<\\(-\\)?\\(\\([a-zA-Z0-9_]+\\)\\|[\"]\\([^\"]+\\)[\"]\\|[']\\([^']+\\)[']\\)"
109 "Regexp to match the beginning of a heredoc."))
111 (defun ruby-here-doc-end-match ()
112 "Return a regexp to find the end of a heredoc.
114 This should only be called after matching against `ruby-here-doc-beg-re'."
115 (concat "^"
116 (if (match-string 2) "[ \t]*" nil)
117 (regexp-quote
118 (or (match-string 4)
119 (match-string 5)
120 (match-string 6)))))
122 (defconst ruby-delimiter
123 (concat "[?$/%(){}#\"'`.:]\\|<<\\|\\[\\|\\]\\|\\_<\\("
124 ruby-block-beg-re
125 "\\)\\_>\\|" ruby-block-end-re
126 "\\|^=begin\\|" ruby-here-doc-beg-re))
128 (defconst ruby-negative
129 (concat "^[ \t]*\\(\\(" ruby-block-mid-re "\\)\\>\\|"
130 ruby-block-end-re "\\|}\\|\\]\\)")
131 "Regexp to match where the indentation gets shallower.")
133 (defconst ruby-operator-re "[-,.+*/%&|^~=<>:]"
134 "Regexp to match operators.")
136 (defconst ruby-symbol-chars "a-zA-Z0-9_"
137 "List of characters that symbol names may contain.")
138 (defconst ruby-symbol-re (concat "[" ruby-symbol-chars "]")
139 "Regexp to match symbols.")
141 (define-abbrev-table 'ruby-mode-abbrev-table ()
142 "Abbrev table in use in Ruby mode buffers.")
144 (defvar ruby-mode-map
145 (let ((map (make-sparse-keymap)))
146 (define-key map (kbd "M-C-b") 'ruby-backward-sexp)
147 (define-key map (kbd "M-C-f") 'ruby-forward-sexp)
148 (define-key map (kbd "M-C-p") 'ruby-beginning-of-block)
149 (define-key map (kbd "M-C-n") 'ruby-end-of-block)
150 (define-key map (kbd "M-C-q") 'ruby-indent-exp)
151 (define-key map (kbd "C-c {") 'ruby-toggle-block)
152 map)
153 "Keymap used in Ruby mode.")
155 (defvar ruby-mode-syntax-table
156 (let ((table (make-syntax-table)))
157 (modify-syntax-entry ?\' "\"" table)
158 (modify-syntax-entry ?\" "\"" table)
159 (modify-syntax-entry ?\` "\"" table)
160 (modify-syntax-entry ?# "<" table)
161 (modify-syntax-entry ?\n ">" 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 ?: "_" 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 table)
185 "Syntax table to use in Ruby mode.")
187 (defcustom ruby-indent-tabs-mode nil
188 "Indentation can insert tabs in Ruby mode if this is non-nil."
189 :type 'boolean :group 'ruby)
191 (defcustom ruby-indent-level 2
192 "Indentation of Ruby statements."
193 :type 'integer :group 'ruby)
195 (defcustom ruby-comment-column 32
196 "Indentation column of comments."
197 :type 'integer :group 'ruby)
199 (defcustom ruby-deep-arglist t
200 "Deep indent lists in parenthesis when non-nil.
201 Also ignores spaces after parenthesis when 'space."
202 :group 'ruby)
204 (defcustom ruby-deep-indent-paren '(?\( ?\[ ?\] t)
205 "Deep indent lists in parenthesis when non-nil.
206 The value t means continuous line.
207 Also ignores spaces after parenthesis when 'space."
208 :group 'ruby)
210 (defcustom ruby-deep-indent-paren-style 'space
211 "Default deep indent style."
212 :options '(t nil space) :group 'ruby)
214 (defcustom ruby-encoding-map '((shift_jis . cp932) (shift-jis . cp932))
215 "Alist to map encoding name from Emacs to Ruby."
216 :group 'ruby)
218 (defcustom ruby-insert-encoding-magic-comment t
219 "Insert a magic Emacs 'coding' comment upon save if this is non-nil."
220 :type 'boolean :group 'ruby)
222 (defcustom ruby-use-encoding-map t
223 "Use `ruby-encoding-map' to set encoding magic comment if this is non-nil."
224 :type 'boolean :group 'ruby)
226 ;; Safe file variables
227 (put 'ruby-indent-tabs-mode 'safe-local-variable 'booleanp)
228 (put 'ruby-indent-level 'safe-local-variable 'integerp)
229 (put 'ruby-comment-column 'safe-local-variable 'integerp)
230 (put 'ruby-deep-arglist 'safe-local-variable 'booleanp)
232 (defun ruby-imenu-create-index-in-block (prefix beg end)
233 "Create an imenu index of methods inside a block."
234 (let ((index-alist '()) (case-fold-search nil)
235 name next pos decl sing)
236 (goto-char beg)
237 (while (re-search-forward "^\\s *\\(\\(class\\s +\\|\\(class\\s *<<\\s *\\)\\|module\\s +\\)\\([^\(<\n ]+\\)\\|\\(def\\|alias\\)\\s +\\([^\(\n ]+\\)\\)" end t)
238 (setq sing (match-beginning 3))
239 (setq decl (match-string 5))
240 (setq next (match-end 0))
241 (setq name (or (match-string 4) (match-string 6)))
242 (setq pos (match-beginning 0))
243 (cond
244 ((string= "alias" decl)
245 (if prefix (setq name (concat prefix name)))
246 (push (cons name pos) index-alist))
247 ((string= "def" decl)
248 (if prefix
249 (setq name
250 (cond
251 ((string-match "^self\." name)
252 (concat (substring prefix 0 -1) (substring name 4)))
253 (t (concat prefix name)))))
254 (push (cons name pos) index-alist)
255 (ruby-accurate-end-of-block end))
257 (if (string= "self" name)
258 (if prefix (setq name (substring prefix 0 -1)))
259 (if prefix (setq name (concat (substring prefix 0 -1) "::" name)))
260 (push (cons name pos) index-alist))
261 (ruby-accurate-end-of-block end)
262 (setq beg (point))
263 (setq index-alist
264 (nconc (ruby-imenu-create-index-in-block
265 (concat name (if sing "." "#"))
266 next beg) index-alist))
267 (goto-char beg))))
268 index-alist))
270 (defun ruby-imenu-create-index ()
271 "Create an imenu index of all methods in the buffer."
272 (nreverse (ruby-imenu-create-index-in-block nil (point-min) nil)))
274 (defun ruby-accurate-end-of-block (&optional end)
275 "TODO: document."
276 (let (state
277 (end (or end (point-max))))
278 (while (and (setq state (apply 'ruby-parse-partial end state))
279 (>= (nth 2 state) 0) (< (point) end)))))
281 (defun ruby-mode-variables ()
282 "Set up initial buffer-local variables for Ruby mode."
283 (set-syntax-table ruby-mode-syntax-table)
284 (setq local-abbrev-table ruby-mode-abbrev-table)
285 (setq indent-tabs-mode ruby-indent-tabs-mode)
286 (set (make-local-variable 'indent-line-function) 'ruby-indent-line)
287 (set (make-local-variable 'require-final-newline) t)
288 (set (make-local-variable 'comment-start) "# ")
289 (set (make-local-variable 'comment-end) "")
290 (set (make-local-variable 'comment-column) ruby-comment-column)
291 (set (make-local-variable 'comment-start-skip) "#+ *")
292 (set (make-local-variable 'parse-sexp-ignore-comments) t)
293 (set (make-local-variable 'parse-sexp-lookup-properties) t)
294 (set (make-local-variable 'paragraph-start) (concat "$\\|" page-delimiter))
295 (set (make-local-variable 'paragraph-separate) paragraph-start)
296 (set (make-local-variable 'paragraph-ignore-fill-prefix) t))
298 (defun ruby-mode-set-encoding ()
299 "Insert a magic comment header with the proper encoding if necessary."
300 (save-excursion
301 (widen)
302 (goto-char (point-min))
303 (when (re-search-forward "[^\0-\177]" nil t)
304 (goto-char (point-min))
305 (let ((coding-system
306 (or coding-system-for-write
307 buffer-file-coding-system)))
308 (if coding-system
309 (setq coding-system
310 (or (coding-system-get coding-system 'mime-charset)
311 (coding-system-change-eol-conversion coding-system nil))))
312 (setq coding-system
313 (if coding-system
314 (symbol-name
315 (or (and ruby-use-encoding-map
316 (cdr (assq coding-system ruby-encoding-map)))
317 coding-system))
318 "ascii-8bit"))
319 (if (looking-at "^#!") (beginning-of-line 2))
320 (cond ((looking-at "\\s *#.*-\*-\\s *\\(en\\)?coding\\s *:\\s *\\([-a-z0-9_]*\\)\\s *\\(;\\|-\*-\\)")
321 (unless (string= (match-string 2) coding-system)
322 (goto-char (match-beginning 2))
323 (delete-region (point) (match-end 2))
324 (and (looking-at "-\*-")
325 (let ((n (skip-chars-backward " ")))
326 (cond ((= n 0) (insert " ") (backward-char))
327 ((= n -1) (insert " "))
328 ((forward-char)))))
329 (insert coding-system)))
330 ((looking-at "\\s *#.*coding\\s *[:=]"))
331 (t (when ruby-insert-encoding-magic-comment
332 (insert "# -*- coding: " coding-system " -*-\n"))))))))
334 (defun ruby-current-indentation ()
335 "Return the indentation level of current line."
336 (save-excursion
337 (beginning-of-line)
338 (back-to-indentation)
339 (current-column)))
341 (defun ruby-indent-line (&optional ignored)
342 "Correct the indentation of the current Ruby line."
343 (interactive)
344 (ruby-indent-to (ruby-calculate-indent)))
346 (defun ruby-indent-to (column)
347 "Indent the current line to COLUMN."
348 (when column
349 (let (shift top beg)
350 (and (< column 0) (error "invalid nest"))
351 (setq shift (current-column))
352 (beginning-of-line)
353 (setq beg (point))
354 (back-to-indentation)
355 (setq top (current-column))
356 (skip-chars-backward " \t")
357 (if (>= shift top) (setq shift (- shift top))
358 (setq shift 0))
359 (if (and (bolp)
360 (= column top))
361 (move-to-column (+ column shift))
362 (move-to-column top)
363 (delete-region beg (point))
364 (beginning-of-line)
365 (indent-to column)
366 (move-to-column (+ column shift))))))
368 (defun ruby-special-char-p (&optional pos)
369 "Return t if the character before POS is a special character.
370 If omitted, POS defaults to the current point.
371 Special characters are `?', `$', `:' when preceded by whitespace,
372 and `\\' when preceded by `?'."
373 (setq pos (or pos (point)))
374 (let ((c (char-before pos)) (b (and (< (point-min) pos)
375 (char-before (1- pos)))))
376 (cond ((or (eq c ??) (eq c ?$)))
377 ((and (eq c ?:) (or (not b) (eq (char-syntax b) ? ))))
378 ((eq c ?\\) (eq b ??)))))
380 (defun ruby-singleton-class-p (&optional pos)
381 (save-excursion
382 (when pos (goto-char pos))
383 (forward-word -1)
384 (and (or (bolp) (not (eq (char-before (point)) ?_)))
385 (looking-at "class\\s *<<"))))
387 (defun ruby-expr-beg (&optional option)
388 "TODO: document."
389 (save-excursion
390 (store-match-data nil)
391 (let ((space (skip-chars-backward " \t"))
392 (start (point)))
393 (cond
394 ((bolp) t)
395 ((progn
396 (forward-char -1)
397 (and (looking-at "\\?")
398 (or (eq (char-syntax (char-before (point))) ?w)
399 (ruby-special-char-p))))
400 nil)
401 ((and (eq option 'heredoc) (< space 0))
402 (not (progn (goto-char start) (ruby-singleton-class-p))))
403 ((or (looking-at ruby-operator-re)
404 (looking-at "[\\[({,;]")
405 (and (looking-at "[!?]")
406 (or (not (eq option 'modifier))
407 (bolp)
408 (save-excursion (forward-char -1) (looking-at "\\Sw$"))))
409 (and (looking-at ruby-symbol-re)
410 (skip-chars-backward ruby-symbol-chars)
411 (cond
412 ((looking-at (regexp-opt
413 (append ruby-block-beg-keywords
414 ruby-block-op-keywords
415 ruby-block-mid-keywords)
416 'words))
417 (goto-char (match-end 0))
418 (not (looking-at "\\s_\\|!")))
419 ((eq option 'expr-qstr)
420 (looking-at "[a-zA-Z][a-zA-z0-9_]* +%[^ \t]"))
421 ((eq option 'expr-re)
422 (looking-at "[a-zA-Z][a-zA-z0-9_]* +/[^ \t]"))
423 (t nil)))))))))
425 (defun ruby-forward-string (term &optional end no-error expand)
426 "TODO: document."
427 (let ((n 1) (c (string-to-char term))
428 (re (if expand
429 (concat "[^\\]\\(\\\\\\\\\\)*\\([" term "]\\|\\(#{\\)\\)")
430 (concat "[^\\]\\(\\\\\\\\\\)*[" term "]"))))
431 (while (and (re-search-forward re end no-error)
432 (if (match-beginning 3)
433 (ruby-forward-string "}{" end no-error nil)
434 (> (setq n (if (eq (char-before (point)) c)
435 (1- n) (1+ n))) 0)))
436 (forward-char -1))
437 (cond ((zerop n))
438 (no-error nil)
439 ((error "unterminated string")))))
441 (defun ruby-deep-indent-paren-p (c)
442 "TODO: document."
443 (cond ((listp ruby-deep-indent-paren)
444 (let ((deep (assoc c ruby-deep-indent-paren)))
445 (cond (deep
446 (or (cdr deep) ruby-deep-indent-paren-style))
447 ((memq c ruby-deep-indent-paren)
448 ruby-deep-indent-paren-style))))
449 ((eq c ruby-deep-indent-paren) ruby-deep-indent-paren-style)
450 ((eq c ?\( ) ruby-deep-arglist)))
452 (defun ruby-parse-partial (&optional end in-string nest depth pcol indent)
453 "TODO: document throughout function body."
454 (or depth (setq depth 0))
455 (or indent (setq indent 0))
456 (when (re-search-forward ruby-delimiter end 'move)
457 (let ((pnt (point)) w re expand)
458 (goto-char (match-beginning 0))
459 (cond
460 ((and (memq (char-before) '(?@ ?$)) (looking-at "\\sw"))
461 (goto-char pnt))
462 ((looking-at "[\"`]") ;skip string
463 (cond
464 ((and (not (eobp))
465 (ruby-forward-string (buffer-substring (point) (1+ (point))) end t t))
466 nil)
468 (setq in-string (point))
469 (goto-char end))))
470 ((looking-at "'")
471 (cond
472 ((and (not (eobp))
473 (re-search-forward "[^\\]\\(\\\\\\\\\\)*'" end t))
474 nil)
476 (setq in-string (point))
477 (goto-char end))))
478 ((looking-at "/=")
479 (goto-char pnt))
480 ((looking-at "/")
481 (cond
482 ((and (not (eobp)) (ruby-expr-beg 'expr-re))
483 (if (ruby-forward-string "/" end t t)
485 (setq in-string (point))
486 (goto-char end)))
488 (goto-char pnt))))
489 ((looking-at "%")
490 (cond
491 ((and (not (eobp))
492 (ruby-expr-beg 'expr-qstr)
493 (not (looking-at "%="))
494 (looking-at "%[QqrxWw]?\\([^a-zA-Z0-9 \t\n]\\)"))
495 (goto-char (match-beginning 1))
496 (setq expand (not (memq (char-before) '(?q ?w))))
497 (setq w (match-string 1))
498 (cond
499 ((string= w "[") (setq re "]["))
500 ((string= w "{") (setq re "}{"))
501 ((string= w "(") (setq re ")("))
502 ((string= w "<") (setq re "><"))
503 ((and expand (string= w "\\"))
504 (setq w (concat "\\" w))))
505 (unless (cond (re (ruby-forward-string re end t expand))
506 (expand (ruby-forward-string w end t t))
507 (t (re-search-forward
508 (if (string= w "\\")
509 "\\\\[^\\]*\\\\"
510 (concat "[^\\]\\(\\\\\\\\\\)*" w))
511 end t)))
512 (setq in-string (point))
513 (goto-char end)))
515 (goto-char pnt))))
516 ((looking-at "\\?") ;skip ?char
517 (cond
518 ((and (ruby-expr-beg)
519 (looking-at "?\\(\\\\C-\\|\\\\M-\\)*\\\\?."))
520 (goto-char (match-end 0)))
522 (goto-char pnt))))
523 ((looking-at "\\$") ;skip $char
524 (goto-char pnt)
525 (forward-char 1))
526 ((looking-at "#") ;skip comment
527 (forward-line 1)
528 (goto-char (point))
530 ((looking-at "[\\[{(]")
531 (let ((deep (ruby-deep-indent-paren-p (char-after))))
532 (if (and deep (or (not (eq (char-after) ?\{)) (ruby-expr-beg)))
533 (progn
534 (and (eq deep 'space) (looking-at ".\\s +[^# \t\n]")
535 (setq pnt (1- (match-end 0))))
536 (setq nest (cons (cons (char-after (point)) pnt) nest))
537 (setq pcol (cons (cons pnt depth) pcol))
538 (setq depth 0))
539 (setq nest (cons (cons (char-after (point)) pnt) nest))
540 (setq depth (1+ depth))))
541 (goto-char pnt)
543 ((looking-at "[])}]")
544 (if (ruby-deep-indent-paren-p (matching-paren (char-after)))
545 (setq depth (cdr (car pcol)) pcol (cdr pcol))
546 (setq depth (1- depth)))
547 (setq nest (cdr nest))
548 (goto-char pnt))
549 ((looking-at ruby-block-end-re)
550 (if (or (and (not (bolp))
551 (progn
552 (forward-char -1)
553 (setq w (char-after (point)))
554 (or (eq ?_ w)
555 (eq ?. w))))
556 (progn
557 (goto-char pnt)
558 (setq w (char-after (point)))
559 (or (eq ?_ w)
560 (eq ?! w)
561 (eq ?? w))))
563 (setq nest (cdr nest))
564 (setq depth (1- depth)))
565 (goto-char pnt))
566 ((looking-at "def\\s +[^(\n;]*")
567 (if (or (bolp)
568 (progn
569 (forward-char -1)
570 (not (eq ?_ (char-after (point))))))
571 (progn
572 (setq nest (cons (cons nil pnt) nest))
573 (setq depth (1+ depth))))
574 (goto-char (match-end 0)))
575 ((looking-at (concat "\\_<\\(" ruby-block-beg-re "\\)\\_>"))
576 (and
577 (save-match-data
578 (or (not (looking-at (concat "do" ruby-keyword-end-re)))
579 (save-excursion
580 (back-to-indentation)
581 (not (looking-at ruby-non-block-do-re)))))
582 (or (bolp)
583 (progn
584 (forward-char -1)
585 (setq w (char-after (point)))
586 (not (or (eq ?_ w)
587 (eq ?. w)))))
588 (goto-char pnt)
589 (setq w (char-after (point)))
590 (not (eq ?! w))
591 (skip-chars-forward " \t")
592 (goto-char (match-beginning 0))
593 (or (not (looking-at ruby-modifier-re))
594 (ruby-expr-beg 'modifier))
595 (goto-char pnt)
596 (setq nest (cons (cons nil pnt) nest))
597 (setq depth (1+ depth)))
598 (goto-char pnt))
599 ((looking-at ":\\(['\"]\\)")
600 (goto-char (match-beginning 1))
601 (ruby-forward-string (match-string 1) end t))
602 ((looking-at ":\\([-,.+*/%&|^~<>]=?\\|===?\\|<=>\\|![~=]?\\)")
603 (goto-char (match-end 0)))
604 ((looking-at ":\\([a-zA-Z_][a-zA-Z_0-9]*[!?=]?\\)?")
605 (goto-char (match-end 0)))
606 ((or (looking-at "\\.\\.\\.?")
607 (looking-at "\\.[0-9]+")
608 (looking-at "\\.[a-zA-Z_0-9]+")
609 (looking-at "\\."))
610 (goto-char (match-end 0)))
611 ((looking-at "^=begin")
612 (if (re-search-forward "^=end" end t)
613 (forward-line 1)
614 (setq in-string (match-end 0))
615 (goto-char end)))
616 ((looking-at "<<")
617 (cond
618 ((and (ruby-expr-beg 'heredoc)
619 (looking-at "<<\\(-\\)?\\(\\([\"'`]\\)\\([^\n]+?\\)\\3\\|\\(?:\\sw\\|\\s_\\)+\\)"))
620 (setq re (regexp-quote (or (match-string 4) (match-string 2))))
621 (if (match-beginning 1) (setq re (concat "\\s *" re)))
622 (let* ((id-end (goto-char (match-end 0)))
623 (line-end-position (point-at-eol))
624 (state (list in-string nest depth pcol indent)))
625 ;; parse the rest of the line
626 (while (and (> line-end-position (point))
627 (setq state (apply 'ruby-parse-partial
628 line-end-position state))))
629 (setq in-string (car state)
630 nest (nth 1 state)
631 depth (nth 2 state)
632 pcol (nth 3 state)
633 indent (nth 4 state))
634 ;; skip heredoc section
635 (if (re-search-forward (concat "^" re "$") end 'move)
636 (forward-line 1)
637 (setq in-string id-end)
638 (goto-char end))))
640 (goto-char pnt))))
641 ((looking-at "^__END__$")
642 (goto-char pnt))
643 ((and (looking-at ruby-here-doc-beg-re)
644 (boundp 'ruby-indent-point))
645 (if (re-search-forward (ruby-here-doc-end-match)
646 ruby-indent-point t)
647 (forward-line 1)
648 (setq in-string (match-end 0))
649 (goto-char ruby-indent-point)))
651 (error (format "bad string %s"
652 (buffer-substring (point) pnt)
653 ))))))
654 (list in-string nest depth pcol))
656 (defun ruby-parse-region (start end)
657 "TODO: document."
658 (let (state)
659 (save-excursion
660 (if start
661 (goto-char start)
662 (ruby-beginning-of-indent))
663 (save-restriction
664 (narrow-to-region (point) end)
665 (while (and (> end (point))
666 (setq state (apply 'ruby-parse-partial end state))))))
667 (list (nth 0 state) ; in-string
668 (car (nth 1 state)) ; nest
669 (nth 2 state) ; depth
670 (car (car (nth 3 state))) ; pcol
671 ;(car (nth 5 state)) ; indent
674 (defun ruby-indent-size (pos nest)
675 "Return the indentation level in spaces NEST levels deeper than POS."
676 (+ pos (* (or nest 1) ruby-indent-level)))
678 (defun ruby-calculate-indent (&optional parse-start)
679 "Return the proper indentation level of the current line."
680 ;; TODO: Document body
681 (save-excursion
682 (beginning-of-line)
683 (let ((ruby-indent-point (point))
684 (case-fold-search nil)
685 state eol begin op-end
686 (paren (progn (skip-syntax-forward " ")
687 (and (char-after) (matching-paren (char-after)))))
688 (indent 0))
689 (if parse-start
690 (goto-char parse-start)
691 (ruby-beginning-of-indent)
692 (setq parse-start (point)))
693 (back-to-indentation)
694 (setq indent (current-column))
695 (setq state (ruby-parse-region parse-start ruby-indent-point))
696 (cond
697 ((nth 0 state) ; within string
698 (setq indent nil)) ; do nothing
699 ((car (nth 1 state)) ; in paren
700 (goto-char (setq begin (cdr (nth 1 state))))
701 (let ((deep (ruby-deep-indent-paren-p (car (nth 1 state)))))
702 (if deep
703 (cond ((and (eq deep t) (eq (car (nth 1 state)) paren))
704 (skip-syntax-backward " ")
705 (setq indent (1- (current-column))))
706 ((let ((s (ruby-parse-region (point) ruby-indent-point)))
707 (and (nth 2 s) (> (nth 2 s) 0)
708 (or (goto-char (cdr (nth 1 s))) t)))
709 (forward-word -1)
710 (setq indent (ruby-indent-size (current-column)
711 (nth 2 state))))
713 (setq indent (current-column))
714 (cond ((eq deep 'space))
715 (paren (setq indent (1- indent)))
716 (t (setq indent (ruby-indent-size (1- indent) 1))))))
717 (if (nth 3 state) (goto-char (nth 3 state))
718 (goto-char parse-start) (back-to-indentation))
719 (setq indent (ruby-indent-size (current-column) (nth 2 state))))
720 (and (eq (car (nth 1 state)) paren)
721 (ruby-deep-indent-paren-p (matching-paren paren))
722 (search-backward (char-to-string paren))
723 (setq indent (current-column)))))
724 ((and (nth 2 state) (> (nth 2 state) 0)) ; in nest
725 (if (null (cdr (nth 1 state)))
726 (error "invalid nest"))
727 (goto-char (cdr (nth 1 state)))
728 (forward-word -1) ; skip back a keyword
729 (setq begin (point))
730 (cond
731 ((looking-at "do\\>[^_]") ; iter block is a special case
732 (if (nth 3 state) (goto-char (nth 3 state))
733 (goto-char parse-start) (back-to-indentation))
734 (setq indent (ruby-indent-size (current-column) (nth 2 state))))
736 (setq indent (+ (current-column) ruby-indent-level)))))
738 ((and (nth 2 state) (< (nth 2 state) 0)) ; in negative nest
739 (setq indent (ruby-indent-size (current-column) (nth 2 state)))))
740 (when indent
741 (goto-char ruby-indent-point)
742 (end-of-line)
743 (setq eol (point))
744 (beginning-of-line)
745 (cond
746 ((and (not (ruby-deep-indent-paren-p paren))
747 (re-search-forward ruby-negative eol t))
748 (and (not (eq ?_ (char-after (match-end 0))))
749 (setq indent (- indent ruby-indent-level))))
750 ((and
751 (save-excursion
752 (beginning-of-line)
753 (not (bobp)))
754 (or (ruby-deep-indent-paren-p t)
755 (null (car (nth 1 state)))))
756 ;; goto beginning of non-empty no-comment line
757 (let (end done)
758 (while (not done)
759 (skip-chars-backward " \t\n")
760 (setq end (point))
761 (beginning-of-line)
762 (if (re-search-forward "^\\s *#" end t)
763 (beginning-of-line)
764 (setq done t))))
765 (end-of-line)
766 ;; skip the comment at the end
767 (skip-chars-backward " \t")
768 (let (end (pos (point)))
769 (beginning-of-line)
770 (while (and (re-search-forward "#" pos t)
771 (setq end (1- (point)))
772 (or (ruby-special-char-p end)
773 (and (setq state (ruby-parse-region parse-start end))
774 (nth 0 state))))
775 (setq end nil))
776 (goto-char (or end pos))
777 (skip-chars-backward " \t")
778 (setq begin (if (and end (nth 0 state)) pos (cdr (nth 1 state))))
779 (setq state (ruby-parse-region parse-start (point))))
780 (or (bobp) (forward-char -1))
781 (and
782 (or (and (looking-at ruby-symbol-re)
783 (skip-chars-backward ruby-symbol-chars)
784 (looking-at (concat "\\<\\(" ruby-block-hanging-re "\\)\\>"))
785 (not (eq (point) (nth 3 state)))
786 (save-excursion
787 (goto-char (match-end 0))
788 (not (looking-at "[a-z_]"))))
789 (and (looking-at ruby-operator-re)
790 (not (ruby-special-char-p))
791 ;; Operator at the end of line.
792 (let ((c (char-after (point))))
793 (and
794 ;; (or (null begin)
795 ;; (save-excursion
796 ;; (goto-char begin)
797 ;; (skip-chars-forward " \t")
798 ;; (not (or (eolp) (looking-at "#")
799 ;; (and (eq (car (nth 1 state)) ?{)
800 ;; (looking-at "|"))))))
801 ;; Not a regexp or percent literal.
802 (null (nth 0 (ruby-parse-region (or begin parse-start)
803 (point))))
804 (or (not (eq ?| (char-after (point))))
805 (save-excursion
806 (or (eolp) (forward-char -1))
807 (cond
808 ((search-backward "|" nil t)
809 (skip-chars-backward " \t\n")
810 (and (not (eolp))
811 (progn
812 (forward-char -1)
813 (not (looking-at "{")))
814 (progn
815 (forward-word -1)
816 (not (looking-at "do\\>[^_]")))))
817 (t t))))
818 (not (eq ?, c))
819 (setq op-end t)))))
820 (setq indent
821 (cond
822 ((and
823 (null op-end)
824 (not (looking-at (concat "\\<\\(" ruby-block-hanging-re "\\)\\>")))
825 (eq (ruby-deep-indent-paren-p t) 'space)
826 (not (bobp)))
827 (widen)
828 (goto-char (or begin parse-start))
829 (skip-syntax-forward " ")
830 (current-column))
831 ((car (nth 1 state)) indent)
833 (+ indent ruby-indent-level))))))))
834 (goto-char ruby-indent-point)
835 (beginning-of-line)
836 (skip-syntax-forward " ")
837 (if (looking-at "\\.[^.]")
838 (+ indent ruby-indent-level)
839 indent))))
841 (defun ruby-beginning-of-defun (&optional arg)
842 "Move backward to the beginning of the current top-level defun.
843 With ARG, move backward multiple defuns. Negative ARG means
844 move forward."
845 (interactive "p")
846 (and (re-search-backward (concat "^\\s *" ruby-defun-beg-re "\\_>")
847 nil t (or arg 1))
848 (beginning-of-line)))
850 (defun ruby-end-of-defun (&optional arg)
851 "Move forward to the end of the current top-level defun.
852 With ARG, move forward multiple defuns. Negative ARG means
853 move backward."
854 (interactive "p")
855 (ruby-forward-sexp)
856 (when (looking-back (concat "^\\s *" ruby-block-end-re))
857 (forward-line 1)))
859 (defun ruby-beginning-of-indent ()
860 "Backtrack to a line which can be used as a reference for
861 calculating indentation on the lines after it."
862 (while (and (re-search-backward ruby-indent-beg-re nil 'move)
863 (if (ruby-in-ppss-context-p 'anything)
865 ;; We can stop, then.
866 (beginning-of-line)))))
868 (defun ruby-move-to-block (n)
869 "Move to the beginning (N < 0) or the end (N > 0) of the current block
870 or blocks containing the current block."
871 ;; TODO: Make this work for n > 1,
872 ;; make it not loop for n = 0,
873 ;; document body
874 (let ((orig (point))
875 (start (ruby-calculate-indent))
876 (down (looking-at (if (< n 0) ruby-block-end-re
877 (concat "\\<\\(" ruby-block-beg-re "\\)\\>"))))
878 pos done)
879 (while (and (not done) (not (if (< n 0) (bobp) (eobp))))
880 (forward-line n)
881 (cond
882 ((looking-at "^\\s *$"))
883 ((looking-at "^\\s *#"))
884 ((and (> n 0) (looking-at "^=begin\\>"))
885 (re-search-forward "^=end\\>"))
886 ((and (< n 0) (looking-at "^=end\\>"))
887 (re-search-backward "^=begin\\>"))
889 (setq pos (current-indentation))
890 (cond
891 ((< start pos)
892 (setq down t))
893 ((and down (= pos start))
894 (setq done t))
895 ((> start pos)
896 (setq done t)))))
897 (if done
898 (save-excursion
899 (back-to-indentation)
900 (if (looking-at (concat "\\<\\(" ruby-block-mid-re "\\)\\>"))
901 (setq done nil)))))
902 (back-to-indentation)))
904 (defun ruby-beginning-of-block (&optional arg)
905 "Move backward to the beginning of the current block.
906 With ARG, move up multiple blocks."
907 (interactive "p")
908 (ruby-move-to-block (- (or arg 1))))
910 (defun ruby-end-of-block (&optional arg)
911 "Move forward to the end of the current block.
912 With ARG, move out of multiple blocks."
913 ;; Passing a value > 1 to ruby-move-to-block currently doesn't work.
914 (interactive)
915 (ruby-move-to-block (or arg 1)))
917 (defun ruby-forward-sexp (&optional arg)
918 "Move forward across one balanced expression (sexp).
919 With ARG, do it many times. Negative ARG means move backward."
920 ;; TODO: Document body
921 (interactive "p")
922 (if (and (numberp arg) (< arg 0))
923 (ruby-backward-sexp (- arg))
924 (let ((i (or arg 1)))
925 (condition-case nil
926 (while (> i 0)
927 (skip-syntax-forward " ")
928 (if (looking-at ",\\s *") (goto-char (match-end 0)))
929 (cond ((looking-at "\\?\\(\\\\[CM]-\\)*\\\\?\\S ")
930 (goto-char (match-end 0)))
931 ((progn
932 (skip-chars-forward ",.:;|&^~=!?\\+\\-\\*")
933 (looking-at "\\s("))
934 (goto-char (scan-sexps (point) 1)))
935 ((and (looking-at (concat "\\<\\(" ruby-block-beg-re "\\)\\>"))
936 (not (eq (char-before (point)) ?.))
937 (not (eq (char-before (point)) ?:)))
938 (ruby-end-of-block)
939 (forward-word 1))
940 ((looking-at "\\(\\$\\|@@?\\)?\\sw")
941 (while (progn
942 (while (progn (forward-word 1) (looking-at "_")))
943 (cond ((looking-at "::") (forward-char 2) t)
944 ((> (skip-chars-forward ".") 0))
945 ((looking-at "\\?\\|!\\(=[~=>]\\|[^~=]\\)")
946 (forward-char 1) nil)))))
947 ((let (state expr)
948 (while
949 (progn
950 (setq expr (or expr (ruby-expr-beg)
951 (looking-at "%\\sw?\\Sw\\|[\"'`/]")))
952 (nth 1 (setq state (apply 'ruby-parse-partial nil state))))
953 (setq expr t)
954 (skip-chars-forward "<"))
955 (not expr))))
956 (setq i (1- i)))
957 ((error) (forward-word 1)))
958 i)))
960 (defun ruby-backward-sexp (&optional arg)
961 "Move backward across one balanced expression (sexp).
962 With ARG, do it many times. Negative ARG means move forward."
963 ;; TODO: Document body
964 (interactive "p")
965 (if (and (numberp arg) (< arg 0))
966 (ruby-forward-sexp (- arg))
967 (let ((i (or arg 1)))
968 (condition-case nil
969 (while (> i 0)
970 (skip-chars-backward " \t\n,.:;|&^~=!?\\+\\-\\*")
971 (forward-char -1)
972 (cond ((looking-at "\\s)")
973 (goto-char (scan-sexps (1+ (point)) -1))
974 (case (char-before)
975 (?% (forward-char -1))
976 ((?q ?Q ?w ?W ?r ?x)
977 (if (eq (char-before (1- (point))) ?%) (forward-char -2))))
978 nil)
979 ((looking-at "\\s\"\\|\\\\\\S_")
980 (let ((c (char-to-string (char-before (match-end 0)))))
981 (while (and (search-backward c)
982 (eq (logand (skip-chars-backward "\\") 1)
983 1))))
984 nil)
985 ((looking-at "\\s.\\|\\s\\")
986 (if (ruby-special-char-p) (forward-char -1)))
987 ((looking-at "\\s(") nil)
989 (forward-char 1)
990 (while (progn (forward-word -1)
991 (case (char-before)
992 (?_ t)
993 (?. (forward-char -1) t)
994 ((?$ ?@)
995 (forward-char -1)
996 (and (eq (char-before) (char-after)) (forward-char -1)))
998 (forward-char -1)
999 (eq (char-before) :)))))
1000 (if (looking-at ruby-block-end-re)
1001 (ruby-beginning-of-block))
1002 nil))
1003 (setq i (1- i)))
1004 ((error)))
1005 i)))
1007 (defun ruby-indent-exp (&optional ignored)
1008 "Indent each line in the balanced expression following the point."
1009 (interactive "*P")
1010 (let ((here (point-marker)) start top column (nest t))
1011 (set-marker-insertion-type here t)
1012 (unwind-protect
1013 (progn
1014 (beginning-of-line)
1015 (setq start (point) top (current-indentation))
1016 (while (and (not (eobp))
1017 (progn
1018 (setq column (ruby-calculate-indent start))
1019 (cond ((> column top)
1020 (setq nest t))
1021 ((and (= column top) nest)
1022 (setq nest nil) t))))
1023 (ruby-indent-to column)
1024 (beginning-of-line 2)))
1025 (goto-char here)
1026 (set-marker here nil))))
1028 (defun ruby-add-log-current-method ()
1029 "Return the current method name as a string.
1030 This string includes all namespaces.
1032 For example:
1034 #exit
1035 String#gsub
1036 Net::HTTP#active?
1037 File::open.
1039 See `add-log-current-defun-function'."
1040 ;; TODO: Document body
1041 ;; Why does this append a period to class methods?
1042 (condition-case nil
1043 (save-excursion
1044 (let (mname mlist (indent 0))
1045 ;; get current method (or class/module)
1046 (if (re-search-backward
1047 (concat "^[ \t]*" ruby-defun-beg-re "[ \t]+"
1048 "\\("
1049 ;; \\. and :: for class method
1050 "\\([A-Za-z_]" ruby-symbol-re "*\\|\\.\\|::" "\\)"
1051 "+\\)")
1052 nil t)
1053 (progn
1054 (setq mname (match-string 2))
1055 (unless (string-equal "def" (match-string 1))
1056 (setq mlist (list mname) mname nil))
1057 (goto-char (match-beginning 1))
1058 (setq indent (current-column))
1059 (beginning-of-line)))
1060 ;; nest class/module
1061 (while (and (> indent 0)
1062 (re-search-backward
1063 (concat
1064 "^[ \t]*\\(class\\|module\\)[ \t]+"
1065 "\\([A-Z]" ruby-symbol-re "*\\)")
1066 nil t))
1067 (goto-char (match-beginning 1))
1068 (if (< (current-column) indent)
1069 (progn
1070 (setq mlist (cons (match-string 2) mlist))
1071 (setq indent (current-column))
1072 (beginning-of-line))))
1073 (when mname
1074 (let ((mn (split-string mname "\\.\\|::")))
1075 (if (cdr mn)
1076 (progn
1077 (cond
1078 ((string-equal "" (car mn))
1079 (setq mn (cdr mn) mlist nil))
1080 ((string-equal "self" (car mn))
1081 (setq mn (cdr mn)))
1082 ((let ((ml (nreverse mlist)))
1083 (while ml
1084 (if (string-equal (car ml) (car mn))
1085 (setq mlist (nreverse (cdr ml)) ml nil))
1086 (or (setq ml (cdr ml)) (nreverse mlist))))))
1087 (if mlist
1088 (setcdr (last mlist) mn)
1089 (setq mlist mn))
1090 (setq mn (last mn 2))
1091 (setq mname (concat "." (cadr mn)))
1092 (setcdr mn nil))
1093 (setq mname (concat "#" mname)))))
1094 ;; generate string
1095 (if (consp mlist)
1096 (setq mlist (mapconcat (function identity) mlist "::")))
1097 (if mname
1098 (if mlist (concat mlist mname) mname)
1099 mlist)))))
1101 (defun ruby-brace-to-do-end (orig end)
1102 (let (beg-marker end-marker)
1103 (goto-char end)
1104 (when (eq (char-before) ?\})
1105 (delete-char -1)
1106 (when (save-excursion
1107 (skip-chars-backward " \t")
1108 (not (bolp)))
1109 (insert "\n"))
1110 (insert "end")
1111 (setq end-marker (point-marker))
1112 (when (and (not (eobp)) (eq (char-syntax (char-after)) ?w))
1113 (insert " "))
1114 (goto-char orig)
1115 (delete-char 1)
1116 (when (eq (char-syntax (char-before)) ?w)
1117 (insert " "))
1118 (insert "do")
1119 (setq beg-marker (point-marker))
1120 (when (looking-at "\\(\\s \\)*|")
1121 (unless (match-beginning 1)
1122 (insert " "))
1123 (goto-char (1+ (match-end 0)))
1124 (search-forward "|"))
1125 (unless (looking-at "\\s *$")
1126 (insert "\n"))
1127 (indent-region beg-marker end-marker)
1128 (goto-char beg-marker)
1129 t)))
1131 (defun ruby-do-end-to-brace (orig end)
1132 (let (beg-marker end-marker beg-pos end-pos)
1133 (goto-char (- end 3))
1134 (when (looking-at ruby-block-end-re)
1135 (delete-char 3)
1136 (setq end-marker (point-marker))
1137 (insert "}")
1138 (goto-char orig)
1139 (delete-char 2)
1140 (insert "{")
1141 (setq beg-marker (point-marker))
1142 (when (looking-at "\\s +|")
1143 (delete-char (- (match-end 0) (match-beginning 0) 1))
1144 (forward-char)
1145 (re-search-forward "|" (line-end-position) t))
1146 (save-excursion
1147 (skip-chars-forward " \t\n\r")
1148 (setq beg-pos (point))
1149 (goto-char end-marker)
1150 (skip-chars-backward " \t\n\r")
1151 (setq end-pos (point)))
1152 (when (or
1153 (< end-pos beg-pos)
1154 (and (= (line-number-at-pos beg-pos) (line-number-at-pos end-pos))
1155 (< (+ (current-column) (- end-pos beg-pos) 2) fill-column)))
1156 (just-one-space -1)
1157 (goto-char end-marker)
1158 (just-one-space -1))
1159 (goto-char beg-marker)
1160 t)))
1162 (defun ruby-toggle-block ()
1163 "Toggle block type from do-end to braces or back.
1164 The block must begin on the current line or above it and end after the point.
1165 If the result is do-end block, it will always be multiline."
1166 (interactive)
1167 (let ((start (point)) beg end)
1168 (end-of-line)
1169 (unless
1170 (if (and (re-search-backward "\\({\\)\\|\\_<do\\(\\s \\|$\\||\\)")
1171 (progn
1172 (setq beg (point))
1173 (save-match-data (ruby-forward-sexp))
1174 (setq end (point))
1175 (> end start)))
1176 (if (match-beginning 1)
1177 (ruby-brace-to-do-end beg end)
1178 (ruby-do-end-to-brace beg end)))
1179 (goto-char start))))
1181 (declare-function ruby-syntax-propertize-heredoc "ruby-mode" (limit))
1182 (declare-function ruby-syntax-enclosing-percent-literal "ruby-mode" (limit))
1183 (declare-function ruby-syntax-propertize-percent-literal "ruby-mode" (limit))
1185 (if (eval-when-compile (fboundp #'syntax-propertize-rules))
1186 ;; New code that works independently from font-lock.
1187 (progn
1188 (eval-and-compile
1189 (defconst ruby-percent-literal-beg-re
1190 "\\(%\\)[qQrswWx]?\\([[:punct:]]\\)"
1191 "Regexp to match the beginning of percent literal.")
1193 (defconst ruby-syntax-methods-before-regexp
1194 '("gsub" "gsub!" "sub" "sub!" "scan" "split" "split!" "index" "match"
1195 "assert_match" "Given" "Then" "When")
1196 "Methods that can take regexp as the first argument.
1197 It will be properly highlighted even when the call omits parens."))
1199 (defun ruby-syntax-propertize-function (start end)
1200 "Syntactic keywords for Ruby mode. See `syntax-propertize-function'."
1201 (goto-char start)
1202 (ruby-syntax-propertize-heredoc end)
1203 (ruby-syntax-enclosing-percent-literal end)
1204 (funcall
1205 (syntax-propertize-rules
1206 ;; $' $" $` .... are variables.
1207 ;; ?' ?" ?` are ascii codes.
1208 ("\\([?$]\\)[#\"'`]"
1209 (1 (unless (save-excursion
1210 ;; Not within a string.
1211 (nth 3 (syntax-ppss (match-beginning 0))))
1212 (string-to-syntax "\\"))))
1213 ;; Regexps: regexps are distinguished from division because
1214 ;; of the keyword, symbol, or method name before them.
1215 ((concat
1216 ;; Special tokens that can't be followed by a division operator.
1217 "\\(^\\|[[=(,~?:;<>]"
1218 ;; Control flow keywords and operators following bol or whitespace.
1219 "\\|\\(?:^\\|\\s \\)"
1220 (regexp-opt '("if" "elsif" "unless" "while" "until" "when" "and"
1221 "or" "not" "&&" "||"))
1222 ;; Method name from the list.
1223 "\\|\\_<"
1224 (regexp-opt ruby-syntax-methods-before-regexp)
1225 "\\)\\s *"
1226 ;; The regular expression itself.
1227 "\\(/\\)[^/\n\\\\]*\\(?:\\\\.[^/\n\\\\]*\\)*\\(/\\)")
1228 (2 (string-to-syntax "\"/"))
1229 (3 (string-to-syntax "\"/")))
1230 ("^=en\\(d\\)\\_>" (1 "!"))
1231 ("^\\(=\\)begin\\_>" (1 "!"))
1232 ;; Handle here documents.
1233 ((concat ruby-here-doc-beg-re ".*\\(\n\\)")
1234 (7 (unless (ruby-singleton-class-p (match-beginning 0))
1235 (put-text-property (match-beginning 7) (match-end 7)
1236 'syntax-table (string-to-syntax "\""))
1237 (ruby-syntax-propertize-heredoc end))))
1238 ;; Handle percent literals: %w(), %q{}, etc.
1239 ((concat "\\(?:^\\|[[ \t\n<+(,=]\\)" ruby-percent-literal-beg-re)
1240 (1 (prog1 "|" (ruby-syntax-propertize-percent-literal end)))))
1241 (point) end))
1243 (defun ruby-syntax-propertize-heredoc (limit)
1244 (let ((ppss (syntax-ppss))
1245 (res '()))
1246 (when (eq ?\n (nth 3 ppss))
1247 (save-excursion
1248 (goto-char (nth 8 ppss))
1249 (beginning-of-line)
1250 (while (re-search-forward ruby-here-doc-beg-re
1251 (line-end-position) t)
1252 (unless (ruby-singleton-class-p (match-beginning 0))
1253 (push (concat (ruby-here-doc-end-match) "\n") res))))
1254 (let ((start (point)))
1255 ;; With multiple openers on the same line, we don't know in which
1256 ;; part `start' is, so we have to go back to the beginning.
1257 (when (cdr res)
1258 (goto-char (nth 8 ppss))
1259 (setq res (nreverse res)))
1260 (while (and res (re-search-forward (pop res) limit 'move))
1261 (if (null res)
1262 (put-text-property (1- (point)) (point)
1263 'syntax-table (string-to-syntax "\""))))
1264 ;; Make extra sure we don't move back, lest we could fall into an
1265 ;; inf-loop.
1266 (if (< (point) start) (goto-char start))))))
1268 (defun ruby-syntax-enclosing-percent-literal (limit)
1269 (let ((state (syntax-ppss))
1270 (start (point)))
1271 ;; When already inside percent literal, re-propertize it.
1272 (when (eq t (nth 3 state))
1273 (goto-char (nth 8 state))
1274 (when (looking-at ruby-percent-literal-beg-re)
1275 (ruby-syntax-propertize-percent-literal limit))
1276 (when (< (point) start) (goto-char start)))))
1278 (defun ruby-syntax-propertize-percent-literal (limit)
1279 (goto-char (match-beginning 2))
1280 ;; Not inside a simple string or comment.
1281 (when (eq t (nth 3 (syntax-ppss)))
1282 (let* ((op (char-after))
1283 (ops (char-to-string op))
1284 (cl (or (cdr (aref (syntax-table) op))
1285 (cdr (assoc op '((?< . ?>))))))
1286 parse-sexp-lookup-properties)
1287 (condition-case nil
1288 (progn
1289 (if cl ; Paired delimiters.
1290 ;; Delimiter pairs of the same kind can be nested
1291 ;; inside the literal, as long as they are balanced.
1292 ;; Create syntax table that ignores other characters.
1293 (with-syntax-table (make-char-table 'syntax-table nil)
1294 (modify-syntax-entry op (concat "(" (char-to-string cl)))
1295 (modify-syntax-entry cl (concat ")" ops))
1296 (modify-syntax-entry ?\\ "\\")
1297 (save-restriction
1298 (narrow-to-region (point) limit)
1299 (forward-list))) ; skip to the paired character
1300 ;; Single character delimiter.
1301 (re-search-forward (concat "[^\\]\\(?:\\\\\\\\\\)*"
1302 (regexp-quote ops)) limit nil))
1303 ;; Found the closing delimiter.
1304 (put-text-property (1- (point)) (point) 'syntax-table
1305 (string-to-syntax "|")))
1306 ;; Unclosed literal, leave the following text unpropertized.
1307 ((scan-error search-failed) (goto-char limit))))))
1310 ;; For Emacsen where syntax-propertize-rules is not (yet) available,
1311 ;; fallback on the old font-lock-syntactic-keywords stuff.
1313 (defconst ruby-here-doc-end-re
1314 "^\\([ \t]+\\)?\\(.*\\)\\(\n\\)"
1315 "Regexp to match the end of heredocs.
1317 This will actually match any line with one or more characters.
1318 It's useful in that it divides up the match string so that
1319 `ruby-here-doc-beg-match' can search for the beginning of the heredoc.")
1321 (defun ruby-here-doc-beg-match ()
1322 "Return a regexp to find the beginning of a heredoc.
1324 This should only be called after matching against `ruby-here-doc-end-re'."
1325 (let ((contents (concat
1326 (regexp-quote (concat (match-string 2) (match-string 3)))
1327 (if (string= (match-string 3) "_") "\\B" "\\b"))))
1328 (concat "<<"
1329 (let ((match (match-string 1)))
1330 (if (and match (> (length match) 0))
1331 (concat "\\(?:-\\([\"']?\\)\\|\\([\"']\\)"
1332 (match-string 1) "\\)"
1333 contents "\\(\\1\\|\\2\\)")
1334 (concat "-?\\([\"']\\|\\)" contents "\\1"))))))
1336 (defconst ruby-font-lock-syntactic-keywords
1338 ;; the last $', $", $` in the respective string is not variable
1339 ;; the last ?', ?", ?` in the respective string is not ascii code
1340 ("\\(^\\|[\[ \t\n<+\(,=]\\)\\(['\"`]\\)\\(\\\\.\\|\\2\\|[^'\"`\n\\\\]\\)*?\\\\?[?$]\\(\\2\\)"
1341 (2 (7 . nil))
1342 (4 (7 . nil)))
1343 ;; $' $" $` .... are variables
1344 ;; ?' ?" ?` are ascii codes
1345 ("\\(^\\|[^\\\\]\\)\\(\\\\\\\\\\)*[?$]\\([#\"'`]\\)" 3 (1 . nil))
1346 ;; regexps
1347 ("\\(^\\|[[=(,~?:;<>]\\|\\(^\\|\\s \\)\\(if\\|elsif\\|unless\\|while\\|until\\|when\\|and\\|or\\|&&\\|||\\)\\|g?sub!?\\|scan\\|split!?\\)\\s *\\(/\\)[^/\n\\\\]*\\(\\\\.[^/\n\\\\]*\\)*\\(/\\)"
1348 (4 (7 . ?/))
1349 (6 (7 . ?/)))
1350 ("^=en\\(d\\)\\_>" 1 "!")
1351 ;; Percent literal.
1352 ("\\(^\\|[[ \t\n<+(,=]\\)\\(%[xrqQwW]?\\([^<[{(a-zA-Z0-9 \n]\\)[^\n\\\\]*\\(\\\\.[^\n\\\\]*\\)*\\(\\3\\)\\)"
1353 (3 "\"")
1354 (5 "\""))
1355 ("^\\(=\\)begin\\_>" 1 (ruby-comment-beg-syntax))
1356 ;; Currently, the following case is highlighted incorrectly:
1358 ;; <<FOO
1359 ;; FOO
1360 ;; <<BAR
1361 ;; <<BAZ
1362 ;; BAZ
1363 ;; BAR
1365 ;; This is because all here-doc beginnings are highlighted before any endings,
1366 ;; so although <<BAR is properly marked as a beginning, when we get to <<BAZ
1367 ;; it thinks <<BAR is part of a string so it's marked as well.
1369 ;; This may be fixable by modifying ruby-in-here-doc-p to use
1370 ;; ruby-in-non-here-doc-string-p rather than syntax-ppss-context,
1371 ;; but I don't want to try that until we've got unit tests set up
1372 ;; to make sure I don't break anything else.
1373 (,(concat ruby-here-doc-beg-re ".*\\(\n\\)")
1374 ,(+ 1 (regexp-opt-depth ruby-here-doc-beg-re))
1375 (ruby-here-doc-beg-syntax))
1376 (,ruby-here-doc-end-re 3 (ruby-here-doc-end-syntax)))
1377 "Syntactic keywords for Ruby mode. See `font-lock-syntactic-keywords'.")
1379 (defun ruby-comment-beg-syntax ()
1380 "Return the syntax cell for a the first character of a =begin.
1381 See the definition of `ruby-font-lock-syntactic-keywords'.
1383 This returns a comment-delimiter cell as long as the =begin
1384 isn't in a string or another comment."
1385 (when (not (nth 3 (syntax-ppss)))
1386 (string-to-syntax "!")))
1388 (defun ruby-in-here-doc-p ()
1389 "Return whether or not the point is in a heredoc."
1390 (save-excursion
1391 (let ((old-point (point)) (case-fold-search nil))
1392 (beginning-of-line)
1393 (catch 'found-beg
1394 (while (and (re-search-backward ruby-here-doc-beg-re nil t)
1395 (not (ruby-singleton-class-p)))
1396 (if (not (or (ruby-in-ppss-context-p 'anything)
1397 (ruby-here-doc-find-end old-point)))
1398 (throw 'found-beg t)))))))
1400 (defun ruby-here-doc-find-end (&optional limit)
1401 "Expects the point to be on a line with one or more heredoc openers.
1402 Returns the buffer position at which all heredocs on the line
1403 are terminated, or nil if they aren't terminated before the
1404 buffer position `limit' or the end of the buffer."
1405 (save-excursion
1406 (beginning-of-line)
1407 (catch 'done
1408 (let ((eol (point-at-eol))
1409 (case-fold-search nil)
1410 ;; Fake match data such that (match-end 0) is at eol
1411 (end-match-data (progn (looking-at ".*$") (match-data)))
1412 beg-match-data end-re)
1413 (while (re-search-forward ruby-here-doc-beg-re eol t)
1414 (setq beg-match-data (match-data))
1415 (setq end-re (ruby-here-doc-end-match))
1417 (set-match-data end-match-data)
1418 (goto-char (match-end 0))
1419 (unless (re-search-forward end-re limit t) (throw 'done nil))
1420 (setq end-match-data (match-data))
1422 (set-match-data beg-match-data)
1423 (goto-char (match-end 0)))
1424 (set-match-data end-match-data)
1425 (goto-char (match-end 0))
1426 (point)))))
1428 (defun ruby-here-doc-beg-syntax ()
1429 "Return the syntax cell for a line that may begin a heredoc.
1430 See the definition of `ruby-font-lock-syntactic-keywords'.
1432 This sets the syntax cell for the newline ending the line
1433 containing the heredoc beginning so that cases where multiple
1434 heredocs are started on one line are handled correctly."
1435 (save-excursion
1436 (goto-char (match-beginning 0))
1437 (unless (or (ruby-in-ppss-context-p 'non-heredoc)
1438 (ruby-in-here-doc-p))
1439 (string-to-syntax "\""))))
1441 (defun ruby-here-doc-end-syntax ()
1442 "Return the syntax cell for a line that may end a heredoc.
1443 See the definition of `ruby-font-lock-syntactic-keywords'."
1444 (let ((pss (syntax-ppss)) (case-fold-search nil))
1445 ;; If we aren't in a string, we definitely aren't ending a heredoc,
1446 ;; so we can just give up.
1447 ;; This means we aren't doing a full-document search
1448 ;; every time we enter a character.
1449 (when (ruby-in-ppss-context-p 'heredoc pss)
1450 (save-excursion
1451 (goto-char (nth 8 pss)) ; Go to the beginning of heredoc.
1452 (let ((eol (point)))
1453 (beginning-of-line)
1454 (if (and (re-search-forward (ruby-here-doc-beg-match) eol t) ; If there is a heredoc that matches this line...
1455 (not (ruby-in-ppss-context-p 'anything)) ; And that's not inside a heredoc/string/comment...
1456 (progn (goto-char (match-end 0)) ; And it's the last heredoc on its line...
1457 (not (re-search-forward ruby-here-doc-beg-re eol t))))
1458 (string-to-syntax "\"")))))))
1460 (unless (functionp 'syntax-ppss)
1461 (defun syntax-ppss (&optional pos)
1462 (parse-partial-sexp (point-min) (or pos (point)))))
1465 (defun ruby-in-ppss-context-p (context &optional ppss)
1466 (let ((ppss (or ppss (syntax-ppss (point)))))
1467 (if (cond
1468 ((eq context 'anything)
1469 (or (nth 3 ppss)
1470 (nth 4 ppss)))
1471 ((eq context 'string)
1472 (nth 3 ppss))
1473 ((eq context 'heredoc)
1474 (eq ?\n (nth 3 ppss)))
1475 ((eq context 'non-heredoc)
1476 (and (ruby-in-ppss-context-p 'anything)
1477 (not (ruby-in-ppss-context-p 'heredoc))))
1478 ((eq context 'comment)
1479 (nth 4 ppss))
1481 (error (concat
1482 "Internal error on `ruby-in-ppss-context-p': "
1483 "context name `" (symbol-name context) "' is unknown"))))
1484 t)))
1486 (if (featurep 'xemacs)
1487 (put 'ruby-mode 'font-lock-defaults
1488 '((ruby-font-lock-keywords)
1489 nil nil nil
1490 beginning-of-line
1491 (font-lock-syntactic-keywords
1492 . ruby-font-lock-syntactic-keywords))))
1494 (defvar ruby-font-lock-syntax-table
1495 (let ((tbl (copy-syntax-table ruby-mode-syntax-table)))
1496 (modify-syntax-entry ?_ "w" tbl)
1497 tbl)
1498 "The syntax table to use for fontifying Ruby mode buffers.
1499 See `font-lock-syntax-table'.")
1501 (defconst ruby-font-lock-keywords
1502 (list
1503 ;; functions
1504 '("^\\s *def\\s +\\([^( \t\n]+\\)"
1505 1 font-lock-function-name-face)
1506 ;; keywords
1507 (cons (concat
1508 "\\(^\\|[^_:.@$]\\|\\.\\.\\)\\b\\(defined\\?\\|"
1509 (regexp-opt
1510 '("alias_method"
1511 "alias"
1512 "and"
1513 "begin"
1514 "break"
1515 "case"
1516 "catch"
1517 "class"
1518 "def"
1519 "do"
1520 "elsif"
1521 "else"
1522 "fail"
1523 "ensure"
1524 "for"
1525 "end"
1526 "if"
1527 "in"
1528 "module_function"
1529 "module"
1530 "next"
1531 "not"
1532 "or"
1533 "public"
1534 "private"
1535 "protected"
1536 "raise"
1537 "redo"
1538 "rescue"
1539 "retry"
1540 "return"
1541 "then"
1542 "throw"
1543 "super"
1544 "unless"
1545 "undef"
1546 "until"
1547 "when"
1548 "while"
1549 "yield")
1551 "\\)"
1552 ruby-keyword-end-re)
1554 ;; here-doc beginnings
1555 (list ruby-here-doc-beg-re 0 'font-lock-string-face)
1556 ;; variables
1557 '("\\(^\\|[^_:.@$]\\|\\.\\.\\)\\b\\(nil\\|self\\|true\\|false\\)\\>"
1558 2 font-lock-variable-name-face)
1559 ;; symbols
1560 '("\\(^\\|[^:]\\)\\(:\\([-+~]@?\\|[/%&|^`]\\|\\*\\*?\\|<\\(<\\|=>?\\)?\\|>[>=]?\\|===?\\|=~\\|![~=]?\\|\\[\\]=?\\|@?\\(\\w\\|_\\)+\\([!?=]\\|\\b_*\\)\\|#{[^}\n\\\\]*\\(\\\\.[^}\n\\\\]*\\)*}\\)\\)"
1561 2 font-lock-constant-face)
1562 ;; variables
1563 '("\\(\\$\\([^a-zA-Z0-9 \n]\\|[0-9]\\)\\)\\W"
1564 1 font-lock-variable-name-face)
1565 '("\\(\\$\\|@\\|@@\\)\\(\\w\\|_\\)+"
1566 0 font-lock-variable-name-face)
1567 ;; constants
1568 '("\\(^\\|[^_]\\)\\b\\([A-Z]+\\(\\w\\|_\\)*\\)"
1569 2 font-lock-type-face)
1570 '("\\(^\\s *\\|[\[\{\(,]\\s *\\|\\sw\\s +\\)\\(\\(\\sw\\|_\\)+\\):[^:]" 2 font-lock-constant-face)
1571 ;; expression expansion
1572 '(ruby-match-expression-expansion
1573 0 font-lock-variable-name-face t)
1574 ;; warn lower camel case
1575 ;'("\\<[a-z]+[a-z0-9]*[A-Z][A-Za-z0-9]*\\([!?]?\\|\\>\\)"
1576 ; 0 font-lock-warning-face)
1578 "Additional expressions to highlight in Ruby mode.")
1580 (defun ruby-match-expression-expansion (limit)
1581 (when (re-search-forward "[^\\]\\(\\\\\\\\\\)*\\(#\\({[^}\n\\\\]*\\(\\\\.[^}\n\\\\]*\\)*}\\|\\(\\$\\|@\\|@@\\)\\(\\w\\|_\\)+\\)\\)" limit 'move)
1582 (or (ruby-in-ppss-context-p 'string)
1583 (ruby-match-expression-expansion limit))))
1585 ;;;###autoload
1586 (define-derived-mode ruby-mode prog-mode "Ruby"
1587 "Major mode for editing Ruby scripts.
1588 \\[ruby-indent-line] properly indents subexpressions of multi-line
1589 class, module, def, if, while, for, do, and case statements, taking
1590 nesting into account.
1592 The variable `ruby-indent-level' controls the amount of indentation.
1594 \\{ruby-mode-map}"
1595 (ruby-mode-variables)
1597 (set (make-local-variable 'imenu-create-index-function)
1598 'ruby-imenu-create-index)
1599 (set (make-local-variable 'add-log-current-defun-function)
1600 'ruby-add-log-current-method)
1601 (set (make-local-variable 'beginning-of-defun-function)
1602 'ruby-beginning-of-defun)
1603 (set (make-local-variable 'end-of-defun-function)
1604 'ruby-end-of-defun)
1606 (add-hook
1607 (cond ((boundp 'before-save-hook) 'before-save-hook)
1608 ((boundp 'write-contents-functions) 'write-contents-functions)
1609 ((boundp 'write-contents-hooks) 'write-contents-hooks))
1610 'ruby-mode-set-encoding nil 'local)
1612 (set (make-local-variable 'electric-indent-chars)
1613 (append '(?\{ ?\}) electric-indent-chars))
1615 (set (make-local-variable 'font-lock-defaults)
1616 '((ruby-font-lock-keywords) nil nil))
1617 (set (make-local-variable 'font-lock-keywords)
1618 ruby-font-lock-keywords)
1619 (set (make-local-variable 'font-lock-syntax-table)
1620 ruby-font-lock-syntax-table)
1622 (if (eval-when-compile (fboundp 'syntax-propertize-rules))
1623 (set (make-local-variable 'syntax-propertize-function)
1624 #'ruby-syntax-propertize-function)
1625 (set (make-local-variable 'font-lock-syntactic-keywords)
1626 ruby-font-lock-syntactic-keywords)))
1628 ;;; Invoke ruby-mode when appropriate
1630 ;;;###autoload
1631 (add-to-list 'auto-mode-alist (cons (purecopy "\\.rb\\'") 'ruby-mode))
1633 ;;;###autoload
1634 (dolist (name (list "ruby" "rbx" "jruby" "ruby1.9" "ruby1.8"))
1635 (add-to-list 'interpreter-mode-alist (cons (purecopy name) 'ruby-mode)))
1637 (provide 'ruby-mode)
1639 ;;; ruby-mode.el ends here