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