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