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