]> code.delx.au - gnu-emacs/blob - lisp/progmodes/ruby-mode.el
Update copyright year to 2015
[gnu-emacs] / lisp / progmodes / ruby-mode.el
1 ;;; ruby-mode.el --- Major mode for editing Ruby files
2
3 ;; Copyright (C) 1994-2015 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 table)
212 "Syntax table to use in Ruby mode.")
213
214 (defcustom ruby-indent-tabs-mode nil
215 "Indentation can insert tabs in Ruby mode if this is non-nil."
216 :type 'boolean
217 :group 'ruby
218 :safe 'booleanp)
219
220 (defcustom ruby-indent-level 2
221 "Indentation of Ruby statements."
222 :type 'integer
223 :group 'ruby
224 :safe 'integerp)
225
226 (defcustom ruby-comment-column (default-value 'comment-column)
227 "Indentation column of comments."
228 :type 'integer
229 :group 'ruby
230 :safe 'integerp)
231
232 (defconst ruby-alignable-keywords '(if while unless until begin case for def)
233 "Keywords that can be used in `ruby-align-to-stmt-keywords'.")
234
235 (defcustom ruby-align-to-stmt-keywords '(def)
236 "Keywords after which we align the expression body to statement.
237
238 When nil, an expression that begins with one these keywords is
239 indented to the column of the keyword. Example:
240
241 tee = if foo
242 bar
243 else
244 qux
245 end
246
247 If this value is t or contains a symbol with the name of given
248 keyword, the expression is indented to align to the beginning of
249 the statement:
250
251 tee = if foo
252 bar
253 else
254 qux
255 end
256
257 Only has effect when `ruby-use-smie' is t.
258 "
259 :type `(choice
260 (const :tag "None" nil)
261 (const :tag "All" t)
262 (repeat :tag "User defined"
263 (choice ,@(mapcar
264 (lambda (kw) (list 'const kw))
265 ruby-alignable-keywords))))
266 :group 'ruby
267 :safe 'listp
268 :version "24.4")
269
270 (defcustom ruby-align-chained-calls nil
271 "If non-nil, align chained method calls.
272
273 Each method call on a separate line will be aligned to the column
274 of its parent.
275
276 Only has effect when `ruby-use-smie' is t."
277 :type 'boolean
278 :group 'ruby
279 :safe 'booleanp
280 :version "24.4")
281
282 (defcustom ruby-deep-arglist t
283 "Deep indent lists in parenthesis when non-nil.
284 Also ignores spaces after parenthesis when `space'.
285 Only has effect when `ruby-use-smie' is nil."
286 :type 'boolean
287 :group 'ruby
288 :safe 'booleanp)
289
290 ;; FIXME Woefully under documented. What is the point of the last `t'?.
291 (defcustom ruby-deep-indent-paren '(?\( ?\[ ?\] t)
292 "Deep indent lists in parenthesis when non-nil.
293 The value t means continuous line.
294 Also ignores spaces after parenthesis when `space'.
295 Only has effect when `ruby-use-smie' is nil."
296 :type '(choice (const nil)
297 character
298 (repeat (choice character
299 (cons character (choice (const nil)
300 (const t)))
301 (const t) ; why?
302 )))
303 :group 'ruby)
304
305 (defcustom ruby-deep-indent-paren-style 'space
306 "Default deep indent style.
307 Only has effect when `ruby-use-smie' is nil."
308 :type '(choice (const t) (const nil) (const space))
309 :group 'ruby)
310
311 (defcustom ruby-encoding-map
312 '((us-ascii . nil) ;; Do not put coding: us-ascii
313 (shift-jis . cp932) ;; Emacs charset name of Shift_JIS
314 (shift_jis . cp932) ;; MIME charset name of Shift_JIS
315 (japanese-cp932 . cp932)) ;; Emacs charset name of CP932
316 "Alist to map encoding name from Emacs to Ruby.
317 Associating an encoding name with nil means it needs not be
318 explicitly declared in magic comment."
319 :type '(repeat (cons (symbol :tag "From") (symbol :tag "To")))
320 :group 'ruby)
321
322 (defcustom ruby-insert-encoding-magic-comment t
323 "Insert a magic Ruby encoding comment upon save if this is non-nil.
324 The encoding will be auto-detected. The format of the encoding comment
325 is customizable via `ruby-encoding-magic-comment-style'.
326
327 When set to `always-utf8' an utf-8 comment will always be added,
328 even if it's not required."
329 :type 'boolean :group 'ruby)
330
331 (defcustom ruby-encoding-magic-comment-style 'ruby
332 "The style of the magic encoding comment to use."
333 :type '(choice
334 (const :tag "Emacs Style" emacs)
335 (const :tag "Ruby Style" ruby)
336 (const :tag "Custom Style" custom))
337 :group 'ruby
338 :version "24.4")
339
340 (defcustom ruby-custom-encoding-magic-comment-template "# encoding: %s"
341 "A custom encoding comment template.
342 It is used when `ruby-encoding-magic-comment-style' is set to `custom'."
343 :type 'string
344 :group 'ruby
345 :version "24.4")
346
347 (defcustom ruby-use-encoding-map t
348 "Use `ruby-encoding-map' to set encoding magic comment if this is non-nil."
349 :type 'boolean :group 'ruby)
350
351 ;;; SMIE support
352
353 (require 'smie)
354
355 ;; Here's a simplified BNF grammar, for reference:
356 ;; http://www.cse.buffalo.edu/~regan/cse305/RubyBNF.pdf
357 (defconst ruby-smie-grammar
358 (smie-prec2->grammar
359 (smie-merge-prec2s
360 (smie-bnf->prec2
361 '((id)
362 (insts (inst) (insts ";" insts))
363 (inst (exp) (inst "iuwu-mod" exp)
364 ;; Somewhat incorrect (both can be used multiple times),
365 ;; but avoids lots of conflicts:
366 (exp "and" exp) (exp "or" exp))
367 (exp (exp1) (exp "," exp) (exp "=" exp)
368 (id " @ " exp))
369 (exp1 (exp2) (exp2 "?" exp1 ":" exp1))
370 (exp2 (exp3) (exp3 "." exp2))
371 (exp3 ("def" insts "end")
372 ("begin" insts-rescue-insts "end")
373 ("do" insts "end")
374 ("class" insts "end") ("module" insts "end")
375 ("for" for-body "end")
376 ("[" expseq "]")
377 ("{" hashvals "}")
378 ("{" insts "}")
379 ("while" insts "end")
380 ("until" insts "end")
381 ("unless" insts "end")
382 ("if" if-body "end")
383 ("case" cases "end"))
384 (formal-params ("opening-|" exp "closing-|"))
385 (for-body (for-head ";" insts))
386 (for-head (id "in" exp))
387 (cases (exp "then" insts)
388 (cases "when" cases) (insts "else" insts))
389 (expseq (exp) );;(expseq "," expseq)
390 (hashvals (id "=>" exp1) (hashvals "," hashvals))
391 (insts-rescue-insts (insts)
392 (insts-rescue-insts "rescue" insts-rescue-insts)
393 (insts-rescue-insts "ensure" insts-rescue-insts))
394 (itheni (insts) (exp "then" insts))
395 (ielsei (itheni) (itheni "else" insts))
396 (if-body (ielsei) (if-body "elsif" if-body)))
397 '((nonassoc "in") (assoc ";") (right " @ ")
398 (assoc ",") (right "="))
399 '((assoc "when"))
400 '((assoc "elsif"))
401 '((assoc "rescue" "ensure"))
402 '((assoc ",")))
403
404 (smie-precs->prec2
405 '((right "=")
406 (right "+=" "-=" "*=" "/=" "%=" "**=" "&=" "|=" "^="
407 "<<=" ">>=" "&&=" "||=")
408 (left ".." "...")
409 (left "+" "-")
410 (left "*" "/" "%" "**")
411 (left "&&" "||")
412 (left "^" "&" "|")
413 (nonassoc "<=>")
414 (nonassoc ">" ">=" "<" "<=")
415 (nonassoc "==" "===" "!=")
416 (nonassoc "=~" "!~")
417 (left "<<" ">>")
418 (right "."))))))
419
420 (defun ruby-smie--bosp ()
421 (save-excursion (skip-chars-backward " \t")
422 (or (bolp) (memq (char-before) '(?\; ?=)))))
423
424 (defun ruby-smie--implicit-semi-p ()
425 (save-excursion
426 (skip-chars-backward " \t")
427 (not (or (bolp)
428 (memq (char-before) '(?\[ ?\())
429 (and (memq (char-before)
430 '(?\; ?- ?+ ?* ?/ ?: ?. ?, ?\\ ?& ?> ?< ?% ?~ ?^))
431 ;; Not a binary operator symbol.
432 (not (eq (char-before (1- (point))) ?:))
433 ;; Not the end of a regexp or a percent literal.
434 (not (memq (car (syntax-after (1- (point)))) '(7 15))))
435 (and (eq (char-before) ?\?)
436 (equal (save-excursion (ruby-smie--backward-token)) "?"))
437 (and (eq (char-before) ?=)
438 ;; Not a symbol :==, :!=, or a foo= method.
439 (string-match "\\`\\s." (save-excursion
440 (ruby-smie--backward-token))))
441 (and (eq (char-before) ?|)
442 (member (save-excursion (ruby-smie--backward-token))
443 '("|" "||")))
444 (and (eq (car (syntax-after (1- (point)))) 2)
445 (member (save-excursion (ruby-smie--backward-token))
446 '("iuwu-mod" "and" "or")))
447 (save-excursion
448 (forward-comment 1)
449 (eq (char-after) ?.))))))
450
451 (defun ruby-smie--redundant-do-p (&optional skip)
452 (save-excursion
453 (if skip (backward-word 1))
454 (member (nth 2 (smie-backward-sexp ";")) '("while" "until" "for"))))
455
456 (defun ruby-smie--opening-pipe-p ()
457 (save-excursion
458 (if (eq ?| (char-before)) (forward-char -1))
459 (skip-chars-backward " \t\n")
460 (or (eq ?\{ (char-before))
461 (looking-back "\\_<do" (- (point) 2)))))
462
463 (defun ruby-smie--closing-pipe-p ()
464 (save-excursion
465 (if (eq ?| (char-before)) (forward-char -1))
466 (and (re-search-backward "|" (line-beginning-position) t)
467 (ruby-smie--opening-pipe-p))))
468
469 (defun ruby-smie--args-separator-p (pos)
470 (and
471 (< pos (line-end-position))
472 (or (eq (char-syntax (preceding-char)) '?w)
473 ;; FIXME: Check that the preceding token is not a keyword.
474 ;; This isn't very important most of the time, though.
475 (and (memq (preceding-char) '(?! ??))
476 (eq (char-syntax (char-before (1- (point)))) '?w)))
477 (save-excursion
478 (goto-char pos)
479 (or (and (eq (char-syntax (char-after)) ?w)
480 (not (looking-at (regexp-opt '("unless" "if" "while" "until" "or"
481 "else" "elsif" "do" "end" "and")
482 'symbols))))
483 (memq (car (syntax-after pos)) '(7 15))
484 (looking-at "[([]\\|[-+!~]\\sw\\|:\\(?:\\sw\\|\\s.\\)")))))
485
486 (defun ruby-smie--at-dot-call ()
487 (and (eq ?w (char-syntax (following-char)))
488 (eq (char-before) ?.)
489 (not (eq (char-before (1- (point))) ?.))))
490
491 (defun ruby-smie--forward-token ()
492 (let ((pos (point)))
493 (skip-chars-forward " \t")
494 (cond
495 ((and (looking-at "\n") (looking-at "\\s\"")) ;A heredoc.
496 ;; Tokenize the whole heredoc as semicolon.
497 (goto-char (scan-sexps (point) 1))
498 ";")
499 ((and (looking-at "[\n#]")
500 (ruby-smie--implicit-semi-p)) ;Only add implicit ; when needed.
501 (if (eolp) (forward-char 1) (forward-comment 1))
502 ";")
503 (t
504 (forward-comment (point-max))
505 (cond
506 ((and (< pos (point))
507 (save-excursion
508 (ruby-smie--args-separator-p (prog1 (point) (goto-char pos)))))
509 " @ ")
510 ((looking-at ":\\s.+")
511 (goto-char (match-end 0)) (match-string 0)) ;bug#15208.
512 ((looking-at "\\s\"") "") ;A string.
513 (t
514 (let ((dot (ruby-smie--at-dot-call))
515 (tok (smie-default-forward-token)))
516 (when dot
517 (setq tok (concat "." tok)))
518 (cond
519 ((member tok '("unless" "if" "while" "until"))
520 (if (save-excursion (forward-word -1) (ruby-smie--bosp))
521 tok "iuwu-mod"))
522 ((string-match-p "\\`|[*&]?\\'" tok)
523 (forward-char (- 1 (length tok)))
524 (setq tok "|")
525 (cond
526 ((ruby-smie--opening-pipe-p) "opening-|")
527 ((ruby-smie--closing-pipe-p) "closing-|")
528 (t tok)))
529 ((and (equal tok "") (looking-at "\\\\\n"))
530 (goto-char (match-end 0)) (ruby-smie--forward-token))
531 ((equal tok "do")
532 (cond
533 ((not (ruby-smie--redundant-do-p 'skip)) tok)
534 ((> (save-excursion (forward-comment (point-max)) (point))
535 (line-end-position))
536 (ruby-smie--forward-token)) ;Fully redundant.
537 (t ";")))
538 (t tok)))))))))
539
540 (defun ruby-smie--backward-token ()
541 (let ((pos (point)))
542 (forward-comment (- (point)))
543 (cond
544 ((and (> pos (line-end-position)) (ruby-smie--implicit-semi-p))
545 (skip-chars-forward " \t") ";")
546 ((and (bolp) (not (bobp))) ;Presumably a heredoc.
547 ;; Tokenize the whole heredoc as semicolon.
548 (goto-char (scan-sexps (point) -1))
549 ";")
550 ((and (> pos (point)) (not (bolp))
551 (ruby-smie--args-separator-p pos))
552 ;; We have "ID SPC ID", which is a method call, but it binds less tightly
553 ;; than commas, since a method call can also be "ID ARG1, ARG2, ARG3".
554 ;; In some textbooks, "e1 @ e2" is used to mean "call e1 with arg e2".
555 " @ ")
556 (t
557 (let ((tok (smie-default-backward-token))
558 (dot (ruby-smie--at-dot-call)))
559 (when dot
560 (setq tok (concat "." tok)))
561 (when (and (eq ?: (char-before)) (string-match "\\`\\s." tok))
562 (forward-char -1) (setq tok (concat ":" tok))) ;; bug#15208.
563 (cond
564 ((member tok '("unless" "if" "while" "until"))
565 (if (ruby-smie--bosp)
566 tok "iuwu-mod"))
567 ((equal tok "|")
568 (cond
569 ((ruby-smie--opening-pipe-p) "opening-|")
570 ((ruby-smie--closing-pipe-p) "closing-|")
571 (t tok)))
572 ((string-match-p "\\`|[*&]\\'" tok)
573 (forward-char 1)
574 (substring tok 1))
575 ((and (equal tok "") (eq ?\\ (char-before)) (looking-at "\n"))
576 (forward-char -1) (ruby-smie--backward-token))
577 ((equal tok "do")
578 (cond
579 ((not (ruby-smie--redundant-do-p)) tok)
580 ((> (save-excursion (forward-word 1)
581 (forward-comment (point-max)) (point))
582 (line-end-position))
583 (ruby-smie--backward-token)) ;Fully redundant.
584 (t ";")))
585 (t tok)))))))
586
587 (defun ruby-smie--indent-to-stmt ()
588 (save-excursion
589 (smie-backward-sexp ";")
590 (cons 'column (smie-indent-virtual))))
591
592 (defun ruby-smie--indent-to-stmt-p (keyword)
593 (or (eq t ruby-align-to-stmt-keywords)
594 (memq (intern keyword) ruby-align-to-stmt-keywords)))
595
596 (defun ruby-smie-rules (kind token)
597 (pcase (cons kind token)
598 (`(:elem . basic) ruby-indent-level)
599 ;; "foo" "bar" is the concatenation of the two strings, so the second
600 ;; should be aligned with the first.
601 (`(:elem . args) (if (looking-at "\\s\"") 0))
602 ;; (`(:after . ",") (smie-rule-separator kind))
603 (`(:before . ";")
604 (cond
605 ((smie-rule-parent-p "def" "begin" "do" "class" "module" "for"
606 "while" "until" "unless"
607 "if" "then" "elsif" "else" "when"
608 "rescue" "ensure" "{")
609 (smie-rule-parent ruby-indent-level))
610 ;; For (invalid) code between switch and case.
611 ;; (if (smie-parent-p "switch") 4)
612 ))
613 (`(:before . ,(or `"(" `"[" `"{"))
614 (cond
615 ((and (equal token "{")
616 (not (smie-rule-prev-p "(" "{" "[" "," "=>" "=" "return" ";"))
617 (save-excursion
618 (forward-comment -1)
619 (not (eq (preceding-char) ?:))))
620 ;; Curly block opener.
621 (ruby-smie--indent-to-stmt))
622 ((smie-rule-hanging-p)
623 ;; Treat purely syntactic block-constructs as being part of their parent,
624 ;; when the opening token is hanging and the parent is not an
625 ;; open-paren.
626 (cond
627 ((eq (car (smie-indent--parent)) t) nil)
628 ;; When after `.', let's always de-indent,
629 ;; because when `.' is inside the line, the
630 ;; additional indentation from it looks out of place.
631 ((smie-rule-parent-p ".")
632 (let (smie--parent)
633 (save-excursion
634 ;; Traverse up the parents until the parent is "." at
635 ;; indentation, or any other token.
636 (while (and (let ((parent (smie-indent--parent)))
637 (goto-char (cadr parent))
638 (save-excursion
639 (unless (integerp (car parent)) (forward-char -1))
640 (not (ruby-smie--bosp))))
641 (progn
642 (setq smie--parent nil)
643 (smie-rule-parent-p "."))))
644 (smie-rule-parent))))
645 (t (smie-rule-parent))))))
646 (`(:after . ,(or `"(" "[" "{"))
647 ;; FIXME: Shouldn't this be the default behavior of
648 ;; `smie-indent-after-keyword'?
649 (save-excursion
650 (forward-char 1)
651 (skip-chars-forward " \t")
652 ;; `smie-rule-hanging-p' is not good enough here,
653 ;; because we want to reject hanging tokens at bol, too.
654 (unless (or (eolp) (forward-comment 1))
655 (cons 'column (current-column)))))
656 (`(:before . " @ ")
657 (save-excursion
658 (skip-chars-forward " \t")
659 (cons 'column (current-column))))
660 (`(:before . "do") (ruby-smie--indent-to-stmt))
661 (`(:before . ".")
662 (if (smie-rule-sibling-p)
663 (and ruby-align-chained-calls 0)
664 ruby-indent-level))
665 (`(:before . ,(or `"else" `"then" `"elsif" `"rescue" `"ensure"))
666 (smie-rule-parent))
667 (`(:before . "when")
668 ;; Align to the previous `when', but look up the virtual
669 ;; indentation of `case'.
670 (if (smie-rule-sibling-p) 0 (smie-rule-parent)))
671 (`(:after . ,(or "=" "iuwu-mod" "+" "-" "*" "/" "&&" "||" "%" "**" "^" "&"
672 "<=>" ">" "<" ">=" "<=" "==" "===" "!=" "<<" ">>"
673 "+=" "-=" "*=" "/=" "%=" "**=" "&=" "|=" "^=" "|"
674 "<<=" ">>=" "&&=" "||=" "and" "or"))
675 (and (smie-rule-parent-p ";" nil)
676 (smie-indent--hanging-p)
677 ruby-indent-level))
678 (`(:after . ,(or "?" ":")) ruby-indent-level)
679 (`(:before . ,(guard (memq (intern-soft token) ruby-alignable-keywords)))
680 (when (not (ruby--at-indentation-p))
681 (if (ruby-smie--indent-to-stmt-p token)
682 (ruby-smie--indent-to-stmt)
683 (cons 'column (current-column)))))
684 ))
685
686 (defun ruby--at-indentation-p (&optional point)
687 (save-excursion
688 (unless point (setq point (point)))
689 (forward-line 0)
690 (skip-chars-forward " \t")
691 (eq (point) point)))
692
693 (defun ruby-imenu-create-index-in-block (prefix beg end)
694 "Create an imenu index of methods inside a block."
695 (let ((index-alist '()) (case-fold-search nil)
696 name next pos decl sing)
697 (goto-char beg)
698 (while (re-search-forward "^\\s *\\(\\(class\\s +\\|\\(class\\s *<<\\s *\\)\\|module\\s +\\)\\([^\(<\n ]+\\)\\|\\(def\\|alias\\)\\s +\\([^\(\n ]+\\)\\)" end t)
699 (setq sing (match-beginning 3))
700 (setq decl (match-string 5))
701 (setq next (match-end 0))
702 (setq name (or (match-string 4) (match-string 6)))
703 (setq pos (match-beginning 0))
704 (cond
705 ((string= "alias" decl)
706 (if prefix (setq name (concat prefix name)))
707 (push (cons name pos) index-alist))
708 ((string= "def" decl)
709 (if prefix
710 (setq name
711 (cond
712 ((string-match "^self\." name)
713 (concat (substring prefix 0 -1) (substring name 4)))
714 (t (concat prefix name)))))
715 (push (cons name pos) index-alist)
716 (ruby-accurate-end-of-block end))
717 (t
718 (if (string= "self" name)
719 (if prefix (setq name (substring prefix 0 -1)))
720 (if prefix (setq name (concat (substring prefix 0 -1) "::" name)))
721 (push (cons name pos) index-alist))
722 (ruby-accurate-end-of-block end)
723 (setq beg (point))
724 (setq index-alist
725 (nconc (ruby-imenu-create-index-in-block
726 (concat name (if sing "." "#"))
727 next beg) index-alist))
728 (goto-char beg))))
729 index-alist))
730
731 (defun ruby-imenu-create-index ()
732 "Create an imenu index of all methods in the buffer."
733 (nreverse (ruby-imenu-create-index-in-block nil (point-min) nil)))
734
735 (defun ruby-accurate-end-of-block (&optional end)
736 "Jump to the end of the current block or END, whichever is closer."
737 (let (state
738 (end (or end (point-max))))
739 (if ruby-use-smie
740 (save-restriction
741 (back-to-indentation)
742 (narrow-to-region (point) end)
743 (smie-forward-sexp))
744 (while (and (setq state (apply 'ruby-parse-partial end state))
745 (>= (nth 2 state) 0) (< (point) end))))))
746
747 (defun ruby-mode-variables ()
748 "Set up initial buffer-local variables for Ruby mode."
749 (setq indent-tabs-mode ruby-indent-tabs-mode)
750 (if ruby-use-smie
751 (smie-setup ruby-smie-grammar #'ruby-smie-rules
752 :forward-token #'ruby-smie--forward-token
753 :backward-token #'ruby-smie--backward-token)
754 (setq-local indent-line-function 'ruby-indent-line))
755 (setq-local comment-start "# ")
756 (setq-local comment-end "")
757 (setq-local comment-column ruby-comment-column)
758 (setq-local comment-start-skip "#+ *")
759 (setq-local parse-sexp-ignore-comments t)
760 (setq-local parse-sexp-lookup-properties t)
761 (setq-local paragraph-start (concat "$\\|" page-delimiter))
762 (setq-local paragraph-separate paragraph-start)
763 (setq-local paragraph-ignore-fill-prefix t))
764
765 (defun ruby--insert-coding-comment (encoding)
766 "Insert a magic coding comment for ENCODING.
767 The style of the comment is controlled by `ruby-encoding-magic-comment-style'."
768 (let ((encoding-magic-comment-template
769 (pcase ruby-encoding-magic-comment-style
770 (`ruby "# coding: %s")
771 (`emacs "# -*- coding: %s -*-")
772 (`custom
773 ruby-custom-encoding-magic-comment-template))))
774 (insert
775 (format encoding-magic-comment-template encoding)
776 "\n")))
777
778 (defun ruby--detect-encoding ()
779 (if (eq ruby-insert-encoding-magic-comment 'always-utf8)
780 "utf-8"
781 (let ((coding-system
782 (or save-buffer-coding-system
783 buffer-file-coding-system)))
784 (if coding-system
785 (setq coding-system
786 (or (coding-system-get coding-system 'mime-charset)
787 (coding-system-change-eol-conversion coding-system nil))))
788 (if coding-system
789 (symbol-name
790 (if ruby-use-encoding-map
791 (let ((elt (assq coding-system ruby-encoding-map)))
792 (if elt (cdr elt) coding-system))
793 coding-system))
794 "ascii-8bit"))))
795
796 (defun ruby--encoding-comment-required-p ()
797 (or (eq ruby-insert-encoding-magic-comment 'always-utf8)
798 (re-search-forward "[^\0-\177]" nil t)))
799
800 (defun ruby-mode-set-encoding ()
801 "Insert a magic comment header with the proper encoding if necessary."
802 (save-excursion
803 (widen)
804 (goto-char (point-min))
805 (when (ruby--encoding-comment-required-p)
806 (goto-char (point-min))
807 (let ((coding-system (ruby--detect-encoding)))
808 (when coding-system
809 (if (looking-at "^#!") (beginning-of-line 2))
810 (cond ((looking-at "\\s *#\\s *.*\\(en\\)?coding\\s *:\\s *\\([-a-z0-9_]*\\)")
811 ;; update existing encoding comment if necessary
812 (unless (string= (match-string 2) coding-system)
813 (goto-char (match-beginning 2))
814 (delete-region (point) (match-end 2))
815 (insert coding-system)))
816 ((looking-at "\\s *#.*coding\\s *[:=]"))
817 (t (when ruby-insert-encoding-magic-comment
818 (ruby--insert-coding-comment coding-system))))
819 (when (buffer-modified-p)
820 (basic-save-buffer-1)))))))
821
822 (defvar ruby--electric-indent-chars '(?. ?\) ?} ?\]))
823
824 (defun ruby--electric-indent-p (char)
825 (cond
826 ((memq char ruby--electric-indent-chars)
827 ;; Reindent after typing a char affecting indentation.
828 (ruby--at-indentation-p (1- (point))))
829 ((memq (char-after) ruby--electric-indent-chars)
830 ;; Reindent after inserting something in front of the above.
831 (ruby--at-indentation-p (1- (point))))
832 ((or (and (>= char ?a) (<= char ?z)) (memq char '(?_ ?? ?! ?:)))
833 (let ((pt (point)))
834 (save-excursion
835 (skip-chars-backward "[:alpha:]:_?!")
836 (and (ruby--at-indentation-p)
837 (looking-at (regexp-opt (cons "end" ruby-block-mid-keywords)))
838 ;; Outdent after typing a keyword.
839 (or (eq (match-end 0) pt)
840 ;; Reindent if it wasn't a keyword after all.
841 (eq (match-end 0) (1- pt)))))))))
842
843 ;; FIXME: Remove this? It's unused here, but some redefinitions of
844 ;; `ruby-calculate-indent' in user init files still call it.
845 (defun ruby-current-indentation ()
846 "Return the indentation level of current line."
847 (save-excursion
848 (beginning-of-line)
849 (back-to-indentation)
850 (current-column)))
851
852 (defun ruby-indent-line (&optional ignored)
853 "Correct the indentation of the current Ruby line."
854 (interactive)
855 (ruby-indent-to (ruby-calculate-indent)))
856
857 (defun ruby-indent-to (column)
858 "Indent the current line to COLUMN."
859 (when column
860 (let (shift top beg)
861 (and (< column 0) (error "Invalid nesting"))
862 (setq shift (current-column))
863 (beginning-of-line)
864 (setq beg (point))
865 (back-to-indentation)
866 (setq top (current-column))
867 (skip-chars-backward " \t")
868 (if (>= shift top) (setq shift (- shift top))
869 (setq shift 0))
870 (if (and (bolp)
871 (= column top))
872 (move-to-column (+ column shift))
873 (move-to-column top)
874 (delete-region beg (point))
875 (beginning-of-line)
876 (indent-to column)
877 (move-to-column (+ column shift))))))
878
879 (defun ruby-special-char-p (&optional pos)
880 "Return t if the character before POS is a special character.
881 If omitted, POS defaults to the current point.
882 Special characters are `?', `$', `:' when preceded by whitespace,
883 and `\\' when preceded by `?'."
884 (setq pos (or pos (point)))
885 (let ((c (char-before pos)) (b (and (< (point-min) pos)
886 (char-before (1- pos)))))
887 (cond ((or (eq c ??) (eq c ?$)))
888 ((and (eq c ?:) (or (not b) (eq (char-syntax b) ? ))))
889 ((eq c ?\\) (eq b ??)))))
890
891 (defun ruby-singleton-class-p (&optional pos)
892 (save-excursion
893 (when pos (goto-char pos))
894 (forward-word -1)
895 (and (or (bolp) (not (eq (char-before (point)) ?_)))
896 (looking-at ruby-singleton-class-re))))
897
898 (defun ruby-expr-beg (&optional option)
899 "Check if point is possibly at the beginning of an expression.
900 OPTION specifies the type of the expression.
901 Can be one of `heredoc', `modifier', `expr-qstr', `expr-re'."
902 (save-excursion
903 (store-match-data nil)
904 (let ((space (skip-chars-backward " \t"))
905 (start (point)))
906 (cond
907 ((bolp) t)
908 ((progn
909 (forward-char -1)
910 (and (looking-at "\\?")
911 (or (eq (char-syntax (char-before (point))) ?w)
912 (ruby-special-char-p))))
913 nil)
914 ((looking-at ruby-operator-re))
915 ((eq option 'heredoc)
916 (and (< space 0) (not (ruby-singleton-class-p start))))
917 ((or (looking-at "[\\[({,;]")
918 (and (looking-at "[!?]")
919 (or (not (eq option 'modifier))
920 (bolp)
921 (save-excursion (forward-char -1) (looking-at "\\Sw$"))))
922 (and (looking-at ruby-symbol-re)
923 (skip-chars-backward ruby-symbol-chars)
924 (cond
925 ((looking-at (regexp-opt
926 (append ruby-block-beg-keywords
927 ruby-block-op-keywords
928 ruby-block-mid-keywords)
929 'words))
930 (goto-char (match-end 0))
931 (not (looking-at "\\s_")))
932 ((eq option 'expr-qstr)
933 (looking-at "[a-zA-Z][a-zA-z0-9_]* +%[^ \t]"))
934 ((eq option 'expr-re)
935 (looking-at "[a-zA-Z][a-zA-z0-9_]* +/[^ \t]"))
936 (t nil)))))))))
937
938 (defun ruby-forward-string (term &optional end no-error expand)
939 "Move forward across one balanced pair of string delimiters.
940 Skips escaped delimiters. If EXPAND is non-nil, also ignores
941 delimiters in interpolated strings.
942
943 TERM should be a string containing either a single, self-matching
944 delimiter (e.g. \"/\"), or a pair of matching delimiters with the
945 close delimiter first (e.g. \"][\").
946
947 When non-nil, search is bounded by position END.
948
949 Throws an error if a balanced match is not found, unless NO-ERROR
950 is non-nil, in which case nil will be returned.
951
952 This command assumes the character after point is an opening
953 delimiter."
954 (let ((n 1) (c (string-to-char term))
955 (re (concat "[^\\]\\(\\\\\\\\\\)*\\("
956 (if (string= term "^") ;[^] is not a valid regexp
957 "\\^"
958 (concat "[" term "]"))
959 (when expand "\\|\\(#{\\)")
960 "\\)")))
961 (while (and (re-search-forward re end no-error)
962 (if (match-beginning 3)
963 (ruby-forward-string "}{" end no-error nil)
964 (> (setq n (if (eq (char-before (point)) c)
965 (1- n) (1+ n))) 0)))
966 (forward-char -1))
967 (cond ((zerop n))
968 (no-error nil)
969 ((error "Unterminated string")))))
970
971 (defun ruby-deep-indent-paren-p (c)
972 "TODO: document."
973 (cond ((listp ruby-deep-indent-paren)
974 (let ((deep (assoc c ruby-deep-indent-paren)))
975 (cond (deep
976 (or (cdr deep) ruby-deep-indent-paren-style))
977 ((memq c ruby-deep-indent-paren)
978 ruby-deep-indent-paren-style))))
979 ((eq c ruby-deep-indent-paren) ruby-deep-indent-paren-style)
980 ((eq c ?\( ) ruby-deep-arglist)))
981
982 (defun ruby-parse-partial (&optional end in-string nest depth pcol indent)
983 "TODO: document throughout function body."
984 (or depth (setq depth 0))
985 (or indent (setq indent 0))
986 (when (re-search-forward ruby-delimiter end 'move)
987 (let ((pnt (point)) w re expand)
988 (goto-char (match-beginning 0))
989 (cond
990 ((and (memq (char-before) '(?@ ?$)) (looking-at "\\sw"))
991 (goto-char pnt))
992 ((looking-at "[\"`]") ;skip string
993 (cond
994 ((and (not (eobp))
995 (ruby-forward-string (buffer-substring (point) (1+ (point)))
996 end t t))
997 nil)
998 (t
999 (setq in-string (point))
1000 (goto-char end))))
1001 ((looking-at "'")
1002 (cond
1003 ((and (not (eobp))
1004 (re-search-forward "[^\\]\\(\\\\\\\\\\)*'" end t))
1005 nil)
1006 (t
1007 (setq in-string (point))
1008 (goto-char end))))
1009 ((looking-at "/=")
1010 (goto-char pnt))
1011 ((looking-at "/")
1012 (cond
1013 ((and (not (eobp)) (ruby-expr-beg 'expr-re))
1014 (if (ruby-forward-string "/" end t t)
1015 nil
1016 (setq in-string (point))
1017 (goto-char end)))
1018 (t
1019 (goto-char pnt))))
1020 ((looking-at "%")
1021 (cond
1022 ((and (not (eobp))
1023 (ruby-expr-beg 'expr-qstr)
1024 (not (looking-at "%="))
1025 (looking-at "%[QqrxWw]?\\([^a-zA-Z0-9 \t\n]\\)"))
1026 (goto-char (match-beginning 1))
1027 (setq expand (not (memq (char-before) '(?q ?w))))
1028 (setq w (match-string 1))
1029 (cond
1030 ((string= w "[") (setq re "]["))
1031 ((string= w "{") (setq re "}{"))
1032 ((string= w "(") (setq re ")("))
1033 ((string= w "<") (setq re "><"))
1034 ((and expand (string= w "\\"))
1035 (setq w (concat "\\" w))))
1036 (unless (cond (re (ruby-forward-string re end t expand))
1037 (expand (ruby-forward-string w end t t))
1038 (t (re-search-forward
1039 (if (string= w "\\")
1040 "\\\\[^\\]*\\\\"
1041 (concat "[^\\]\\(\\\\\\\\\\)*" w))
1042 end t)))
1043 (setq in-string (point))
1044 (goto-char end)))
1045 (t
1046 (goto-char pnt))))
1047 ((looking-at "\\?") ;skip ?char
1048 (cond
1049 ((and (ruby-expr-beg)
1050 (looking-at "?\\(\\\\C-\\|\\\\M-\\)*\\\\?."))
1051 (goto-char (match-end 0)))
1052 (t
1053 (goto-char pnt))))
1054 ((looking-at "\\$") ;skip $char
1055 (goto-char pnt)
1056 (forward-char 1))
1057 ((looking-at "#") ;skip comment
1058 (forward-line 1)
1059 (goto-char (point))
1060 )
1061 ((looking-at "[\\[{(]")
1062 (let ((deep (ruby-deep-indent-paren-p (char-after))))
1063 (if (and deep (or (not (eq (char-after) ?\{)) (ruby-expr-beg)))
1064 (progn
1065 (and (eq deep 'space) (looking-at ".\\s +[^# \t\n]")
1066 (setq pnt (1- (match-end 0))))
1067 (setq nest (cons (cons (char-after (point)) pnt) nest))
1068 (setq pcol (cons (cons pnt depth) pcol))
1069 (setq depth 0))
1070 (setq nest (cons (cons (char-after (point)) pnt) nest))
1071 (setq depth (1+ depth))))
1072 (goto-char pnt)
1073 )
1074 ((looking-at "[])}]")
1075 (if (ruby-deep-indent-paren-p (matching-paren (char-after)))
1076 (setq depth (cdr (car pcol)) pcol (cdr pcol))
1077 (setq depth (1- depth)))
1078 (setq nest (cdr nest))
1079 (goto-char pnt))
1080 ((looking-at ruby-block-end-re)
1081 (if (or (and (not (bolp))
1082 (progn
1083 (forward-char -1)
1084 (setq w (char-after (point)))
1085 (or (eq ?_ w)
1086 (eq ?. w))))
1087 (progn
1088 (goto-char pnt)
1089 (setq w (char-after (point)))
1090 (or (eq ?_ w)
1091 (eq ?! w)
1092 (eq ?? w))))
1093 nil
1094 (setq nest (cdr nest))
1095 (setq depth (1- depth)))
1096 (goto-char pnt))
1097 ((looking-at "def\\s +[^(\n;]*")
1098 (if (or (bolp)
1099 (progn
1100 (forward-char -1)
1101 (not (eq ?_ (char-after (point))))))
1102 (progn
1103 (setq nest (cons (cons nil pnt) nest))
1104 (setq depth (1+ depth))))
1105 (goto-char (match-end 0)))
1106 ((looking-at (concat "\\_<\\(" ruby-block-beg-re "\\)\\_>"))
1107 (and
1108 (save-match-data
1109 (or (not (looking-at "do\\_>"))
1110 (save-excursion
1111 (back-to-indentation)
1112 (not (looking-at ruby-non-block-do-re)))))
1113 (or (bolp)
1114 (progn
1115 (forward-char -1)
1116 (setq w (char-after (point)))
1117 (not (or (eq ?_ w)
1118 (eq ?. w)))))
1119 (goto-char pnt)
1120 (not (eq ?! (char-after (point))))
1121 (skip-chars-forward " \t")
1122 (goto-char (match-beginning 0))
1123 (or (not (looking-at ruby-modifier-re))
1124 (ruby-expr-beg 'modifier))
1125 (goto-char pnt)
1126 (setq nest (cons (cons nil pnt) nest))
1127 (setq depth (1+ depth)))
1128 (goto-char pnt))
1129 ((looking-at ":\\(['\"]\\)")
1130 (goto-char (match-beginning 1))
1131 (ruby-forward-string (match-string 1) end t))
1132 ((looking-at ":\\([-,.+*/%&|^~<>]=?\\|===?\\|<=>\\|![~=]?\\)")
1133 (goto-char (match-end 0)))
1134 ((looking-at ":\\([a-zA-Z_][a-zA-Z_0-9]*[!?=]?\\)?")
1135 (goto-char (match-end 0)))
1136 ((or (looking-at "\\.\\.\\.?")
1137 (looking-at "\\.[0-9]+")
1138 (looking-at "\\.[a-zA-Z_0-9]+")
1139 (looking-at "\\."))
1140 (goto-char (match-end 0)))
1141 ((looking-at "^=begin")
1142 (if (re-search-forward "^=end" end t)
1143 (forward-line 1)
1144 (setq in-string (match-end 0))
1145 (goto-char end)))
1146 ((looking-at "<<")
1147 (cond
1148 ((and (ruby-expr-beg 'heredoc)
1149 (looking-at "<<\\(-\\)?\\(\\([\"'`]\\)\\([^\n]+?\\)\\3\\|\\(?:\\sw\\|\\s_\\)+\\)"))
1150 (setq re (regexp-quote (or (match-string 4) (match-string 2))))
1151 (if (match-beginning 1) (setq re (concat "\\s *" re)))
1152 (let* ((id-end (goto-char (match-end 0)))
1153 (line-end-position (point-at-eol))
1154 (state (list in-string nest depth pcol indent)))
1155 ;; parse the rest of the line
1156 (while (and (> line-end-position (point))
1157 (setq state (apply 'ruby-parse-partial
1158 line-end-position state))))
1159 (setq in-string (car state)
1160 nest (nth 1 state)
1161 depth (nth 2 state)
1162 pcol (nth 3 state)
1163 indent (nth 4 state))
1164 ;; skip heredoc section
1165 (if (re-search-forward (concat "^" re "$") end 'move)
1166 (forward-line 1)
1167 (setq in-string id-end)
1168 (goto-char end))))
1169 (t
1170 (goto-char pnt))))
1171 ((looking-at "^__END__$")
1172 (goto-char pnt))
1173 ((and (looking-at ruby-here-doc-beg-re)
1174 (boundp 'ruby-indent-point))
1175 (if (re-search-forward (ruby-here-doc-end-match)
1176 ruby-indent-point t)
1177 (forward-line 1)
1178 (setq in-string (match-end 0))
1179 (goto-char ruby-indent-point)))
1180 (t
1181 (error (format "Bad string %s"
1182 (buffer-substring (point) pnt)
1183 ))))))
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 -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 -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 -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 (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-function (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 ;; Regular expressions. Start with matching unescaped slash.
1861 ("\\(?:\\=\\|[^\\]\\)\\(?:\\\\\\\\\\)*\\(/\\)"
1862 (1 (let ((state (save-excursion (syntax-ppss (match-beginning 1)))))
1863 (when (or
1864 ;; Beginning of a regexp.
1865 (and (null (nth 8 state))
1866 (save-excursion
1867 (forward-char -1)
1868 (looking-back ruby-syntax-before-regexp-re
1869 (point-at-bol))))
1870 ;; End of regexp. We don't match the whole
1871 ;; regexp at once because it can have
1872 ;; string interpolation inside, or span
1873 ;; several lines.
1874 (eq ?/ (nth 3 state)))
1875 (string-to-syntax "\"/")))))
1876 ;; Expression expansions in strings. We're handling them
1877 ;; here, so that the regexp rule never matches inside them.
1878 (ruby-expression-expansion-re
1879 (0 (ignore (ruby-syntax-propertize-expansion))))
1880 ("^=en\\(d\\)\\_>" (1 "!"))
1881 ("^\\(=\\)begin\\_>" (1 "!"))
1882 ;; Handle here documents.
1883 ((concat ruby-here-doc-beg-re ".*\\(\n\\)")
1884 (7 (unless (or (nth 8 (save-excursion
1885 (syntax-ppss (match-beginning 0))))
1886 (ruby-singleton-class-p (match-beginning 0)))
1887 (put-text-property (match-beginning 7) (match-end 7)
1888 'syntax-table (string-to-syntax "\""))
1889 (ruby-syntax-propertize-heredoc end))))
1890 ;; Handle percent literals: %w(), %q{}, etc.
1891 ((concat "\\(?:^\\|[[ \t\n<+(,=]\\)" ruby-percent-literal-beg-re)
1892 (1 (prog1 "|" (ruby-syntax-propertize-percent-literal end)))))
1893 (point) end)))
1894
1895 (defun ruby-syntax-propertize-heredoc (limit)
1896 (let ((ppss (syntax-ppss))
1897 (res '()))
1898 (when (eq ?\n (nth 3 ppss))
1899 (save-excursion
1900 (goto-char (nth 8 ppss))
1901 (beginning-of-line)
1902 (while (re-search-forward ruby-here-doc-beg-re
1903 (line-end-position) t)
1904 (unless (ruby-singleton-class-p (match-beginning 0))
1905 (push (concat (ruby-here-doc-end-match) "\n") res))))
1906 (save-excursion
1907 ;; With multiple openers on the same line, we don't know in which
1908 ;; part `start' is, so we have to go back to the beginning.
1909 (when (cdr res)
1910 (goto-char (nth 8 ppss))
1911 (setq res (nreverse res)))
1912 (while (and res (re-search-forward (pop res) limit 'move))
1913 (if (null res)
1914 (put-text-property (1- (point)) (point)
1915 'syntax-table (string-to-syntax "\""))))
1916 ;; End up at bol following the heredoc openers.
1917 ;; Propertize expression expansions from this point forward.
1918 ))))
1919
1920 (defun ruby-syntax-enclosing-percent-literal (limit)
1921 (let ((state (syntax-ppss))
1922 (start (point)))
1923 ;; When already inside percent literal, re-propertize it.
1924 (when (eq t (nth 3 state))
1925 (goto-char (nth 8 state))
1926 (when (looking-at ruby-percent-literal-beg-re)
1927 (ruby-syntax-propertize-percent-literal limit))
1928 (when (< (point) start) (goto-char start)))))
1929
1930 (defun ruby-syntax-propertize-percent-literal (limit)
1931 (goto-char (match-beginning 2))
1932 ;; Not inside a simple string or comment.
1933 (when (eq t (nth 3 (syntax-ppss)))
1934 (let* ((op (char-after))
1935 (ops (char-to-string op))
1936 (cl (or (cdr (aref (syntax-table) op))
1937 (cdr (assoc op '((?< . ?>))))))
1938 parse-sexp-lookup-properties)
1939 (save-excursion
1940 (condition-case nil
1941 (progn
1942 (if cl ; Paired delimiters.
1943 ;; Delimiter pairs of the same kind can be nested
1944 ;; inside the literal, as long as they are balanced.
1945 ;; Create syntax table that ignores other characters.
1946 (with-syntax-table (make-char-table 'syntax-table nil)
1947 (modify-syntax-entry op (concat "(" (char-to-string cl)))
1948 (modify-syntax-entry cl (concat ")" ops))
1949 (modify-syntax-entry ?\\ "\\")
1950 (save-restriction
1951 (narrow-to-region (point) limit)
1952 (forward-list))) ; skip to the paired character
1953 ;; Single character delimiter.
1954 (re-search-forward (concat "[^\\]\\(?:\\\\\\\\\\)*"
1955 (regexp-quote ops)) limit nil))
1956 ;; Found the closing delimiter.
1957 (put-text-property (1- (point)) (point) 'syntax-table
1958 (string-to-syntax "|")))
1959 ;; Unclosed literal, do nothing.
1960 ((scan-error search-failed)))))))
1961
1962 (defun ruby-syntax-propertize-expansion ()
1963 ;; Save the match data to a text property, for font-locking later.
1964 ;; Set the syntax of all double quotes and backticks to punctuation.
1965 (let* ((beg (match-beginning 2))
1966 (end (match-end 2))
1967 (state (and beg (save-excursion (syntax-ppss beg)))))
1968 (when (ruby-syntax-expansion-allowed-p state)
1969 (put-text-property beg (1+ beg) 'ruby-expansion-match-data
1970 (match-data))
1971 (goto-char beg)
1972 (while (re-search-forward "[\"`]" end 'move)
1973 (put-text-property (match-beginning 0) (match-end 0)
1974 'syntax-table (string-to-syntax "."))))))
1975
1976 (defun ruby-syntax-expansion-allowed-p (parse-state)
1977 "Return non-nil if expression expansion is allowed."
1978 (let ((term (nth 3 parse-state)))
1979 (cond
1980 ((memq term '(?\" ?` ?\n ?/)))
1981 ((eq term t)
1982 (save-match-data
1983 (save-excursion
1984 (goto-char (nth 8 parse-state))
1985 (looking-at "%\\(?:[QWrxI]\\|\\W\\)")))))))
1986
1987 (defun ruby-syntax-propertize-expansions (start end)
1988 (save-excursion
1989 (goto-char start)
1990 (while (re-search-forward ruby-expression-expansion-re end 'move)
1991 (ruby-syntax-propertize-expansion))))
1992
1993 (defun ruby-in-ppss-context-p (context &optional ppss)
1994 (let ((ppss (or ppss (syntax-ppss (point)))))
1995 (if (cond
1996 ((eq context 'anything)
1997 (or (nth 3 ppss)
1998 (nth 4 ppss)))
1999 ((eq context 'string)
2000 (nth 3 ppss))
2001 ((eq context 'heredoc)
2002 (eq ?\n (nth 3 ppss)))
2003 ((eq context 'non-heredoc)
2004 (and (ruby-in-ppss-context-p 'anything)
2005 (not (ruby-in-ppss-context-p 'heredoc))))
2006 ((eq context 'comment)
2007 (nth 4 ppss))
2008 (t
2009 (error (concat
2010 "Internal error on `ruby-in-ppss-context-p': "
2011 "context name `" (symbol-name context) "' is unknown"))))
2012 t)))
2013
2014 (defvar ruby-font-lock-syntax-table
2015 (let ((tbl (copy-syntax-table ruby-mode-syntax-table)))
2016 (modify-syntax-entry ?_ "w" tbl)
2017 tbl)
2018 "The syntax table to use for fontifying Ruby mode buffers.
2019 See `font-lock-syntax-table'.")
2020
2021 (defconst ruby-font-lock-keyword-beg-re "\\(?:^\\|[^.@$]\\|\\.\\.\\)")
2022
2023 (defconst ruby-font-lock-keywords
2024 `(;; Functions.
2025 ("^\\s *def\\s +\\(?:[^( \t\n.]*\\.\\)?\\([^( \t\n]+\\)"
2026 1 font-lock-function-name-face)
2027 ;; Keywords.
2028 (,(concat
2029 ruby-font-lock-keyword-beg-re
2030 (regexp-opt
2031 '("alias"
2032 "and"
2033 "begin"
2034 "break"
2035 "case"
2036 "class"
2037 "def"
2038 "defined?"
2039 "do"
2040 "elsif"
2041 "else"
2042 "fail"
2043 "ensure"
2044 "for"
2045 "end"
2046 "if"
2047 "in"
2048 "module"
2049 "next"
2050 "not"
2051 "or"
2052 "redo"
2053 "rescue"
2054 "retry"
2055 "return"
2056 "then"
2057 "super"
2058 "unless"
2059 "undef"
2060 "until"
2061 "when"
2062 "while"
2063 "yield")
2064 'symbols))
2065 (1 font-lock-keyword-face))
2066 ;; Core methods that have required arguments.
2067 (,(concat
2068 ruby-font-lock-keyword-beg-re
2069 (regexp-opt
2070 '( ;; built-in methods on Kernel
2071 "at_exit"
2072 "autoload"
2073 "autoload?"
2074 "catch"
2075 "eval"
2076 "exec"
2077 "fork"
2078 "format"
2079 "lambda"
2080 "load"
2081 "loop"
2082 "open"
2083 "p"
2084 "print"
2085 "printf"
2086 "proc"
2087 "putc"
2088 "puts"
2089 "require"
2090 "require_relative"
2091 "spawn"
2092 "sprintf"
2093 "syscall"
2094 "system"
2095 "trap"
2096 "warn"
2097 ;; keyword-like private methods on Module
2098 "alias_method"
2099 "attr"
2100 "attr_accessor"
2101 "attr_reader"
2102 "attr_writer"
2103 "define_method"
2104 "extend"
2105 "include"
2106 "module_function"
2107 "prepend"
2108 "private_class_method"
2109 "private_constant"
2110 "public_class_method"
2111 "public_constant"
2112 "refine"
2113 "using")
2114 'symbols))
2115 (1 (unless (looking-at " *\\(?:[]|,.)}=]\\|$\\)")
2116 font-lock-builtin-face)))
2117 ;; Kernel methods that have no required arguments.
2118 (,(concat
2119 ruby-font-lock-keyword-beg-re
2120 (regexp-opt
2121 '("__callee__"
2122 "__dir__"
2123 "__method__"
2124 "abort"
2125 "at_exit"
2126 "binding"
2127 "block_given?"
2128 "caller"
2129 "exit"
2130 "exit!"
2131 "fail"
2132 "private"
2133 "protected"
2134 "public"
2135 "raise"
2136 "rand"
2137 "readline"
2138 "readlines"
2139 "sleep"
2140 "srand"
2141 "throw")
2142 'symbols))
2143 (1 font-lock-builtin-face))
2144 ;; Here-doc beginnings.
2145 (,ruby-here-doc-beg-re
2146 (0 (unless (ruby-singleton-class-p (match-beginning 0))
2147 'font-lock-string-face)))
2148 ;; Perl-ish keywords.
2149 "\\_<\\(?:BEGIN\\|END\\)\\_>\\|^__END__$"
2150 ;; Variables.
2151 (,(concat ruby-font-lock-keyword-beg-re
2152 "\\_<\\(nil\\|self\\|true\\|false\\)\\_>")
2153 1 font-lock-variable-name-face)
2154 ;; Keywords that evaluate to certain values.
2155 ("\\_<__\\(?:LINE\\|ENCODING\\|FILE\\)__\\_>"
2156 (0 font-lock-builtin-face))
2157 ;; Symbols.
2158 ("\\(^\\|[^:]\\)\\(:\\([-+~]@?\\|[/%&|^`]\\|\\*\\*?\\|<\\(<\\|=>?\\)?\\|>[>=]?\\|===?\\|=~\\|![~=]?\\|\\[\\]=?\\|@?\\(\\w\\|_\\)+\\([!?=]\\|\\b_*\\)\\|#{[^}\n\\\\]*\\(\\\\.[^}\n\\\\]*\\)*}\\)\\)"
2159 2 font-lock-constant-face)
2160 ;; Special globals.
2161 (,(concat "\\$\\(?:[:\"!@;,/\\._><\\$?~=*&`'+0-9]\\|-[0adFiIlpvw]\\|"
2162 (regexp-opt '("LOAD_PATH" "LOADED_FEATURES" "PROGRAM_NAME"
2163 "ERROR_INFO" "ERROR_POSITION"
2164 "FS" "FIELD_SEPARATOR"
2165 "OFS" "OUTPUT_FIELD_SEPARATOR"
2166 "RS" "INPUT_RECORD_SEPARATOR"
2167 "ORS" "OUTPUT_RECORD_SEPARATOR"
2168 "NR" "INPUT_LINE_NUMBER"
2169 "LAST_READ_LINE" "DEFAULT_OUTPUT" "DEFAULT_INPUT"
2170 "PID" "PROCESS_ID" "CHILD_STATUS"
2171 "LAST_MATCH_INFO" "IGNORECASE"
2172 "ARGV" "MATCH" "PREMATCH" "POSTMATCH"
2173 "LAST_PAREN_MATCH" "stdin" "stdout" "stderr"
2174 "DEBUG" "FILENAME" "VERBOSE" "SAFE" "CLASSPATH"
2175 "JRUBY_VERSION" "JRUBY_REVISION" "ENV_JAVA"))
2176 "\\_>\\)")
2177 0 font-lock-builtin-face)
2178 ("\\(\\$\\|@\\|@@\\)\\(\\w\\|_\\)+"
2179 0 font-lock-variable-name-face)
2180 ;; Constants.
2181 ("\\(?:\\_<\\|::\\)\\([A-Z]+\\(\\w\\|_\\)*\\)"
2182 1 (unless (eq ?\( (char-after)) font-lock-type-face))
2183 ("\\(^\\s *\\|[\[\{\(,]\\s *\\|\\sw\\s +\\)\\(\\(\\sw\\|_\\)+\\):[^:]"
2184 (2 font-lock-constant-face))
2185 ;; Conversion methods on Kernel.
2186 (,(concat ruby-font-lock-keyword-beg-re
2187 (regexp-opt '("Array" "Complex" "Float" "Hash"
2188 "Integer" "Rational" "String") 'symbols))
2189 (1 font-lock-builtin-face))
2190 ;; Expression expansion.
2191 (ruby-match-expression-expansion
2192 2 font-lock-variable-name-face t)
2193 ;; Negation char.
2194 ("\\(?:^\\|[^[:alnum:]_]\\)\\(!+\\)[^=~]"
2195 1 font-lock-negation-char-face)
2196 ;; Character literals.
2197 ;; FIXME: Support longer escape sequences.
2198 ("\\_<\\?\\\\?\\S " 0 font-lock-string-face)
2199 ;; Regexp options.
2200 ("\\(?:\\s|\\|/\\)\\([imxo]+\\)"
2201 1 (when (save-excursion
2202 (let ((state (syntax-ppss (match-beginning 0))))
2203 (and (nth 3 state)
2204 (or (eq (char-after) ?/)
2205 (progn
2206 (goto-char (nth 8 state))
2207 (looking-at "%r"))))))
2208 font-lock-preprocessor-face))
2209 )
2210 "Additional expressions to highlight in Ruby mode.")
2211
2212 (defun ruby-match-expression-expansion (limit)
2213 (let* ((prop 'ruby-expansion-match-data)
2214 (pos (next-single-char-property-change (point) prop nil limit))
2215 value)
2216 (when (and pos (> pos (point)))
2217 (goto-char pos)
2218 (or (and (setq value (get-text-property pos prop))
2219 (progn (set-match-data value) t))
2220 (ruby-match-expression-expansion limit)))))
2221
2222 ;;;###autoload
2223 (define-derived-mode ruby-mode prog-mode "Ruby"
2224 "Major mode for editing Ruby code.
2225
2226 \\{ruby-mode-map}"
2227 (ruby-mode-variables)
2228
2229 (setq-local imenu-create-index-function 'ruby-imenu-create-index)
2230 (setq-local add-log-current-defun-function 'ruby-add-log-current-method)
2231 (setq-local beginning-of-defun-function 'ruby-beginning-of-defun)
2232 (setq-local end-of-defun-function 'ruby-end-of-defun)
2233
2234 (add-hook 'after-save-hook 'ruby-mode-set-encoding nil 'local)
2235 (add-hook 'electric-indent-functions 'ruby--electric-indent-p nil 'local)
2236
2237 (setq-local font-lock-defaults '((ruby-font-lock-keywords) nil nil))
2238 (setq-local font-lock-keywords ruby-font-lock-keywords)
2239 (setq-local font-lock-syntax-table ruby-font-lock-syntax-table)
2240
2241 (setq-local syntax-propertize-function #'ruby-syntax-propertize-function))
2242
2243 ;;; Invoke ruby-mode when appropriate
2244
2245 ;;;###autoload
2246 (add-to-list 'auto-mode-alist
2247 (cons (purecopy (concat "\\(?:\\."
2248 "rb\\|ru\\|rake\\|thor"
2249 "\\|jbuilder\\|rabl\\|gemspec\\|podspec"
2250 "\\|/"
2251 "\\(?:Gem\\|Rake\\|Cap\\|Thor"
2252 "\\|Puppet\\|Berks"
2253 "\\|Vagrant\\|Guard\\|Pod\\)file"
2254 "\\)\\'")) 'ruby-mode))
2255
2256 ;;;###autoload
2257 (dolist (name (list "ruby" "rbx" "jruby" "ruby1.9" "ruby1.8"))
2258 (add-to-list 'interpreter-mode-alist (cons (purecopy name) 'ruby-mode)))
2259
2260 (provide 'ruby-mode)
2261
2262 ;;; ruby-mode.el ends here