* lisp/progmodes/ruby-mode.el (ruby-smie--implicit-semi-p): Handle the
[bpt/emacs.git] / lisp / progmodes / ruby-mode.el
index 631bada..c96eccb 100644 (file)
   :prefix "ruby-"
   :group 'languages)
 
-(defconst ruby-keyword-end-re
-  (if (string-match "\\_>" "ruby")
-      "\\_>"
-    "\\>"))
-
 (defconst ruby-block-beg-keywords
   '("class" "module" "def" "if" "unless" "case" "while" "until" "for" "begin" "do")
   "Keywords at the beginning of blocks.")
@@ -60,7 +55,7 @@
   "Regexp to match the beginning of blocks.")
 
 (defconst ruby-non-block-do-re
-  (concat (regexp-opt '("while" "until" "for" "rescue") t) ruby-keyword-end-re)
+  (regexp-opt '("while" "until" "for" "rescue") 'symbols)
   "Regexp to match keywords that nest without blocks.")
 
 (defconst ruby-indent-beg-re
   "Regexp to match the beginning of a heredoc.")
 
   (defconst ruby-expression-expansion-re
-    "[^\\]\\(\\\\\\\\\\)*\\(#\\({[^}\n\\\\]*\\(\\\\.[^}\n\\\\]*\\)*}\\|\\(\\$\\|@\\|@@\\)\\(\\w\\|_\\)+\\)\\)"))
+    "\\(?:[^\\]\\|\\=\\)\\(\\\\\\\\\\)*\\(#\\({[^}\n\\\\]*\\(\\\\.[^}\n\\\\]*\\)*}\\|\\(\\$\\|@\\|@@\\)\\(\\w\\|_\\)+\\)\\)"))
 
 (defun ruby-here-doc-end-match ()
   "Return a regexp to find the end of a heredoc.
@@ -137,24 +132,28 @@ This should only be called after matching against `ruby-here-doc-beg-re'."
           ruby-block-end-re "\\|}\\|\\]\\)")
   "Regexp to match where the indentation gets shallower.")
 
-(defconst ruby-operator-re "[-,.+*/%&|^~=<>:]"
+(defconst ruby-operator-re "[-,.+*/%&|^~=<>:]\\|\\\\$"
   "Regexp to match operators.")
 
 (defconst ruby-symbol-chars "a-zA-Z0-9_"
   "List of characters that symbol names may contain.")
+
 (defconst ruby-symbol-re (concat "[" ruby-symbol-chars "]")
   "Regexp to match symbols.")
 
 (define-abbrev-table 'ruby-mode-abbrev-table ()
   "Abbrev table in use in Ruby mode buffers.")
 
+(defvar ruby-use-smie t)
+
 (defvar ruby-mode-map
   (let ((map (make-sparse-keymap)))
-    (define-key map (kbd "M-C-b") 'ruby-backward-sexp)
-    (define-key map (kbd "M-C-f") 'ruby-forward-sexp)
+    (unless ruby-use-smie
+      (define-key map (kbd "M-C-b") 'ruby-backward-sexp)
+      (define-key map (kbd "M-C-f") 'ruby-forward-sexp)
+      (define-key map (kbd "M-C-q") 'ruby-indent-exp))
     (define-key map (kbd "M-C-p") 'ruby-beginning-of-block)
     (define-key map (kbd "M-C-n") 'ruby-end-of-block)
-    (define-key map (kbd "M-C-q") 'ruby-indent-exp)
     (define-key map (kbd "C-c {") 'ruby-toggle-block)
     map)
   "Keymap used in Ruby mode.")
@@ -199,7 +198,7 @@ This should only be called after matching against `ruby-here-doc-beg-re'."
   "Indentation of Ruby statements."
   :type 'integer :group 'ruby)
 
