emacsconfigmodefont-lock

setting font-lock-face to different values for different major-modes


I am trying to set for example font-lock-comment-face to Blue for csharp-mode and for c++-mode to Red is this possible or not?

Right now im using:

(set-face-attribute 'font-lock-comment-face nil :foreground "#57a64a")
(set-face-attribute 'font-lock-keyword-face nil :foreground "#569cd6")

but this sets the value globally and not only for the mode.

Forgot to add the version im using: GNU Emacs 24.4.1 (i686-pc-mingw32) of 2014-10-24 on LEG570 on Windows 8


Solution

  • Wow! Thank you, I've thought it's not possible, but then i've found this: http://www.emacswiki.org/emacs/FacesPerBuffer

    Just look at the example from wiki, seems like exactly what you need:

     (make-face 'php-comment-face)
     (set-face-foreground 'php-comment-face "LightGrey")
     (add-hook 'php-mode-hook 
           (lambda ()
            ;; ...
            (set (make-local-variable 'font-lock-comment-face)
                 'php-comment-face)
            ;; ...
    

    Thanks to this question from related: Set Emacs defaut font face per-buffer/mode

    UPD

    to win the cc-mode bindings, you should put the (add-hook csharp-mode-hook ... after (add-hook c-mode-hook ..., like this:

    (make-face 'c-comment-face)
    (set-face-foreground 'c-comment-face "Red")
    
    (add-hook 'c-mode-hook
           (lambda ()
            ;; ...
            (set (make-local-variable 'font-lock-comment-face)
                 'c-comment-face)))
    
    
    (make-face 'cs-comment-face)
    (set-face-foreground 'cs-comment-face "Blue")
    
    (add-hook 'csharp-mode-hook
           (lambda ()
            ;; ...
            (set (make-local-variable 'font-lock-comment-face)
                 'cs-comment-face)))
    

    If you have hook codes in separate files, you should load csharp-mode settings after c-mode. Don't forget to (remove-hook ... to try this out.