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