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