Sunday, February 13, 2011

Fontifying variable references within string literals in Emacs font-lock-mode

When I type the following code in Emacs ruby-mode, the "#{foo}" is fontified in a different color than the enclosing string. How do I do this in my own Emacs mode? I tried to decipher the ruby-mode source code but couldn't understand it in a reasonable amount of time.

"a #{foo} a"
  • Search for where ruby-mode.el sets font-lock-syntactic-keywords:

    (setq ruby-font-lock-syntactic-keywords
      '(
        ;; #{ }, #$hoge, #@foo are not comments
        ("\\(#\\)[{$@]" 1 (1 . nil))
    

    Here's some documentation on the similar font-lock-keywords variable, which is what you should use to accomplish the same type of fontification.

    From bmdhacks
  • Finally figured it out. The answer is that the "override" parameter in a fontification rule should be set to t, which means that the given face will override the string face. See the documentation for the variable "font-lock-keywords" for details. Here's an example:

    (define-derived-mode temp-mode fundamental-mode "Temp"
      "Temporary major mode."
      (set (make-local-variable 'font-lock-defaults)
           '((temp-mode-font-lock-keywords) nil nil nil nil)))
    
    (defconst temp-mode-font-lock-keywords
      (list (list "$[A-Za-z0-9]+" 0 font-lock-variable-name-face t)))
    

0 comments:

Post a Comment