5

I'm trying to write a major mode for a language that supports normal strings and triple-quoted strings ("foo" and """foo""").

(defconst my-string-mode-syntax-table
  (let ((table (make-syntax-table)))
    (modify-syntax-entry ?\" "\"" table)
    table))

(defconst my-string-mode-triple-quoted
  (rx "\"\"\"" (group (*? anything) "\"\"\"")))

(define-derived-mode my-string-mode prog-mode "My Mode"
  "testing"
  :syntax-table my-string-mode-syntax-table
  (set (make-local-variable 'font-lock-defaults)
       `(((,my-string-mode-triple-quoted 1 'font-lock-string-face t))))
  (font-lock-fontify-buffer))

I've marked " as a string delimiter, and highlighted triple-quoted strings.

This works in some cases:

"""foo "bar" baz"""

However, string highlighting is broken when I have an odd number of double quotes:

 """foo " bar"""

It also breaks parse-partial-sexp as it no longer returns strings in the correct places.

What's the correct emacs functionality to handle this?

  • A fast (but possibly not very helpful) hint would be to check out python-mode.el, since Python supports this syntax. – Patrick Steele Nov 18 '14 at 23:11
3

You want to setup a syntax-propertize-function. As Patrick Steele suggests, you can look for an existing example in python.el.

2

You can use syntax-propertize-function or font-lock-syntactic-keywords.

Here's a simple example:

(defconst my-string-mode-syntax-table
  (make-syntax-table))

(defconst my-string-mode-triple-quoted
  (rx (group "\"") (group "\"\"" (*? anything) "\"\"") (group "\"")))

(define-derived-mode my-string-mode prog-mode "My Mode"
  "testing"
  :syntax-table my-string-mode-syntax-table
  (set (make-local-variable 'font-lock-syntactic-keywords)
       (list
        `(,my-string-mode-triple-quoted
          (1 "\"")
          (2 ".")
          (3 "\"")
          )))
  (font-lock-fontify-buffer))

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.