How do I change Emacs's font face for Python docstrings?

1.7k views Asked by At

I'm just starting to learn Python and use Emacs as my editor. Currently, Emacs uses the same color for normal strings (single quotes) and docstrings (triple quotes). I want docstrings to be a different color, so I used the 'Options->Customize Emacs' menu option to change 'font-lock-doc-face' to a new color and saved the changes. However, Emacs continues to keep docstrings the same color as normal strings. Changing the color of normal strings applies the change to docstrings as well.

It would seem that Emacs is treating docstrings and normal strings as the same. Is there a way to get Emacs to properly find and color Python docstrings separately from normal strings?

Edit: I'm using Emacs 23.1.1 (Kubuntu 10.10 package) with the default Python mode settings. I also use the color-theme package with the midnight theme.

2

There are 2 answers

3
tangentstorm On BEST ANSWER

Interesting. I was going to say that due to the way the emacs syntax table works, emacs thinks """ and ''' represent an empty string folowed by the start of a new string.

You can easily verify this in your copy of emacs by pasting the following code into a python buffer:

class MrsRobinson(object):
    '''
    What's that you say?
    '''
    pass

In emacs 23.1.1 [update: and apparently on stackoveflow!] this completely breaks the syntax highlighting for the rest of the file.

I always use """ specifically to avoid apostrophe problems in docstrings, so I didn't notice until right this minute that in emacs 23.2.1, this is somehow finally fixed...

(Yep, there's a new function called python-quote-syntax in python.el)

So: in your version of emacs, this is impossible because the strings aren't parsed correctly. If you upgrade to the latest emacs, you may be able to make it happen by modifying that function in python.el to treat them differently.

0
WickedJargon On

I was able to accomplish this:

By doing M-x customize-face and enter: font-lock-doc-face.

The reason they are both the same color is because font-lock-doc-face inherits from font-lock-string-face:

I updated font-lock-string-face to font-lock-comment-face (as I prefer my doc-strings to have the same color as my comments). You can either do the same or select "Show all attributes" to choose your own