42e1ac72b339baf86a02db2850dea16a51f0b347
[bpt/emacs.git] / lisp / progmodes / ruby-mode.el
1 ;;; ruby-mode.el --- Major mode for editing Ruby files
2
3 ;; Copyright (C) 1994-2012 Free Software Foundation, Inc.
4
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
11
12 ;; This file is part of GNU Emacs.
13
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.
18
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.
23
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/>.
26
27 ;;; Commentary:
28
29 ;; Provides font-locking, indentation support, and navigation for Ruby code.
30 ;;
31 ;; If you're installing manually, you should add this to your .emacs
32 ;; file after putting it on your load path:
33 ;;
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))
37 ;;
38 ;; Still needs more docstrings; search below for TODO.
39
40 ;;; Code:
41
42 (eval-when-compile (require 'cl))
43
44 (defgroup ruby nil
45 "Major mode for editing Ruby code."
46 :prefix "ruby-"
47 :group 'languages)
48
49 (defconst ruby-keyword-end-re
50 (if (string-match "\\_>" "ruby")
51 "\\_>"
52 "\\>"))
53
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.")
57
58 (defconst ruby-block-beg-re
59 (regexp-opt ruby-block-beg-keywords)
60 "Regexp to match the beginning of blocks.")
61
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.")
65
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.")
70
71 (defconst ruby-modifier-beg-keywords
72 '("if" "unless" "while" "until")
73 "Modifiers that are the same as the beginning of blocks.")
74
75 (defconst ruby-modifier-beg-re
76 (regexp-opt ruby-modifier-beg-keywords)
77 "Regexp to match modifiers same as the beginning of blocks.")
78
79 (defconst ruby-modifier-re
80 (regexp-opt (cons "rescue" ruby-modifier-beg-keywords))
81 "Regexp to match modifiers.")
82
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.")
86
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.")
90
91 (defconst ruby-block-op-keywords
92 '("and" "or" "not")
93 "Regexp to match boolean keywords.")
94
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.")
98
99 (defconst ruby-block-end-re "\\_<end\\_>")
100
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."))
105
106 (defun ruby-here-doc-end-match ()
107 "Return a regexp to find the end of a heredoc.
108
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)))))
116
117 (defconst ruby-delimiter
118 (concat "[?$/%(){}#\"'`.:]\\|<<\\|\\[\\|\\]\\|\\_<\\("
119 ruby-block-beg-re
120 "\\)\\_>\\|" ruby-block-end-re
121 "\\|^=begin\\|" ruby-here-doc-beg-re))
122
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.")
127
128 (defconst ruby-operator-re "[-,.+*/%&|^~=<>:]"
129 "Regexp to match operators.")
130
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.")
135
136 (define-abbrev-table 'ruby-mode-abbrev-table ()
137 "Abbrev table in use in Ruby mode buffers.")
138
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.")
156
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.")
188
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)
192
193 (defcustom ruby-indent-level 2
194 "Indentation of Ruby statements."
195 :type 'integer :group 'ruby)
196
197 (defcustom ruby-comment-column 32
198 "Indentation column of comments."
199 :type 'integer :group 'ruby)
200
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)
205
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)
211
212 (defcustom ruby-deep-indent-paren-style 'space
213 "Default deep indent style."
214 :options '(t nil space) :group 'ruby)
215
216 (defcustom ruby-encoding-map '((shift_jis . cp932) (shift-jis . cp932))
217 "Alist to map encoding name from Emacs to Ruby."
218 :group 'ruby)
219
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)
223
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)
227
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)
233
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))
258 (t
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))
271
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)))
275
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)))))
282
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))
299
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"))))))))
335
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)))
342
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)))
347
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))))))
369
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 ??)))))
381
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 *<<"))))
388
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)))))))))
426
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")))))
442
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)))
453
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)
469 (t
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)
477 (t
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)
486 nil
487 (setq in-string (point))
488 (goto-char end)))
489 (t
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)))
516 (t
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)))
523 (t
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))
531 )
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)
544 )
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))))
564 nil
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))))
641 (t
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)))
652 (t
653 (error (format "bad string %s"
654 (buffer-substring (point) pnt)
655 ))))))
656 (list in-string nest depth pcol))
657
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
674 )))
675
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)))
679
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))))
714 (t
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))))
737 (t
738 (setq indent (+ (current-column) ruby-indent-level)))))
739
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 percent 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)
834 (t
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))))
842
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))
848
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)))
858
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))
868
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)))
877
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\\>"))
898 (t
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)))))
923
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))))
929
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)))
936
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)))
979
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)
1008 (t
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)))
1017 (?:
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)))
1026
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))
1035
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))))
1056
1057 (defun ruby-add-log-current-method ()
1058 "Return the current method name as a string.
1059 This string includes all namespaces.
1060
1061 For example:
1062
1063 #exit
1064 String#gsub
1065 Net::HTTP#active?
1066 File::open.
1067
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)))))
1129
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))))
1149
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))))
1165
1166 (defun ruby-toggle-block ()
1167 (interactive)
1168 (or (ruby-brace-to-do-end)
1169 (ruby-do-end-to-brace)))
1170
1171 (declare-function ruby-syntax-propertize-heredoc "ruby-mode" (limit))
1172 (declare-function ruby-syntax-enclosing-percent-literal "ruby-mode" (limit))
1173 (declare-function ruby-syntax-propertize-percent-literal "ruby-mode" (limit))
1174
1175 (if (eval-when-compile (fboundp #'syntax-propertize-rules))
1176 ;; New code that works independently from font-lock.
1177 (progn
1178 (eval-and-compile
1179 (defconst ruby-percent-literal-beg-re
1180 "\\(%\\)[qQrswWx]?\\([[:punct:]]\\)"
1181 "Regexp to match the beginning of percent literal."))
1182
1183 (defun ruby-syntax-propertize-function (start end)
1184 "Syntactic keywords for Ruby mode. See `syntax-propertize-function'."
1185 (goto-char start)
1186 (ruby-syntax-propertize-heredoc end)
1187 (ruby-syntax-enclosing-percent-literal end)
1188 (funcall
1189 (syntax-propertize-rules
1190 ;; #{ }, #$hoge, #@foo are not comments.
1191 ("\\(#\\)[{$@]" (1 "."))
1192 ;; $' $" $` .... are variables.
1193 ;; ?' ?" ?` are ascii codes.
1194 ("\\([?$]\\)[#\"'`]"
1195 (1 (unless (save-excursion
1196 ;; Not within a string.
1197 (nth 3 (syntax-ppss (match-beginning 0))))
1198 (string-to-syntax "\\"))))
1199 ;; Regexps: regexps are distinguished from division either because
1200 ;; of the keyword/symbol before them, or because of the code
1201 ;; following them.
1202 ((concat
1203 ;; Special tokens that can't be followed by a division operator.
1204 "\\(?:\\(^\\|[[=(,~?:;<>]\\|\\(?:^\\|\\s \\)"
1205 (regexp-opt '("if" "elsif" "unless" "while" "until" "when" "and"
1206 "or" "&&" "||"
1207 "gsub" "gsub!" "sub" "sub!" "scan" "split" "split!"))
1208 "\\)\\s *\\)?"
1209 ;; The regular expression itself.
1210 "\\(/\\)[^/\n\\\\]*\\(?:\\\\.[^/\n\\\\]*\\)*\\(/\\)"
1211 ;; Special code that cannot follow a division operator.
1212 ;; FIXME: Just because the second slash of "/foo/ do bar" can't
1213 ;; be a division, doesn't mean it can't *start* a regexp, as in
1214 ;; "x = toto/foo; if /do bar/".
1215 "\\([imxo]*\\s *\\(?:,\\|\\_<do\\_>\\)\\)?")
1216 (2 (when (or (match-beginning 1) (match-beginning 4))
1217 (string-to-syntax "\"/")))
1218 (3 (if (or (match-beginning 1) (match-beginning 4))
1219 (string-to-syntax "\"/")
1220 (goto-char (match-end 2)))))
1221 ("^=en\\(d\\)\\_>" (1 "!"))
1222 ("^\\(=\\)begin\\_>" (1 "!"))
1223 ;; Handle here documents.
1224 ((concat ruby-here-doc-beg-re ".*\\(\n\\)")
1225 (7 (unless (ruby-singleton-class-p (match-beginning 0))
1226 (put-text-property (match-beginning 7) (match-end 7)
1227 'syntax-table (string-to-syntax "\""))
1228 (ruby-syntax-propertize-heredoc end))))
1229 ;; Handle percent literals: %w(), %q{}, etc.
1230 ((concat "\\(?:^\\|[[ \t\n<+(,=]\\)" ruby-percent-literal-beg-re)
1231 (1 (prog1 "|" (ruby-syntax-propertize-percent-literal end)))))
1232 (point) end))
1233
1234 (defun ruby-syntax-propertize-heredoc (limit)
1235 (let ((ppss (syntax-ppss))
1236 (res '()))
1237 (when (eq ?\n (nth 3 ppss))
1238 (save-excursion
1239 (goto-char (nth 8 ppss))
1240 (beginning-of-line)
1241 (while (re-search-forward ruby-here-doc-beg-re
1242 (line-end-position) t)
1243 (unless (ruby-singleton-class-p (match-beginning 0))
1244 (push (concat (ruby-here-doc-end-match) "\n") res))))
1245 (let ((start (point)))
1246 ;; With multiple openers on the same line, we don't know in which
1247 ;; part `start' is, so we have to go back to the beginning.
1248 (when (cdr res)
1249 (goto-char (nth 8 ppss))
1250 (setq res (nreverse res)))
1251 (while (and res (re-search-forward (pop res) limit 'move))
1252 (if (null res)
1253 (put-text-property (1- (point)) (point)
1254 'syntax-table (string-to-syntax "\""))))
1255 ;; Make extra sure we don't move back, lest we could fall into an
1256 ;; inf-loop.
1257 (if (< (point) start) (goto-char start))))))
1258
1259 (defun ruby-syntax-enclosing-percent-literal (limit)
1260 (let ((state (syntax-ppss))
1261 (start (point)))
1262 ;; When already inside percent literal, re-propertize it.
1263 (when (eq t (nth 3 state))
1264 (goto-char (nth 8 state))
1265 (when (looking-at ruby-percent-literal-beg-re)
1266 (ruby-syntax-propertize-percent-literal limit))
1267 (when (< (point) start) (goto-char start)))))
1268
1269 (defun ruby-syntax-propertize-percent-literal (limit)
1270 (goto-char (match-beginning 2))
1271 ;; Not inside a simple string or comment.
1272 (when (eq t (nth 3 (syntax-ppss)))
1273 (let* ((op (char-after))
1274 (ops (char-to-string op))
1275 (cl (or (cdr (aref (syntax-table) op))
1276 (cdr (assoc op '((?< . ?>))))))
1277 parse-sexp-lookup-properties)
1278 (condition-case nil
1279 (progn
1280 (if cl ; Paired delimiters.
1281 ;; Delimiter pairs of the same kind can be nested
1282 ;; inside the literal, as long as they are balanced.
1283 ;; Create syntax table that ignores other characters.
1284 (with-syntax-table (make-char-table 'syntax-table nil)
1285 (modify-syntax-entry op (concat "(" (char-to-string cl)))
1286 (modify-syntax-entry cl (concat ")" ops))
1287 (modify-syntax-entry ?\\ "\\")
1288 (save-restriction
1289 (narrow-to-region (point) limit)
1290 (forward-list))) ; skip to the paired character
1291 ;; Single character delimiter.
1292 (re-search-forward (concat "[^\\]\\(?:\\\\\\\\\\)*"
1293 (regexp-quote ops)) limit nil))
1294 ;; Found the closing delimiter.
1295 (put-text-property (1- (point)) (point) 'syntax-table
1296 (string-to-syntax "|")))
1297 ;; Unclosed literal, leave the following text unpropertized.
1298 ((scan-error search-failed) (goto-char limit))))))
1299 )
1300
1301 ;; For Emacsen where syntax-propertize-rules is not (yet) available,
1302 ;; fallback on the old font-lock-syntactic-keywords stuff.
1303
1304 (defconst ruby-here-doc-end-re
1305 "^\\([ \t]+\\)?\\(.*\\)\\(\n\\)"
1306 "Regexp to match the end of heredocs.
1307
1308 This will actually match any line with one or more characters.
1309 It's useful in that it divides up the match string so that
1310 `ruby-here-doc-beg-match' can search for the beginning of the heredoc.")
1311
1312 (defun ruby-here-doc-beg-match ()
1313 "Return a regexp to find the beginning of a heredoc.
1314
1315 This should only be called after matching against `ruby-here-doc-end-re'."
1316 (let ((contents (concat
1317 (regexp-quote (concat (match-string 2) (match-string 3)))
1318 (if (string= (match-string 3) "_") "\\B" "\\b"))))
1319 (concat "<<"
1320 (let ((match (match-string 1)))
1321 (if (and match (> (length match) 0))
1322 (concat "\\(?:-\\([\"']?\\)\\|\\([\"']\\)"
1323 (match-string 1) "\\)"
1324 contents "\\(\\1\\|\\2\\)")
1325 (concat "-?\\([\"']\\|\\)" contents "\\1"))))))
1326
1327 (defconst ruby-font-lock-syntactic-keywords
1328 `( ;; #{ }, #$hoge, #@foo are not comments
1329 ("\\(#\\)[{$@]" 1 (1 . nil))
1330 ;; the last $', $", $` in the respective string is not variable
1331 ;; the last ?', ?", ?` in the respective string is not ascii code
1332 ("\\(^\\|[\[ \t\n<+\(,=]\\)\\(['\"`]\\)\\(\\\\.\\|\\2\\|[^'\"`\n\\\\]\\)*?\\\\?[?$]\\(\\2\\)"
1333 (2 (7 . nil))
1334 (4 (7 . nil)))
1335 ;; $' $" $` .... are variables
1336 ;; ?' ?" ?` are ascii codes
1337 ("\\(^\\|[^\\\\]\\)\\(\\\\\\\\\\)*[?$]\\([#\"'`]\\)" 3 (1 . nil))
1338 ;; regexps
1339 ("\\(^\\|[[=(,~?:;<>]\\|\\(^\\|\\s \\)\\(if\\|elsif\\|unless\\|while\\|until\\|when\\|and\\|or\\|&&\\|||\\)\\|g?sub!?\\|scan\\|split!?\\)\\s *\\(/\\)[^/\n\\\\]*\\(\\\\.[^/\n\\\\]*\\)*\\(/\\)"
1340 (4 (7 . ?/))
1341 (6 (7 . ?/)))
1342 ("^=en\\(d\\)\\_>" 1 "!")
1343 ;; Percent literal.
1344 ("\\(^\\|[[ \t\n<+(,=]\\)\\(%[xrqQwW]?\\([^<[{(a-zA-Z0-9 \n]\\)[^\n\\\\]*\\(\\\\.[^\n\\\\]*\\)*\\(\\3\\)\\)"
1345 (3 "\"")
1346 (5 "\""))
1347 ("^\\(=\\)begin\\_>" 1 (ruby-comment-beg-syntax))
1348 ;; Currently, the following case is highlighted incorrectly:
1349 ;;
1350 ;; <<FOO
1351 ;; FOO
1352 ;; <<BAR
1353 ;; <<BAZ
1354 ;; BAZ
1355 ;; BAR
1356 ;;
1357 ;; This is because all here-doc beginnings are highlighted before any endings,
1358 ;; so although <<BAR is properly marked as a beginning, when we get to <<BAZ
1359 ;; it thinks <<BAR is part of a string so it's marked as well.
1360 ;;
1361 ;; This may be fixable by modifying ruby-in-here-doc-p to use
1362 ;; ruby-in-non-here-doc-string-p rather than syntax-ppss-context,
1363 ;; but I don't want to try that until we've got unit tests set up
1364 ;; to make sure I don't break anything else.
1365 (,(concat ruby-here-doc-beg-re ".*\\(\n\\)")
1366 ,(+ 1 (regexp-opt-depth ruby-here-doc-beg-re))
1367 (ruby-here-doc-beg-syntax))
1368 (,ruby-here-doc-end-re 3 (ruby-here-doc-end-syntax)))
1369 "Syntactic keywords for Ruby mode. See `font-lock-syntactic-keywords'.")
1370
1371 (defun ruby-comment-beg-syntax ()
1372 "Return the syntax cell for a the first character of a =begin.
1373 See the definition of `ruby-font-lock-syntactic-keywords'.
1374
1375 This returns a comment-delimiter cell as long as the =begin
1376 isn't in a string or another comment."
1377 (when (not (nth 3 (syntax-ppss)))
1378 (string-to-syntax "!")))
1379
1380 (defun ruby-in-here-doc-p ()
1381 "Return whether or not the point is in a heredoc."
1382 (save-excursion
1383 (let ((old-point (point)) (case-fold-search nil))
1384 (beginning-of-line)
1385 (catch 'found-beg
1386 (while (and (re-search-backward ruby-here-doc-beg-re nil t)
1387 (not (ruby-singleton-class-p)))
1388 (if (not (or (ruby-in-ppss-context-p 'anything)
1389 (ruby-here-doc-find-end old-point)))
1390 (throw 'found-beg t)))))))
1391
1392 (defun ruby-here-doc-find-end (&optional limit)
1393 "Expects the point to be on a line with one or more heredoc openers.
1394 Returns the buffer position at which all heredocs on the line
1395 are terminated, or nil if they aren't terminated before the
1396 buffer position `limit' or the end of the buffer."
1397 (save-excursion
1398 (beginning-of-line)
1399 (catch 'done
1400 (let ((eol (point-at-eol))
1401 (case-fold-search nil)
1402 ;; Fake match data such that (match-end 0) is at eol
1403 (end-match-data (progn (looking-at ".*$") (match-data)))
1404 beg-match-data end-re)
1405 (while (re-search-forward ruby-here-doc-beg-re eol t)
1406 (setq beg-match-data (match-data))
1407 (setq end-re (ruby-here-doc-end-match))
1408
1409 (set-match-data end-match-data)
1410 (goto-char (match-end 0))
1411 (unless (re-search-forward end-re limit t) (throw 'done nil))
1412 (setq end-match-data (match-data))
1413
1414 (set-match-data beg-match-data)
1415 (goto-char (match-end 0)))
1416 (set-match-data end-match-data)
1417 (goto-char (match-end 0))
1418 (point)))))
1419
1420 (defun ruby-here-doc-beg-syntax ()
1421 "Return the syntax cell for a line that may begin a heredoc.
1422 See the definition of `ruby-font-lock-syntactic-keywords'.
1423
1424 This sets the syntax cell for the newline ending the line
1425 containing the heredoc beginning so that cases where multiple
1426 heredocs are started on one line are handled correctly."
1427 (save-excursion
1428 (goto-char (match-beginning 0))
1429 (unless (or (ruby-in-ppss-context-p 'non-heredoc)
1430 (ruby-in-here-doc-p))
1431 (string-to-syntax "\""))))
1432
1433 (defun ruby-here-doc-end-syntax ()
1434 "Return the syntax cell for a line that may end a heredoc.
1435 See the definition of `ruby-font-lock-syntactic-keywords'."
1436 (let ((pss (syntax-ppss)) (case-fold-search nil))
1437 ;; If we aren't in a string, we definitely aren't ending a heredoc,
1438 ;; so we can just give up.
1439 ;; This means we aren't doing a full-document search
1440 ;; every time we enter a character.
1441 (when (ruby-in-ppss-context-p 'heredoc pss)
1442 (save-excursion
1443 (goto-char (nth 8 pss)) ; Go to the beginning of heredoc.
1444 (let ((eol (point)))
1445 (beginning-of-line)
1446 (if (and (re-search-forward (ruby-here-doc-beg-match) eol t) ; If there is a heredoc that matches this line...
1447 (not (ruby-in-ppss-context-p 'anything)) ; And that's not inside a heredoc/string/comment...
1448 (progn (goto-char (match-end 0)) ; And it's the last heredoc on its line...
1449 (not (re-search-forward ruby-here-doc-beg-re eol t))))
1450 (string-to-syntax "\"")))))))
1451
1452 (unless (functionp 'syntax-ppss)
1453 (defun syntax-ppss (&optional pos)
1454 (parse-partial-sexp (point-min) (or pos (point)))))
1455 )
1456
1457 (defun ruby-in-ppss-context-p (context &optional ppss)
1458 (let ((ppss (or ppss (syntax-ppss (point)))))
1459 (if (cond
1460 ((eq context 'anything)
1461 (or (nth 3 ppss)
1462 (nth 4 ppss)))
1463 ((eq context 'string)
1464 (nth 3 ppss))
1465 ((eq context 'heredoc)
1466 (eq ?\n (nth 3 ppss)))
1467 ((eq context 'non-heredoc)
1468 (and (ruby-in-ppss-context-p 'anything)
1469 (not (ruby-in-ppss-context-p 'heredoc))))
1470 ((eq context 'comment)
1471 (nth 4 ppss))
1472 (t
1473 (error (concat
1474 "Internal error on `ruby-in-ppss-context-p': "
1475 "context name `" (symbol-name context) "' is unknown"))))
1476 t)))
1477
1478 (if (featurep 'xemacs)
1479 (put 'ruby-mode 'font-lock-defaults
1480 '((ruby-font-lock-keywords)
1481 nil nil nil
1482 beginning-of-line
1483 (font-lock-syntactic-keywords
1484 . ruby-font-lock-syntactic-keywords))))
1485
1486 (defvar ruby-font-lock-syntax-table
1487 (let ((tbl (copy-syntax-table ruby-mode-syntax-table)))
1488 (modify-syntax-entry ?_ "w" tbl)
1489 tbl)
1490 "The syntax table to use for fontifying Ruby mode buffers.
1491 See `font-lock-syntax-table'.")
1492
1493 (defconst ruby-font-lock-keywords
1494 (list
1495 ;; functions
1496 '("^\\s *def\\s +\\([^( \t\n]+\\)"
1497 1 font-lock-function-name-face)
1498 ;; keywords
1499 (cons (concat
1500 "\\(^\\|[^_:.@$]\\|\\.\\.\\)\\b\\(defined\\?\\|"
1501 (regexp-opt
1502 '("alias_method"
1503 "alias"
1504 "and"
1505 "begin"
1506 "break"
1507 "case"
1508 "catch"
1509 "class"
1510 "def"
1511 "do"
1512 "elsif"
1513 "else"
1514 "fail"
1515 "ensure"
1516 "for"
1517 "end"
1518 "if"
1519 "in"
1520 "module_function"
1521 "module"
1522 "next"
1523 "not"
1524 "or"
1525 "public"
1526 "private"
1527 "protected"
1528 "raise"
1529 "redo"
1530 "rescue"
1531 "retry"
1532 "return"
1533 "then"
1534 "throw"
1535 "super"
1536 "unless"
1537 "undef"
1538 "until"
1539 "when"
1540 "while"
1541 "yield")
1542 t)
1543 "\\)"
1544 ruby-keyword-end-re)
1545 2)
1546 ;; here-doc beginnings
1547 (list ruby-here-doc-beg-re 0 'font-lock-string-face)
1548 ;; variables
1549 '("\\(^\\|[^_:.@$]\\|\\.\\.\\)\\b\\(nil\\|self\\|true\\|false\\)\\>"
1550 2 font-lock-variable-name-face)
1551 ;; variables
1552 '("\\(\\$\\([^a-zA-Z0-9 \n]\\|[0-9]\\)\\)\\W"
1553 1 font-lock-variable-name-face)
1554 '("\\(\\$\\|@\\|@@\\)\\(\\w\\|_\\)+"
1555 0 font-lock-variable-name-face)
1556 ;; constants
1557 '("\\(^\\|[^_]\\)\\b\\([A-Z]+\\(\\w\\|_\\)*\\)"
1558 2 font-lock-type-face)
1559 ;; symbols
1560 '("\\(^\\|[^:]\\)\\(:\\([-+~]@?\\|[/%&|^`]\\|\\*\\*?\\|<\\(<\\|=>?\\)?\\|>[>=]?\\|===?\\|=~\\|![~=]?\\|\\[\\]=?\\|\\(\\w\\|_\\)+\\([!?=]\\|\\b_*\\)\\|#{[^}\n\\\\]*\\(\\\\.[^}\n\\\\]*\\)*}\\)\\)"
1561 2 font-lock-reference-face)
1562 '("\\(^\\s *\\|[\[\{\(,]\\s *\\|\\sw\\s +\\)\\(\\(\\sw\\|_\\)+\\):[^:]" 2 font-lock-reference-face)
1563 ;; expression expansion
1564 '("#\\({[^}\n\\\\]*\\(\\\\.[^}\n\\\\]*\\)*}\\|\\(\\$\\|@\\|@@\\)\\(\\w\\|_\\)+\\)"
1565 0 font-lock-variable-name-face t)
1566 ;; warn lower camel case
1567 ;'("\\<[a-z]+[a-z0-9]*[A-Z][A-Za-z0-9]*\\([!?]?\\|\\>\\)"
1568 ; 0 font-lock-warning-face)
1569 )
1570 "Additional expressions to highlight in Ruby mode.")
1571
1572 ;;;###autoload
1573 (define-derived-mode ruby-mode prog-mode "Ruby"
1574 "Major mode for editing Ruby scripts.
1575 \\[ruby-indent-line] properly indents subexpressions of multi-line
1576 class, module, def, if, while, for, do, and case statements, taking
1577 nesting into account.
1578
1579 The variable `ruby-indent-level' controls the amount of indentation.
1580
1581 \\{ruby-mode-map}"
1582 (ruby-mode-variables)
1583
1584 (set (make-local-variable 'imenu-create-index-function)
1585 'ruby-imenu-create-index)
1586 (set (make-local-variable 'add-log-current-defun-function)
1587 'ruby-add-log-current-method)
1588
1589 (add-hook
1590 (cond ((boundp 'before-save-hook) 'before-save-hook)
1591 ((boundp 'write-contents-functions) 'write-contents-functions)
1592 ((boundp 'write-contents-hooks) 'write-contents-hooks))
1593 'ruby-mode-set-encoding nil 'local)
1594
1595 (set (make-local-variable 'electric-indent-chars)
1596 (append '(?\{ ?\}) electric-indent-chars))
1597
1598 (set (make-local-variable 'font-lock-defaults)
1599 '((ruby-font-lock-keywords) nil nil))
1600 (set (make-local-variable 'font-lock-keywords)
1601 ruby-font-lock-keywords)
1602 (set (make-local-variable 'font-lock-syntax-table)
1603 ruby-font-lock-syntax-table)
1604
1605 (if (eval-when-compile (fboundp 'syntax-propertize-rules))
1606 (set (make-local-variable 'syntax-propertize-function)
1607 #'ruby-syntax-propertize-function)
1608 (set (make-local-variable 'font-lock-syntactic-keywords)
1609 ruby-font-lock-syntactic-keywords)))
1610
1611 ;;; Invoke ruby-mode when appropriate
1612
1613 ;;;###autoload
1614 (add-to-list 'auto-mode-alist (cons (purecopy "\\.rb\\'") 'ruby-mode))
1615
1616 ;;;###autoload
1617 (dolist (name (list "ruby" "rbx" "jruby" "ruby1.9" "ruby1.8"))
1618 (add-to-list 'interpreter-mode-alist (cons (purecopy name) 'ruby-mode)))
1619
1620 (provide 'ruby-mode)
1621
1622 ;;; ruby-mode.el ends here