Merge from emacs-24; up to 2013-01-03T02:31:36Z!rgm@gnu.org
[emacs.git] / lisp / progmodes / ruby-mode.el
blob95206c153901f8fe9867be2162ea83a02c3f120c
1 ;;; ruby-mode.el --- Major mode for editing Ruby files
3 ;; Copyright (C) 1994-2013 Free Software Foundation, Inc.
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.2
12 ;; This file is part of GNU Emacs.
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.
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.
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/>.
27 ;;; Commentary:
29 ;; Provides font-locking, indentation support, and navigation for Ruby code.
31 ;; If you're installing manually, you should add this to your .emacs
32 ;; file after putting it on your load path:
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))
38 ;; Still needs more docstrings; search below for TODO.
40 ;;; Code:
42 (eval-when-compile (require 'cl))
44 (defgroup ruby nil
45 "Major mode for editing Ruby code."
46 :prefix "ruby-"
47 :group 'languages)
49 (defconst ruby-block-beg-keywords
50 '("class" "module" "def" "if" "unless" "case" "while" "until" "for" "begin" "do")
51 "Keywords at the beginning of blocks.")
53 (defconst ruby-block-beg-re
54 (regexp-opt ruby-block-beg-keywords)
55 "Regexp to match the beginning of blocks.")
57 (defconst ruby-non-block-do-re
58 (regexp-opt '("while" "until" "for" "rescue") 'symbols)
59 "Regexp to match keywords that nest without blocks.")
61 (defconst ruby-indent-beg-re
62 (concat "^\\(\\s *" (regexp-opt '("class" "module" "def")) "\\|"
63 (regexp-opt '("if" "unless" "case" "while" "until" "for" "begin"))
64 "\\)\\_>")
65 "Regexp to match where the indentation gets deeper.")
67 (defconst ruby-modifier-beg-keywords
68 '("if" "unless" "while" "until")
69 "Modifiers that are the same as the beginning of blocks.")
71 (defconst ruby-modifier-beg-re
72 (regexp-opt ruby-modifier-beg-keywords)
73 "Regexp to match modifiers same as the beginning of blocks.")
75 (defconst ruby-modifier-re
76 (regexp-opt (cons "rescue" ruby-modifier-beg-keywords))
77 "Regexp to match modifiers.")
79 (defconst ruby-block-mid-keywords
80 '("then" "else" "elsif" "when" "rescue" "ensure")
81 "Keywords where the indentation gets shallower in middle of block statements.")
83 (defconst ruby-block-mid-re
84 (regexp-opt ruby-block-mid-keywords)
85 "Regexp to match where the indentation gets shallower in middle of block statements.")
87 (defconst ruby-block-op-keywords
88 '("and" "or" "not")
89 "Regexp to match boolean keywords.")
91 (defconst ruby-block-hanging-re
92 (regexp-opt (append ruby-modifier-beg-keywords ruby-block-op-keywords))
93 "Regexp to match hanging block modifiers.")
95 (defconst ruby-block-end-re "\\_<end\\_>")
97 (defconst ruby-defun-beg-re
98 '"\\(def\\|class\\|module\\)"
99 "Regexp to match the beginning of a defun, in the general sense.")
101 (defconst ruby-singleton-class-re
102 "class\\s *<<"
103 "Regexp to match the beginning of a singleton class context.")
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.")
110 (defconst ruby-expression-expansion-re
111 "\\(?:[^\\]\\|\\=\\)\\(\\\\\\\\\\)*\\(#\\({[^}\n\\\\]*\\(\\\\.[^}\n\\\\]*\\)*}\\|\\(\\$\\|@\\|@@\\)\\(\\w\\|_\\)+\\)\\)"))
113 (defun ruby-here-doc-end-match ()
114 "Return a regexp to find the end of a heredoc.
116 This should only be called after matching against `ruby-here-doc-beg-re'."
117 (concat "^"
118 (if (match-string 2) "[ \t]*" nil)
119 (regexp-quote
120 (or (match-string 4)
121 (match-string 5)
122 (match-string 6)))))
124 (defconst ruby-delimiter
125 (concat "[?$/%(){}#\"'`.:]\\|<<\\|\\[\\|\\]\\|\\_<\\("
126 ruby-block-beg-re
127 "\\)\\_>\\|" ruby-block-end-re
128 "\\|^=begin\\|" ruby-here-doc-beg-re))
130 (defconst ruby-negative
131 (concat "^[ \t]*\\(\\(" ruby-block-mid-re "\\)\\>\\|"
132 ruby-block-end-re "\\|}\\|\\]\\)")
133 "Regexp to match where the indentation gets shallower.")
135 (defconst ruby-operator-re "[-,.+*/%&|^~=<>:]\\|\\\\$"
136 "Regexp to match operators.")
138 (defconst ruby-symbol-chars "a-zA-Z0-9_"
139 "List of characters that symbol names may contain.")
141 (defconst ruby-symbol-re (concat "[" ruby-symbol-chars "]")
142 "Regexp to match symbols.")
144 (define-abbrev-table 'ruby-mode-abbrev-table ()
145 "Abbrev table in use in Ruby mode buffers.")
147 (defvar ruby-use-smie nil)
149 (defvar ruby-mode-map
150 (let ((map (make-sparse-keymap)))
151 (unless ruby-use-smie
152 (define-key map (kbd "M-C-b") 'ruby-backward-sexp)
153 (define-key map (kbd "M-C-f") 'ruby-forward-sexp)
154 (define-key map (kbd "M-C-q") 'ruby-indent-exp))
155 (define-key map (kbd "M-C-p") 'ruby-beginning-of-block)
156 (define-key map (kbd "M-C-n") 'ruby-end-of-block)
157 (define-key map (kbd "C-c {") 'ruby-toggle-block)
158 map)
159 "Keymap used in Ruby mode.")
161 (defvar ruby-mode-syntax-table
162 (let ((table (make-syntax-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 ?\n ">" 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 (modify-syntax-entry ?\[ "(]" table)
189 (modify-syntax-entry ?\] ")[" table)
190 table)
191 "Syntax table to use in Ruby mode.")
193 (defcustom ruby-indent-tabs-mode nil
194 "Indentation can insert tabs in Ruby mode if this is non-nil."
195 :type 'boolean :group 'ruby)
197 (defcustom ruby-indent-level 2
198 "Indentation of Ruby statements."
199 :type 'integer :group 'ruby)
201 (defcustom ruby-comment-column 32
202 "Indentation column of comments."
203 :type 'integer :group 'ruby)
205 (defcustom ruby-deep-arglist t
206 "Deep indent lists in parenthesis when non-nil.
207 Also ignores spaces after parenthesis when 'space."
208 :group 'ruby)
210 (defcustom ruby-deep-indent-paren '(?\( ?\[ ?\] t)
211 "Deep indent lists in parenthesis when non-nil.
212 The value t means continuous line.
213 Also ignores spaces after parenthesis when 'space."
214 :group 'ruby)
216 (defcustom ruby-deep-indent-paren-style 'space
217 "Default deep indent style."
218 :options '(t nil space) :group 'ruby)
220 (defcustom ruby-encoding-map '((shift_jis . cp932) (shift-jis . cp932))
221 "Alist to map encoding name from Emacs to Ruby."
222 :group 'ruby)
224 (defcustom ruby-insert-encoding-magic-comment t
225 "Insert a magic Emacs 'coding' comment upon save if this is non-nil."
226 :type 'boolean :group 'ruby)
228 (defcustom ruby-use-encoding-map t
229 "Use `ruby-encoding-map' to set encoding magic comment if this is non-nil."
230 :type 'boolean :group 'ruby)
232 ;; Safe file variables
233 (put 'ruby-indent-tabs-mode 'safe-local-variable 'booleanp)
234 (put 'ruby-indent-level 'safe-local-variable 'integerp)
235 (put 'ruby-comment-column 'safe-local-variable 'integerp)
236 (put 'ruby-deep-arglist 'safe-local-variable 'booleanp)
238 ;;; SMIE support
240 (require 'smie)
242 (defconst ruby-smie-grammar
243 ;; FIXME: Add support for Cucumber.
244 (smie-prec2->grammar
245 (smie-bnf->prec2
246 '((id)
247 (insts (inst) (insts ";" insts))
248 (inst (exp) (inst "iuwu-mod" exp))
249 (exp (exp1) (exp "," exp))
250 (exp1 (exp2) (exp2 "?" exp1 ":" exp1))
251 (exp2 ("def" insts "end")
252 ("begin" insts-rescue-insts "end")
253 ("do" insts "end")
254 ("class" insts "end") ("module" insts "end")
255 ("for" for-body "end")
256 ("[" expseq "]")
257 ("{" hashvals "}")
258 ("{" insts "}")
259 ("while" insts "end")
260 ("until" insts "end")
261 ("unless" insts "end")
262 ("if" if-body "end")
263 ("case" cases "end"))
264 (formal-params ("opening-|" exp "|"))
265 (for-body (for-head ";" insts))
266 (for-head (id "in" exp))
267 (cases (exp "then" insts) ;; FIXME: Ruby also allows (exp ":" insts).
268 (cases "when" cases) (insts "else" insts))
269 (expseq (exp) );;(expseq "," expseq)
270 (hashvals (id "=>" exp1) (hashvals "," hashvals))
271 (insts-rescue-insts (insts)
272 (insts-rescue-insts "rescue" insts-rescue-insts)
273 (insts-rescue-insts "ensure" insts-rescue-insts))
274 (itheni (insts) (exp "then" insts))
275 (ielsei (itheni) (itheni "else" insts))
276 (if-body (ielsei) (if-body "elsif" if-body)))
277 '((nonassoc "in") (assoc ";") (assoc ","))
278 '((assoc "when"))
279 '((assoc "elsif"))
280 '((assoc "rescue" "ensure"))
281 '((assoc ",")))))
283 (defun ruby-smie--bosp ()
284 (save-excursion (skip-chars-backward " \t")
285 (or (bolp) (eq (char-before) ?\;))))
287 (defun ruby-smie--implicit-semi-p ()
288 (save-excursion
289 (skip-chars-backward " \t")
290 (not (or (bolp)
291 (and (memq (char-before) '(?\; ?- ?+ ?* ?/ ?: ?.))
292 ;; Make sure it's not the end of a regexp.
293 (not (eq (car (syntax-after (1- (point)))) 7)))
294 (and (memq (char-before) '(?\? ?=))
295 (let ((tok (ruby-smie--backward-token)))
296 (or (equal tok "?")
297 (string-match "\\`\\s." tok))))))))
299 (defun ruby-smie--opening-pipe-p ()
300 (save-excursion
301 (if (eq ?| (char-before)) (forward-char -1))
302 (skip-chars-backward " \t\n")
303 (or (eq ?\{ (char-before))
304 (looking-back "\\_<do" (- (point) 2)))))
306 (defun ruby-smie--forward-token ()
307 (skip-chars-forward " \t")
308 (if (and (looking-at "[\n#]")
309 ;; Only add implicit ; when needed.
310 (ruby-smie--implicit-semi-p))
311 (progn
312 (if (eolp) (forward-char 1) (forward-comment 1))
313 ";")
314 (forward-comment (point-max))
315 (if (looking-at ":\\s.+")
316 (progn (goto-char (match-end 0)) (match-string 0)) ;; bug#15208.
317 (let ((tok (smie-default-forward-token)))
318 (cond
319 ((member tok '("unless" "if" "while" "until"))
320 (if (save-excursion (forward-word -1) (ruby-smie--bosp))
321 tok "iuwu-mod"))
322 ((equal tok "|")
323 (if (ruby-smie--opening-pipe-p) "opening-|" tok))
324 (t tok))))))
326 (defun ruby-smie--backward-token ()
327 (let ((pos (point)))
328 (forward-comment (- (point)))
329 (if (and (> pos (line-end-position))
330 (ruby-smie--implicit-semi-p))
331 (progn (skip-chars-forward " \t")
332 ";")
333 (let ((tok (smie-default-backward-token)))
334 (when (and (eq ?: (char-before)) (string-match "\\`\\s." tok))
335 (forward-char -1) (setq tok (concat ":" tok))) ;; bug#15208.
336 (cond
337 ((member tok '("unless" "if" "while" "until"))
338 (if (ruby-smie--bosp)
339 tok "iuwu-mod"))
340 ((equal tok "|")
341 (if (ruby-smie--opening-pipe-p) "opening-|" tok))
342 (t tok))))))
344 (defun ruby-smie-rules (kind token)
345 (pcase (cons kind token)
346 (`(:elem . basic) ruby-indent-level)
347 (`(:after . ";")
348 (if (smie-rule-parent-p "def" "begin" "do" "class" "module" "for"
349 "[" "{" "while" "until" "unless"
350 "if" "then" "elsif" "else" "when"
351 "rescue" "ensure")
352 (smie-rule-parent ruby-indent-level)
353 ;; For (invalid) code between switch and case.
354 ;; (if (smie-parent-p "switch") 4)
356 (`(:before . "do")
357 (when
358 (save-excursion
359 (forward-word 1) ;Skip "do"
360 (skip-chars-forward " \t")
361 (and (equal (save-excursion (ruby-smie--forward-token)) "opening-|")
362 (save-excursion (forward-sexp 1)
363 (skip-chars-forward " \t")
364 (or (eolp)
365 (looking-at comment-start-skip)))))
366 ;; `(column . ,(smie-indent-virtual))
367 (smie-rule-parent)))
368 (`(:before . ,(or `"else" `"then" `"elsif" `"rescue")) 0)
369 (`(:before . ,(or `"when"))
370 (if (not (smie-rule-sibling-p)) 0)) ;; ruby-indent-level
371 ;; Hack attack: Since newlines are separators, don't try to align args that
372 ;; appear on a separate line.
373 (`(:list-intro . ";") t)))
375 (defun ruby-imenu-create-index-in-block (prefix beg end)
376 "Create an imenu index of methods inside a block."
377 (let ((index-alist '()) (case-fold-search nil)
378 name next pos decl sing)
379 (goto-char beg)
380 (while (re-search-forward "^\\s *\\(\\(class\\s +\\|\\(class\\s *<<\\s *\\)\\|module\\s +\\)\\([^\(<\n ]+\\)\\|\\(def\\|alias\\)\\s +\\([^\(\n ]+\\)\\)" end t)
381 (setq sing (match-beginning 3))
382 (setq decl (match-string 5))
383 (setq next (match-end 0))
384 (setq name (or (match-string 4) (match-string 6)))
385 (setq pos (match-beginning 0))
386 (cond
387 ((string= "alias" decl)
388 (if prefix (setq name (concat prefix name)))
389 (push (cons name pos) index-alist))
390 ((string= "def" decl)
391 (if prefix
392 (setq name
393 (cond
394 ((string-match "^self\." name)
395 (concat (substring prefix 0 -1) (substring name 4)))
396 (t (concat prefix name)))))
397 (push (cons name pos) index-alist)
398 (ruby-accurate-end-of-block end))
400 (if (string= "self" name)
401 (if prefix (setq name (substring prefix 0 -1)))
402 (if prefix (setq name (concat (substring prefix 0 -1) "::" name)))
403 (push (cons name pos) index-alist))
404 (ruby-accurate-end-of-block end)
405 (setq beg (point))
406 (setq index-alist
407 (nconc (ruby-imenu-create-index-in-block
408 (concat name (if sing "." "#"))
409 next beg) index-alist))
410 (goto-char beg))))
411 index-alist))
413 (defun ruby-imenu-create-index ()
414 "Create an imenu index of all methods in the buffer."
415 (nreverse (ruby-imenu-create-index-in-block nil (point-min) nil)))
417 (defun ruby-accurate-end-of-block (&optional end)
418 "TODO: document."
419 (let (state
420 (end (or end (point-max))))
421 (while (and (setq state (apply 'ruby-parse-partial end state))
422 (>= (nth 2 state) 0) (< (point) end)))))
424 (defun ruby-mode-variables ()
425 "Set up initial buffer-local variables for Ruby mode."
426 (set-syntax-table ruby-mode-syntax-table)
427 (setq local-abbrev-table ruby-mode-abbrev-table)
428 (setq indent-tabs-mode ruby-indent-tabs-mode)
429 (if ruby-use-smie
430 (smie-setup ruby-smie-grammar #'ruby-smie-rules
431 :forward-token #'ruby-smie--forward-token
432 :backward-token #'ruby-smie--backward-token)
433 (set (make-local-variable 'indent-line-function) 'ruby-indent-line))
434 (set (make-local-variable 'require-final-newline) t)
435 (set (make-local-variable 'comment-start) "# ")
436 (set (make-local-variable 'comment-end) "")
437 (set (make-local-variable 'comment-column) ruby-comment-column)
438 (set (make-local-variable 'comment-start-skip) "#+ *")
439 (set (make-local-variable 'parse-sexp-ignore-comments) t)
440 (set (make-local-variable 'parse-sexp-lookup-properties) t)
441 (set (make-local-variable 'paragraph-start) (concat "$\\|" page-delimiter))
442 (set (make-local-variable 'paragraph-separate) paragraph-start)
443 (set (make-local-variable 'paragraph-ignore-fill-prefix) t))
445 (defun ruby-mode-set-encoding ()
446 "Insert a magic comment header with the proper encoding if necessary."
447 (save-excursion
448 (widen)
449 (goto-char (point-min))
450 (when (re-search-forward "[^\0-\177]" nil t)
451 (goto-char (point-min))
452 (let ((coding-system
453 (or coding-system-for-write
454 buffer-file-coding-system)))
455 (if coding-system
456 (setq coding-system
457 (or (coding-system-get coding-system 'mime-charset)
458 (coding-system-change-eol-conversion coding-system nil))))
459 (setq coding-system
460 (if coding-system
461 (symbol-name
462 (or (and ruby-use-encoding-map
463 (cdr (assq coding-system ruby-encoding-map)))
464 coding-system))
465 "ascii-8bit"))
466 (if (looking-at "^#!") (beginning-of-line 2))
467 (cond ((looking-at "\\s *#.*-\*-\\s *\\(en\\)?coding\\s *:\\s *\\([-a-z0-9_]*\\)\\s *\\(;\\|-\*-\\)")
468 (unless (string= (match-string 2) coding-system)
469 (goto-char (match-beginning 2))
470 (delete-region (point) (match-end 2))
471 (and (looking-at "-\*-")
472 (let ((n (skip-chars-backward " ")))
473 (cond ((= n 0) (insert " ") (backward-char))
474 ((= n -1) (insert " "))
475 ((forward-char)))))
476 (insert coding-system)))
477 ((looking-at "\\s *#.*coding\\s *[:=]"))
478 (t (when ruby-insert-encoding-magic-comment
479 (insert "# -*- coding: " coding-system " -*-\n"))))))))
481 (defun ruby-current-indentation ()
482 "Return the indentation level of current line."
483 (save-excursion
484 (beginning-of-line)
485 (back-to-indentation)
486 (current-column)))
488 (defun ruby-indent-line (&optional ignored)
489 "Correct the indentation of the current Ruby line."
490 (interactive)
491 (ruby-indent-to (ruby-calculate-indent)))
493 (defun ruby-indent-to (column)
494 "Indent the current line to COLUMN."
495 (when column
496 (let (shift top beg)
497 (and (< column 0) (error "invalid nest"))
498 (setq shift (current-column))
499 (beginning-of-line)
500 (setq beg (point))
501 (back-to-indentation)
502 (setq top (current-column))
503 (skip-chars-backward " \t")
504 (if (>= shift top) (setq shift (- shift top))
505 (setq shift 0))
506 (if (and (bolp)
507 (= column top))
508 (move-to-column (+ column shift))
509 (move-to-column top)
510 (delete-region beg (point))
511 (beginning-of-line)
512 (indent-to column)
513 (move-to-column (+ column shift))))))
515 (defun ruby-special-char-p (&optional pos)
516 "Return t if the character before POS is a special character.
517 If omitted, POS defaults to the current point.
518 Special characters are `?', `$', `:' when preceded by whitespace,
519 and `\\' when preceded by `?'."
520 (setq pos (or pos (point)))
521 (let ((c (char-before pos)) (b (and (< (point-min) pos)
522 (char-before (1- pos)))))
523 (cond ((or (eq c ??) (eq c ?$)))
524 ((and (eq c ?:) (or (not b) (eq (char-syntax b) ? ))))
525 ((eq c ?\\) (eq b ??)))))
527 (defun ruby-singleton-class-p (&optional pos)
528 (save-excursion
529 (when pos (goto-char pos))
530 (forward-word -1)
531 (and (or (bolp) (not (eq (char-before (point)) ?_)))
532 (looking-at ruby-singleton-class-re))))
534 (defun ruby-expr-beg (&optional option)
535 "Check if point is possibly at the beginning of an expression.
536 OPTION specifies the type of the expression.
537 Can be one of `heredoc', `modifier', `expr-qstr', `expr-re'."
538 (save-excursion
539 (store-match-data nil)
540 (let ((space (skip-chars-backward " \t"))
541 (start (point)))
542 (cond
543 ((bolp) t)
544 ((progn
545 (forward-char -1)
546 (and (looking-at "\\?")
547 (or (eq (char-syntax (char-before (point))) ?w)
548 (ruby-special-char-p))))
549 nil)
550 ((looking-at ruby-operator-re))
551 ((eq option 'heredoc)
552 (and (< space 0) (not (ruby-singleton-class-p start))))
553 ((or (looking-at "[\\[({,;]")
554 (and (looking-at "[!?]")
555 (or (not (eq option 'modifier))
556 (bolp)
557 (save-excursion (forward-char -1) (looking-at "\\Sw$"))))
558 (and (looking-at ruby-symbol-re)
559 (skip-chars-backward ruby-symbol-chars)
560 (cond
561 ((looking-at (regexp-opt
562 (append ruby-block-beg-keywords
563 ruby-block-op-keywords
564 ruby-block-mid-keywords)
565 'words))
566 (goto-char (match-end 0))
567 (not (looking-at "\\s_\\|!")))
568 ((eq option 'expr-qstr)
569 (looking-at "[a-zA-Z][a-zA-z0-9_]* +%[^ \t]"))
570 ((eq option 'expr-re)
571 (looking-at "[a-zA-Z][a-zA-z0-9_]* +/[^ \t]"))
572 (t nil)))))))))
574 (defun ruby-forward-string (term &optional end no-error expand)
575 "TODO: document."
576 (let ((n 1) (c (string-to-char term))
577 (re (if expand
578 (concat "[^\\]\\(\\\\\\\\\\)*\\([" term "]\\|\\(#{\\)\\)")
579 (concat "[^\\]\\(\\\\\\\\\\)*[" term "]"))))
580 (while (and (re-search-forward re end no-error)
581 (if (match-beginning 3)
582 (ruby-forward-string "}{" end no-error nil)
583 (> (setq n (if (eq (char-before (point)) c)
584 (1- n) (1+ n))) 0)))
585 (forward-char -1))
586 (cond ((zerop n))
587 (no-error nil)
588 ((error "unterminated string")))))
590 (defun ruby-deep-indent-paren-p (c)
591 "TODO: document."
592 (cond ((listp ruby-deep-indent-paren)
593 (let ((deep (assoc c ruby-deep-indent-paren)))
594 (cond (deep
595 (or (cdr deep) ruby-deep-indent-paren-style))
596 ((memq c ruby-deep-indent-paren)
597 ruby-deep-indent-paren-style))))
598 ((eq c ruby-deep-indent-paren) ruby-deep-indent-paren-style)
599 ((eq c ?\( ) ruby-deep-arglist)))
601 (defun ruby-parse-partial (&optional end in-string nest depth pcol indent)
602 "TODO: document throughout function body."
603 (or depth (setq depth 0))
604 (or indent (setq indent 0))
605 (when (re-search-forward ruby-delimiter end 'move)
606 (let ((pnt (point)) w re expand)
607 (goto-char (match-beginning 0))
608 (cond
609 ((and (memq (char-before) '(?@ ?$)) (looking-at "\\sw"))
610 (goto-char pnt))
611 ((looking-at "[\"`]") ;skip string
612 (cond
613 ((and (not (eobp))
614 (ruby-forward-string (buffer-substring (point) (1+ (point))) end t t))
615 nil)
617 (setq in-string (point))
618 (goto-char end))))
619 ((looking-at "'")
620 (cond
621 ((and (not (eobp))
622 (re-search-forward "[^\\]\\(\\\\\\\\\\)*'" end t))
623 nil)
625 (setq in-string (point))
626 (goto-char end))))
627 ((looking-at "/=")
628 (goto-char pnt))
629 ((looking-at "/")
630 (cond
631 ((and (not (eobp)) (ruby-expr-beg 'expr-re))
632 (if (ruby-forward-string "/" end t t)
634 (setq in-string (point))
635 (goto-char end)))
637 (goto-char pnt))))
638 ((looking-at "%")
639 (cond
640 ((and (not (eobp))
641 (ruby-expr-beg 'expr-qstr)
642 (not (looking-at "%="))
643 (looking-at "%[QqrxWw]?\\([^a-zA-Z0-9 \t\n]\\)"))
644 (goto-char (match-beginning 1))
645 (setq expand (not (memq (char-before) '(?q ?w))))
646 (setq w (match-string 1))
647 (cond
648 ((string= w "[") (setq re "]["))
649 ((string= w "{") (setq re "}{"))
650 ((string= w "(") (setq re ")("))
651 ((string= w "<") (setq re "><"))
652 ((and expand (string= w "\\"))
653 (setq w (concat "\\" w))))
654 (unless (cond (re (ruby-forward-string re end t expand))
655 (expand (ruby-forward-string w end t t))
656 (t (re-search-forward
657 (if (string= w "\\")
658 "\\\\[^\\]*\\\\"
659 (concat "[^\\]\\(\\\\\\\\\\)*" w))
660 end t)))
661 (setq in-string (point))
662 (goto-char end)))
664 (goto-char pnt))))
665 ((looking-at "\\?") ;skip ?char
666 (cond
667 ((and (ruby-expr-beg)
668 (looking-at "?\\(\\\\C-\\|\\\\M-\\)*\\\\?."))
669 (goto-char (match-end 0)))
671 (goto-char pnt))))
672 ((looking-at "\\$") ;skip $char
673 (goto-char pnt)
674 (forward-char 1))
675 ((looking-at "#") ;skip comment
676 (forward-line 1)
677 (goto-char (point))
679 ((looking-at "[\\[{(]")
680 (let ((deep (ruby-deep-indent-paren-p (char-after))))
681 (if (and deep (or (not (eq (char-after) ?\{)) (ruby-expr-beg)))
682 (progn
683 (and (eq deep 'space) (looking-at ".\\s +[^# \t\n]")
684 (setq pnt (1- (match-end 0))))
685 (setq nest (cons (cons (char-after (point)) pnt) nest))
686 (setq pcol (cons (cons pnt depth) pcol))
687 (setq depth 0))
688 (setq nest (cons (cons (char-after (point)) pnt) nest))
689 (setq depth (1+ depth))))
690 (goto-char pnt)
692 ((looking-at "[])}]")
693 (if (ruby-deep-indent-paren-p (matching-paren (char-after)))
694 (setq depth (cdr (car pcol)) pcol (cdr pcol))
695 (setq depth (1- depth)))
696 (setq nest (cdr nest))
697 (goto-char pnt))
698 ((looking-at ruby-block-end-re)
699 (if (or (and (not (bolp))
700 (progn
701 (forward-char -1)
702 (setq w (char-after (point)))
703 (or (eq ?_ w)
704 (eq ?. w))))
705 (progn
706 (goto-char pnt)
707 (setq w (char-after (point)))
708 (or (eq ?_ w)
709 (eq ?! w)
710 (eq ?? w))))
712 (setq nest (cdr nest))
713 (setq depth (1- depth)))
714 (goto-char pnt))
715 ((looking-at "def\\s +[^(\n;]*")
716 (if (or (bolp)
717 (progn
718 (forward-char -1)
719 (not (eq ?_ (char-after (point))))))
720 (progn
721 (setq nest (cons (cons nil pnt) nest))
722 (setq depth (1+ depth))))
723 (goto-char (match-end 0)))
724 ((looking-at (concat "\\_<\\(" ruby-block-beg-re "\\)\\_>"))
725 (and
726 (save-match-data
727 (or (not (looking-at "do\\_>"))
728 (save-excursion
729 (back-to-indentation)
730 (not (looking-at ruby-non-block-do-re)))))
731 (or (bolp)
732 (progn
733 (forward-char -1)
734 (setq w (char-after (point)))
735 (not (or (eq ?_ w)
736 (eq ?. w)))))
737 (goto-char pnt)
738 (not (eq ?! (char-after (point))))
739 (skip-chars-forward " \t")
740 (goto-char (match-beginning 0))
741 (or (not (looking-at ruby-modifier-re))
742 (ruby-expr-beg 'modifier))
743 (goto-char pnt)
744 (setq nest (cons (cons nil pnt) nest))
745 (setq depth (1+ depth)))
746 (goto-char pnt))
747 ((looking-at ":\\(['\"]\\)")
748 (goto-char (match-beginning 1))
749 (ruby-forward-string (match-string 1) end t))
750 ((looking-at ":\\([-,.+*/%&|^~<>]=?\\|===?\\|<=>\\|![~=]?\\)")
751 (goto-char (match-end 0)))
752 ((looking-at ":\\([a-zA-Z_][a-zA-Z_0-9]*[!?=]?\\)?")
753 (goto-char (match-end 0)))
754 ((or (looking-at "\\.\\.\\.?")
755 (looking-at "\\.[0-9]+")
756 (looking-at "\\.[a-zA-Z_0-9]+")
757 (looking-at "\\."))
758 (goto-char (match-end 0)))
759 ((looking-at "^=begin")
760 (if (re-search-forward "^=end" end t)
761 (forward-line 1)
762 (setq in-string (match-end 0))
763 (goto-char end)))
764 ((looking-at "<<")
765 (cond
766 ((and (ruby-expr-beg 'heredoc)
767 (looking-at "<<\\(-\\)?\\(\\([\"'`]\\)\\([^\n]+?\\)\\3\\|\\(?:\\sw\\|\\s_\\)+\\)"))
768 (setq re (regexp-quote (or (match-string 4) (match-string 2))))
769 (if (match-beginning 1) (setq re (concat "\\s *" re)))
770 (let* ((id-end (goto-char (match-end 0)))
771 (line-end-position (point-at-eol))
772 (state (list in-string nest depth pcol indent)))
773 ;; parse the rest of the line
774 (while (and (> line-end-position (point))
775 (setq state (apply 'ruby-parse-partial
776 line-end-position state))))
777 (setq in-string (car state)
778 nest (nth 1 state)
779 depth (nth 2 state)
780 pcol (nth 3 state)
781 indent (nth 4 state))
782 ;; skip heredoc section
783 (if (re-search-forward (concat "^" re "$") end 'move)
784 (forward-line 1)
785 (setq in-string id-end)
786 (goto-char end))))
788 (goto-char pnt))))
789 ((looking-at "^__END__$")
790 (goto-char pnt))
791 ((and (looking-at ruby-here-doc-beg-re)
792 (boundp 'ruby-indent-point))
793 (if (re-search-forward (ruby-here-doc-end-match)
794 ruby-indent-point t)
795 (forward-line 1)
796 (setq in-string (match-end 0))
797 (goto-char ruby-indent-point)))
799 (error (format "bad string %s"
800 (buffer-substring (point) pnt)
801 ))))))
802 (list in-string nest depth pcol))
804 (defun ruby-parse-region (start end)
805 "TODO: document."
806 (let (state)
807 (save-excursion
808 (if start
809 (goto-char start)
810 (ruby-beginning-of-indent))
811 (save-restriction
812 (narrow-to-region (point) end)
813 (while (and (> end (point))
814 (setq state (apply 'ruby-parse-partial end state))))))
815 (list (nth 0 state) ; in-string
816 (car (nth 1 state)) ; nest
817 (nth 2 state) ; depth
818 (car (car (nth 3 state))) ; pcol
819 ;(car (nth 5 state)) ; indent
822 (defun ruby-indent-size (pos nest)
823 "Return the indentation level in spaces NEST levels deeper than POS."
824 (+ pos (* (or nest 1) ruby-indent-level)))
826 (defun ruby-calculate-indent (&optional parse-start)
827 "Return the proper indentation level of the current line."
828 ;; TODO: Document body
829 (save-excursion
830 (beginning-of-line)
831 (let ((ruby-indent-point (point))
832 (case-fold-search nil)
833 state eol begin op-end
834 (paren (progn (skip-syntax-forward " ")
835 (and (char-after) (matching-paren (char-after)))))
836 (indent 0))
837 (if parse-start
838 (goto-char parse-start)
839 (ruby-beginning-of-indent)
840 (setq parse-start (point)))
841 (back-to-indentation)
842 (setq indent (current-column))
843 (setq state (ruby-parse-region parse-start ruby-indent-point))
844 (cond
845 ((nth 0 state) ; within string
846 (setq indent nil)) ; do nothing
847 ((car (nth 1 state)) ; in paren
848 (goto-char (setq begin (cdr (nth 1 state))))
849 (let ((deep (ruby-deep-indent-paren-p (car (nth 1 state)))))
850 (if deep
851 (cond ((and (eq deep t) (eq (car (nth 1 state)) paren))
852 (skip-syntax-backward " ")
853 (setq indent (1- (current-column))))
854 ((let ((s (ruby-parse-region (point) ruby-indent-point)))
855 (and (nth 2 s) (> (nth 2 s) 0)
856 (or (goto-char (cdr (nth 1 s))) t)))
857 (forward-word -1)
858 (setq indent (ruby-indent-size (current-column)
859 (nth 2 state))))
861 (setq indent (current-column))
862 (cond ((eq deep 'space))
863 (paren (setq indent (1- indent)))
864 (t (setq indent (ruby-indent-size (1- indent) 1))))))
865 (if (nth 3 state) (goto-char (nth 3 state))
866 (goto-char parse-start) (back-to-indentation))
867 (setq indent (ruby-indent-size (current-column) (nth 2 state))))
868 (and (eq (car (nth 1 state)) paren)
869 (ruby-deep-indent-paren-p (matching-paren paren))
870 (search-backward (char-to-string paren))
871 (setq indent (current-column)))))
872 ((and (nth 2 state) (> (nth 2 state) 0)) ; in nest
873 (if (null (cdr (nth 1 state)))
874 (error "invalid nest"))
875 (goto-char (cdr (nth 1 state)))
876 (forward-word -1) ; skip back a keyword
877 (setq begin (point))
878 (cond
879 ((looking-at "do\\>[^_]") ; iter block is a special case
880 (if (nth 3 state) (goto-char (nth 3 state))
881 (goto-char parse-start) (back-to-indentation))
882 (setq indent (ruby-indent-size (current-column) (nth 2 state))))
884 (setq indent (+ (current-column) ruby-indent-level)))))
886 ((and (nth 2 state) (< (nth 2 state) 0)) ; in negative nest
887 (setq indent (ruby-indent-size (current-column) (nth 2 state)))))
888 (when indent
889 (goto-char ruby-indent-point)
890 (end-of-line)
891 (setq eol (point))
892 (beginning-of-line)
893 (cond
894 ((and (not (ruby-deep-indent-paren-p paren))
895 (re-search-forward ruby-negative eol t))
896 (and (not (eq ?_ (char-after (match-end 0))))
897 (setq indent (- indent ruby-indent-level))))
898 ((and
899 (save-excursion
900 (beginning-of-line)
901 (not (bobp)))
902 (or (ruby-deep-indent-paren-p t)
903 (null (car (nth 1 state)))))
904 ;; goto beginning of non-empty no-comment line
905 (let (end done)
906 (while (not done)
907 (skip-chars-backward " \t\n")
908 (setq end (point))
909 (beginning-of-line)
910 (if (re-search-forward "^\\s *#" end t)
911 (beginning-of-line)
912 (setq done t))))
913 (end-of-line)
914 ;; skip the comment at the end
915 (skip-chars-backward " \t")
916 (let (end (pos (point)))
917 (beginning-of-line)
918 (while (and (re-search-forward "#" pos t)
919 (setq end (1- (point)))
920 (or (ruby-special-char-p end)
921 (and (setq state (ruby-parse-region parse-start end))
922 (nth 0 state))))
923 (setq end nil))
924 (goto-char (or end pos))
925 (skip-chars-backward " \t")
926 (setq begin (if (and end (nth 0 state)) pos (cdr (nth 1 state))))
927 (setq state (ruby-parse-region parse-start (point))))
928 (or (bobp) (forward-char -1))
929 (and
930 (or (and (looking-at ruby-symbol-re)
931 (skip-chars-backward ruby-symbol-chars)
932 (looking-at (concat "\\<\\(" ruby-block-hanging-re "\\)\\>"))
933 (not (eq (point) (nth 3 state)))
934 (save-excursion
935 (goto-char (match-end 0))
936 (not (looking-at "[a-z_]"))))
937 (and (looking-at ruby-operator-re)
938 (not (ruby-special-char-p))
939 (save-excursion
940 (forward-char -1)
941 (or (not (looking-at ruby-operator-re))
942 (not (eq (char-before) ?:))))
943 ;; Operator at the end of line.
944 (let ((c (char-after (point))))
945 (and
946 ;; (or (null begin)
947 ;; (save-excursion
948 ;; (goto-char begin)
949 ;; (skip-chars-forward " \t")
950 ;; (not (or (eolp) (looking-at "#")
951 ;; (and (eq (car (nth 1 state)) ?{)
952 ;; (looking-at "|"))))))
953 ;; Not a regexp or percent literal.
954 (null (nth 0 (ruby-parse-region (or begin parse-start)
955 (point))))
956 (or (not (eq ?| (char-after (point))))
957 (save-excursion
958 (or (eolp) (forward-char -1))
959 (cond
960 ((search-backward "|" nil t)
961 (skip-chars-backward " \t\n")
962 (and (not (eolp))
963 (progn
964 (forward-char -1)
965 (not (looking-at "{")))
966 (progn
967 (forward-word -1)
968 (not (looking-at "do\\>[^_]")))))
969 (t t))))
970 (not (eq ?, c))
971 (setq op-end t)))))
972 (setq indent
973 (cond
974 ((and
975 (null op-end)
976 (not (looking-at (concat "\\<\\(" ruby-block-hanging-re "\\)\\>")))
977 (eq (ruby-deep-indent-paren-p t) 'space)
978 (not (bobp)))
979 (widen)
980 (goto-char (or begin parse-start))
981 (skip-syntax-forward " ")
982 (current-column))
983 ((car (nth 1 state)) indent)
985 (+ indent ruby-indent-level))))))))
986 (goto-char ruby-indent-point)
987 (beginning-of-line)
988 (skip-syntax-forward " ")
989 (if (looking-at "\\.[^.]")
990 (+ indent ruby-indent-level)
991 indent))))
993 (defun ruby-beginning-of-defun (&optional arg)
994 "Move backward to the beginning of the current defun.
995 With ARG, move backward multiple defuns. Negative ARG means
996 move forward."
997 (interactive "p")
998 (let (case-fold-search)
999 (and (re-search-backward (concat "^\\s *" ruby-defun-beg-re "\\_>")
1000 nil t (or arg 1))
1001 (beginning-of-line))))
1003 (defun ruby-end-of-defun ()
1004 "Move point to the end of the current defun.
1005 The defun begins at or after the point. This function is called
1006 by `end-of-defun'."
1007 (interactive "p")
1008 (ruby-forward-sexp)
1009 (let (case-fold-search)
1010 (when (looking-back (concat "^\\s *" ruby-block-end-re))
1011 (forward-line 1))))
1013 (defun ruby-beginning-of-indent ()
1014 "Backtrack to a line which can be used as a reference for
1015 calculating indentation on the lines after it."
1016 (while (and (re-search-backward ruby-indent-beg-re nil 'move)
1017 (if (ruby-in-ppss-context-p 'anything)
1019 ;; We can stop, then.
1020 (beginning-of-line)))))
1022 (defun ruby-move-to-block (n)
1023 "Move to the beginning (N < 0) or the end (N > 0) of the
1024 current block, a sibling block, or an outer block. Do that (abs N) times."
1025 (back-to-indentation)
1026 (let ((signum (if (> n 0) 1 -1))
1027 (backward (< n 0))
1028 (depth (or (nth 2 (ruby-parse-region (point) (line-end-position))) 0))
1029 case-fold-search
1030 down done)
1031 (when (looking-at ruby-block-mid-re)
1032 (setq depth (+ depth signum)))
1033 (when (< (* depth signum) 0)
1034 ;; Moving end -> end or beginning -> beginning.
1035 (setq depth 0))
1036 (dotimes (_ (abs n))
1037 (setq done nil)
1038 (setq down (save-excursion
1039 (back-to-indentation)
1040 ;; There is a block start or block end keyword on this
1041 ;; line, don't need to look for another block.
1042 (and (re-search-forward
1043 (if backward ruby-block-end-re
1044 (concat "\\_<\\(" ruby-block-beg-re "\\)\\_>"))
1045 (line-end-position) t)
1046 (not (nth 8 (syntax-ppss))))))
1047 (while (and (not done) (not (if backward (bobp) (eobp))))
1048 (forward-line signum)
1049 (cond
1050 ;; Skip empty and commented out lines.
1051 ((looking-at "^\\s *$"))
1052 ((looking-at "^\\s *#"))
1053 ;; Skip block comments;
1054 ((and (not backward) (looking-at "^=begin\\>"))
1055 (re-search-forward "^=end\\>"))
1056 ((and backward (looking-at "^=end\\>"))
1057 (re-search-backward "^=begin\\>"))
1058 ;; Jump over a multiline literal.
1059 ((ruby-in-ppss-context-p 'string)
1060 (goto-char (nth 8 (syntax-ppss)))
1061 (unless backward
1062 (forward-sexp)
1063 (when (bolp) (forward-char -1)))) ; After a heredoc.
1065 (let ((state (ruby-parse-region (point) (line-end-position))))
1066 (unless (car state) ; Line ends with unfinished string.
1067 (setq depth (+ (nth 2 state) depth))))
1068 (cond
1069 ;; Increased depth, we found a block.
1070 ((> (* signum depth) 0)
1071 (setq down t))
1072 ;; We're at the same depth as when we started, and we've
1073 ;; encountered a block before. Stop.
1074 ((and down (zerop depth))
1075 (setq done t))
1076 ;; Lower depth, means outer block, can stop now.
1077 ((< (* signum depth) 0)
1078 (setq done t)))))))
1079 (back-to-indentation)))
1081 (defun ruby-beginning-of-block (&optional arg)
1082 "Move backward to the beginning of the current block.
1083 With ARG, move up multiple blocks."
1084 (interactive "p")
1085 (ruby-move-to-block (- (or arg 1))))
1087 (defun ruby-end-of-block (&optional arg)
1088 "Move forward to the end of the current block.
1089 With ARG, move out of multiple blocks."
1090 (interactive "p")
1091 (ruby-move-to-block (or arg 1)))
1093 (defun ruby-forward-sexp (&optional arg)
1094 "Move forward across one balanced expression (sexp).
1095 With ARG, do it many times. Negative ARG means move backward."
1096 ;; TODO: Document body
1097 (interactive "p")
1098 (if (and (numberp arg) (< arg 0))
1099 (ruby-backward-sexp (- arg))
1100 (let ((i (or arg 1)))
1101 (condition-case nil
1102 (while (> i 0)
1103 (skip-syntax-forward " ")
1104 (if (looking-at ",\\s *") (goto-char (match-end 0)))
1105 (cond ((looking-at "\\?\\(\\\\[CM]-\\)*\\\\?\\S ")
1106 (goto-char (match-end 0)))
1107 ((progn
1108 (skip-chars-forward ",.:;|&^~=!?\\+\\-\\*")
1109 (looking-at "\\s("))
1110 (goto-char (scan-sexps (point) 1)))
1111 ((and (looking-at (concat "\\<\\(" ruby-block-beg-re "\\)\\>"))
1112 (not (eq (char-before (point)) ?.))
1113 (not (eq (char-before (point)) ?:)))
1114 (ruby-end-of-block)
1115 (forward-word 1))
1116 ((looking-at "\\(\\$\\|@@?\\)?\\sw")
1117 (while (progn
1118 (while (progn (forward-word 1) (looking-at "_")))
1119 (cond ((looking-at "::") (forward-char 2) t)
1120 ((> (skip-chars-forward ".") 0))
1121 ((looking-at "\\?\\|!\\(=[~=>]\\|[^~=]\\)")
1122 (forward-char 1) nil)))))
1123 ((let (state expr)
1124 (while
1125 (progn
1126 (setq expr (or expr (ruby-expr-beg)
1127 (looking-at "%\\sw?\\Sw\\|[\"'`/]")))
1128 (nth 1 (setq state (apply 'ruby-parse-partial nil state))))
1129 (setq expr t)
1130 (skip-chars-forward "<"))
1131 (not expr))))
1132 (setq i (1- i)))
1133 ((error) (forward-word 1)))
1134 i)))
1136 (defun ruby-backward-sexp (&optional arg)
1137 "Move backward across one balanced expression (sexp).
1138 With ARG, do it many times. Negative ARG means move forward."
1139 ;; TODO: Document body
1140 (interactive "p")
1141 (if (and (numberp arg) (< arg 0))
1142 (ruby-forward-sexp (- arg))
1143 (let ((i (or arg 1)))
1144 (condition-case nil
1145 (while (> i 0)
1146 (skip-chars-backward " \t\n,.:;|&^~=!?\\+\\-\\*")
1147 (forward-char -1)
1148 (cond ((looking-at "\\s)")
1149 (goto-char (scan-sexps (1+ (point)) -1))
1150 (case (char-before)
1151 (?% (forward-char -1))
1152 ((?q ?Q ?w ?W ?r ?x)
1153 (if (eq (char-before (1- (point))) ?%) (forward-char -2))))
1154 nil)
1155 ((looking-at "\\s\"\\|\\\\\\S_")
1156 (let ((c (char-to-string (char-before (match-end 0)))))
1157 (while (and (search-backward c)
1158 (eq (logand (skip-chars-backward "\\") 1)
1159 1))))
1160 nil)
1161 ((looking-at "\\s.\\|\\s\\")
1162 (if (ruby-special-char-p) (forward-char -1)))
1163 ((looking-at "\\s(") nil)
1165 (forward-char 1)
1166 (while (progn (forward-word -1)
1167 (case (char-before)
1168 (?_ t)
1169 (?. (forward-char -1) t)
1170 ((?$ ?@)
1171 (forward-char -1)
1172 (and (eq (char-before) (char-after)) (forward-char -1)))
1174 (forward-char -1)
1175 (eq (char-before) :)))))
1176 (if (looking-at ruby-block-end-re)
1177 (ruby-beginning-of-block))
1178 nil))
1179 (setq i (1- i)))
1180 ((error)))
1181 i)))
1183 (defun ruby-indent-exp (&optional ignored)
1184 "Indent each line in the balanced expression following the point."
1185 (interactive "*P")
1186 (let ((here (point-marker)) start top column (nest t))
1187 (set-marker-insertion-type here t)
1188 (unwind-protect
1189 (progn
1190 (beginning-of-line)
1191 (setq start (point) top (current-indentation))
1192 (while (and (not (eobp))
1193 (progn
1194 (setq column (ruby-calculate-indent start))
1195 (cond ((> column top)
1196 (setq nest t))
1197 ((and (= column top) nest)
1198 (setq nest nil) t))))
1199 (ruby-indent-to column)
1200 (beginning-of-line 2)))
1201 (goto-char here)
1202 (set-marker here nil))))
1204 (defun ruby-add-log-current-method ()
1205 "Return the current method name as a string.
1206 This string includes all namespaces.
1208 For example:
1210 #exit
1211 String#gsub
1212 Net::HTTP#active?
1213 File.open
1215 See `add-log-current-defun-function'."
1216 (condition-case nil
1217 (save-excursion
1218 (let* ((indent 0) mname mlist
1219 (start (point))
1220 (make-definition-re
1221 (lambda (re)
1222 (concat "^[ \t]*" re "[ \t]+"
1223 "\\("
1224 ;; \\. and :: for class methods
1225 "\\([A-Za-z_]" ruby-symbol-re "*\\|\\.\\|::" "\\)"
1226 "+\\)")))
1227 (definition-re (funcall make-definition-re ruby-defun-beg-re))
1228 (module-re (funcall make-definition-re "\\(class\\|module\\)")))
1229 ;; Get the current method definition (or class/module).
1230 (when (re-search-backward definition-re nil t)
1231 (goto-char (match-beginning 1))
1232 (if (not (string-equal "def" (match-string 1)))
1233 (setq mlist (list (match-string 2)))
1234 ;; We're inside the method. For classes and modules,
1235 ;; this check is skipped for performance.
1236 (when (ruby-block-contains-point start)
1237 (setq mname (match-string 2))))
1238 (setq indent (current-column))
1239 (beginning-of-line))
1240 ;; Walk up the class/module nesting.
1241 (while (and (> indent 0)
1242 (re-search-backward module-re nil t))
1243 (goto-char (match-beginning 1))
1244 (when (< (current-column) indent)
1245 (setq mlist (cons (match-string 2) mlist))
1246 (setq indent (current-column))
1247 (beginning-of-line)))
1248 ;; Process the method name.
1249 (when mname
1250 (let ((mn (split-string mname "\\.\\|::")))
1251 (if (cdr mn)
1252 (progn
1253 (unless (string-equal "self" (car mn)) ; def self.foo
1254 ;; def C.foo
1255 (let ((ml (nreverse mlist)))
1256 ;; If the method name references one of the
1257 ;; containing modules, drop the more nested ones.
1258 (while ml
1259 (if (string-equal (car ml) (car mn))
1260 (setq mlist (nreverse (cdr ml)) ml nil))
1261 (or (setq ml (cdr ml)) (nreverse mlist))))
1262 (if mlist
1263 (setcdr (last mlist) (butlast mn))
1264 (setq mlist (butlast mn))))
1265 (setq mname (concat "." (car (last mn)))))
1266 ;; See if the method is in singleton class context.
1267 (let ((in-singleton-class
1268 (when (re-search-forward ruby-singleton-class-re start t)
1269 (goto-char (match-beginning 0))
1270 ;; FIXME: Optimize it out, too?
1271 ;; This can be slow in a large file, but
1272 ;; unlike class/module declaration
1273 ;; indentations, method definitions can be
1274 ;; intermixed with these, and may or may not
1275 ;; be additionally indented after visibility
1276 ;; keywords.
1277 (ruby-block-contains-point start))))
1278 (setq mname (concat
1279 (if in-singleton-class "." "#")
1280 mname))))))
1281 ;; Generate the string.
1282 (if (consp mlist)
1283 (setq mlist (mapconcat (function identity) mlist "::")))
1284 (if mname
1285 (if mlist (concat mlist mname) mname)
1286 mlist)))))
1288 (defun ruby-block-contains-point (pt)
1289 (save-excursion
1290 (save-match-data
1291 (ruby-forward-sexp)
1292 (> (point) pt))))
1294 (defun ruby-brace-to-do-end (orig end)
1295 (let (beg-marker end-marker)
1296 (goto-char end)
1297 (when (eq (char-before) ?\})
1298 (delete-char -1)
1299 (when (save-excursion
1300 (skip-chars-backward " \t")
1301 (not (bolp)))
1302 (insert "\n"))
1303 (insert "end")
1304 (setq end-marker (point-marker))
1305 (when (and (not (eobp)) (eq (char-syntax (char-after)) ?w))
1306 (insert " "))
1307 (goto-char orig)
1308 (delete-char 1)
1309 (when (eq (char-syntax (char-before)) ?w)
1310 (insert " "))
1311 (insert "do")
1312 (setq beg-marker (point-marker))
1313 (when (looking-at "\\(\\s \\)*|")
1314 (unless (match-beginning 1)
1315 (insert " "))
1316 (goto-char (1+ (match-end 0)))
1317 (search-forward "|"))
1318 (unless (looking-at "\\s *$")
1319 (insert "\n"))
1320 (indent-region beg-marker end-marker)
1321 (goto-char beg-marker)
1322 t)))
1324 (defun ruby-do-end-to-brace (orig end)
1325 (let (beg-marker end-marker beg-pos end-pos)
1326 (goto-char (- end 3))
1327 (when (looking-at ruby-block-end-re)
1328 (delete-char 3)
1329 (setq end-marker (point-marker))
1330 (insert "}")
1331 (goto-char orig)
1332 (delete-char 2)
1333 (insert "{")
1334 (setq beg-marker (point-marker))
1335 (when (looking-at "\\s +|")
1336 (delete-char (- (match-end 0) (match-beginning 0) 1))
1337 (forward-char)
1338 (re-search-forward "|" (line-end-position) t))
1339 (save-excursion
1340 (skip-chars-forward " \t\n\r")
1341 (setq beg-pos (point))
1342 (goto-char end-marker)
1343 (skip-chars-backward " \t\n\r")
1344 (setq end-pos (point)))
1345 (when (or
1346 (< end-pos beg-pos)
1347 (and (= (line-number-at-pos beg-pos) (line-number-at-pos end-pos))
1348 (< (+ (current-column) (- end-pos beg-pos) 2) fill-column)))
1349 (just-one-space -1)
1350 (goto-char end-marker)
1351 (just-one-space -1))
1352 (goto-char beg-marker)
1353 t)))
1355 (defun ruby-toggle-block ()
1356 "Toggle block type from do-end to braces or back.
1357 The block must begin on the current line or above it and end after the point.
1358 If the result is do-end block, it will always be multiline."
1359 (interactive)
1360 (let ((start (point)) beg end)
1361 (end-of-line)
1362 (unless
1363 (if (and (re-search-backward "\\({\\)\\|\\_<do\\(\\s \\|$\\||\\)")
1364 (progn
1365 (setq beg (point))
1366 (save-match-data (ruby-forward-sexp))
1367 (setq end (point))
1368 (> end start)))
1369 (if (match-beginning 1)
1370 (ruby-brace-to-do-end beg end)
1371 (ruby-do-end-to-brace beg end)))
1372 (goto-char start))))
1374 (declare-function ruby-syntax-propertize-heredoc "ruby-mode" (limit))
1375 (declare-function ruby-syntax-enclosing-percent-literal "ruby-mode" (limit))
1376 (declare-function ruby-syntax-propertize-percent-literal "ruby-mode" (limit))
1377 ;; Unusual code layout confuses the byte-compiler.
1378 (declare-function ruby-syntax-propertize-expansion "ruby-mode" ())
1379 (declare-function ruby-syntax-expansion-allowed-p "ruby-mode" (parse-state))
1380 (declare-function ruby-syntax-propertize-function "ruby-mode" (start end))
1382 (if (eval-when-compile (fboundp #'syntax-propertize-rules))
1383 ;; New code that works independently from font-lock.
1384 (progn
1385 (eval-and-compile
1386 (defconst ruby-percent-literal-beg-re
1387 "\\(%\\)[qQrswWxIi]?\\([[:punct:]]\\)"
1388 "Regexp to match the beginning of percent literal.")
1390 (defconst ruby-syntax-methods-before-regexp
1391 '("gsub" "gsub!" "sub" "sub!" "scan" "split" "split!" "index" "match"
1392 "assert_match" "Given" "Then" "When")
1393 "Methods that can take regexp as the first argument.
1394 It will be properly highlighted even when the call omits parens.")
1396 (defvar ruby-syntax-before-regexp-re
1397 (concat
1398 ;; Special tokens that can't be followed by a division operator.
1399 "\\(^\\|[[=(,~;<>]"
1400 ;; Distinguish ternary operator tokens.
1401 ;; FIXME: They don't really have to be separated with spaces.
1402 "\\|[?:] "
1403 ;; Control flow keywords and operators following bol or whitespace.
1404 "\\|\\(?:^\\|\\s \\)"
1405 (regexp-opt '("if" "elsif" "unless" "while" "until" "when" "and"
1406 "or" "not" "&&" "||"))
1407 ;; Method name from the list.
1408 "\\|\\_<"
1409 (regexp-opt ruby-syntax-methods-before-regexp)
1410 "\\)\\s *")
1411 "Regexp to match text that can be followed by a regular expression."))
1413 (defun ruby-syntax-propertize-function (start end)
1414 "Syntactic keywords for Ruby mode. See `syntax-propertize-function'."
1415 (let (case-fold-search)
1416 (goto-char start)
1417 (remove-text-properties start end '(ruby-expansion-match-data))
1418 (ruby-syntax-propertize-heredoc end)
1419 (ruby-syntax-enclosing-percent-literal end)
1420 (funcall
1421 (syntax-propertize-rules
1422 ;; $' $" $` .... are variables.
1423 ;; ?' ?" ?` are character literals (one-char strings in 1.9+).
1424 ("\\([?$]\\)[#\"'`]"
1425 (1 (unless (save-excursion
1426 ;; Not within a string.
1427 (nth 3 (syntax-ppss (match-beginning 0))))
1428 (string-to-syntax "\\"))))
1429 ;; Regular expressions. Start with matching unescaped slash.
1430 ("\\(?:\\=\\|[^\\]\\)\\(?:\\\\\\\\\\)*\\(/\\)"
1431 (1 (let ((state (save-excursion (syntax-ppss (match-beginning 1)))))
1432 (when (or
1433 ;; Beginning of a regexp.
1434 (and (null (nth 8 state))
1435 (save-excursion
1436 (forward-char -1)
1437 (looking-back ruby-syntax-before-regexp-re
1438 (point-at-bol))))
1439 ;; End of regexp. We don't match the whole
1440 ;; regexp at once because it can have
1441 ;; string interpolation inside, or span
1442 ;; several lines.
1443 (eq ?/ (nth 3 state)))
1444 (string-to-syntax "\"/")))))
1445 ;; Expression expansions in strings. We're handling them
1446 ;; here, so that the regexp rule never matches inside them.
1447 (ruby-expression-expansion-re
1448 (0 (ignore (ruby-syntax-propertize-expansion))))
1449 ("^=en\\(d\\)\\_>" (1 "!"))
1450 ("^\\(=\\)begin\\_>" (1 "!"))
1451 ;; Handle here documents.
1452 ((concat ruby-here-doc-beg-re ".*\\(\n\\)")
1453 (7 (unless (or (nth 8 (save-excursion
1454 (syntax-ppss (match-beginning 0))))
1455 (ruby-singleton-class-p (match-beginning 0)))
1456 (put-text-property (match-beginning 7) (match-end 7)
1457 'syntax-table (string-to-syntax "\""))
1458 (ruby-syntax-propertize-heredoc end))))
1459 ;; Handle percent literals: %w(), %q{}, etc.
1460 ((concat "\\(?:^\\|[[ \t\n<+(,=]\\)" ruby-percent-literal-beg-re)
1461 (1 (prog1 "|" (ruby-syntax-propertize-percent-literal end)))))
1462 (point) end)))
1464 (defun ruby-syntax-propertize-heredoc (limit)
1465 (let ((ppss (syntax-ppss))
1466 (res '()))
1467 (when (eq ?\n (nth 3 ppss))
1468 (save-excursion
1469 (goto-char (nth 8 ppss))
1470 (beginning-of-line)
1471 (while (re-search-forward ruby-here-doc-beg-re
1472 (line-end-position) t)
1473 (unless (ruby-singleton-class-p (match-beginning 0))
1474 (push (concat (ruby-here-doc-end-match) "\n") res))))
1475 (save-excursion
1476 ;; With multiple openers on the same line, we don't know in which
1477 ;; part `start' is, so we have to go back to the beginning.
1478 (when (cdr res)
1479 (goto-char (nth 8 ppss))
1480 (setq res (nreverse res)))
1481 (while (and res (re-search-forward (pop res) limit 'move))
1482 (if (null res)
1483 (put-text-property (1- (point)) (point)
1484 'syntax-table (string-to-syntax "\""))))
1485 ;; End up at bol following the heredoc openers.
1486 ;; Propertize expression expansions from this point forward.
1487 ))))
1489 (defun ruby-syntax-enclosing-percent-literal (limit)
1490 (let ((state (syntax-ppss))
1491 (start (point)))
1492 ;; When already inside percent literal, re-propertize it.
1493 (when (eq t (nth 3 state))
1494 (goto-char (nth 8 state))
1495 (when (looking-at ruby-percent-literal-beg-re)
1496 (ruby-syntax-propertize-percent-literal limit))
1497 (when (< (point) start) (goto-char start)))))
1499 (defun ruby-syntax-propertize-percent-literal (limit)
1500 (goto-char (match-beginning 2))
1501 ;; Not inside a simple string or comment.
1502 (when (eq t (nth 3 (syntax-ppss)))
1503 (let* ((op (char-after))
1504 (ops (char-to-string op))
1505 (cl (or (cdr (aref (syntax-table) op))
1506 (cdr (assoc op '((?< . ?>))))))
1507 parse-sexp-lookup-properties)
1508 (save-excursion
1509 (condition-case nil
1510 (progn
1511 (if cl ; Paired delimiters.
1512 ;; Delimiter pairs of the same kind can be nested
1513 ;; inside the literal, as long as they are balanced.
1514 ;; Create syntax table that ignores other characters.
1515 (with-syntax-table (make-char-table 'syntax-table nil)
1516 (modify-syntax-entry op (concat "(" (char-to-string cl)))
1517 (modify-syntax-entry cl (concat ")" ops))
1518 (modify-syntax-entry ?\\ "\\")
1519 (save-restriction
1520 (narrow-to-region (point) limit)
1521 (forward-list))) ; skip to the paired character
1522 ;; Single character delimiter.
1523 (re-search-forward (concat "[^\\]\\(?:\\\\\\\\\\)*"
1524 (regexp-quote ops)) limit nil))
1525 ;; Found the closing delimiter.
1526 (put-text-property (1- (point)) (point) 'syntax-table
1527 (string-to-syntax "|")))
1528 ;; Unclosed literal, do nothing.
1529 ((scan-error search-failed)))))))
1531 (defun ruby-syntax-propertize-expansion ()
1532 ;; Save the match data to a text property, for font-locking later.
1533 ;; Set the syntax of all double quotes and backticks to punctuation.
1534 (let* ((beg (match-beginning 2))
1535 (end (match-end 2))
1536 (state (and beg (save-excursion (syntax-ppss beg)))))
1537 (when (ruby-syntax-expansion-allowed-p state)
1538 (put-text-property beg (1+ beg) 'ruby-expansion-match-data
1539 (match-data))
1540 (goto-char beg)
1541 (while (re-search-forward "[\"`]" end 'move)
1542 (put-text-property (match-beginning 0) (match-end 0)
1543 'syntax-table (string-to-syntax "."))))))
1545 (defun ruby-syntax-expansion-allowed-p (parse-state)
1546 "Return non-nil if expression expansion is allowed."
1547 (let ((term (nth 3 parse-state)))
1548 (cond
1549 ((memq term '(?\" ?` ?\n ?/)))
1550 ((eq term t)
1551 (save-match-data
1552 (save-excursion
1553 (goto-char (nth 8 parse-state))
1554 (looking-at "%\\(?:[QWrxI]\\|\\W\\)")))))))
1556 (defun ruby-syntax-propertize-expansions (start end)
1557 (save-excursion
1558 (goto-char start)
1559 (while (re-search-forward ruby-expression-expansion-re end 'move)
1560 (ruby-syntax-propertize-expansion))))
1563 ;; For Emacsen where syntax-propertize-rules is not (yet) available,
1564 ;; fallback on the old font-lock-syntactic-keywords stuff.
1566 (defconst ruby-here-doc-end-re
1567 "^\\([ \t]+\\)?\\(.*\\)\\(\n\\)"
1568 "Regexp to match the end of heredocs.
1570 This will actually match any line with one or more characters.
1571 It's useful in that it divides up the match string so that
1572 `ruby-here-doc-beg-match' can search for the beginning of the heredoc.")
1574 (defun ruby-here-doc-beg-match ()
1575 "Return a regexp to find the beginning of a heredoc.
1577 This should only be called after matching against `ruby-here-doc-end-re'."
1578 (let ((contents (concat
1579 (regexp-quote (concat (match-string 2) (match-string 3)))
1580 (if (string= (match-string 3) "_") "\\B" "\\b"))))
1581 (concat "<<"
1582 (let ((match (match-string 1)))
1583 (if (and match (> (length match) 0))
1584 (concat "\\(?:-\\([\"']?\\)\\|\\([\"']\\)"
1585 (match-string 1) "\\)"
1586 contents "\\(\\1\\|\\2\\)")
1587 (concat "-?\\([\"']\\|\\)" contents "\\1"))))))
1589 (defconst ruby-font-lock-syntactic-keywords
1591 ;; the last $', $", $` in the respective string is not variable
1592 ;; the last ?', ?", ?` in the respective string is not ascii code
1593 ("\\(^\\|[\[ \t\n<+\(,=]\\)\\(['\"`]\\)\\(\\\\.\\|\\2\\|[^'\"`\n\\\\]\\)*?\\\\?[?$]\\(\\2\\)"
1594 (2 (7 . nil))
1595 (4 (7 . nil)))
1596 ;; $' $" $` .... are variables
1597 ;; ?' ?" ?` are ascii codes
1598 ("\\(^\\|[^\\\\]\\)\\(\\\\\\\\\\)*[?$]\\([#\"'`]\\)" 3 (1 . nil))
1599 ;; regexps
1600 ("\\(^\\|[[=(,~?:;<>]\\|\\(^\\|\\s \\)\\(if\\|elsif\\|unless\\|while\\|until\\|when\\|and\\|or\\|&&\\|||\\)\\|g?sub!?\\|scan\\|split!?\\)\\s *\\(/\\)[^/\n\\\\]*\\(\\\\.[^/\n\\\\]*\\)*\\(/\\)"
1601 (4 (7 . ?/))
1602 (6 (7 . ?/)))
1603 ("^=en\\(d\\)\\_>" 1 "!")
1604 ;; Percent literal.
1605 ("\\(^\\|[[ \t\n<+(,=]\\)\\(%[xrqQwW]?\\([^<[{(a-zA-Z0-9 \n]\\)[^\n\\\\]*\\(\\\\.[^\n\\\\]*\\)*\\(\\3\\)\\)"
1606 (3 "\"")
1607 (5 "\""))
1608 ("^\\(=\\)begin\\_>" 1 (ruby-comment-beg-syntax))
1609 ;; Currently, the following case is highlighted incorrectly:
1611 ;; <<FOO
1612 ;; FOO
1613 ;; <<BAR
1614 ;; <<BAZ
1615 ;; BAZ
1616 ;; BAR
1618 ;; This is because all here-doc beginnings are highlighted before any endings,
1619 ;; so although <<BAR is properly marked as a beginning, when we get to <<BAZ
1620 ;; it thinks <<BAR is part of a string so it's marked as well.
1622 ;; This may be fixable by modifying ruby-in-here-doc-p to use
1623 ;; ruby-in-non-here-doc-string-p rather than syntax-ppss-context,
1624 ;; but I don't want to try that until we've got unit tests set up
1625 ;; to make sure I don't break anything else.
1626 (,(concat ruby-here-doc-beg-re ".*\\(\n\\)")
1627 ,(+ 1 (regexp-opt-depth ruby-here-doc-beg-re))
1628 (ruby-here-doc-beg-syntax))
1629 (,ruby-here-doc-end-re 3 (ruby-here-doc-end-syntax)))
1630 "Syntactic keywords for Ruby mode. See `font-lock-syntactic-keywords'.")
1632 (defun ruby-comment-beg-syntax ()
1633 "Return the syntax cell for a the first character of a =begin.
1634 See the definition of `ruby-font-lock-syntactic-keywords'.
1636 This returns a comment-delimiter cell as long as the =begin
1637 isn't in a string or another comment."
1638 (when (not (nth 3 (syntax-ppss)))
1639 (string-to-syntax "!")))
1641 (defun ruby-in-here-doc-p ()
1642 "Return whether or not the point is in a heredoc."
1643 (save-excursion
1644 (let ((old-point (point)) (case-fold-search nil))
1645 (beginning-of-line)
1646 (catch 'found-beg
1647 (while (and (re-search-backward ruby-here-doc-beg-re nil t)
1648 (not (ruby-singleton-class-p)))
1649 (if (not (or (ruby-in-ppss-context-p 'anything)
1650 (ruby-here-doc-find-end old-point)))
1651 (throw 'found-beg t)))))))
1653 (defun ruby-here-doc-find-end (&optional limit)
1654 "Expects the point to be on a line with one or more heredoc openers.
1655 Returns the buffer position at which all heredocs on the line
1656 are terminated, or nil if they aren't terminated before the
1657 buffer position `limit' or the end of the buffer."
1658 (save-excursion
1659 (beginning-of-line)
1660 (catch 'done
1661 (let ((eol (point-at-eol))
1662 (case-fold-search nil)
1663 ;; Fake match data such that (match-end 0) is at eol
1664 (end-match-data (progn (looking-at ".*$") (match-data)))
1665 beg-match-data end-re)
1666 (while (re-search-forward ruby-here-doc-beg-re eol t)
1667 (setq beg-match-data (match-data))
1668 (setq end-re (ruby-here-doc-end-match))
1670 (set-match-data end-match-data)
1671 (goto-char (match-end 0))
1672 (unless (re-search-forward end-re limit t) (throw 'done nil))
1673 (setq end-match-data (match-data))
1675 (set-match-data beg-match-data)
1676 (goto-char (match-end 0)))
1677 (set-match-data end-match-data)
1678 (goto-char (match-end 0))
1679 (point)))))
1681 (defun ruby-here-doc-beg-syntax ()
1682 "Return the syntax cell for a line that may begin a heredoc.
1683 See the definition of `ruby-font-lock-syntactic-keywords'.
1685 This sets the syntax cell for the newline ending the line
1686 containing the heredoc beginning so that cases where multiple
1687 heredocs are started on one line are handled correctly."
1688 (save-excursion
1689 (goto-char (match-beginning 0))
1690 (unless (or (ruby-in-ppss-context-p 'non-heredoc)
1691 (ruby-in-here-doc-p))
1692 (string-to-syntax "\""))))
1694 (defun ruby-here-doc-end-syntax ()
1695 "Return the syntax cell for a line that may end a heredoc.
1696 See the definition of `ruby-font-lock-syntactic-keywords'."
1697 (let ((pss (syntax-ppss)) (case-fold-search nil))
1698 ;; If we aren't in a string, we definitely aren't ending a heredoc,
1699 ;; so we can just give up.
1700 ;; This means we aren't doing a full-document search
1701 ;; every time we enter a character.
1702 (when (ruby-in-ppss-context-p 'heredoc pss)
1703 (save-excursion
1704 (goto-char (nth 8 pss)) ; Go to the beginning of heredoc.
1705 (let ((eol (point)))
1706 (beginning-of-line)
1707 (if (and (re-search-forward (ruby-here-doc-beg-match) eol t) ; If there is a heredoc that matches this line...
1708 (not (ruby-in-ppss-context-p 'anything)) ; And that's not inside a heredoc/string/comment...
1709 (progn (goto-char (match-end 0)) ; And it's the last heredoc on its line...
1710 (not (re-search-forward ruby-here-doc-beg-re eol t))))
1711 (string-to-syntax "\"")))))))
1713 (unless (functionp 'syntax-ppss)
1714 (defun syntax-ppss (&optional pos)
1715 (parse-partial-sexp (point-min) (or pos (point)))))
1718 (defun ruby-in-ppss-context-p (context &optional ppss)
1719 (let ((ppss (or ppss (syntax-ppss (point)))))
1720 (if (cond
1721 ((eq context 'anything)
1722 (or (nth 3 ppss)
1723 (nth 4 ppss)))
1724 ((eq context 'string)
1725 (nth 3 ppss))
1726 ((eq context 'heredoc)
1727 (eq ?\n (nth 3 ppss)))
1728 ((eq context 'non-heredoc)
1729 (and (ruby-in-ppss-context-p 'anything)
1730 (not (ruby-in-ppss-context-p 'heredoc))))
1731 ((eq context 'comment)
1732 (nth 4 ppss))
1734 (error (concat
1735 "Internal error on `ruby-in-ppss-context-p': "
1736 "context name `" (symbol-name context) "' is unknown"))))
1737 t)))
1739 (if (featurep 'xemacs)
1740 (put 'ruby-mode 'font-lock-defaults
1741 '((ruby-font-lock-keywords)
1742 nil nil nil
1743 beginning-of-line
1744 (font-lock-syntactic-keywords
1745 . ruby-font-lock-syntactic-keywords))))
1747 (defvar ruby-font-lock-syntax-table
1748 (let ((tbl (copy-syntax-table ruby-mode-syntax-table)))
1749 (modify-syntax-entry ?_ "w" tbl)
1750 tbl)
1751 "The syntax table to use for fontifying Ruby mode buffers.
1752 See `font-lock-syntax-table'.")
1754 (defconst ruby-font-lock-keyword-beg-re "\\(?:^\\|[^.@$]\\|\\.\\.\\)")
1756 (defconst ruby-font-lock-keywords
1757 (list
1758 ;; functions
1759 '("^\\s *def\\s +\\(?:[^( \t\n.]*\\.\\)?\\([^( \t\n]+\\)"
1760 1 font-lock-function-name-face)
1761 ;; keywords
1762 (list (concat
1763 ruby-font-lock-keyword-beg-re
1764 (regexp-opt
1765 '("alias"
1766 "and"
1767 "begin"
1768 "break"
1769 "case"
1770 "class"
1771 "def"
1772 "defined?"
1773 "do"
1774 "elsif"
1775 "else"
1776 "fail"
1777 "ensure"
1778 "for"
1779 "end"
1780 "if"
1781 "in"
1782 "module"
1783 "next"
1784 "not"
1785 "or"
1786 "redo"
1787 "rescue"
1788 "retry"
1789 "return"
1790 "then"
1791 "super"
1792 "unless"
1793 "undef"
1794 "until"
1795 "when"
1796 "while"
1797 "yield")
1798 'symbols))
1799 1 'font-lock-keyword-face)
1800 ;; some core methods
1801 (list (concat
1802 ruby-font-lock-keyword-beg-re
1803 (regexp-opt
1804 '(;; built-in methods on Kernel
1805 "__callee__"
1806 "__dir__"
1807 "__method__"
1808 "abort"
1809 "at_exit"
1810 "autoload"
1811 "autoload?"
1812 "binding"
1813 "block_given?"
1814 "caller"
1815 "catch"
1816 "eval"
1817 "exec"
1818 "exit"
1819 "exit!"
1820 "fail"
1821 "fork"
1822 "format"
1823 "lambda"
1824 "load"
1825 "loop"
1826 "open"
1828 "print"
1829 "printf"
1830 "proc"
1831 "putc"
1832 "puts"
1833 "raise"
1834 "rand"
1835 "readline"
1836 "readlines"
1837 "require"
1838 "require_relative"
1839 "sleep"
1840 "spawn"
1841 "sprintf"
1842 "srand"
1843 "syscall"
1844 "system"
1845 "throw"
1846 "trap"
1847 "warn"
1848 ;; keyword-like private methods on Module
1849 "alias_method"
1850 "attr"
1851 "attr_accessor"
1852 "attr_reader"
1853 "attr_writer"
1854 "define_method"
1855 "extend"
1856 "include"
1857 "module_function"
1858 "prepend"
1859 "private"
1860 "protected"
1861 "public"
1862 "refine"
1863 "using")
1864 'symbols))
1865 1 'font-lock-builtin-face)
1866 ;; here-doc beginnings
1867 `(,ruby-here-doc-beg-re 0 (unless (ruby-singleton-class-p (match-beginning 0))
1868 'font-lock-string-face))
1869 ;; Perl-ish keywords
1870 "\\_<\\(?:BEGIN\\|END\\)\\_>\\|^__END__$"
1871 ;; variables
1872 `(,(concat ruby-font-lock-keyword-beg-re
1873 "\\_<\\(nil\\|self\\|true\\|false\\)\\>")
1874 1 font-lock-variable-name-face)
1875 ;; keywords that evaluate to certain values
1876 '("\\_<__\\(?:LINE\\|ENCODING\\|FILE\\)__\\_>" 0 font-lock-variable-name-face)
1877 ;; symbols
1878 '("\\(^\\|[^:]\\)\\(:\\([-+~]@?\\|[/%&|^`]\\|\\*\\*?\\|<\\(<\\|=>?\\)?\\|>[>=]?\\|===?\\|=~\\|![~=]?\\|\\[\\]=?\\|@?\\(\\w\\|_\\)+\\([!?=]\\|\\b_*\\)\\|#{[^}\n\\\\]*\\(\\\\.[^}\n\\\\]*\\)*}\\)\\)"
1879 2 font-lock-constant-face)
1880 ;; variables
1881 '("\\(\\$\\([^a-zA-Z0-9 \n]\\|[0-9]\\)\\)\\W"
1882 1 font-lock-variable-name-face)
1883 '("\\(\\$\\|@\\|@@\\)\\(\\w\\|_\\)+"
1884 0 font-lock-variable-name-face)
1885 ;; constants
1886 '("\\(?:\\_<\\|::\\)\\([A-Z]+\\(\\w\\|_\\)*\\)"
1887 1 (unless (eq ?\( (char-after)) font-lock-type-face))
1888 '("\\(^\\s *\\|[\[\{\(,]\\s *\\|\\sw\\s +\\)\\(\\(\\sw\\|_\\)+\\):[^:]" 2 font-lock-constant-face)
1889 ;; conversion methods on Kernel
1890 (list (concat ruby-font-lock-keyword-beg-re
1891 (regexp-opt '("Array" "Complex" "Float" "Hash"
1892 "Integer" "Rational" "String") 'symbols))
1893 1 font-lock-builtin-face)
1894 ;; expression expansion
1895 '(ruby-match-expression-expansion
1896 2 font-lock-variable-name-face t)
1897 ;; negation char
1898 '("[^[:alnum:]_]\\(!\\)[^=]"
1899 1 font-lock-negation-char-face)
1900 ;; character literals
1901 ;; FIXME: Support longer escape sequences.
1902 '("\\_<\\?\\\\?\\S " 0 font-lock-string-face)
1904 "Additional expressions to highlight in Ruby mode.")
1906 (defun ruby-match-expression-expansion (limit)
1907 (let* ((prop 'ruby-expansion-match-data)
1908 (pos (next-single-char-property-change (point) prop nil limit))
1909 value)
1910 (when (and pos (> pos (point)))
1911 (goto-char pos)
1912 (or (and (setq value (get-text-property pos prop))
1913 (progn (set-match-data value) t))
1914 (ruby-match-expression-expansion limit)))))
1916 ;;;###autoload
1917 (define-derived-mode ruby-mode prog-mode "Ruby"
1918 "Major mode for editing Ruby scripts.
1919 \\[ruby-indent-line] properly indents subexpressions of multi-line
1920 class, module, def, if, while, for, do, and case statements, taking
1921 nesting into account.
1923 The variable `ruby-indent-level' controls the amount of indentation.
1925 \\{ruby-mode-map}"
1926 (ruby-mode-variables)
1928 (set (make-local-variable 'imenu-create-index-function)
1929 'ruby-imenu-create-index)
1930 (set (make-local-variable 'add-log-current-defun-function)
1931 'ruby-add-log-current-method)
1932 (set (make-local-variable 'beginning-of-defun-function)
1933 'ruby-beginning-of-defun)
1934 (set (make-local-variable 'end-of-defun-function)
1935 'ruby-end-of-defun)
1937 (add-hook
1938 (cond ((boundp 'before-save-hook) 'before-save-hook)
1939 ((boundp 'write-contents-functions) 'write-contents-functions)
1940 ((boundp 'write-contents-hooks) 'write-contents-hooks))
1941 'ruby-mode-set-encoding nil 'local)
1943 (set (make-local-variable 'electric-indent-chars)
1944 (append '(?\{ ?\}) electric-indent-chars))
1946 (set (make-local-variable 'font-lock-defaults)
1947 '((ruby-font-lock-keywords) nil nil))
1948 (set (make-local-variable 'font-lock-keywords)
1949 ruby-font-lock-keywords)
1950 (set (make-local-variable 'font-lock-syntax-table)
1951 ruby-font-lock-syntax-table)
1953 (if (eval-when-compile (fboundp 'syntax-propertize-rules))
1954 (set (make-local-variable 'syntax-propertize-function)
1955 #'ruby-syntax-propertize-function)
1956 (set (make-local-variable 'font-lock-syntactic-keywords)
1957 ruby-font-lock-syntactic-keywords)))
1959 ;;; Invoke ruby-mode when appropriate
1961 ;;;###autoload
1962 (add-to-list 'auto-mode-alist
1963 (cons (purecopy (concat "\\(?:\\."
1964 "rb\\|ru\\|rake\\|thor"
1965 "\\|jbuilder\\|gemspec"
1966 "\\|/"
1967 "\\(?:Gem\\|Rake\\|Cap\\|Thor"
1968 "Vagrant\\|Guard\\)file"
1969 "\\)\\'")) 'ruby-mode))
1971 ;;;###autoload
1972 (dolist (name (list "ruby" "rbx" "jruby" "ruby1.9" "ruby1.8"))
1973 (add-to-list 'interpreter-mode-alist (cons (purecopy name) 'ruby-mode)))
1975 (provide 'ruby-mode)
1977 ;;; ruby-mode.el ends here