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