I'm trying to understand how syntax tables work, but my minimal major mode doesn't highlight anything.

I've written the following elisp, which is just supposed to highlight comments:

(defconst my-yaml-mode-syntax-table
  (let ((table (make-syntax-table)))
    (modify-syntax-entry ?# "<" table)
    (modify-syntax-entry ?\n ">" table)
  "Syntax table for `my-yaml-mode'.")

(define-derived-mode my-yaml-mode fundamental-mode "My YAML"
  :syntax-table my-yaml-mode-syntax-table)

However, given a file:

# foo
# bar

If I activate my major-mode with M-x my-yaml-mode, I don't get any highlighting. C-u C-x = shows that no faces have been applied.

  • Does M-; correctly insert a #? If yes, the syntax table is applied. You should look into font-lock specifications to get syntax highlighting. – T. Verron Sep 25 '14 at 12:35
  • 1
    M-; is bound to comment-dwim from newcomment.el, which uses comment-start rather than the syntax table. AIUI. – Wilfred Hughes Sep 25 '14 at 12:37
  • Hm, indeed, sorry. Instead, you can place the point on a # and press C-u C-x =, the output should contain the line syntax: < which means: comment. – T. Verron Sep 25 '14 at 12:41
  • Indeed it does! So if my syntax table is correct and is being applied, why isn't there any highlighting? – Wilfred Hughes Sep 25 '14 at 12:43
  • 1
    After testing with your code, it is simply a matter of turning font-lock-mode on in your my-yaml-mode buffer. :) – T. Verron Sep 25 '14 at 12:44

It is correct, but it is not being refontified just because you change major modes.

Enable your major mode and put your cursor in the comment then run M-x eval-expression (syntax-ppss-context (syntax-ppss (point))), it should yield 'comment and you'll see that the syntax table is setup correctly.

A simple fix would be to call (font-lock-fontify-buffer) when enabling your mode.

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.