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