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