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