emacselisphighlightemacs-faces

How to set face for keywords which occur in first line?


How do I set face for specified keywords but only ones in first line? For example having this file

--- cut here ---
hello world    <-- this "hello" should have face set
hello world    <-- while this "hello" should not
--- cut here ---

only first hello should have face set

I tried this

(defun first-line-hello(limit)
  (and (save-excursion (beginning-of-line)
                       (bobp))
       (re-search-forward "hello" limit)))

 (font-lock-add-keywords 'emacs-lisp-mode
                         '((first-line-hello . font-lock-warning-face)))

but it seems that for some reason (bobp) returns always true when used in font-lock-keywords. I also tried using line-number-at-pos with the same result.


Solution

  • You're close, but there are a few problems. 'limit' could be well beyond the end of the first line, you need to not have an error if the search fails, and you need to move point regardless of the search pass/fail. Which all boils down to changing one line in your function:

    (defun first-line-hello(limit)
      (and (save-excursion (beginning-of-line)
                           (bobp))
           (re-search-forward "hello" (min (point-at-eol) limit) 'go)))