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