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