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