如何使用font-lock-defaults指定自定义面孔?


11

如果我使用现有的面孔定义字体锁定关键字,则可以突出显示字符串'foo'。

(defconst my-mode-font-lock-keywords
  (list
   (cons "foo" 'font-lock-type-face)))

(define-derived-mode my-mode fundamental-mode "My mode"
  "A demo mode."
  (set (make-local-variable 'font-lock-defaults) '(my-mode-font-lock-keywords)))

这正确地突出显示:

foo正确突出显示

但是,如果我定义自己的脸:

(defface my-mode-foo-face
  '((t :inherit font-lock-preprocessor-face))
  "Face for highlighting 'foo'.")

(defconst my-mode-font-lock-keywords
  (list
   (cons "foo" 'my-mode-foo-face)))

(define-derived-mode my-mode fundamental-mode "My mode"
  "A demo mode."
  (set (make-local-variable 'font-lock-defaults) '(my-mode-font-lock-keywords)))

没有应用突出显示:

没有突出显示

如何font-lock-defaults定义自己的面孔?

Answers:


8

看看C-hvfont-lock-type-face的值仅仅是符号font-lock-type-face。现在来看的C-hvmy-mode-foo-face。不好了!你不能!这不是变量!

您需要一个变量来访问您的脸。声明foo-face面并不声明foo-face变量。

(defvar my-mode-foo-face 'my-mode-foo-face)在面部定义之后添加,然后字体锁定可以使用您的my-mode-foo-facevar访问my-mode-foo-face面部。我知道了。


编辑:基于font-lock.el所说的似乎有一个更好的解决方案:

;; Originally these variable values were face names such as `bold' etc.
;; Now we create our own faces, but we keep these variables for compatibility
;; and they give users another mechanism for changing face appearance.
;; We now allow a FACENAME in `font-lock-keywords' to be any expression that
;; returns a face.  So the easiest thing is to continue using these variables,
;; rather than sometimes evalling FACENAME and sometimes not.  sm.

;; Note that in new code, in the vast majority of cases there is no
;; need to create variables that specify face names.  Simply using
;; faces directly is enough.  Font-lock is not a template to be
;; followed in this area.

这可能是威尔弗雷德(Wilfred)在关键字中双引号的方法。


3
啊哈,所以它期待一个变量。(cons "foo" ''my-mode-foo-face))也可以,但是我不确定哪个是惯用的。
Wilfred Hughes 2014年

1
嗯,根据我正在阅读的内容,我的答案似乎是过时的解决方案font-lock.el
Jordon Biondo

3
实际上,它期望一个表达式,它将对其求值。因此,您也可以在其中添加一些逻辑。
德米特里
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.