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