-(defcustom ruby-comment-column 32
+(defcustom ruby-comment-column (default-value 'comment-column)
   "Indentation column of comments."
   :type 'integer :group 'ruby)
 
@@ -236,6 +235,209 @@ Also ignores spaces after parenthesis when 'space."
 (put 'ruby-comment-column 'safe-local-variable 'integerp)
 (put 'ruby-deep-arglist 'safe-local-variable 'booleanp)
 
+;;; SMIE support
+
+(require 'smie)
+
+(defconst ruby-smie-grammar
+  ;; FIXME: Add support for Cucumber.
+  (smie-prec2->grammar
+   (smie-bnf->prec2
+    '((id)
+      (insts (inst) (insts ";" insts))
+      (inst (exp) (inst "iuwu-mod" exp))
+      (exp  (exp1) (exp "," exp) (exp "=" exp) (exp "-" exp)  (exp "+" exp))
+      (exp1 (exp2) (exp2 "?" exp1 ":" exp1))
+      (exp2 ("def" insts "end")
+            ("begin" insts-rescue-insts "end")
+            ("do" insts "end")
+            ("class" insts "end") ("module" insts "end")
+            ("for" for-body "end")
+            ("[" expseq "]")
+            ("{" hashvals "}")
+            ("{" insts "}")
+            ("while" insts "end")
+            ("until" insts "end")
+            ("unless" insts "end")
+            ("if" if-body "end")
+            ("case"  cases "end"))
+      (formal-params ("opening-|" exp "|"))
+      (for-body (for-head ";" insts))
+      (for-head (id "in" exp))
+      (cases (exp "then" insts) ;; FIXME: Ruby also allows (exp ":" insts).
+             (cases "when" cases) (insts "else" insts))
+      (expseq (exp) );;(expseq "," expseq)
+      (hashvals (id "=>" exp1) (hashvals "," hashvals))
+      (insts-rescue-insts (insts)
+                          (insts-rescue-insts "rescue" insts-rescue-insts)
+                          (insts-rescue-insts "ensure" insts-rescue-insts))
+      (itheni (insts) (exp "then" insts))
+      (ielsei (itheni) (itheni "else" insts))
+      (if-body (ielsei) (if-body "elsif" if-body)))
+    '((nonassoc "in") (assoc ";") (assoc ",") (right "=") (assoc "-" "+"))
+    '((assoc "when"))
+    '((assoc "elsif"))
+    '((assoc "rescue" "ensure"))
+    '((assoc ",")))))
+
+(defun ruby-smie--bosp ()
+  (save-excursion (skip-chars-backward " \t")
+                  (or (bolp) (eq (char-before) ?\;))))
+
+(defun ruby-smie--implicit-semi-p ()
+  (save-excursion
+    (skip-chars-backward " \t")
+    (not (or (bolp)
+             (and (memq (char-before)
+                        '(?\; ?- ?+ ?* ?/ ?: ?. ?, ?\[ ?\( ?\{ ?\\))
+                  ;; Make sure it's not the end of a regexp.
+                  (not (eq (car (syntax-after (1- (point)))) 7)))
+             (and (memq (char-before) '(?\? ?=))
+                  (let ((tok (ruby-smie--backward-token)))
+                    (or (equal tok "?")
+                        (string-match "\\`\\s." tok))))
+             (save-excursion
+               (forward-comment 1)
+               (eq (char-after) ?.))))))
+
+(defun ruby-smie--redundant-do-p (&optional skip)
+  (save-excursion
+    (if skip (backward-word 1))
+    (member (nth 2 (smie-backward-sexp ";")) '("while"))))
+
+(defun ruby-smie--opening-pipe-p ()
+  (save-excursion
+    (if (eq ?| (char-before)) (forward-char -1))
+    (skip-chars-backward " \t\n")
+    (or (eq ?\{ (char-before))
+        (looking-back "\\_<do" (- (point) 2)))))
+
+(defun ruby-smie--forward-id ()
+  (when (and (not (eobp))
+             (eq ?w (char-syntax (char-after))))
+    (let ((tok (smie-default-forward-token)))
+      (when (eq ?. (char-after))
+        (forward-char 1)
+        (setq tok (concat tok "." (ruby-smie--forward-id))))
+      tok)))
+
+(defun ruby-smie--forward-token ()
+  (skip-chars-forward " \t")
+  (cond
+   ((looking-at "\\s\"") "")            ;A heredoc or a string.
+   ((and (looking-at "[\n#]")
+         (ruby-smie--implicit-semi-p))  ;Only add implicit ; when needed.
+    (if (eolp) (forward-char 1) (forward-comment 1))
+    ";")
+   (t
+    (forward-comment (point-max))
+    (if (looking-at ":\\s.+")
+        (progn (goto-char (match-end 0)) (match-string 0)) ;; bug#15208.
+      (let ((tok (smie-default-forward-token)))
+        (when (eq ?. (char-after))
+          (forward-char 1)
+          (setq tok (concat tok "." (ruby-smie--forward-id))))
+        (cond
+         ((member tok '("unless" "if" "while" "until"))
+          (if (save-excursion (forward-word -1) (ruby-smie--bosp))
+              tok "iuwu-mod"))
+         ((equal tok "|")
+          (if (ruby-smie--opening-pipe-p) "opening-|" tok))
+         ((and (equal tok "") (looking-at "\\\\\n"))
+          (goto-char (match-end 0)) (ruby-smie--forward-token))
+         ((equal tok "do")
+          (cond
+           ((not (ruby-smie--redundant-do-p 'skip)) tok)
+           ((> (save-excursion (forward-comment (point-max)) (point))
+               (line-end-position))
+            (ruby-smie--forward-token)) ;Fully redundant.
+           (t ";")))
+         ((equal tok ".") (concat tok (ruby-smie--forward-id)))
+         (t tok)))))))
+
+(defun ruby-smie--backward-id ()
+  (when (and (not (bobp))
+             (eq ?w (char-syntax (char-before))))
+    (let ((tok (smie-default-backward-token)))
+      (when (eq ?. (char-before))
+        (forward-char -1)
+        (setq tok (concat (ruby-smie--backward-id) "." tok)))
+      tok)))
+
+(defun ruby-smie--backward-token ()
+  (let ((pos (point)))
+    (forward-comment (- (point)))
+    (cond
+     ((and (> pos (line-end-position)) (ruby-smie--implicit-semi-p))
+      (skip-chars-forward " \t") ";")
+     ((and (bolp) (not (bobp))) "")         ;Presumably a heredoc.
+     (t
+      (let ((tok (smie-default-backward-token)))
+        (when (eq ?. (char-before))
+          (forward-char -1)
+          (setq tok (concat (ruby-smie--backward-id) "." tok)))
+        (when (and (eq ?: (char-before)) (string-match "\\`\\s." tok))
+          (forward-char -1) (setq tok (concat ":" tok))) ;; bug#15208.
+        (cond
+         ((member tok '("unless" "if" "while" "until"))
+          (if (ruby-smie--bosp)
+              tok "iuwu-mod"))
+         ((equal tok "|")
+          (if (ruby-smie--opening-pipe-p) "opening-|" tok))
+         ((and (equal tok "") (eq ?\\ (char-before)) (looking-at "\n"))
+          (forward-char -1) (ruby-smie--backward-token))
+         ((equal tok "do")
+          (cond
+           ((not (ruby-smie--redundant-do-p)) tok)
+           ((> (save-excursion (forward-word 1)
+                               (forward-comment (point-max)) (point))
+               (line-end-position))
+            (ruby-smie--backward-token)) ;Fully redundant.
+           (t ";")))
+         ((equal tok ".")
+          (concat (ruby-smie--backward-id) tok))
+         (t tok)))))))
+
+(defun ruby-smie-rules (kind token)
+  (pcase (cons kind token)
+    (`(:elem . basic) ruby-indent-level)
+    ;; "foo" "bar" is the concatenation of the two strings, so the second
+    ;; should be aligned with the first.
+    (`(:elem . args) (if (looking-at "\\s\"") 0))
+    ;; (`(:after . ",") (smie-rule-separator kind))
+    (`(:after . ";")
+     (if (smie-rule-parent-p "def" "begin" "do" "class" "module" "for"
+                             "while" "until" "unless"
+                             "if" "then" "elsif" "else" "when"
+                             "rescue" "ensure")
+         (smie-rule-parent ruby-indent-level)
+       ;; For (invalid) code between switch and case.
+       ;; (if (smie-parent-p "switch") 4)
+       0))
+    (`(:before . ,(or `"(" `"[" `"{"))
+     ;; Treat purely syntactic block-constructs as being part of their parent,
+     ;; when the opening statement is hanging.
+     (when (smie-rule-hanging-p)
+       (smie-backward-sexp 'halfsexp) (smie-indent-virtual)))
+    (`(:after . "=") 2)
+    (`(:before . "do")
+     (when (or (smie-rule-hanging-p)
+               (save-excursion
+                 (forward-word 1)       ;Skip "do"
+                 (skip-chars-forward " \t")
+                 (and (equal (save-excursion (ruby-smie--forward-token))
+                             "opening-|")
+                      (save-excursion (forward-sexp 1)
+                                      (skip-chars-forward " \t")
+                                      (or (eolp)
+                                          (looking-at comment-start-skip))))))
+       ;; `(column . ,(smie-indent-virtual))
+       (smie-rule-parent)))
+    (`(:before . ,(or `"else" `"then" `"elsif" `"rescue" `"ensure")) 0)
+    (`(:before . ,(or `"when"))
+     (if (not (smie-rule-sibling-p)) 0)) ;; ruby-indent-level
+    ))
+
 (defun ruby-imenu-create-index-in-block (prefix beg end)
   "Create an imenu index of methods inside a block."
   (let ((index-alist '()) (case-fold-search nil)
@@ -290,7 +492,11 @@ Also ignores spaces after parenthesis when 'space."
   (set-syntax-table ruby-mode-syntax-table)
   (setq local-abbrev-table ruby-mode-abbrev-table)
   (setq indent-tabs-mode ruby-indent-tabs-mode)
-  (set (make-local-variable 'indent-line-function) 'ruby-indent-line)
+  (if ruby-use-smie
+      (smie-setup ruby-smie-grammar #'ruby-smie-rules
+                  :forward-token  #'ruby-smie--forward-token
+                  :backward-token #'ruby-smie--backward-token)
+    (set (make-local-variable 'indent-line-function) 'ruby-indent-line))
   (set (make-local-variable 'require-final-newline) t)
   (set (make-local-variable 'comment-start) "# ")
   (set (make-local-variable 'comment-end) "")
@@ -584,7 +790,7 @@ Can be one of `heredoc', `modifier', `expr-qstr', `expr-re'."
        ((looking-at (concat "\\_<\\(" ruby-block-beg-re "\\)\\_>"))
         (and
          (save-match-data
-           (or (not (looking-at (concat "do" ruby-keyword-end-re)))
+           (or (not (looking-at "do\\_>"))
                (save-excursion
                  (back-to-indentation)
                  (not (looking-at ruby-non-block-do-re)))))
@@ -796,6 +1002,10 @@ Can be one of `heredoc', `modifier', `expr-qstr', `expr-re'."
                       (not (looking-at "[a-z_]"))))
                (and (looking-at ruby-operator-re)
                     (not (ruby-special-char-p))
+                    (save-excursion
+                      (forward-char -1)
+                      (or (not (looking-at ruby-operator-re))
+                          (not (eq (char-before) ?:))))
                     ;; Operator at the end of line.
                     (let ((c (char-after (point))))
                       (and
@@ -878,13 +1088,14 @@ calculating indentation on the lines after it."
 (defun ruby-move-to-block (n)
   "Move to the beginning (N < 0) or the end (N > 0) of the
 current block, a sibling block, or an outer block.  Do that (abs N) times."
+  (back-to-indentation)
   (let ((signum (if (> n 0) 1 -1))
         (backward (< n 0))
-        (depth (or (nth 2 (ruby-parse-region (line-beginning-position)
-                                             (line-end-position)))
-                   0))
+        (depth (or (nth 2 (ruby-parse-region (point) (line-end-position))) 0))
         case-fold-search
         down done)
+    (when (looking-at ruby-block-mid-re)
+      (setq depth (+ depth signum)))
     (when (< (* depth signum) 0)
       ;; Moving end -> end or beginning -> beginning.
       (setq depth 0))
@@ -921,22 +1132,16 @@ current block, a sibling block, or an outer block.  Do that (abs N) times."
             (unless (car state) ; Line ends with unfinished string.
               (setq depth (+ (nth 2 state) depth))))
           (cond
-           ;; Deeper indentation, we found a block.
-           ;; FIXME: We can't recognize empty blocks this way.
+           ;; Increased depth, we found a block.
            ((> (* signum depth) 0)
             (setq down t))
-           ;; Block found, and same indentation as when started, stop.
+           ;; We're at the same depth as when we started, and we've
+           ;; encountered a block before.  Stop.
            ((and down (zerop depth))
             (setq done t))
-           ;; Shallower indentation, means outer block, can stop now.
+           ;; Lower depth, means outer block, can stop now.
            ((< (* signum depth) 0)
-            (setq done t)))))
-        (if done
-            (save-excursion
-              (back-to-indentation)
-              ;; Not really at the first or last line of the block, move on.
-              (if (looking-at (concat "\\<\\(" ruby-block-mid-re "\\)\\>"))
-                  (setq done nil))))))
+            (setq done t)))))))
     (back-to-indentation)))
 
 (defun ruby-beginning-of-block (&optional arg)
@@ -956,8 +1161,10 @@ With ARG, move out of multiple blocks."
 With ARG, do it many times.  Negative ARG means move backward."
   ;; TODO: Document body
   (interactive "p")
-  (if (and (numberp arg) (< arg 0))
-      (ruby-backward-sexp (- arg))
+  (cond
+   (ruby-use-smie (forward-sexp arg))
+   ((and (numberp arg) (< arg 0)) (ruby-backward-sexp (- arg)))
+   (t
     (let ((i (or arg 1)))
       (condition-case nil
           (while (> i 0)
@@ -992,15 +1199,17 @@ With ARG, do it many times.  Negative ARG means move backward."
                      (not expr))))
             (setq i (1- i)))
         ((error) (forward-word 1)))
-      i)))
+      i))))
 
 (defun ruby-backward-sexp (&optional arg)
   "Move backward across one balanced expression (sexp).
 With ARG, do it many times.  Negative ARG means move forward."
   ;; TODO: Document body
   (interactive "p")
-  (if (and (numberp arg) (< arg 0))
-      (ruby-forward-sexp (- arg))
+  (cond
+   (ruby-use-smie (backward-sexp arg))
+   ((and (numberp arg) (< arg 0)) (ruby-forward-sexp (- arg)))
+   (t
     (let ((i (or arg 1)))
       (condition-case nil
           (while (> i 0)
@@ -1039,7 +1248,7 @@ With ARG, do it many times.  Negative ARG means move forward."
                    nil))
             (setq i (1- i)))
         ((error)))
-      i)))
+      i))))
 
 (defun ruby-indent-exp (&optional ignored)
   "Indent each line in the balanced expression following the point."
@@ -1235,67 +1444,92 @@ If the result is do-end block, it will always be multiline."
 (declare-function ruby-syntax-propertize-heredoc "ruby-mode" (limit))
 (declare-function ruby-syntax-enclosing-percent-literal "ruby-mode" (limit))
 (declare-function ruby-syntax-propertize-percent-literal "ruby-mode" (limit))
+;; Unusual code layout confuses the byte-compiler.
+(declare-function ruby-syntax-propertize-expansion "ruby-mode" ())
+(declare-function ruby-syntax-expansion-allowed-p "ruby-mode" (parse-state))
+(declare-function ruby-syntax-propertize-function "ruby-mode" (start end))
 
 (if (eval-when-compile (fboundp #'syntax-propertize-rules))
     ;; New code that works independently from font-lock.
     (progn
       (eval-and-compile
         (defconst ruby-percent-literal-beg-re
-          "\\(%\\)[qQrswWx]?\\([[:punct:]]\\)"
+          "\\(%\\)[qQrswWxIi]?\\([[:punct:]]\\)"
           "Regexp to match the beginning of percent literal.")
 
         (defconst ruby-syntax-methods-before-regexp
           '("gsub" "gsub!" "sub" "sub!" "scan" "split" "split!" "index" "match"
             "assert_match" "Given" "Then" "When")
           "Methods that can take regexp as the first argument.
-It will be properly highlighted even when the call omits parens."))
+It will be properly highlighted even when the call omits parens.")
+
+        (defvar ruby-syntax-before-regexp-re
+          (concat
+           ;; Special tokens that can't be followed by a division operator.
+           "\\(^\\|[[=(,~;<>]"
+           ;; Distinguish ternary operator tokens.
+           ;; FIXME: They don't really have to be separated with spaces.
+           "\\|[?:] "
+           ;; Control flow keywords and operators following bol or whitespace.
+           "\\|\\(?:^\\|\\s \\)"
+           (regexp-opt '("if" "elsif" "unless" "while" "until" "when" "and"
+                         "or" "not" "&&" "||"))
+           ;; Method name from the list.
+           "\\|\\_<"
+           (regexp-opt ruby-syntax-methods-before-regexp)
+           "\\)\\s *")
+          "Regexp to match text that can be followed by a regular expression."))
 
       (defun ruby-syntax-propertize-function (start end)
         "Syntactic keywords for Ruby mode.  See `syntax-propertize-function'."
-        (goto-char start)
-        (ruby-syntax-propertize-heredoc end)
-        (ruby-syntax-enclosing-percent-literal end)
-        (funcall
-         (syntax-propertize-rules
-          ;; $' $" $` .... are variables.
-          ;; ?' ?" ?` are ascii codes.
-          ("\\([?$]\\)[#\"'`]"
-           (1 (unless (save-excursion
-                        ;; Not within a string.
-                        (nth 3 (syntax-ppss (match-beginning 0))))
-                (string-to-syntax "\\"))))
-          ;; Regexps: regexps are distinguished from division because
-          ;; of the keyword, symbol, or method name before them.
-          ((concat
-            ;; Special tokens that can't be followed by a division operator.
-            "\\(^\\|[[=(,~?:;<>]"
-            ;; Control flow keywords and operators following bol or whitespace.
-            "\\|\\(?:^\\|\\s \\)"
-            (regexp-opt '("if" "elsif" "unless" "while" "until" "when" "and"
-                          "or" "not" "&&" "||"))
-            ;; Method name from the list.
-            "\\|\\_<"
-            (regexp-opt ruby-syntax-methods-before-regexp)
-            "\\)\\s *"
-            ;; The regular expression itself.
-            "\\(/\\)[^/\n\\\\]*\\(?:\\\\.[^/\n\\\\]*\\)*\\(/\\)")
-           (3 (unless (nth 3 (syntax-ppss (match-beginning 2)))
-                (put-text-property (match-beginning 2) (match-end 2)
-                                   'syntax-table (string-to-syntax "\"/"))
-                (string-to-syntax "\"/"))))
-          ("^=en\\(d\\)\\_>" (1 "!"))
-          ("^\\(=\\)begin\\_>" (1 "!"))
-          ;; Handle here documents.
-          ((concat ruby-here-doc-beg-re ".*\\(\n\\)")
-           (7 (unless (ruby-singleton-class-p (match-beginning 0))
-                (put-text-property (match-beginning 7) (match-end 7)
-                                   'syntax-table (string-to-syntax "\""))
-                (ruby-syntax-propertize-heredoc end))))
-          ;; Handle percent literals: %w(), %q{}, etc.
-          ((concat "\\(?:^\\|[[ \t\n<+(,=]\\)" ruby-percent-literal-beg-re)
-           (1 (prog1 "|" (ruby-syntax-propertize-percent-literal end)))))
-         (point) end)
-        (ruby-syntax-propertize-expansions start end))
+        (let (case-fold-search)
+          (goto-char start)
+          (remove-text-properties start end '(ruby-expansion-match-data))
+          (ruby-syntax-propertize-heredoc end)
+          (ruby-syntax-enclosing-percent-literal end)
+          (funcall
+           (syntax-propertize-rules
+            ;; $' $" $` .... are variables.
+            ;; ?' ?" ?` are character literals (one-char strings in 1.9+).
+            ("\\([?$]\\)[#\"'`]"
+             (1 (unless (save-excursion
+                          ;; Not within a string.
+                          (nth 3 (syntax-ppss (match-beginning 0))))
+                  (string-to-syntax "\\"))))
+            ;; Regular expressions.  Start with matching unescaped slash.
+            ("\\(?:\\=\\|[^\\]\\)\\(?:\\\\\\\\\\)*\\(/\\)"
+             (1 (let ((state (save-excursion (syntax-ppss (match-beginning 1)))))
+                  (when (or
+                         ;; Beginning of a regexp.
+                         (and (null (nth 8 state))
+                              (save-excursion
+                                (forward-char -1)
+                                (looking-back ruby-syntax-before-regexp-re
+                                              (point-at-bol))))
+                         ;; End of regexp.  We don't match the whole
+                         ;; regexp at once because it can have
+                         ;; string interpolation inside, or span
+                         ;; several lines.
+                         (eq ?/ (nth 3 state)))
+                    (string-to-syntax "\"/")))))
+            ;; Expression expansions in strings.  We're handling them
+            ;; here, so that the regexp rule never matches inside them.
+            (ruby-expression-expansion-re
+             (0 (ignore (ruby-syntax-propertize-expansion))))
+            ("^=en\\(d\\)\\_>" (1 "!"))
+            ("^\\(=\\)begin\\_>" (1 "!"))
+            ;; Handle here documents.
+            ((concat ruby-here-doc-beg-re ".*\\(\n\\)")
+             (7 (unless (or (nth 8 (save-excursion
+                                     (syntax-ppss (match-beginning 0))))
+                            (ruby-singleton-class-p (match-beginning 0)))
+                  (put-text-property (match-beginning 7) (match-end 7)
+                                     'syntax-table (string-to-syntax "\""))
+                  (ruby-syntax-propertize-heredoc end))))
+            ;; Handle percent literals: %w(), %q{}, etc.
+            ((concat "\\(?:^\\|[[ \t\n<+(,=]\\)" ruby-percent-literal-beg-re)
+             (1 (prog1 "|" (ruby-syntax-propertize-percent-literal end)))))
+           (point) end)))
 
       (defun ruby-syntax-propertize-heredoc (limit)
         (let ((ppss (syntax-ppss))
@@ -1308,7 +1542,7 @@ It will be properly highlighted even when the call omits parens."))
                                         (line-end-position) t)
                 (unless (ruby-singleton-class-p (match-beginning 0))
                   (push (concat (ruby-here-doc-end-match) "\n") res))))
-            (let ((start (point)))
+            (save-excursion
               ;; With multiple openers on the same line, we don't know in which
               ;; part `start' is, so we have to go back to the beginning.
               (when (cdr res)
@@ -1318,9 +1552,9 @@ It will be properly highlighted even when the call omits parens."))
                 (if (null res)
                     (put-text-property (1- (point)) (point)
                                        'syntax-table (string-to-syntax "\""))))
-              ;; Make extra sure we don't move back, lest we could fall into an
-              ;; inf-loop.
-              (if (< (point) start) (goto-char start))))))
+              ;; End up at bol following the heredoc openers.
+              ;; Propertize expression expansions from this point forward.
+              ))))
 
       (defun ruby-syntax-enclosing-percent-literal (limit)
         (let ((state (syntax-ppss))
@@ -1341,44 +1575,59 @@ It will be properly highlighted even when the call omits parens."))
                  (cl (or (cdr (aref (syntax-table) op))
                          (cdr (assoc op '((?< . ?>))))))
                  parse-sexp-lookup-properties)
-            (condition-case nil
-                (progn
-                  (if cl ; Paired delimiters.
-                      ;; Delimiter pairs of the same kind can be nested
-                      ;; inside the literal, as long as they are balanced.
-                      ;; Create syntax table that ignores other characters.
-                      (with-syntax-table (make-char-table 'syntax-table nil)
-                        (modify-syntax-entry op (concat "(" (char-to-string cl)))
-                        (modify-syntax-entry cl (concat ")" ops))
-                        (modify-syntax-entry ?\\ "\\")
-                        (save-restriction
-                          (narrow-to-region (point) limit)
-                          (forward-list))) ; skip to the paired character
-                    ;; Single character delimiter.
-                    (re-search-forward (concat "[^\\]\\(?:\\\\\\\\\\)*"
-                                               (regexp-quote ops)) limit nil))
-                  ;; Found the closing delimiter.
-                  (put-text-property (1- (point)) (point) 'syntax-table
-                                     (string-to-syntax "|")))
-              ;; Unclosed literal, leave the following text unpropertized.
-              ((scan-error search-failed) (goto-char limit))))))
+            (save-excursion
+              (condition-case nil
+                  (progn
+                    (if cl              ; Paired delimiters.
+                        ;; Delimiter pairs of the same kind can be nested
+                        ;; inside the literal, as long as they are balanced.
+                        ;; Create syntax table that ignores other characters.
+                        (with-syntax-table (make-char-table 'syntax-table nil)
+                          (modify-syntax-entry op (concat "(" (char-to-string cl)))
+                          (modify-syntax-entry cl (concat ")" ops))
+                          (modify-syntax-entry ?\\ "\\")
+                          (save-restriction
+                            (narrow-to-region (point) limit)
+                            (forward-list))) ; skip to the paired character
+                      ;; Single character delimiter.
+                      (re-search-forward (concat "[^\\]\\(?:\\\\\\\\\\)*"
+                                                 (regexp-quote ops)) limit nil))
+                    ;; Found the closing delimiter.
+                    (put-text-property (1- (point)) (point) 'syntax-table
+                                       (string-to-syntax "|")))
+                ;; Unclosed literal, do nothing.
+                ((scan-error search-failed)))))))
+
+      (defun ruby-syntax-propertize-expansion ()
+        ;; Save the match data to a text property, for font-locking later.
+        ;; Set the syntax of all double quotes and backticks to punctuation.
+        (let* ((beg (match-beginning 2))
+               (end (match-end 2))
+               (state (and beg (save-excursion (syntax-ppss beg)))))
+          (when (ruby-syntax-expansion-allowed-p state)
+            (put-text-property beg (1+ beg) 'ruby-expansion-match-data
+                               (match-data))
+            (goto-char beg)
+            (while (re-search-forward "[\"`]" end 'move)
+              (put-text-property (match-beginning 0) (match-end 0)
+                                 'syntax-table (string-to-syntax "."))))))
+
+      (defun ruby-syntax-expansion-allowed-p (parse-state)
+        "Return non-nil if expression expansion is allowed."
+        (let ((term (nth 3 parse-state)))
+          (cond
+           ((memq term '(?\" ?` ?\n ?/)))
+           ((eq term t)
+            (save-match-data
+              (save-excursion
+                (goto-char (nth 8 parse-state))
+                (looking-at "%\\(?:[QWrxI]\\|\\W\\)")))))))
 
       (defun ruby-syntax-propertize-expansions (start end)
-        (remove-text-properties start end '(ruby-expansion-match-data))
-        (goto-char start)
-        ;; Find all expression expansions and
-        ;; - save the match data to a text property, for font-locking later,
-        ;; - set the syntax of all double quotes and backticks to punctuation.
-        (while (re-search-forward ruby-expression-expansion-re end 'move)
-          (let ((beg (match-beginning 2))
-                (end (match-end 2)))
-            (when (and beg (save-excursion (nth 3 (syntax-ppss beg))))
-              (put-text-property beg (1+ beg) 'ruby-expansion-match-data
-                                 (match-data))
-              (goto-char beg)
-              (while (re-search-forward "[\"`]" end 'move)
-                (put-text-property (match-beginning 0) (match-end 0)
-                                   'syntax-table (string-to-syntax ".")))))))
+        (save-excursion
+          (goto-char start)
+          (while (re-search-forward ruby-expression-expansion-re end 'move)
+            (ruby-syntax-propertize-expansion))))
       )
 
   ;; For Emacsen where syntax-propertize-rules is not (yet) available,
@@ -1572,24 +1821,25 @@ See the definition of `ruby-font-lock-syntactic-keywords'."
   "The syntax table to use for fontifying Ruby mode buffers.
 See `font-lock-syntax-table'.")
 
+(defconst ruby-font-lock-keyword-beg-re "\\(?:^\\|[^.@$]\\|\\.\\.\\)")
+
 (defconst ruby-font-lock-keywords
   (list
    ;; functions
-   '("^\\s *def\\s +\\([^( \t\n]+\\)"
+   '("^\\s *def\\s +\\(?:[^( \t\n.]*\\.\\)?\\([^( \t\n]+\\)"
      1 font-lock-function-name-face)
    ;; keywords
-   (cons (concat
-          "\\(^\\|[^.@$]\\|\\.\\.\\)\\_<\\(defined\\?\\|"
+   (list (concat
+          ruby-font-lock-keyword-beg-re
           (regexp-opt
-           '("alias_method"
-             "alias"
+           '("alias"
              "and"
              "begin"
              "break"
              "case"
-             "catch"
              "class"
              "def"
+             "defined?"
              "do"
              "elsif"
              "else"
@@ -1599,21 +1849,15 @@ See `font-lock-syntax-table'.")
              "end"
              "if"
              "in"
-             "module_function"
              "module"
              "next"
              "not"
              "or"
-             "public"
-             "private"
-             "protected"
-             "raise"
              "redo"
              "rescue"
              "retry"
              "return"
              "then"
-             "throw"
              "super"
              "unless"
              "undef"
@@ -1621,16 +1865,85 @@ See `font-lock-syntax-table'.")
              "when"
              "while"
              "yield")
-           t)
-          "\\)"
-          ruby-keyword-end-re)
-         2)
+           'symbols))
+         1 'font-lock-keyword-face)
+   ;; some core methods
+   (list (concat
+          ruby-font-lock-keyword-beg-re
+          (regexp-opt
+           '(;; built-in methods on Kernel
+             "__callee__"
+             "__dir__"
+             "__method__"
+             "abort"
+             "at_exit"
+             "autoload"
+             "autoload?"
+             "binding"
+             "block_given?"
+             "caller"
+             "catch"
+             "eval"
+             "exec"
+             "exit"
+             "exit!"
+             "fail"
+             "fork"
+             "format"
+             "lambda"
+             "load"
+             "loop"
+             "open"
+             "p"
+             "print"
+             "printf"
+             "proc"
+             "putc"
+             "puts"
+             "raise"
+             "rand"
+             "readline"
+             "readlines"
+             "require"
+             "require_relative"
+             "sleep"
+             "spawn"
+             "sprintf"
+             "srand"
+             "syscall"
+             "system"
+             "throw"
+             "trap"
+             "warn"
+             ;; keyword-like private methods on Module
+             "alias_method"
+             "attr"
+             "attr_accessor"
+             "attr_reader"
+             "attr_writer"
+             "define_method"
+             "extend"
+             "include"
+             "module_function"
+             "prepend"
+             "private"
+             "protected"
+             "public"
+             "refine"
+             "using")
+           'symbols))
+         1 'font-lock-builtin-face)
    ;; here-doc beginnings
    `(,ruby-here-doc-beg-re 0 (unless (ruby-singleton-class-p (match-beginning 0))
                                'font-lock-string-face))
+   ;; Perl-ish keywords
+   "\\_<\\(?:BEGIN\\|END\\)\\_>\\|^__END__$"
    ;; variables
-   '("\\(^\\|[^.@$]\\|\\.\\.\\)\\_<\\(nil\\|self\\|true\\|false\\)\\>"
-     2 font-lock-variable-name-face)
+   `(,(concat ruby-font-lock-keyword-beg-re
+              "\\_<\\(nil\\|self\\|true\\|false\\)\\>")
+     1 font-lock-variable-name-face)
+   ;; keywords that evaluate to certain values
+   '("\\_<__\\(?:LINE\\|ENCODING\\|FILE\\)__\\_>" 0 font-lock-variable-name-face)
    ;; symbols
    '("\\(^\\|[^:]\\)\\(:\\([-+~]@?\\|[/%&|^`]\\|\\*\\*?\\|<\\(<\\|=>?\\)?\\|>[>=]?\\|===?\\|=~\\|![~=]?\\|\\[\\]=?\\|@?\\(\\w\\|_\\)+\\([!?=]\\|\\b_*\\)\\|#{[^}\n\\\\]*\\(\\\\.[^}\n\\\\]*\\)*}\\)\\)"
      2 font-lock-constant-face)
@@ -1641,14 +1954,22 @@ See `font-lock-syntax-table'.")
      0 font-lock-variable-name-face)
    ;; constants
    '("\\(?:\\_<\\|::\\)\\([A-Z]+\\(\\w\\|_\\)*\\)"
-     1 font-lock-type-face)
+     1 (unless (eq ?\( (char-after)) font-lock-type-face))
    '("\\(^\\s *\\|[\[\{\(,]\\s *\\|\\sw\\s +\\)\\(\\(\\sw\\|_\\)+\\):[^:]" 2 font-lock-constant-face)
+   ;; conversion methods on Kernel
+   (list (concat ruby-font-lock-keyword-beg-re
+                 (regexp-opt '("Array" "Complex" "Float" "Hash"
+                               "Integer" "Rational" "String") 'symbols))
+         1 font-lock-builtin-face)
    ;; expression expansion
    '(ruby-match-expression-expansion
      2 font-lock-variable-name-face t)
-   ;; warn lower camel case
-                                        ;'("\\<[a-z]+[a-z0-9]*[A-Z][A-Za-z0-9]*\\([!?]?\\|\\>\\)"
-                                        ;  0 font-lock-warning-face)
+   ;; negation char
+   '("[^[:alnum:]_]\\(!\\)[^=]"
+     1 font-lock-negation-char-face)
+   ;; character literals
+   ;; FIXME: Support longer escape sequences.
+   '("\\_<\\?\\\\?\\S " 0 font-lock-string-face)
    )
   "Additional expressions to highlight in Ruby mode.")
 
@@ -1708,11 +2029,14 @@ The variable `ruby-indent-level' controls the amount of indentation.
 ;;; Invoke ruby-mode when appropriate
 
 ;;;###autoload
-(add-to-list 'auto-mode-alist (cons (purecopy "\\.rb\\'") 'ruby-mode))
-;;;###autoload
-(add-to-list 'auto-mode-alist (cons (purecopy "Rakefile\\'") 'ruby-mode))
-;;;###autoload
-(add-to-list 'auto-mode-alist (cons (purecopy "\\.gemspec\\'") 'ruby-mode))
+(add-to-list 'auto-mode-alist
+             (cons (purecopy (concat "\\(?:\\."
+                                     "rb\\|ru\\|rake\\|thor"
+                                     "\\|jbuilder\\|gemspec"
+                                     "\\|/"
+                                     "\\(?:Gem\\|Rake\\|Cap\\|Thor"
+                                     "Vagrant\\|Guard\\)file"
+                                     "\\)\\'")) 'ruby-mode))
 
 ;;;###autoload
 (dolist (name (list "ruby" "rbx" "jruby" "ruby1.9" "ruby1.8"))