1

I'm writing a major mode to handle syntax highlighting for a language that allows namespaces just like in C++ e.g. somewhere::out_there.

I'd like to highlight the text somewhere, but leave the namespace operator :: in the default face (as is done in cc-mode). So I'd like to match text that is followed by a pattern, without matching that pattern too.

I spent some time working with lookahead stuff, trying things like [a-zA-Z]+\(?::\) but it seems I've bumped into the optional group syntax \(?: ... \) that's just optionally including a single : in the match.

Searching around for methods to fix this, it seems that emacs doesn't actually support lookahead at all!

Since the solution may not be regex-based, let me give a bit more context: I'm setting font-lock-defaults and define-derived-mode, and my code follows this form:

;; define regexes for different text categories
(setq aql-numeric-regexp "[-+]?\\.?\\_<[0-9]*\\.?[0-9]+\\.?\\(?:[eE][-+]?[0-9]+\\)?\\_>\\.?")
(setq aql-bindvar-regexp "\\(^\\|[ \t]\\)@@?[a-zA-z_]+")

;; Associate categories with faces                                                                                                                                                                                                             
(setq aql-font-lock-keywords
  `(
    (,aql-numeric-regexp . font-lock-warning-face)
    (,aql-bindvar-regexp . font-lock-variable-name-face)
    ))

and then inside define-derived-mode I include:

(setq font-lock-defaults '((aql-font-lock-keywords)))
(set (make-local-variable 'font-lock-defaults) '(aql-font-lock-keywords nil t))

Any strategies for dealing with this sort of thing? Any workarounds that will enable me to approximate lookaheads? Or other methods to tell emacs what to highlight?

2

You can match for something like \(\_<[a-zA-Z_][a-zA-Z0-9_]*\):: and specify that group number 1 should be highlighted.

  • After digging around a bit, I figured out how to do what you suggest. I added (setq aql-namespace-regexp "\\([a-zA-Z]+\\)::") and then updated aql-font-lock-keywords with (,aql-namespace-regexp 1 font-lock-constant-face). Replacing the . with the group number is the key. – ohruunuruus Sep 5 '16 at 16:15
  • You can also write it as (,aql-namespace-regexp . (1 font-lock-constant-face)) if you prefer. – troelskn Nov 26 '16 at 22:33

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.