[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Fontify Hex colors
From: |
Sébastien Vauban |
Subject: |
Re: Fontify Hex colors |
Date: |
Wed, 08 Dec 2010 15:12:14 -0000 |
User-agent: |
Gnus/5.13 (Gnus v5.13) Emacs/23.1.50 (gnu/linux) |
Hi Andreas,
Andreas Politz wrote:
> Sébastien Vauban <wxhgmqzgwmuf@spammotel.com> writes:
>
>> I'd like to automatically get Hex colors fontified -- when opening my Emacs
>> color-theme, an HTML/CSS file or a LaTeX class file with color definitions.
>>
>> To (try to) do so, I've added the following snippet of code into my
>> `.emacs' file:
>>
>> #105099
>> ;; #105099
>> ;; this `#105099' is it
>>
>> (defun fontify-hex-colors (start end)
>> "Fontify Hex colors."
>> (interactive "r")
>> (save-restriction
>> (narrow-to-region start end)
>> (goto-char (point-min))
>> (while (search-forward-regexp
>>
>> "\\(#[0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f]\\)"
>> nil t)
>> (put-text-property (match-beginning 0) (match-end 0)
>> 'font-lock-face (list :background (match-string
>> 1))))))
>>
>> Though, calling `M-x fontify-hex-colors' on that same region only
>> highlights the first occurrence of the color code `#105099'. The two others
>> get overridden by their normal color applied by the `emacs-lisp-mode'.
>>
>> The same appears in whatever mode that uses `font-lock'...
>>
>> Any idea how to go around this?
>
> I don't know exactly, why this doesn't work. But instead of working against
> font-lock, why not let it work for you.
>
> I also don't know if and how it would be possible to use dynamic faces in
> regular font-lock keywords. But you can use overlays combined with a pseudo
> font-lock function.
>
> (defun fontify-hex-colors (limit)
> (remove-overlays (point) limit 'fontify-hex-colors t)
> (while (re-search-forward "\\(#[[:xdigit:]]\\{6\\}\\)" limit t)
> (let ((ov (make-overlay (match-beginning 0)
> (match-end 0))))
> (overlay-put ov 'face (list :background (match-string 1)))
> (overlay-put ov 'fontify-hex-colors t)
> (overlay-put ov 'evaporate t)))
> ;; return nil telling font-lock not to fontify anything from this
> ;; function
> nil)
>
> (font-lock-add-keywords nil
> '((fontify-hex-colors)))
>
> I think this is safe, because fontifying always starts at bol, but I am not
> shure about this either.
I did not know about all this. Thanks a lot for the explanation, and for the
code.
I've used it for the past day, and it seems to work exactly as expected.
Thank you very much,
Seb
--
Sébastien Vauban