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