2009-03-18

emacs, how to attach text property

how to write a function that colors particular words matching regex inside a region?

I was thinking using font-lock-add-keywords, but that does to the whole buffer.

i haven't studied emacs's face, display property etc systems. But could anyone give me a rough guide on what function i should use or lookup?

Here's a bit detail on what i need to do. I'm writing a mode for Linden scripting language (LSL). Colors are specified using lsl's vector type, like this:

vector red = <1,0,0>;
vector green = <0,1,0>;
vector blue = <0,0,1>;
vector black = <0,0,0>;
vector white = <1,1,1>;
vector pink = <1,0.07843,0.5765>;
vector orange = <1,0.6471,0>;
vector brown = <0.5451,0.1373,0.1373>;
vector purple = <0.3333,0.102,0.5451>;
vector gold = <1,0.8431,0>;

I want to be able write a function, something named color-vectors-region, so that any 's background is colored using the rgb value. (each is a float from 0 to 1.) The part i don't know how, is how to attach a text color property to a piece of text.

Thanks.

Xah
∑ http://xahlee.org/



Here's the code i did.

(defun convert-rgb-vector-to-hex (rgb)
"Convert color RGB from “[r g b]” notation to “\"rrggbb\"” notation.
Example:
(convert-rgb-vector-to-hex [0 1 0.5])
returns
\"00ff80\"
"
(mapconcat
(lambda (x)
(format "%02x" (round (* x 255.0)) ))
rgb ""))

(defun syntax-color-vector (start end)
"Make vectors syntax colored "
(interactive "r")
(save-restriction
(narrow-to-region start end)
(goto-char (point-min))
(while (search-forward-regexp
"< *\\([0-9.]+\\) *, *\\([0-9.]+\\) *, *\\([0-9.]+\\) *>" nil t)
(put-text-property (match-beginning 0)
(match-end 0) 'face (list :background

(concat "#" (convert-rgb-vector-to-hex
(vector
(string-to-number (match-string 1))
(string-to-number (match-string 2))
(string-to-number (match-string 3))
)))
)))))

spent some 4 hours on this. Some 80% time is spend on the hex/decimal conversion, digging into some details of emacs float, string, hex, round, etc issues. (^_^)

Xah
∑ http://xahlee.org/

No comments:

Post a Comment