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