V
V
Vasily Demin2018-05-21 07:07:59
Lisp
Vasily Demin, 2018-05-21 07:07:59

How to create an emacs lisp function for syntax highlighting?

The task was to write haskell syntax highlighting in Emacs. The problem is that Emacs Lisp regular expressions do not support forward and backward lookups (?=) and (?<=). I read on the gnu site that you can create a function to look for words that will be highlighted. The function accepts a search limit, it should return non-nil and set match-beginning and match-end.
The function you wrote has been tested, it works, but the syntax highlighting doesn't.

(defun get-cur-character (pos)
  (aref (buffer-substring (1- pos) pos) 0))

(defun find-equal-character (pos)
  (let ((curchar ?0)
  (result nil)
  (max-pos (point-max)))
    (while (and (not (equal curchar ?\n)) (< pos max-pos))
      (setq curchar (get-cur-character pos))
      (setq pos (1+ pos))
      (if (equal curchar ?=)
    (progn
      (setq result t)
      (setq curchar ?\n))))
    result))

(defun highlight-haskell-function (limit)
  (save-excursion
    (if (not (null (re-search-forward "^\\([a-z]+\\w*\\)" limit t)))
  (find-equal-character (match-end 0))
      (nil))))

(provide 'haskell-mode)
(font-lock-add-keywords 'haskell-mode '((highlight-haskell-function . 'font-lock-keyword-face)))

Feature Descriptions:
  1. get-cur-character returns a character by position.
  2. find-equal-character looks for an equal character, starting at the position passed to it and ending with a newline character.
  3. highlight-haskell-function - Looks for words at the beginning of a line that begin with a lowercase letter. It then passes the found position to find-equal-character and returns either t or nil.

As a result of these functions, match-beginning and match-end resulting from re-search-forward do not change.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question