Merge from trunk.
[bpt/emacs.git] / lisp / progmodes / ruby-mode.el
1 ;;; ruby-mode.el --- Major mode for editing Ruby files
2
3 ;; Copyright (C) 1994-2012 Free Software Foundation, Inc.
4
5 ;; Authors: Yukihiro Matsumoto
6 ;; Nobuyoshi Nakada
7 ;; URL: http://www.emacswiki.org/cgi-bin/wiki/RubyMode
8 ;; Created: Fri Feb 4 14:49:13 JST 1994
9 ;; Keywords: languages ruby
10 ;; Version: 1.0
11
12 ;; This file is part of GNU Emacs.
13
14 ;; GNU Emacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
18
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
23
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26
27 ;;; Commentary:
28
29 ;; Provides font-locking, indentation support, and navigation for Ruby code.
30 ;;
31 ;; If you're installing manually, you should add this to your .emacs
32 ;; file after putting it on your load path:
33 ;;
34 ;; (autoload 'ruby-mode "ruby-mode" "Major mode for ruby files" t)
35 ;; (add-to-list 'auto-mode-alist '("\\.rb$" . ruby-mode))
36 ;; (add-to-list 'interpreter-mode-alist '("ruby" . ruby-mode))
37 ;;
38 ;; Still needs more docstrings; search below for TODO.
39
40 ;;; Code:
41
42 (eval-when-compile (require 'cl))
43
44 (defgroup ruby nil
45 "Major mode for editing Ruby code."
46 :prefix "ruby-"
47 :group 'languages)
48
49 (defconst ruby-keyword-end-re
50 (if (string-match "\\_>" "ruby")
51 "\\_>"
52 "\\>"))
53
54 (defconst ruby-block-beg-keywords
55 '("class" "module" "def" "if" "unless" "case" "while" "until" "for" "begin" "do")
56 "Keywords at the beginning of blocks.")
57
58 (defconst ruby-block-beg-re
59 (regexp-opt ruby-block-beg-keywords)
60 "Regexp to match the beginning of blocks.")
61
62 (defconst ruby-non-block-do-re
63 (concat (regexp-opt '("while" "until" "for" "rescue") t) ruby-keyword-end-re)
64 "Regexp to match keywords that nest without blocks.")
65
66 (defconst ruby-indent-beg-re
67 (concat "\\(\\s *" (regexp-opt '("class" "module" "def") t) "\\)\\|"
68 (regexp-opt '("if" "unless" "case" "while" "until" "for" "begin")))
69 "Regexp to match where the indentation gets deeper.")
70
71 (defconst ruby-modifier-beg-keywords
72 '("if" "unless" "while" "until")
73 "Modifiers that are the same as the beginning of blocks.")
74
75 (defconst ruby-modifier-beg-re
76 (regexp-opt ruby-modifier-beg-keywords)
77 "Regexp to match modifiers same as the beginning of blocks.")
78
79 (defconst ruby-modifier-re
80 (regexp-opt (cons "rescue" ruby-modifier-beg-keywords))
81 "Regexp to match modifiers.")
82
83 (defconst ruby-block-mid-keywords
84 '("then" "else" "elsif" "when" "rescue" "ensure")
85 "Keywords where the indentation gets shallower in middle of block statements.")
86
87 (defconst ruby-block-mid-re
88 (regexp-opt ruby-block-mid-keywords)
89 "Regexp to match where the indentation gets shallower in middle of block statements.")
90
91 (defconst ruby-block-op-keywords
92 '("and" "or" "not")
93 "Regexp to match boolean keywords.")
94
95 (defconst ruby-block-hanging-re
96 (regexp-opt (append ruby-modifier-beg-keywords ruby-block-op-keywords))
97 "Regexp to match hanging block modifiers.")
98
99 (defconst ruby-block-end-re "\\<end\\>")
100
101 (eval-and-compile
102 (defconst ruby-here-doc-beg-re
103 "\\(<\\)<\\(-\\)?\\(\\([a-zA-Z0-9_]+\\)\\|[\"]\\([^\"]+\\)[\"]\\|[']\\([^']+\\)[']\\)"
104 "Regexp to match the beginning of a heredoc."))
105
106 (defun ruby-here-doc-end-match ()
107 "Return a regexp to find the end of a heredoc.
108
109 This should only be called after matching against `ruby-here-doc-beg-re'."
110 (concat "^"
111 (if (match-string 2) "[ \t]*" nil)
112 (regexp-quote
113 (or (match-string 4)
114 (match-string 5)
115 (match-string 6)))))
116
117 (defconst ruby-delimiter
118 (concat "[?$/%(){}#\"'`.:]\\|<<\\|\\[\\|\\]\\|\\<\\("
119 ruby-block-beg-re
120 "\\)\\>\\|" ruby-block-end-re
121 "\\|^=begin\\|" ruby-here-doc-beg-re))
122
123 (defconst ruby-negative
124 (concat "^[ \t]*\\(\\(" ruby-block-mid-re "\\)\\>\\|"
125 ruby-block-end-re "\\|}\\|\\]\\)")
126 "Regexp to match where the indentation gets shallower.")
127
128 (defconst ruby-operator-re "[-,.+*/%&|^~=<>:]"
129 "Regexp to match operators.")
130
131 (defconst ruby-symbol-chars "a-zA-Z0-9_"
132 "List of characters that symbol names may contain.")
133 (defconst ruby-symbol-re (concat "[" ruby-symbol-chars "]")
134 "Regexp to match symbols.")
135
136 (define-abbrev-table 'ruby-mode-abbrev-table ()
137 "Abbrev table in use in Ruby mode buffers.")
138
139 (defvar ruby-mode-map
140 (let ((map (make-sparse-keymap)))
141 (define-key map "{" 'ruby-electric-brace)
142 (define-key map "}" 'ruby-electric-brace)
143 (define-key map (kbd "M-C-a") 'ruby-beginning-of-defun)
144 (define-key map (kbd "M-C-e") 'ruby-end-of-defun)
145 (define-key map (kbd "M-C-b") 'ruby-backward-sexp)
146 (define-key map (kbd "M-C-f") 'ruby-forward-sexp)
147 (define-key map (kbd "M-C-p") 'ruby-beginning-of-block)
148 (define-key map (kbd "M-C-n") 'ruby-end-of-block)
149 (define-key map (kbd "M-C-h") 'ruby-mark-defun)
150 (define-key map (kbd "M-C-q") 'ruby-indent-exp)
151 (define-key map (kbd "C-M-h") 'backward-kill-word)
152 (define-key map (kbd "C-j") 'reindent-then-newline-and-indent)
153 (define-key map (kbd "C-m") 'newline)
154 (define-key map (kbd "C-c C-c") 'comment-region)
155 map)
156 "Keymap used in Ruby mode.")
157
158 (defvar ruby-mode-syntax-table
159 (let ((table (make-syntax-table)))
160 (modify-syntax-entry ?\' "\"" table)
161 (modify-syntax-entry ?\" "\"" table)
162 (modify-syntax-entry ?\` "\"" table)
163 (modify-syntax-entry ?# "<" table)
164 (modify-syntax-entry ?\n ">" 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-expr-beg (&optional option)
383 "TODO: document."
384 (save-excursion
385 (store-match-data nil)
386 (let ((space (skip-chars-backward " \t")))
387 (cond
388 ((bolp) t)
389 ((progn
390 (forward-char -1)
391 (and (looking-at "\\?")
392 (or (eq (char-syntax (char-before (point))) ?w)
393 (ruby-special-char-p))))
394 nil)
395 ((and (eq option 'heredoc) (< space 0)) t)
396 ((or (looking-at ruby-operator-re)
397 (looking-at "[\\[({,;]")
398 (and (looking-at "[!?]")
399 (or (not (eq option 'modifier))
400 (bolp)
401 (save-excursion (forward-char -1) (looking-at "\\Sw$"))))
402 (and (looking-at ruby-symbol-re)
403 (skip-chars-backward ruby-symbol-chars)
404 (cond
405 ((looking-at (regexp-opt
406 (append ruby-block-beg-keywords
407 ruby-block-op-keywords
408 ruby-block-mid-keywords)
409 'words))
410 (goto-char (match-end 0))
411 (not (looking-at "\\s_")))
412 ((eq option 'expr-qstr)
413 (looking-at "[a-zA-Z][a-zA-z0-9_]* +%[^ \t]"))
414 ((eq option 'expr-re)
415 (looking-at "[a-zA-Z][a-zA-z0-9_]* +/[^ \t]"))
416 (t nil)))))))))
417
418 (defun ruby-forward-string (term &optional end no-error expand)
419 "TODO: document."
420 (let ((n 1) (c (string-to-char term))
421 (re (if expand
422 (concat "[^\\]\\(\\\\\\\\\\)*\\([" term "]\\|\\(#{\\)\\)")
423 (concat "[^\\]\\(\\\\\\\\\\)*[" term "]"))))
424 (while (and (re-search-forward re end no-error)
425 (if (match-beginning 3)
426 (ruby-forward-string "}{" end no-error nil)
427 (> (setq n (if (eq (char-before (point)) c)
428 (1- n) (1+ n))) 0)))
429 (forward-char -1))
430 (cond ((zerop n))
431 (no-error nil)
432 ((error "unterminated string")))))
433
434 (defun ruby-deep-indent-paren-p (c)
435 "TODO: document."
436 (cond ((listp ruby-deep-indent-paren)
437 (let ((deep (assoc c ruby-deep-indent-paren)))
438 (cond (deep
439 (or (cdr deep) ruby-deep-indent-paren-style))
440 ((memq c ruby-deep-indent-paren)
441 ruby-deep-indent-paren-style))))
442 ((eq c ruby-deep-indent-paren) ruby-deep-indent-paren-style)
443 ((eq c ?\( ) ruby-deep-arglist)))
444
445 (defun ruby-parse-partial (&optional end in-string nest depth pcol indent)
446 "TODO: document throughout function body."
447 (or depth (setq depth 0))
448 (or indent (setq indent 0))
449 (when (re-search-forward ruby-delimiter end 'move)
450 (let ((pnt (point)) w re expand)
451 (goto-char (match-beginning 0))
452 (cond
453 ((and (memq (char-before) '(?@ ?$)) (looking-at "\\sw"))
454 (goto-char pnt))
455 ((looking-at "[\"`]") ;skip string
456 (cond
457 ((and (not (eobp))
458 (ruby-forward-string (buffer-substring (point) (1+ (point))) end t t))
459 nil)
460 (t
461 (setq in-string (point))
462 (goto-char end))))
463 ((looking-at "'")
464 (cond
465 ((and (not (eobp))
466 (re-search-forward "[^\\]\\(\\\\\\\\\\)*'" end t))
467 nil)
468 (t
469 (setq in-string (point))
470 (goto-char end))))
471 ((looking-at "/=")
472 (goto-char pnt))
473 ((looking-at "/")
474 (cond
475 ((and (not (eobp)) (ruby-expr-beg 'expr-re))
476 (if (ruby-forward-string "/" end t t)
477 nil
478 (setq in-string (point))
479 (goto-char end)))
480 (t
481 (goto-char pnt))))
482 ((looking-at "%")
483 (cond
484 ((and (not (eobp))
485 (ruby-expr-beg 'expr-qstr)
486 (not (looking-at "%="))
487 (looking-at "%[QqrxWw]?\\([^a-zA-Z0-9 \t\n]\\)"))
488 (goto-char (match-beginning 1))
489 (setq expand (not (memq (char-before) '(?q ?w))))
490 (setq w (match-string 1))
491 (cond
492 ((string= w "[") (setq re "]["))
493 ((string= w "{") (setq re "}{"))
494 ((string= w "(") (setq re ")("))
495 ((string= w "<") (setq re "><"))
496 ((and expand (string= w "\\"))
497 (setq w (concat "\\" w))))
498 (unless (cond (re (ruby-forward-string re end t expand))
499 (expand (ruby-forward-string w end t t))
500 (t (re-search-forward
501 (if (string= w "\\")
502 "\\\\[^\\]*\\\\"
503 (concat "[^\\]\\(\\\\\\\\\\)*" w))
504 end t)))
505 (setq in-string (point))
506 (goto-char end)))
507 (t
508 (goto-char pnt))))
509 ((looking-at "\\?") ;skip ?char
510 (cond
511 ((and (ruby-expr-beg)
512 (looking-at "?\\(\\\\C-\\|\\\\M-\\)*\\\\?."))
513 (goto-char (match-end 0)))
514 (t
515 (goto-char pnt))))
516 ((looking-at "\\$") ;skip $char
517 (goto-char pnt)
518 (forward-char 1))
519 ((looking-at "#") ;skip comment
520 (forward-line 1)
521 (goto-char (point))
522 )
523 ((looking-at "[\\[{(]")
524 (let ((deep (ruby-deep-indent-paren-p (char-after))))
525 (if (and deep (or (not (eq (char-after) ?\{)) (ruby-expr-beg)))
526 (progn
527 (and (eq deep 'space) (looking-at ".\\s +[^# \t\n]")
528 (setq pnt (1- (match-end 0))))
529 (setq nest (cons (cons (char-after (point)) pnt) nest))
530 (setq pcol (cons (cons pnt depth) pcol))
531 (setq depth 0))
532 (setq nest (cons (cons (char-after (point)) pnt) nest))
533 (setq depth (1+ depth))))
534 (goto-char pnt)
535 )
536 ((looking-at "[])}]")
537 (if (ruby-deep-indent-paren-p (matching-paren (char-after)))
538 (setq depth (cdr (car pcol)) pcol (cdr pcol))
539 (setq depth (1- depth)))
540 (setq nest (cdr nest))
541 (goto-char pnt))
542 ((looking-at ruby-block-end-re)
543 (if (or (and (not (bolp))
544 (progn
545 (forward-char -1)
546 (setq w (char-after (point)))
547 (or (eq ?_ w)
548 (eq ?. w))))
549 (progn
550 (goto-char pnt)
551 (setq w (char-after (point)))
552 (or (eq ?_ w)
553 (eq ?! w)
554 (eq ?? w))))
555 nil
556 (setq nest (cdr nest))
557 (setq depth (1- depth)))
558 (goto-char pnt))
559 ((looking-at "def\\s +[^(\n;]*")
560 (if (or (bolp)
561 (progn
562 (forward-char -1)
563 (not (eq ?_ (char-after (point))))))
564 (progn
565 (setq nest (cons (cons nil pnt) nest))
566 (setq depth (1+ depth))))
567 (goto-char (match-end 0)))
568 ((looking-at (concat "\\<\\(" ruby-block-beg-re "\\)\\>"))
569 (and
570 (save-match-data
571 (or (not (looking-at (concat "do" ruby-keyword-end-re)))
572 (save-excursion
573 (back-to-indentation)
574 (not (looking-at ruby-non-block-do-re)))))
575 (or (bolp)
576 (progn
577 (forward-char -1)
578 (setq w (char-after (point)))
579 (not (or (eq ?_ w)
580 (eq ?. w)))))
581 (goto-char pnt)
582 (setq w (char-after (point)))
583 (not (eq ?_ w))
584 (not (eq ?! w))
585 (not (eq ?? w))
586 (skip-chars-forward " \t")
587 (goto-char (match-beginning 0))
588 (or (not (looking-at ruby-modifier-re))
589 (ruby-expr-beg 'modifier))
590 (goto-char pnt)
591 (setq nest (cons (cons nil pnt) nest))
592 (setq depth (1+ depth)))
593 (goto-char pnt))
594 ((looking-at ":\\(['\"]\\)")
595 (goto-char (match-beginning 1))
596 (ruby-forward-string (buffer-substring (match-beginning 1) (match-end 1)) end))
597 ((looking-at ":\\([-,.+*/%&|^~<>]=?\\|===?\\|<=>\\|![~=]?\\)")
598 (goto-char (match-end 0)))
599 ((looking-at ":\\([a-zA-Z_][a-zA-Z_0-9]*[!?=]?\\)?")
600 (goto-char (match-end 0)))
601 ((or (looking-at "\\.\\.\\.?")
602 (looking-at "\\.[0-9]+")
603 (looking-at "\\.[a-zA-Z_0-9]+")
604 (looking-at "\\."))
605 (goto-char (match-end 0)))
606 ((looking-at "^=begin")
607 (if (re-search-forward "^=end" end t)
608 (forward-line 1)
609 (setq in-string (match-end 0))
610 (goto-char end)))
611 ((looking-at "<<")
612 (cond
613 ((and (ruby-expr-beg 'heredoc)
614 (looking-at "<<\\(-\\)?\\(\\([\"'`]\\)\\([^\n]+?\\)\\3\\|\\(?:\\sw\\|\\s_\\)+\\)"))
615 (setq re (regexp-quote (or (match-string 4) (match-string 2))))
616 (if (match-beginning 1) (setq re (concat "\\s *" re)))
617 (let* ((id-end (goto-char (match-end 0)))
618 (line-end-position (point-at-eol))
619 (state (list in-string nest depth pcol indent)))
620 ;; parse the rest of the line
621 (while (and (> line-end-position (point))
622 (setq state (apply 'ruby-parse-partial
623 line-end-position state))))
624 (setq in-string (car state)
625 nest (nth 1 state)
626 depth (nth 2 state)
627 pcol (nth 3 state)
628 indent (nth 4 state))
629 ;; skip heredoc section
630 (if (re-search-forward (concat "^" re "$") end 'move)
631 (forward-line 1)
632 (setq in-string id-end)
633 (goto-char end))))
634 (t
635 (goto-char pnt))))
636 ((looking-at "^__END__$")
637 (goto-char pnt))
638 ((and (looking-at ruby-here-doc-beg-re)
639 (boundp 'ruby-indent-point))
640 (if (re-search-forward (ruby-here-doc-end-match)
641 ruby-indent-point t)
642 (forward-line 1)
643 (setq in-string (match-end 0))
644 (goto-char ruby-indent-point)))
645 (t
646 (error (format "bad string %s"
647 (buffer-substring (point) pnt)
648 ))))))
649 (list in-string nest depth pcol))
650
651 (defun ruby-parse-region (start end)
652 "TODO: document."
653 (let (state)
654 (save-excursion
655 (if start
656 (goto-char start)
657 (ruby-beginning-of-indent))
658 (save-restriction
659 (narrow-to-region (point) end)
660 (while (and (> end (point))
661 (setq state (apply 'ruby-parse-partial end state))))))
662 (list (nth 0 state) ; in-string
663 (car (nth 1 state)) ; nest
664 (nth 2 state) ; depth
665 (car (car (nth 3 state))) ; pcol
666 ;(car (nth 5 state)) ; indent
667 )))
668
669 (defun ruby-indent-size (pos nest)
670 "Return the indentation level in spaces NEST levels deeper than POS."
671 (+ pos (* (or nest 1) ruby-indent-level)))
672
673 (defun ruby-calculate-indent (&optional parse-start)
674 "Return the proper indentation level of the current line."
675 ;; TODO: Document body
676 (save-excursion
677 (beginning-of-line)
678 (let ((ruby-indent-point (point))
679 (case-fold-search nil)
680 state eol begin op-end
681 (paren (progn (skip-syntax-forward " ")
682 (and (char-after) (matching-paren (char-after)))))
683 (indent 0))
684 (if parse-start
685 (goto-char parse-start)
686 (ruby-beginning-of-indent)
687 (setq parse-start (point)))
688 (back-to-indentation)
689 (setq indent (current-column))
690 (setq state (ruby-parse-region parse-start ruby-indent-point))
691 (cond
692 ((nth 0 state) ; within string
693 (setq indent nil)) ; do nothing
694 ((car (nth 1 state)) ; in paren
695 (goto-char (setq begin (cdr (nth 1 state))))
696 (let ((deep (ruby-deep-indent-paren-p (car (nth 1 state)))))
697 (if deep
698 (cond ((and (eq deep t) (eq (car (nth 1 state)) paren))
699 (skip-syntax-backward " ")
700 (setq indent (1- (current-column))))
701 ((let ((s (ruby-parse-region (point) ruby-indent-point)))
702 (and (nth 2 s) (> (nth 2 s) 0)
703 (or (goto-char (cdr (nth 1 s))) t)))
704 (forward-word -1)
705 (setq indent (ruby-indent-size (current-column)
706 (nth 2 state))))
707 (t
708 (setq indent (current-column))
709 (cond ((eq deep 'space))
710 (paren (setq indent (1- indent)))
711 (t (setq indent (ruby-indent-size (1- indent) 1))))))
712 (if (nth 3 state) (goto-char (nth 3 state))
713 (goto-char parse-start) (back-to-indentation))
714 (setq indent (ruby-indent-size (current-column) (nth 2 state))))
715 (and (eq (car (nth 1 state)) paren)
716 (ruby-deep-indent-paren-p (matching-paren paren))
717 (search-backward (char-to-string paren))
718 (setq indent (current-column)))))
719 ((and (nth 2 state) (> (nth 2 state) 0)) ; in nest
720 (if (null (cdr (nth 1 state)))
721 (error "invalid nest"))
722 (goto-char (cdr (nth 1 state)))
723 (forward-word -1) ; skip back a keyword
724 (setq begin (point))
725 (cond
726 ((looking-at "do\\>[^_]") ; iter block is a special case
727 (if (nth 3 state) (goto-char (nth 3 state))
728 (goto-char parse-start) (back-to-indentation))
729 (setq indent (ruby-indent-size (current-column) (nth 2 state))))
730 (t
731 (setq indent (+ (current-column) ruby-indent-level)))))
732
733 ((and (nth 2 state) (< (nth 2 state) 0)) ; in negative nest
734 (setq indent (ruby-indent-size (current-column) (nth 2 state)))))
735 (when indent
736 (goto-char ruby-indent-point)
737 (end-of-line)
738 (setq eol (point))
739 (beginning-of-line)
740 (cond
741 ((and (not (ruby-deep-indent-paren-p paren))
742 (re-search-forward ruby-negative eol t))
743 (and (not (eq ?_ (char-after (match-end 0))))
744 (setq indent (- indent ruby-indent-level))))
745 ((and
746 (save-excursion
747 (beginning-of-line)
748 (not (bobp)))
749 (or (ruby-deep-indent-paren-p t)
750 (null (car (nth 1 state)))))
751 ;; goto beginning of non-empty no-comment line
752 (let (end done)
753 (while (not done)
754 (skip-chars-backward " \t\n")
755 (setq end (point))
756 (beginning-of-line)
757 (if (re-search-forward "^\\s *#" end t)
758 (beginning-of-line)
759 (setq done t))))
760 (end-of-line)
761 ;; skip the comment at the end
762 (skip-chars-backward " \t")
763 (let (end (pos (point)))
764 (beginning-of-line)
765 (while (and (re-search-forward "#" pos t)
766 (setq end (1- (point)))
767 (or (ruby-special-char-p end)
768 (and (setq state (ruby-parse-region parse-start end))
769 (nth 0 state))))
770 (setq end nil))
771 (goto-char (or end pos))
772 (skip-chars-backward " \t")
773 (setq begin (if (and end (nth 0 state)) pos (cdr (nth 1 state))))
774 (setq state (ruby-parse-region parse-start (point))))
775 (or (bobp) (forward-char -1))
776 (and
777 (or (and (looking-at ruby-symbol-re)
778 (skip-chars-backward ruby-symbol-chars)
779 (looking-at (concat "\\<\\(" ruby-block-hanging-re "\\)\\>"))
780 (not (eq (point) (nth 3 state)))
781 (save-excursion
782 (goto-char (match-end 0))
783 (not (looking-at "[a-z_]"))))
784 (and (looking-at ruby-operator-re)
785 (not (ruby-special-char-p))
786 ;; operator at the end of line
787 (let ((c (char-after (point))))
788 (and
789 ;; (or (null begin)
790 ;; (save-excursion
791 ;; (goto-char begin)
792 ;; (skip-chars-forward " \t")
793 ;; (not (or (eolp) (looking-at "#")
794 ;; (and (eq (car (nth 1 state)) ?{)
795 ;; (looking-at "|"))))))
796 (or (not (eq ?/ c))
797 (null (nth 0 (ruby-parse-region (or begin parse-start) (point)))))
798 (or (not (eq ?| (char-after (point))))
799 (save-excursion
800 (or (eolp) (forward-char -1))
801 (cond
802 ((search-backward "|" nil t)
803 (skip-chars-backward " \t\n")
804 (and (not (eolp))
805 (progn
806 (forward-char -1)
807 (not (looking-at "{")))
808 (progn
809 (forward-word -1)
810 (not (looking-at "do\\>[^_]")))))
811 (t t))))
812 (not (eq ?, c))
813 (setq op-end t)))))
814 (setq indent
815 (cond
816 ((and
817 (null op-end)
818 (not (looking-at (concat "\\<\\(" ruby-block-hanging-re "\\)\\>")))
819 (eq (ruby-deep-indent-paren-p t) 'space)
820 (not (bobp)))
821 (widen)
822 (goto-char (or begin parse-start))
823 (skip-syntax-forward " ")
824 (current-column))
825 ((car (nth 1 state)) indent)
826 (t
827 (+ indent ruby-indent-level))))))))
828 (goto-char ruby-indent-point)
829 (beginning-of-line)
830 (skip-syntax-forward " ")
831 (if (looking-at "\\.[^.]")
832 (+ indent ruby-indent-level)
833 indent))))
834
835 (defun ruby-electric-brace (arg)
836 "Insert a brace and re-indent the current line."
837 (interactive "P")
838 (self-insert-command (prefix-numeric-value arg))
839 (ruby-indent-line t))
840
841 ;; TODO: Why isn't one ruby-*-of-defun written in terms of the other?
842 (defun ruby-beginning-of-defun (&optional arg)
843 "Move backward to the beginning of the current top-level defun.
844 With ARG, move backward multiple defuns. Negative ARG means
845 move forward."
846 (interactive "p")
847 (and (re-search-backward (concat "^\\(" ruby-block-beg-re "\\)\\b")
848 nil 'move (or arg 1))
849 (beginning-of-line)))
850
851 (defun ruby-end-of-defun (&optional arg)
852 "Move forward to the end of the current top-level defun.
853 With ARG, move forward multiple defuns. Negative ARG means
854 move backward."
855 (interactive "p")
856 (and (re-search-forward (concat "^\\(" ruby-block-end-re "\\)\\($\\|\\b[^_]\\)")
857 nil 'move (or arg 1))
858 (beginning-of-line))
859 (forward-line 1))
860
861 (defun ruby-beginning-of-indent ()
862 "TODO: document"
863 ;; I don't understand this function.
864 ;; It seems like it should move to the line where indentation should deepen,
865 ;; but ruby-indent-beg-re only accounts for whitespace before class, module and def,
866 ;; so this will only match other block beginners at the beginning of the line.
867 (and (re-search-backward (concat "^\\(" ruby-indent-beg-re "\\)\\b") nil 'move)
868 (beginning-of-line)))
869
870 (defun ruby-move-to-block (n)
871 "Move to the beginning (N < 0) or the end (N > 0) of the current block
872 or blocks containing the current block."
873 ;; TODO: Make this work for n > 1,
874 ;; make it not loop for n = 0,
875 ;; document body
876 (let (start pos done down)
877 (setq start (ruby-calculate-indent))
878 (setq down (looking-at (if (< n 0) ruby-block-end-re
879 (concat "\\<\\(" ruby-block-beg-re "\\)\\>"))))
880 (while (and (not done) (not (if (< n 0) (bobp) (eobp))))
881 (forward-line n)
882 (cond
883 ((looking-at "^\\s *$"))
884 ((looking-at "^\\s *#"))
885 ((and (> n 0) (looking-at "^=begin\\>"))
886 (re-search-forward "^=end\\>"))
887 ((and (< n 0) (looking-at "^=end\\>"))
888 (re-search-backward "^=begin\\>"))
889 (t
890 (setq pos (current-indentation))
891 (cond
892 ((< start pos)
893 (setq down t))
894 ((and down (= pos start))
895 (setq done t))
896 ((> start pos)
897 (setq done t)))))
898 (if done
899 (save-excursion
900 (back-to-indentation)
901 (if (looking-at (concat "\\<\\(" ruby-block-mid-re "\\)\\>"))
902 (setq done nil))))))
903 (back-to-indentation))
904
905 (defun ruby-beginning-of-block (&optional arg)
906 "Move backward to the beginning of the current block.
907 With ARG, move up multiple blocks."
908 (interactive "p")
909 (ruby-move-to-block (- (or arg 1))))
910
911 (defun ruby-end-of-block (&optional arg)
912 "Move forward to the end of the current block.
913 With ARG, move out of multiple blocks."
914 ;; Passing a value > 1 to ruby-move-to-block currently doesn't work.
915 (interactive)
916 (ruby-move-to-block (or arg 1)))
917
918 (defun ruby-forward-sexp (&optional arg)
919 "Move forward across one balanced expression (sexp).
920 With ARG, do it many times. Negative ARG means move backward."
921 ;; TODO: Document body
922 (interactive "p")
923 (if (and (numberp arg) (< arg 0))
924 (ruby-backward-sexp (- arg))
925 (let ((i (or arg 1)))
926 (condition-case nil
927 (while (> i 0)
928 (skip-syntax-forward " ")
929 (if (looking-at ",\\s *") (goto-char (match-end 0)))
930 (cond ((looking-at "\\?\\(\\\\[CM]-\\)*\\\\?\\S ")
931 (goto-char (match-end 0)))
932 ((progn
933 (skip-chars-forward ",.:;|&^~=!?\\+\\-\\*")
934 (looking-at "\\s("))
935 (goto-char (scan-sexps (point) 1)))
936 ((and (looking-at (concat "\\<\\(" ruby-block-beg-re "\\)\\>"))
937 (not (eq (char-before (point)) ?.))
938 (not (eq (char-before (point)) ?:)))
939 (ruby-end-of-block)
940 (forward-word 1))
941 ((looking-at "\\(\\$\\|@@?\\)?\\sw")
942 (while (progn
943 (while (progn (forward-word 1) (looking-at "_")))
944 (cond ((looking-at "::") (forward-char 2) t)
945 ((> (skip-chars-forward ".") 0))
946 ((looking-at "\\?\\|!\\(=[~=>]\\|[^~=]\\)")
947 (forward-char 1) nil)))))
948 ((let (state expr)
949 (while
950 (progn
951 (setq expr (or expr (ruby-expr-beg)
952 (looking-at "%\\sw?\\Sw\\|[\"'`/]")))
953 (nth 1 (setq state (apply 'ruby-parse-partial nil state))))
954 (setq expr t)
955 (skip-chars-forward "<"))
956 (not expr))))
957 (setq i (1- i)))
958 ((error) (forward-word 1)))
959 i)))
960
961 (defun ruby-backward-sexp (&optional arg)
962 "Move backward across one balanced expression (sexp).
963 With ARG, do it many times. Negative ARG means move forward."
964 ;; TODO: Document body
965 (interactive "p")
966 (if (and (numberp arg) (< arg 0))
967 (ruby-forward-sexp (- arg))
968 (let ((i (or arg 1)))
969 (condition-case nil
970 (while (> i 0)
971 (skip-chars-backward " \t\n,.:;|&^~=!?\\+\\-\\*")
972 (forward-char -1)
973 (cond ((looking-at "\\s)")
974 (goto-char (scan-sexps (1+ (point)) -1))
975 (case (char-before)
976 (?% (forward-char -1))
977 ((?q ?Q ?w ?W ?r ?x)
978 (if (eq (char-before (1- (point))) ?%) (forward-char -2))))
979 nil)
980 ((looking-at "\\s\"\\|\\\\\\S_")
981 (let ((c (char-to-string (char-before (match-end 0)))))
982 (while (and (search-backward c)
983 (eq (logand (skip-chars-backward "\\") 1)
984 1))))
985 nil)
986 ((looking-at "\\s.\\|\\s\\")
987 (if (ruby-special-char-p) (forward-char -1)))
988 ((looking-at "\\s(") nil)
989 (t
990 (forward-char 1)
991 (while (progn (forward-word -1)
992 (case (char-before)
993 (?_ t)
994 (?. (forward-char -1) t)
995 ((?$ ?@)
996 (forward-char -1)
997 (and (eq (char-before) (char-after)) (forward-char -1)))
998 (?:
999 (forward-char -1)
1000 (eq (char-before) :)))))
1001 (if (looking-at ruby-block-end-re)
1002 (ruby-beginning-of-block))
1003 nil))
1004 (setq i (1- i)))
1005 ((error)))
1006 i)))
1007
1008 (defun ruby-mark-defun ()
1009 "Put mark at end of this Ruby function, point at beginning."
1010 (interactive)
1011 (push-mark (point))
1012 (ruby-end-of-defun)
1013 (push-mark (point) nil t)
1014 (ruby-beginning-of-defun)
1015 (re-search-backward "^\n" (- (point) 1) t))
1016
1017 (defun ruby-indent-exp (&optional ignored)
1018 "Indent each line in the balanced expression following the point."
1019 (interactive "*P")
1020 (let ((here (point-marker)) start top column (nest t))
1021 (set-marker-insertion-type here t)
1022 (unwind-protect
1023 (progn
1024 (beginning-of-line)
1025 (setq start (point) top (current-indentation))
1026 (while (and (not (eobp))
1027 (progn
1028 (setq column (ruby-calculate-indent start))
1029 (cond ((> column top)
1030 (setq nest t))
1031 ((and (= column top) nest)
1032 (setq nest nil) t))))
1033 (ruby-indent-to column)
1034 (beginning-of-line 2)))
1035 (goto-char here)
1036 (set-marker here nil))))
1037
1038 (defun ruby-add-log-current-method ()
1039 "Return the current method name as a string.
1040 This string includes all namespaces.
1041
1042 For example:
1043
1044 #exit
1045 String#gsub
1046 Net::HTTP#active?
1047 File::open.
1048
1049 See `add-log-current-defun-function'."
1050 ;; TODO: Document body
1051 ;; Why does this append a period to class methods?
1052 (condition-case nil
1053 (save-excursion
1054 (let (mname mlist (indent 0))
1055 ;; get current method (or class/module)
1056 (if (re-search-backward
1057 (concat "^[ \t]*\\(def\\|class\\|module\\)[ \t]+"
1058 "\\("
1059 ;; \\. and :: for class method
1060 "\\([A-Za-z_]" ruby-symbol-re "*\\|\\.\\|::" "\\)"
1061 "+\\)")
1062 nil t)
1063 (progn
1064 (setq mname (match-string 2))
1065 (unless (string-equal "def" (match-string 1))
1066 (setq mlist (list mname) mname nil))
1067 (goto-char (match-beginning 1))
1068 (setq indent (current-column))
1069 (beginning-of-line)))
1070 ;; nest class/module
1071 (while (and (> indent 0)
1072 (re-search-backward
1073 (concat
1074 "^[ \t]*\\(class\\|module\\)[ \t]+"
1075 "\\([A-Z]" ruby-symbol-re "*\\)")
1076 nil t))
1077 (goto-char (match-beginning 1))
1078 (if (< (current-column) indent)
1079 (progn
1080 (setq mlist (cons (match-string 2) mlist))
1081 (setq indent (current-column))
1082 (beginning-of-line))))
1083 (when mname
1084 (let ((mn (split-string mname "\\.\\|::")))
1085 (if (cdr mn)
1086 (progn
1087 (cond
1088 ((string-equal "" (car mn))
1089 (setq mn (cdr mn) mlist nil))
1090 ((string-equal "self" (car mn))
1091 (setq mn (cdr mn)))
1092 ((let ((ml (nreverse mlist)))
1093 (while ml
1094 (if (string-equal (car ml) (car mn))
1095 (setq mlist (nreverse (cdr ml)) ml nil))
1096 (or (setq ml (cdr ml)) (nreverse mlist))))))
1097 (if mlist
1098 (setcdr (last mlist) mn)
1099 (setq mlist mn))
1100 (setq mn (last mn 2))
1101 (setq mname (concat "." (cadr mn)))
1102 (setcdr mn nil))
1103 (setq mname (concat "#" mname)))))
1104 ;; generate string
1105 (if (consp mlist)
1106 (setq mlist (mapconcat (function identity) mlist "::")))
1107 (if mname
1108 (if mlist (concat mlist mname) mname)
1109 mlist)))))
1110
1111 (declare-function ruby-syntax-propertize-heredoc "ruby-mode" (limit))
1112
1113 (if (eval-when-compile (fboundp #'syntax-propertize-rules))
1114 ;; New code that works independently from font-lock.
1115 (progn
1116 (defun ruby-syntax-propertize-function (start end)
1117 "Syntactic keywords for Ruby mode. See `syntax-propertize-function'."
1118 (goto-char start)
1119 (ruby-syntax-propertize-heredoc end)
1120 (funcall
1121 (syntax-propertize-rules
1122 ;; #{ }, #$hoge, #@foo are not comments
1123 ("\\(#\\)[{$@]" (1 "."))
1124 ;; $' $" $` .... are variables
1125 ;; ?' ?" ?` are ascii codes
1126 ("\\([?$]\\)[#\"'`]"
1127 (1 (unless (save-excursion
1128 ;; Not within a string.
1129 (nth 3 (syntax-ppss (match-beginning 0))))
1130 (string-to-syntax "\\"))))
1131 ;; regexps
1132 ("\\(^\\|[[=(,~?:;<>]\\|\\(^\\|\\s \\)\\(if\\|elsif\\|unless\\|while\\|until\\|when\\|and\\|or\\|&&\\|||\\)\\|g?sub!?\\|scan\\|split!?\\)\\s *\\(/\\)[^/\n\\\\]*\\(\\\\.[^/\n\\\\]*\\)*\\(/\\)"
1133 (4 "\"/")
1134 (6 "\"/"))
1135 ("^=en\\(d\\)\\_>" (1 "!"))
1136 ("^\\(=\\)begin\\_>" (1 "!"))
1137 ;; Handle here documents.
1138 ((concat ruby-here-doc-beg-re ".*\\(\n\\)")
1139 (7 (prog1 "\"" (ruby-syntax-propertize-heredoc end)))))
1140 (point) end))
1141
1142 (defun ruby-syntax-propertize-heredoc (limit)
1143 (let ((ppss (syntax-ppss))
1144 (res '()))
1145 (when (eq ?\n (nth 3 ppss))
1146 (save-excursion
1147 (goto-char (nth 8 ppss))
1148 (beginning-of-line)
1149 (while (re-search-forward ruby-here-doc-beg-re
1150 (line-end-position) t)
1151 (push (concat (ruby-here-doc-end-match) "\n") res)))
1152 (let ((start (point)))
1153 ;; With multiple openers on the same line, we don't know in which
1154 ;; part `start' is, so we have to go back to the beginning.
1155 (when (cdr res)
1156 (goto-char (nth 8 ppss))
1157 (setq res (nreverse res)))
1158 (while (and res (re-search-forward (pop res) limit 'move))
1159 (if (null res)
1160 (put-text-property (1- (point)) (point)
1161 'syntax-table (string-to-syntax "\""))))
1162 ;; Make extra sure we don't move back, lest we could fall into an
1163 ;; inf-loop.
1164 (if (< (point) start) (goto-char start))))))
1165 )
1166
1167 ;; For Emacsen where syntax-propertize-rules is not (yet) available,
1168 ;; fallback on the old font-lock-syntactic-keywords stuff.
1169
1170 (defconst ruby-here-doc-end-re
1171 "^\\([ \t]+\\)?\\(.*\\)\\(\n\\)"
1172 "Regexp to match the end of heredocs.
1173
1174 This will actually match any line with one or more characters.
1175 It's useful in that it divides up the match string so that
1176 `ruby-here-doc-beg-match' can search for the beginning of the heredoc.")
1177
1178 (defun ruby-here-doc-beg-match ()
1179 "Return a regexp to find the beginning of a heredoc.
1180
1181 This should only be called after matching against `ruby-here-doc-end-re'."
1182 (let ((contents (concat
1183 (regexp-quote (concat (match-string 2) (match-string 3)))
1184 (if (string= (match-string 3) "_") "\\B" "\\b"))))
1185 (concat "<<"
1186 (let ((match (match-string 1)))
1187 (if (and match (> (length match) 0))
1188 (concat "\\(?:-\\([\"']?\\)\\|\\([\"']\\)"
1189 (match-string 1) "\\)"
1190 contents "\\(\\1\\|\\2\\)")
1191 (concat "-?\\([\"']\\|\\)" contents "\\1"))))))
1192
1193 (defconst ruby-font-lock-syntactic-keywords
1194 `( ;; #{ }, #$hoge, #@foo are not comments
1195 ("\\(#\\)[{$@]" 1 (1 . nil))
1196 ;; the last $', $", $` in the respective string is not variable
1197 ;; the last ?', ?", ?` in the respective string is not ascii code
1198 ("\\(^\\|[\[ \t\n<+\(,=]\\)\\(['\"`]\\)\\(\\\\.\\|\\2\\|[^'\"`\n\\\\]\\)*?\\\\?[?$]\\(\\2\\)"
1199 (2 (7 . nil))
1200 (4 (7 . nil)))
1201 ;; $' $" $` .... are variables
1202 ;; ?' ?" ?` are ascii codes
1203 ("\\(^\\|[^\\\\]\\)\\(\\\\\\\\\\)*[?$]\\([#\"'`]\\)" 3 (1 . nil))
1204 ;; regexps
1205 ("\\(^\\|[[=(,~?:;<>]\\|\\(^\\|\\s \\)\\(if\\|elsif\\|unless\\|while\\|until\\|when\\|and\\|or\\|&&\\|||\\)\\|g?sub!?\\|scan\\|split!?\\)\\s *\\(/\\)[^/\n\\\\]*\\(\\\\.[^/\n\\\\]*\\)*\\(/\\)"
1206 (4 (7 . ?/))
1207 (6 (7 . ?/)))
1208 ("^=en\\(d\\)\\_>" 1 "!")
1209 ("^\\(=\\)begin\\_>" 1 (ruby-comment-beg-syntax))
1210 ;; Currently, the following case is highlighted incorrectly:
1211 ;;
1212 ;; <<FOO
1213 ;; FOO
1214 ;; <<BAR
1215 ;; <<BAZ
1216 ;; BAZ
1217 ;; BAR
1218 ;;
1219 ;; This is because all here-doc beginnings are highlighted before any endings,
1220 ;; so although <<BAR is properly marked as a beginning, when we get to <<BAZ
1221 ;; it thinks <<BAR is part of a string so it's marked as well.
1222 ;;
1223 ;; This may be fixable by modifying ruby-in-here-doc-p to use
1224 ;; ruby-in-non-here-doc-string-p rather than syntax-ppss-context,
1225 ;; but I don't want to try that until we've got unit tests set up
1226 ;; to make sure I don't break anything else.
1227 (,(concat ruby-here-doc-beg-re ".*\\(\n\\)")
1228 ,(+ 1 (regexp-opt-depth ruby-here-doc-beg-re))
1229 (ruby-here-doc-beg-syntax))
1230 (,ruby-here-doc-end-re 3 (ruby-here-doc-end-syntax)))
1231 "Syntactic keywords for Ruby mode. See `font-lock-syntactic-keywords'.")
1232
1233 (defun ruby-comment-beg-syntax ()
1234 "Return the syntax cell for a the first character of a =begin.
1235 See the definition of `ruby-font-lock-syntactic-keywords'.
1236
1237 This returns a comment-delimiter cell as long as the =begin
1238 isn't in a string or another comment."
1239 (when (not (nth 3 (syntax-ppss)))
1240 (string-to-syntax "!")))
1241
1242 (defun ruby-in-here-doc-p ()
1243 "Return whether or not the point is in a heredoc."
1244 (save-excursion
1245 (let ((old-point (point)) (case-fold-search nil))
1246 (beginning-of-line)
1247 (catch 'found-beg
1248 (while (re-search-backward ruby-here-doc-beg-re nil t)
1249 (if (not (or (ruby-in-ppss-context-p 'anything)
1250 (ruby-here-doc-find-end old-point)))
1251 (throw 'found-beg t)))))))
1252
1253 (defun ruby-here-doc-find-end (&optional limit)
1254 "Expects the point to be on a line with one or more heredoc openers.
1255 Returns the buffer position at which all heredocs on the line
1256 are terminated, or nil if they aren't terminated before the
1257 buffer position `limit' or the end of the buffer."
1258 (save-excursion
1259 (beginning-of-line)
1260 (catch 'done
1261 (let ((eol (point-at-eol))
1262 (case-fold-search nil)
1263 ;; Fake match data such that (match-end 0) is at eol
1264 (end-match-data (progn (looking-at ".*$") (match-data)))
1265 beg-match-data end-re)
1266 (while (re-search-forward ruby-here-doc-beg-re eol t)
1267 (setq beg-match-data (match-data))
1268 (setq end-re (ruby-here-doc-end-match))
1269
1270 (set-match-data end-match-data)
1271 (goto-char (match-end 0))
1272 (unless (re-search-forward end-re limit t) (throw 'done nil))
1273 (setq end-match-data (match-data))
1274
1275 (set-match-data beg-match-data)
1276 (goto-char (match-end 0)))
1277 (set-match-data end-match-data)
1278 (goto-char (match-end 0))
1279 (point)))))
1280
1281 (defun ruby-here-doc-beg-syntax ()
1282 "Return the syntax cell for a line that may begin a heredoc.
1283 See the definition of `ruby-font-lock-syntactic-keywords'.
1284
1285 This sets the syntax cell for the newline ending the line
1286 containing the heredoc beginning so that cases where multiple
1287 heredocs are started on one line are handled correctly."
1288 (save-excursion
1289 (goto-char (match-beginning 0))
1290 (unless (or (ruby-in-ppss-context-p 'non-heredoc)
1291 (ruby-in-here-doc-p))
1292 (string-to-syntax "\""))))
1293
1294 (defun ruby-here-doc-end-syntax ()
1295 "Return the syntax cell for a line that may end a heredoc.
1296 See the definition of `ruby-font-lock-syntactic-keywords'."
1297 (let ((pss (syntax-ppss)) (case-fold-search nil))
1298 ;; If we aren't in a string, we definitely aren't ending a heredoc,
1299 ;; so we can just give up.
1300 ;; This means we aren't doing a full-document search
1301 ;; every time we enter a character.
1302 (when (ruby-in-ppss-context-p 'heredoc pss)
1303 (save-excursion
1304 (goto-char (nth 8 pss)) ; Go to the beginning of heredoc.
1305 (let ((eol (point)))
1306 (beginning-of-line)
1307 (if (and (re-search-forward (ruby-here-doc-beg-match) eol t) ; If there is a heredoc that matches this line...
1308 (not (ruby-in-ppss-context-p 'anything)) ; And that's not inside a heredoc/string/comment...
1309 (progn (goto-char (match-end 0)) ; And it's the last heredoc on its line...
1310 (not (re-search-forward ruby-here-doc-beg-re eol t))))
1311 (string-to-syntax "\"")))))))
1312
1313 (unless (functionp 'syntax-ppss)
1314 (defun syntax-ppss (&optional pos)
1315 (parse-partial-sexp (point-min) (or pos (point)))))
1316 )
1317
1318 (defun ruby-in-ppss-context-p (context &optional ppss)
1319 (let ((ppss (or ppss (syntax-ppss (point)))))
1320 (if (cond
1321 ((eq context 'anything)
1322 (or (nth 3 ppss)
1323 (nth 4 ppss)))
1324 ((eq context 'string)
1325 (nth 3 ppss))
1326 ((eq context 'heredoc)
1327 (eq ?\n (nth 3 ppss)))
1328 ((eq context 'non-heredoc)
1329 (and (ruby-in-ppss-context-p 'anything)
1330 (not (ruby-in-ppss-context-p 'heredoc))))
1331 ((eq context 'comment)
1332 (nth 4 ppss))
1333 (t
1334 (error (concat
1335 "Internal error on `ruby-in-ppss-context-p': "
1336 "context name `" (symbol-name context) "' is unknown"))))
1337 t)))
1338
1339 (if (featurep 'xemacs)
1340 (put 'ruby-mode 'font-lock-defaults
1341 '((ruby-font-lock-keywords)
1342 nil nil nil
1343 beginning-of-line
1344 (font-lock-syntactic-keywords
1345 . ruby-font-lock-syntactic-keywords))))
1346
1347 (defvar ruby-font-lock-syntax-table
1348 (let ((tbl (copy-syntax-table ruby-mode-syntax-table)))
1349 (modify-syntax-entry ?_ "w" tbl)
1350 tbl)
1351 "The syntax table to use for fontifying Ruby mode buffers.
1352 See `font-lock-syntax-table'.")
1353
1354 (defconst ruby-font-lock-keywords
1355 (list
1356 ;; functions
1357 '("^\\s *def\\s +\\([^( \t\n]+\\)"
1358 1 font-lock-function-name-face)
1359 ;; keywords
1360 (cons (concat
1361 "\\(^\\|[^_:.@$]\\|\\.\\.\\)\\b\\(defined\\?\\|"
1362 (regexp-opt
1363 '("alias_method"
1364 "alias"
1365 "and"
1366 "begin"
1367 "break"
1368 "case"
1369 "catch"
1370 "class"
1371 "def"
1372 "do"
1373 "elsif"
1374 "else"
1375 "fail"
1376 "ensure"
1377 "for"
1378 "end"
1379 "if"
1380 "in"
1381 "module_function"
1382 "module"
1383 "next"
1384 "not"
1385 "or"
1386 "public"
1387 "private"
1388 "protected"
1389 "raise"
1390 "redo"
1391 "rescue"
1392 "retry"
1393 "return"
1394 "then"
1395 "throw"
1396 "super"
1397 "unless"
1398 "undef"
1399 "until"
1400 "when"
1401 "while"
1402 "yield")
1403 t)
1404 "\\)"
1405 ruby-keyword-end-re)
1406 2)
1407 ;; here-doc beginnings
1408 (list ruby-here-doc-beg-re 0 'font-lock-string-face)
1409 ;; variables
1410 '("\\(^\\|[^_:.@$]\\|\\.\\.\\)\\b\\(nil\\|self\\|true\\|false\\)\\>"
1411 2 font-lock-variable-name-face)
1412 ;; variables
1413 '("\\(\\$\\([^a-zA-Z0-9 \n]\\|[0-9]\\)\\)\\W"
1414 1 font-lock-variable-name-face)
1415 '("\\(\\$\\|@\\|@@\\)\\(\\w\\|_\\)+"
1416 0 font-lock-variable-name-face)
1417 ;; general delimited string
1418 '("\\(^\\|[[ \t\n<+(,=]\\)\\(%[xrqQwW]?\\([^<[{(a-zA-Z0-9 \n]\\)[^\n\\\\]*\\(\\\\.[^\n\\\\]*\\)*\\(\\3\\)\\)"
1419 (2 font-lock-string-face))
1420 ;; constants
1421 '("\\(^\\|[^_]\\)\\b\\([A-Z]+\\(\\w\\|_\\)*\\)"
1422 2 font-lock-type-face)
1423 ;; symbols
1424 '("\\(^\\|[^:]\\)\\(:\\([-+~]@?\\|[/%&|^`]\\|\\*\\*?\\|<\\(<\\|=>?\\)?\\|>[>=]?\\|===?\\|=~\\|![~=]?\\|\\[\\]=?\\|\\(\\w\\|_\\)+\\([!?=]\\|\\b_*\\)\\|#{[^}\n\\\\]*\\(\\\\.[^}\n\\\\]*\\)*}\\)\\)"
1425 2 font-lock-reference-face)
1426 '("\\(^\\s *\\|[\[\{\(,]\\s *\\|\\sw\\s +\\)\\(\\(\\sw\\|_\\)+\\):[^:]" 2 font-lock-reference-face)
1427 ;; expression expansion
1428 '("#\\({[^}\n\\\\]*\\(\\\\.[^}\n\\\\]*\\)*}\\|\\(\\$\\|@\\|@@\\)\\(\\w\\|_\\)+\\)"
1429 0 font-lock-variable-name-face t)
1430 ;; warn lower camel case
1431 ;'("\\<[a-z]+[a-z0-9]*[A-Z][A-Za-z0-9]*\\([!?]?\\|\\>\\)"
1432 ; 0 font-lock-warning-face)
1433 )
1434 "Additional expressions to highlight in Ruby mode.")
1435
1436 ;;;###autoload
1437 (define-derived-mode ruby-mode prog-mode "Ruby"
1438 "Major mode for editing Ruby scripts.
1439 \\[ruby-indent-line] properly indents subexpressions of multi-line
1440 class, module, def, if, while, for, do, and case statements, taking
1441 nesting into account.
1442
1443 The variable `ruby-indent-level' controls the amount of indentation.
1444
1445 \\{ruby-mode-map}"
1446 (ruby-mode-variables)
1447
1448 (set (make-local-variable 'imenu-create-index-function)
1449 'ruby-imenu-create-index)
1450 (set (make-local-variable 'add-log-current-defun-function)
1451 'ruby-add-log-current-method)
1452
1453 (add-hook
1454 (cond ((boundp 'before-save-hook) 'before-save-hook)
1455 ((boundp 'write-contents-functions) 'write-contents-functions)
1456 ((boundp 'write-contents-hooks) 'write-contents-hooks))
1457 'ruby-mode-set-encoding nil 'local)
1458
1459 (set (make-local-variable 'electric-indent-chars)
1460 (append '(?\{ ?\}) electric-indent-chars))
1461
1462 (set (make-local-variable 'font-lock-defaults)
1463 '((ruby-font-lock-keywords) nil nil))
1464 (set (make-local-variable 'font-lock-keywords)
1465 ruby-font-lock-keywords)
1466 (set (make-local-variable 'font-lock-syntax-table)
1467 ruby-font-lock-syntax-table)
1468
1469 (if (eval-when-compile (fboundp 'syntax-propertize-rules))
1470 (set (make-local-variable 'syntax-propertize-function)
1471 #'ruby-syntax-propertize-function)
1472 (set (make-local-variable 'font-lock-syntactic-keywords)
1473 ruby-font-lock-syntactic-keywords)))
1474
1475 ;;; Invoke ruby-mode when appropriate
1476
1477 ;;;###autoload
1478 (add-to-list 'auto-mode-alist (cons (purecopy "\\.rb\\'") 'ruby-mode))
1479
1480 ;;;###autoload
1481 (dolist (name (list "ruby" "rbx" "jruby" "ruby1.9" "ruby1.8"))
1482 (add-to-list 'interpreter-mode-alist (cons (purecopy name) 'ruby-mode)))
1483
1484 (provide 'ruby-mode)
1485
1486 ;;; ruby-mode.el ends here