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