Suppose I have a python-mode user buffer with content import os, I can use (buffer-substring (point-min) (point-max)) to get a colorized string

#("import os" 0 6
(fontified t face font-lock-keyword-face)
6 9
(fontified t))

But now I want to generate this using emacs lisp code like

(setq string
        (font-lock-mode 1)
        (insert "import os")
        (buffer-substring (point-min) (point-max))))

but got result

#("import os" 0 9 (fontified nil))

So my question is how can I generate the same string just as I substring it from a truly existed user buffer?

Thanks in advance.


You need to tell font-lock to fontify the text you entered. Font-lock generally behaves lazily. It has already font-locked the text shown in the window, and you need to tell it to do so again, to pick up the text you just inserted.

See the commands and other functions whose names start with font-lock-fontify-: M-x font-lock-fontify- TAB.

For example: font-lock-fontify-block, which is bound by default to M-o M-o:

font-lock-fontify-block is an interactive compiled Lisp function in ‘font-lock.el’.

It is bound to M-o M-o.

(font-lock-fontify-block &optional ARG)

Fontify some lines the way font-lock-fontify-buffer would. The lines could be a function or paragraph, or a specified number of lines.

If ARG is given, fontify that many lines before and after point, or 16 lines if no ARG is given and font-lock-mark-block-function is nil.

If font-lock-mark-block-function non-nil and no ARG is given, it is used to delimit the region to fontify.

| improve this answer | |
  • (font-lock-fontify-region (point-min) (point-max)) usually does the trick. Note that font-lock-fontify-buffer doesn't fontify the entire buffer. – Lindydancer Apr 4 '17 at 17:52
  • Thanks for the font-lock-fontify-* function! – stackunderflow Apr 5 '17 at 1:35

The function designed specifically for that purpose is font-lock-ensure. So just call (font-lock-ensure) or (font-lock-ensure START END) before your call to buffer-substring.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.