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