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