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