]> code.delx.au - gnu-emacs/blob - lisp/progmodes/ruby-mode.el
Make special-display-* and display-buffer-reuse-frames obsolete.
[gnu-emacs] / 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 (defconst ruby-syntax-methods-before-regexp
1184 '("gsub" "gsub!" "sub" "sub!" "scan" "split" "split!" "index" "match"
1185 "assert_match" "Given" "Then" "When")
1186 "Methods that can take regexp as the first argument.
1187 It will be properly highlighted even when the call omits parens."))
1188
1189 (defun ruby-syntax-propertize-function (start end)
1190 "Syntactic keywords for Ruby mode. See `syntax-propertize-function'."
1191 (goto-char start)
1192 (ruby-syntax-propertize-heredoc end)
1193 (ruby-syntax-enclosing-percent-literal end)
1194 (funcall
1195 (syntax-propertize-rules
1196 ;; #{ }, #$hoge, #@foo are not comments.
1197 ("\\(#\\)[{$@]" (1 "."))
1198 ;; $' $" $` .... are variables.
1199 ;; ?' ?" ?` are ascii codes.
1200 ("\\([?$]\\)[#\"'`]"
1201 (1 (unless (save-excursion
1202 ;; Not within a string.
1203 (nth 3 (syntax-ppss (match-beginning 0))))
1204 (string-to-syntax "\\"))))
1205 ;; Regexps: regexps are distinguished from division because
1206 ;; of the keyword, symbol, or method name before them.
1207 ((concat
1208 ;; Special tokens that can't be followed by a division operator.
1209 "\\(^\\|[[=(,~?:;<>]"
1210 ;; Control flow keywords and operators following bol or whitespace.
1211 "\\|\\(?:^\\|\\s \\)"
1212 (regexp-opt '("if" "elsif" "unless" "while" "until" "when" "and"
1213 "or" "not" "&&" "||"))
1214 ;; Method name from the list.
1215 "\\|\\_<"
1216 (regexp-opt ruby-syntax-methods-before-regexp)
1217 "\\)\\s *"
1218 ;; The regular expression itself.
1219 "\\(/\\)[^/\n\\\\]*\\(?:\\\\.[^/\n\\\\]*\\)*\\(/\\)")
1220 (2 (string-to-syntax "\"/"))
1221 (3 (string-to-syntax "\"/")))
1222 ("^=en\\(d\\)\\_>" (1 "!"))
1223 ("^\\(=\\)begin\\_>" (1 "!"))
1224 ;; Handle here documents.
1225 ((concat ruby-here-doc-beg-re ".*\\(\n\\)")
1226 (7 (unless (ruby-singleton-class-p (match-beginning 0))
1227 (put-text-property (match-beginning 7) (match-end 7)
1228 'syntax-table (string-to-syntax "\""))
1229 (ruby-syntax-propertize-heredoc end))))
1230 ;; Handle percent literals: %w(), %q{}, etc.
1231 ((concat "\\(?:^\\|[[ \t\n<+(,=]\\)" ruby-percent-literal-beg-re)
1232 (1 (prog1 "|" (ruby-syntax-propertize-percent-literal end)))))
1233 (point) end))
1234
1235 (defun ruby-syntax-propertize-heredoc (limit)
1236 (let ((ppss (syntax-ppss))
1237 (res '()))
1238 (when (eq ?\n (nth 3 ppss))
1239 (save-excursion
1240 (goto-char (nth 8 ppss))
1241 (beginning-of-line)
1242 (while (re-search-forward ruby-here-doc-beg-re
1243 (line-end-position) t)
1244 (unless (ruby-singleton-class-p (match-beginning 0))
1245 (push (concat (ruby-here-doc-end-match) "\n") res))))
1246 (let ((start (point)))
1247 ;; With multiple openers on the same line, we don't know in which
1248 ;; part `start' is, so we have to go back to the beginning.
1249 (when (cdr res)
1250 (goto-char (nth 8 ppss))
1251 (setq res (nreverse res)))
1252 (while (and res (re-search-forward (pop res) limit 'move))
1253 (if (null res)
1254 (put-text-property (1- (point)) (point)
1255 'syntax-table (string-to-syntax "\""))))
1256 ;; Make extra sure we don't move back, lest we could fall into an
1257 ;; inf-loop.
1258 (if (< (point) start) (goto-char start))))))
1259
1260 (defun ruby-syntax-enclosing-percent-literal (limit)
1261 (let ((state (syntax-ppss))
1262 (start (point)))
1263 ;; When already inside percent literal, re-propertize it.
1264 (when (eq t (nth 3 state))
1265 (goto-char (nth 8 state))
1266 (when (looking-at ruby-percent-literal-beg-re)
1267 (ruby-syntax-propertize-percent-literal limit))
1268 (when (< (point) start) (goto-char start)))))
1269
1270 (defun ruby-syntax-propertize-percent-literal (limit)
1271 (goto-char (match-beginning 2))
1272 ;; Not inside a simple string or comment.
1273 (when (eq t (nth 3 (syntax-ppss)))
1274 (let* ((op (char-after))
1275 (ops (char-to-string op))
1276 (cl (or (cdr (aref (syntax-table) op))
1277 (cdr (assoc op '((?< . ?>))))))
1278 parse-sexp-lookup-properties)
1279 (condition-case nil
1280 (progn
1281 (if cl ; Paired delimiters.
1282 ;; Delimiter pairs of the same kind can be nested
1283 ;; inside the literal, as long as they are balanced.
1284 ;; Create syntax table that ignores other characters.
1285 (with-syntax-table (make-char-table 'syntax-table nil)
1286 (modify-syntax-entry op (concat "(" (char-to-string cl)))
1287 (modify-syntax-entry cl (concat ")" ops))
1288 (modify-syntax-entry ?\\ "\\")
1289 (save-restriction
1290 (narrow-to-region (point) limit)
1291 (forward-list))) ; skip to the paired character
1292 ;; Single character delimiter.
1293 (re-search-forward (concat "[^\\]\\(?:\\\\\\\\\\)*"
1294 (regexp-quote ops)) limit nil))
1295 ;; Found the closing delimiter.
1296 (put-text-property (1- (point)) (point) 'syntax-table
1297 (string-to-syntax "|")))
1298 ;; Unclosed literal, leave the following text unpropertized.
1299 ((scan-error search-failed) (goto-char limit))))))
1300 )
1301
1302 ;; For Emacsen where syntax-propertize-rules is not (yet) available,
1303 ;; fallback on the old font-lock-syntactic-keywords stuff.
1304
1305 (defconst ruby-here-doc-end-re
1306 "^\\([ \t]+\\)?\\(.*\\)\\(\n\\)"
1307 "Regexp to match the end of heredocs.
1308
1309 This will actually match any line with one or more characters.
1310 It's useful in that it divides up the match string so that
1311 `ruby-here-doc-beg-match' can search for the beginning of the heredoc.")
1312
1313 (defun ruby-here-doc-beg-match ()
1314 "Return a regexp to find the beginning of a heredoc.
1315
1316 This should only be called after matching against `ruby-here-doc-end-re'."
1317 (let ((contents (concat
1318 (regexp-quote (concat (match-string 2) (match-string 3)))
1319 (if (string= (match-string 3) "_") "\\B" "\\b"))))
1320 (concat "<<"
1321 (let ((match (match-string 1)))
1322 (if (and match (> (length match) 0))
1323 (concat "\\(?:-\\([\"']?\\)\\|\\([\"']\\)"
1324 (match-string 1) "\\)"
1325 contents "\\(\\1\\|\\2\\)")
1326 (concat "-?\\([\"']\\|\\)" contents "\\1"))))))
1327
1328 (defconst ruby-font-lock-syntactic-keywords
1329 `( ;; #{ }, #$hoge, #@foo are not comments
1330 ("\\(#\\)[{$@]" 1 (1 . nil))
1331 ;; the last $', $", $` in the respective string is not variable
1332 ;; the last ?', ?", ?` in the respective string is not ascii code
1333 ("\\(^\\|[\[ \t\n<+\(,=]\\)\\(['\"`]\\)\\(\\\\.\\|\\2\\|[^'\"`\n\\\\]\\)*?\\\\?[?$]\\(\\2\\)"
1334 (2 (7 . nil))
1335 (4 (7 . nil)))
1336 ;; $' $" $` .... are variables
1337 ;; ?' ?" ?` are ascii codes
1338 ("\\(^\\|[^\\\\]\\)\\(\\\\\\\\\\)*[?$]\\([#\"'`]\\)" 3 (1 . nil))
1339 ;; regexps
1340 ("\\(^\\|[[=(,~?:;<>]\\|\\(^\\|\\s \\)\\(if\\|elsif\\|unless\\|while\\|until\\|when\\|and\\|or\\|&&\\|||\\)\\|g?sub!?\\|scan\\|split!?\\)\\s *\\(/\\)[^/\n\\\\]*\\(\\\\.[^/\n\\\\]*\\)*\\(/\\)"
1341 (4 (7 . ?/))
1342 (6 (7 . ?/)))
1343 ("^=en\\(d\\)\\_>" 1 "!")
1344 ;; Percent literal.
1345 ("\\(^\\|[[ \t\n<+(,=]\\)\\(%[xrqQwW]?\\([^<[{(a-zA-Z0-9 \n]\\)[^\n\\\\]*\\(\\\\.[^\n\\\\]*\\)*\\(\\3\\)\\)"
1346 (3 "\"")
1347 (5 "\""))
1348 ("^\\(=\\)begin\\_>" 1 (ruby-comment-beg-syntax))
1349 ;; Currently, the following case is highlighted incorrectly:
1350 ;;
1351 ;; <<FOO
1352 ;; FOO
1353 ;; <<BAR
1354 ;; <<BAZ
1355 ;; BAZ
1356 ;; BAR
1357 ;;
1358 ;; This is because all here-doc beginnings are highlighted before any endings,
1359 ;; so although <<BAR is properly marked as a beginning, when we get to <<BAZ
1360 ;; it thinks <<BAR is part of a string so it's marked as well.
1361 ;;
1362 ;; This may be fixable by modifying ruby-in-here-doc-p to use
1363 ;; ruby-in-non-here-doc-string-p rather than syntax-ppss-context,
1364 ;; but I don't want to try that until we've got unit tests set up
1365 ;; to make sure I don't break anything else.
1366 (,(concat ruby-here-doc-beg-re ".*\\(\n\\)")
1367 ,(+ 1 (regexp-opt-depth ruby-here-doc-beg-re))
1368 (ruby-here-doc-beg-syntax))
1369 (,ruby-here-doc-end-re 3 (ruby-here-doc-end-syntax)))
1370 "Syntactic keywords for Ruby mode. See `font-lock-syntactic-keywords'.")
1371
1372 (defun ruby-comment-beg-syntax ()
1373 "Return the syntax cell for a the first character of a =begin.
1374 See the definition of `ruby-font-lock-syntactic-keywords'.
1375
1376 This returns a comment-delimiter cell as long as the =begin
1377 isn't in a string or another comment."
1378 (when (not (nth 3 (syntax-ppss)))
1379 (string-to-syntax "!")))
1380
1381 (defun ruby-in-here-doc-p ()
1382 "Return whether or not the point is in a heredoc."
1383 (save-excursion
1384 (let ((old-point (point)) (case-fold-search nil))
1385 (beginning-of-line)
1386 (catch 'found-beg
1387 (while (and (re-search-backward ruby-here-doc-beg-re nil t)
1388 (not (ruby-singleton-class-p)))
1389 (if (not (or (ruby-in-ppss-context-p 'anything)
1390 (ruby-here-doc-find-end old-point)))
1391 (throw 'found-beg t)))))))
1392
1393 (defun ruby-here-doc-find-end (&optional limit)
1394 "Expects the point to be on a line with one or more heredoc openers.
1395 Returns the buffer position at which all heredocs on the line
1396 are terminated, or nil if they aren't terminated before the
1397 buffer position `limit' or the end of the buffer."
1398 (save-excursion
1399 (beginning-of-line)
1400 (catch 'done
1401 (let ((eol (point-at-eol))
1402 (case-fold-search nil)
1403 ;; Fake match data such that (match-end 0) is at eol
1404 (end-match-data (progn (looking-at ".*$") (match-data)))
1405 beg-match-data end-re)
1406 (while (re-search-forward ruby-here-doc-beg-re eol t)
1407 (setq beg-match-data (match-data))
1408 (setq end-re (ruby-here-doc-end-match))
1409
1410 (set-match-data end-match-data)
1411 (goto-char (match-end 0))
1412 (unless (re-search-forward end-re limit t) (throw 'done nil))
1413 (setq end-match-data (match-data))
1414
1415 (set-match-data beg-match-data)
1416 (goto-char (match-end 0)))
1417 (set-match-data end-match-data)
1418 (goto-char (match-end 0))
1419 (point)))))
1420
1421 (defun ruby-here-doc-beg-syntax ()
1422 "Return the syntax cell for a line that may begin a heredoc.
1423 See the definition of `ruby-font-lock-syntactic-keywords'.
1424
1425 This sets the syntax cell for the newline ending the line
1426 containing the heredoc beginning so that cases where multiple
1427 heredocs are started on one line are handled correctly."
1428 (save-excursion
1429 (goto-char (match-beginning 0))
1430 (unless (or (ruby-in-ppss-context-p 'non-heredoc)
1431 (ruby-in-here-doc-p))
1432 (string-to-syntax "\""))))
1433
1434 (defun ruby-here-doc-end-syntax ()
1435 "Return the syntax cell for a line that may end a heredoc.
1436 See the definition of `ruby-font-lock-syntactic-keywords'."
1437 (let ((pss (syntax-ppss)) (case-fold-search nil))
1438 ;; If we aren't in a string, we definitely aren't ending a heredoc,
1439 ;; so we can just give up.
1440 ;; This means we aren't doing a full-document search
1441 ;; every time we enter a character.
1442 (when (ruby-in-ppss-context-p 'heredoc pss)
1443 (save-excursion
1444 (goto-char (nth 8 pss)) ; Go to the beginning of heredoc.
1445 (let ((eol (point)))
1446 (beginning-of-line)
1447 (if (and (re-search-forward (ruby-here-doc-beg-match) eol t) ; If there is a heredoc that matches this line...
1448 (not (ruby-in-ppss-context-p 'anything)) ; And that's not inside a heredoc/string/comment...
1449 (progn (goto-char (match-end 0)) ; And it's the last heredoc on its line...
1450 (not (re-search-forward ruby-here-doc-beg-re eol t))))
1451 (string-to-syntax "\"")))))))
1452
1453 (unless (functionp 'syntax-ppss)
1454 (defun syntax-ppss (&optional pos)
1455 (parse-partial-sexp (point-min) (or pos (point)))))
1456 )
1457
1458 (defun ruby-in-ppss-context-p (context &optional ppss)
1459 (let ((ppss (or ppss (syntax-ppss (point)))))
1460 (if (cond
1461 ((eq context 'anything)
1462 (or (nth 3 ppss)
1463 (nth 4 ppss)))
1464 ((eq context 'string)
1465 (nth 3 ppss))
1466 ((eq context 'heredoc)
1467 (eq ?\n (nth 3 ppss)))
1468 ((eq context 'non-heredoc)
1469 (and (ruby-in-ppss-context-p 'anything)
1470 (not (ruby-in-ppss-context-p 'heredoc))))
1471 ((eq context 'comment)
1472 (nth 4 ppss))
1473 (t
1474 (error (concat
1475 "Internal error on `ruby-in-ppss-context-p': "
1476 "context name `" (symbol-name context) "' is unknown"))))
1477 t)))
1478
1479 (if (featurep 'xemacs)
1480 (put 'ruby-mode 'font-lock-defaults
1481 '((ruby-font-lock-keywords)
1482 nil nil nil
1483 beginning-of-line
1484 (font-lock-syntactic-keywords
1485 . ruby-font-lock-syntactic-keywords))))
1486
1487 (defvar ruby-font-lock-syntax-table
1488 (let ((tbl (copy-syntax-table ruby-mode-syntax-table)))
1489 (modify-syntax-entry ?_ "w" tbl)
1490 tbl)
1491 "The syntax table to use for fontifying Ruby mode buffers.
1492 See `font-lock-syntax-table'.")
1493
1494 (defconst ruby-font-lock-keywords
1495 (list
1496 ;; functions
1497 '("^\\s *def\\s +\\([^( \t\n]+\\)"
1498 1 font-lock-function-name-face)
1499 ;; keywords
1500 (cons (concat
1501 "\\(^\\|[^_:.@$]\\|\\.\\.\\)\\b\\(defined\\?\\|"
1502 (regexp-opt
1503 '("alias_method"
1504 "alias"
1505 "and"
1506 "begin"
1507 "break"
1508 "case"
1509 "catch"
1510 "class"
1511 "def"
1512 "do"
1513 "elsif"
1514 "else"
1515 "fail"
1516 "ensure"
1517 "for"
1518 "end"
1519 "if"
1520 "in"
1521 "module_function"
1522 "module"
1523 "next"
1524 "not"
1525 "or"
1526 "public"
1527 "private"
1528 "protected"
1529 "raise"
1530 "redo"
1531 "rescue"
1532 "retry"
1533 "return"
1534 "then"
1535 "throw"
1536 "super"
1537 "unless"
1538 "undef"
1539 "until"
1540 "when"
1541 "while"
1542 "yield")
1543 t)
1544 "\\)"
1545 ruby-keyword-end-re)
1546 2)
1547 ;; here-doc beginnings
1548 (list ruby-here-doc-beg-re 0 'font-lock-string-face)
1549 ;; variables
1550 '("\\(^\\|[^_:.@$]\\|\\.\\.\\)\\b\\(nil\\|self\\|true\\|false\\)\\>"
1551 2 font-lock-variable-name-face)
1552 ;; variables
1553 '("\\(\\$\\([^a-zA-Z0-9 \n]\\|[0-9]\\)\\)\\W"
1554 1 font-lock-variable-name-face)
1555 '("\\(\\$\\|@\\|@@\\)\\(\\w\\|_\\)+"
1556 0 font-lock-variable-name-face)
1557 ;; constants
1558 '("\\(^\\|[^_]\\)\\b\\([A-Z]+\\(\\w\\|_\\)*\\)"
1559 2 font-lock-type-face)
1560 ;; symbols
1561 '("\\(^\\|[^:]\\)\\(:\\([-+~]@?\\|[/%&|^`]\\|\\*\\*?\\|<\\(<\\|=>?\\)?\\|>[>=]?\\|===?\\|=~\\|![~=]?\\|\\[\\]=?\\|\\(\\w\\|_\\)+\\([!?=]\\|\\b_*\\)\\|#{[^}\n\\\\]*\\(\\\\.[^}\n\\\\]*\\)*}\\)\\)"
1562 2 font-lock-reference-face)
1563 '("\\(^\\s *\\|[\[\{\(,]\\s *\\|\\sw\\s +\\)\\(\\(\\sw\\|_\\)+\\):[^:]" 2 font-lock-reference-face)
1564 ;; expression expansion
1565 '("#\\({[^}\n\\\\]*\\(\\\\.[^}\n\\\\]*\\)*}\\|\\(\\$\\|@\\|@@\\)\\(\\w\\|_\\)+\\)"
1566 0 font-lock-variable-name-face t)
1567 ;; warn lower camel case
1568 ;'("\\<[a-z]+[a-z0-9]*[A-Z][A-Za-z0-9]*\\([!?]?\\|\\>\\)"
1569 ; 0 font-lock-warning-face)
1570 )
1571 "Additional expressions to highlight in Ruby mode.")
1572
1573 ;;;###autoload
1574 (define-derived-mode ruby-mode prog-mode "Ruby"
1575 "Major mode for editing Ruby scripts.
1576 \\[ruby-indent-line] properly indents subexpressions of multi-line
1577 class, module, def, if, while, for, do, and case statements, taking
1578 nesting into account.
1579
1580 The variable `ruby-indent-level' controls the amount of indentation.
1581
1582 \\{ruby-mode-map}"
1583 (ruby-mode-variables)
1584
1585 (set (make-local-variable 'imenu-create-index-function)
1586 'ruby-imenu-create-index)
1587 (set (make-local-variable 'add-log-current-defun-function)
1588 'ruby-add-log-current-method)
1589
1590 (add-hook
1591 (cond ((boundp 'before-save-hook) 'before-save-hook)
1592 ((boundp 'write-contents-functions) 'write-contents-functions)
1593 ((boundp 'write-contents-hooks) 'write-contents-hooks))
1594 'ruby-mode-set-encoding nil 'local)
1595
1596 (set (make-local-variable 'electric-indent-chars)
1597 (append '(?\{ ?\}) electric-indent-chars))
1598
1599 (set (make-local-variable 'font-lock-defaults)
1600 '((ruby-font-lock-keywords) nil nil))
1601 (set (make-local-variable 'font-lock-keywords)
1602 ruby-font-lock-keywords)
1603 (set (make-local-variable 'font-lock-syntax-table)
1604 ruby-font-lock-syntax-table)
1605
1606 (if (eval-when-compile (fboundp 'syntax-propertize-rules))
1607 (set (make-local-variable 'syntax-propertize-function)
1608 #'ruby-syntax-propertize-function)
1609 (set (make-local-variable 'font-lock-syntactic-keywords)
1610 ruby-font-lock-syntactic-keywords)))
1611
1612 ;;; Invoke ruby-mode when appropriate
1613
1614 ;;;###autoload
1615 (add-to-list 'auto-mode-alist (cons (purecopy "\\.rb\\'") 'ruby-mode))
1616
1617 ;;;###autoload
1618 (dolist (name (list "ruby" "rbx" "jruby" "ruby1.9" "ruby1.8"))
1619 (add-to-list 'interpreter-mode-alist (cons (purecopy name) 'ruby-mode)))
1620
1621 (provide 'ruby-mode)
1622
1623 ;;; ruby-mode.el ends here