Emacs: highlight balanced expressions (e.g. LaTeX tags)

Which would be a good way to get Emacs to highlight an expression that can include things like balanced brackets - for example, something like

\highlightthis{some \textit{text} here
some more text
done now}

highlight-regex works great for simple things, but I had trouble writing a regular emacs expression to recognize line breaks, and of course it matches up to the first closing parenthesis.

(as a secondary question: pointers to any packages that extend the regex emacs syntax will be very appreciated - it’s quite difficult for me with it, and I am pretty familiar with regular expressions in perl.)

Change . For my specific purpose (highlighting LaTeX tags in AUCTeX buffer), I managed to get this to work by setting up a special AUCTeX variable font-latex-user-keyword-classesthat adds something like this custom-set-variablesto .emacs:

'(font-latex-user-keyword-classes (quote (("mycommands" (("highlightthis" "{")) (:slant italic :foreground "red") command))))

A more general solution would be nice to have at least!

+5
source share
1 answer

You can use functions acting on s-expressions to work with the area you want to highlight, and use one of the solutions mentioned in this question to actually highlight it.

Here is an example:

(defun my/highlight-function ()
  (interactive)
  (save-excursion
    (goto-char (point-min))
    (search-forward "\highlightthis")
    (let ((end (scan-sexps (point) 1)))
      (add-text-properties (point) end '(comment t face highlight)))))

EDIT: Emacs, search- emacs- lisp:

(defun my/highlight-function (bound)
  (if (search-forward "\highlightthis" bound 'noerror)
      (let ((begin  (match-end 0))
            (end    (scan-sexps (point) 1)))
        (set-match-data (list begin end))
        t)
    nil))
(add-hook 'LaTeX-mode-hook
          (lambda ()
            (font-lock-add-keywords nil '(my/highlight-function))))
+1

All Articles