Initial revision
[chise/xemacs-chise.git.1] / lisp / font.el
1 ;;; font.el --- New font model
2 ;; Author: wmperry
3 ;; Created: 1997/09/05 15:44:37
4 ;; Version: 1.52
5 ;; Keywords: faces
6
7 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
8 ;;; Copyright (c) 1995, 1996 by William M. Perry (wmperry@cs.indiana.edu)
9 ;;; Copyright (c) 1996, 1997 Free Software Foundation, Inc.
10 ;;;
11 ;;; This file is part of GNU Emacs.
12 ;;;
13 ;;; GNU Emacs is free software; you can redistribute it and/or modify
14 ;;; it under the terms of the GNU General Public License as published by
15 ;;; the Free Software Foundation; either version 2, or (at your option)
16 ;;; any later version.
17 ;;;
18 ;;; GNU Emacs is distributed in the hope that it will be useful,
19 ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21 ;;; GNU General Public License for more details.
22 ;;;
23 ;;; You should have received a copy of the GNU General Public License
24 ;;; along with GNU Emacs; see the file COPYING.  If not, write to the
25 ;;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
26 ;;; Boston, MA 02111-1307, USA.
27 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
28
29 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
30 ;;; The emacsen compatibility package - load it up before anything else
31 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
32 (require 'cl)
33
34 (eval-and-compile
35   (defvar device-fonts-cache)
36   (condition-case ()
37       (require 'custom)
38     (error nil))
39   (if (and (featurep 'custom) (fboundp 'custom-declare-variable))
40       nil ;; We've got what we needed
41     ;; We have the old custom-library, hack around it!
42     (defmacro defgroup (&rest args)
43       nil)
44     (defmacro defcustom (var value doc &rest args)
45       `(defvar ,var ,value ,doc))))
46
47 (if (not (fboundp 'try-font-name))
48     (defun try-font-name (fontname &rest args)
49       (case window-system
50         ((x pm) (car-safe (x-list-fonts fontname)))
51         (mswindows (car-safe (mswindows-list-fonts fontname)))
52         (ns (car-safe (ns-list-fonts fontname)))
53         (otherwise nil))))
54
55 (if (not (fboundp 'facep))
56     (defun facep (face)
57       "Return t if X is a face name or an internal face vector."
58       (if (not window-system)
59           nil                           ; FIXME if FSF ever does TTY faces
60         (and (or (internal-facep face)
61                  (and (symbolp face) (assq face global-face-data)))
62              t))))
63
64 (if (not (fboundp 'set-face-property))
65     (defun set-face-property (face property value &optional locale
66                                    tag-set how-to-add)
67       "Change a property of FACE."
68       (and (symbolp face)
69            (put face property value))))
70
71 (if (not (fboundp 'face-property))
72     (defun face-property (face property &optional locale tag-set exact-p)
73       "Return FACE's value of the given PROPERTY."
74       (and (symbolp face) (get face property))))
75
76 (require 'disp-table)
77
78 (if (not (fboundp '<<))   (fset '<< 'lsh))
79 (if (not (fboundp '&))    (fset '& 'logand))
80 (if (not (fboundp '|))    (fset '| 'logior))
81 (if (not (fboundp '~))    (fset '~ 'lognot))
82 (if (not (fboundp '>>))   (defun >> (value count) (<< value (- count))))
83
84 \f
85 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
86 ;;; Lots of variables / keywords for use later in the program
87 ;;; Not much should need to be modified
88 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
89 (defconst font-running-xemacs (string-match "XEmacs" (emacs-version))
90   "Whether we are running in XEmacs or not.")
91
92 (defmacro define-font-keywords (&rest keys)
93   `(eval-and-compile
94      (let ((keywords (quote ,keys)))
95        (while keywords
96          (or (boundp (car keywords))
97              (set (car keywords) (car keywords)))
98          (setq keywords (cdr keywords))))))
99
100 (defconst font-window-system-mappings
101   '((x         . (x-font-create-name x-font-create-object))
102     (ns        . (ns-font-create-name ns-font-create-object))
103     (mswindows . (mswindows-font-create-name mswindows-font-create-object))
104     (pm        . (x-font-create-name x-font-create-object)) ; Change? FIXME
105     (tty       . (tty-font-create-plist tty-font-create-object)))
106   "An assoc list mapping device types to a list of translations.
107
108 The first function creates a font name from a font descriptor object.
109 The second performs the reverse translation.")
110
111 (defconst ns-font-weight-mappings
112   '((:extra-light . "extralight")
113     (:light       . "light")
114     (:demi-light  . "demilight")
115     (:medium      . "medium")
116     (:normal      . "medium")
117     (:demi-bold   . "demibold")
118     (:bold        . "bold")
119     (:extra-bold  . "extrabold"))
120   "An assoc list mapping keywords to actual NeXTstep specific
121 information to use")
122
123 (defconst x-font-weight-mappings
124   '((:extra-light . "extralight")
125     (:light       . "light")
126     (:demi-light  . "demilight")
127     (:demi        . "demi")
128     (:book        . "book")
129     (:medium      . "medium")
130     (:normal      . "medium")
131     (:demi-bold   . "demibold")
132     (:bold        . "bold")
133     (:extra-bold  . "extrabold"))
134   "An assoc list mapping keywords to actual Xwindow specific strings
135 for use in the 'weight' field of an X font string.")
136
137 (defconst font-possible-weights
138   (mapcar 'car x-font-weight-mappings))
139
140 (defvar font-rgb-file nil
141   "Where the RGB file was found.")
142
143 (defvar font-maximum-slippage "1pt"
144   "How much a font is allowed to vary from the desired size.")
145
146 ;; Canonical (internal) sizes are in points.
147 ;; Registry
148 (define-font-keywords :family :style :size :registry :encoding)
149
150 (define-font-keywords
151   :weight :extra-light :light :demi-light :medium :normal :demi-bold
152   :bold :extra-bold)
153
154 (defvar font-style-keywords nil)
155
156 (defsubst set-font-family (fontobj family)
157   (aset fontobj 1 family))
158
159 (defsubst set-font-weight (fontobj weight)
160   (aset fontobj 3 weight))
161
162 (defsubst set-font-style (fontobj style)
163   (aset fontobj 5 style))
164
165 (defsubst set-font-size (fontobj size)
166   (aset fontobj 7 size))
167
168 (defsubst set-font-registry (fontobj reg)
169   (aset fontobj 9 reg))
170
171 (defsubst set-font-encoding (fontobj enc)
172   (aset fontobj 11 enc))
173
174 (defsubst font-family (fontobj)
175   (aref fontobj 1))
176
177 (defsubst font-weight (fontobj)
178   (aref fontobj 3))
179
180 (defsubst font-style (fontobj)
181   (aref fontobj 5))
182
183 (defsubst font-size (fontobj)
184   (aref fontobj 7))
185
186 (defsubst font-registry (fontobj)
187   (aref fontobj 9))
188
189 (defsubst font-encoding (fontobj)
190   (aref fontobj 11))
191
192 (eval-when-compile
193   (defmacro define-new-mask (attr mask)
194     `(progn
195        (setq font-style-keywords
196              (cons (cons (quote ,attr)
197                          (cons
198                           (quote ,(intern (format "set-font-%s-p" attr)))
199                           (quote ,(intern (format "font-%s-p" attr)))))
200                    font-style-keywords))
201        (defconst ,(intern (format "font-%s-mask" attr)) (<< 1 ,mask)
202          ,(format
203            "Bitmask for whether a font is to be rendered in %s or not."
204            attr))
205        (defun ,(intern (format "font-%s-p" attr)) (fontobj)
206          ,(format "Whether FONTOBJ will be renderd in `%s' or not." attr)
207          (if (/= 0 (& (font-style fontobj)
208                       ,(intern (format "font-%s-mask" attr))))
209              t
210            nil))
211        (defun ,(intern (format "set-font-%s-p" attr)) (fontobj val)
212          ,(format "Set whether FONTOBJ will be renderd in `%s' or not."
213                   attr)
214          (cond
215           (val
216            (set-font-style fontobj (| (font-style fontobj)
217                                       ,(intern
218                                         (format "font-%s-mask" attr)))))
219           ((,(intern (format "font-%s-p" attr)) fontobj)
220            (set-font-style fontobj (- (font-style fontobj)
221                                       ,(intern
222                                         (format "font-%s-mask" attr)))))))
223        )))
224
225 (let ((mask 0))
226   (define-new-mask bold        (setq mask (1+ mask)))
227   (define-new-mask italic      (setq mask (1+ mask)))
228   (define-new-mask oblique     (setq mask (1+ mask)))
229   (define-new-mask dim         (setq mask (1+ mask)))
230   (define-new-mask underline   (setq mask (1+ mask)))
231   (define-new-mask overline    (setq mask (1+ mask)))
232   (define-new-mask linethrough (setq mask (1+ mask)))
233   (define-new-mask strikethru  (setq mask (1+ mask)))
234   (define-new-mask reverse     (setq mask (1+ mask)))
235   (define-new-mask blink       (setq mask (1+ mask)))
236   (define-new-mask smallcaps   (setq mask (1+ mask)))
237   (define-new-mask bigcaps     (setq mask (1+ mask)))
238   (define-new-mask dropcaps    (setq mask (1+ mask))))
239
240 (defvar font-caps-display-table
241   (let ((table (make-display-table))
242         (i 0))
243     ;; Standard ASCII characters
244     (while (< i 26)
245       (aset table (+ i ?a) (+ i ?A))
246       (setq i (1+ i)))
247     ;; Now ISO translations
248     (setq i 224)
249     (while (< i 247)                    ;; Agrave - Ouml
250       (aset table i (- i 32))
251       (setq i (1+ i)))
252     (setq i 248)
253     (while (< i 255)                    ;; Oslash - Thorn
254       (aset table i (- i 32))
255       (setq i (1+ i)))
256     table))
257 \f
258 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
259 ;;; Utility functions
260 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
261 (defsubst set-font-style-by-keywords (fontobj styles)
262   (make-local-variable 'font-func)
263   (declare (special font-func))
264   (if (listp styles)
265       (while styles
266         (setq font-func (car-safe (cdr-safe (assq (car styles) font-style-keywords)))
267               styles (cdr styles))
268         (and (fboundp font-func) (funcall font-func fontobj t)))
269     (setq font-func (car-safe (cdr-safe (assq styles font-style-keywords))))
270     (and (fboundp font-func) (funcall font-func fontobj t))))
271
272 (defsubst font-properties-from-style (fontobj)
273   (let ((style (font-style fontobj))
274         (todo font-style-keywords)
275         type func retval)
276     (while todo
277       (setq func (cdr (cdr (car todo)))
278             type (car (pop todo)))
279       (if (funcall func fontobj)
280           (setq retval (cons type retval))))
281     retval))
282
283 (defun font-unique (list)
284   (let ((retval)
285         (cur))
286     (while list
287       (setq cur (car list)
288             list (cdr list))
289       (if (member cur retval)
290           nil
291         (setq retval (cons cur retval))))
292     (nreverse retval)))
293
294 (defun font-higher-weight (w1 w2)
295   (let ((index1 (length (memq w1 font-possible-weights)))
296         (index2 (length (memq w2 font-possible-weights))))
297     (cond
298      ((<= index1 index2)
299       (or w1 w2))
300      ((not w2)
301       w1)
302      (t
303       w2))))
304
305 (defun font-spatial-to-canonical (spec &optional device)
306   "Convert SPEC (in inches, millimeters, points, picas, or pixels) into points.
307
308 Canonical sizes are in points.  If SPEC is null, nil is returned.  If SPEC is
309 a number, it is interpreted as the desired point size and returned unchanged.
310 Otherwise SPEC must be a string consisting of a number and an optional type.
311 The type may be the strings \"px\", \"pix\", or \"pixel\" (pixels), \"pt\" or
312 \"point\" (points), \"pa\" or \"pica\" (picas), \"in\" or \"inch\" (inches), \"cm\"
313 (centimeters), or \"mm\" (millimeters).
314
315 1 in = 2.54 cm = 6 pa = 25.4 mm = 72 pt.  Pixel size is device-dependent."
316   (cond
317    ((numberp spec)
318     spec)
319    ((null spec)
320     nil)
321    (t
322     (let ((num nil)
323           (type nil)
324           ;; If for any reason we get null for any of this, default
325           ;; to 1024x768 resolution on a 17" screen
326           (pix-width (float (or (device-pixel-width device) 1024)))
327           (mm-width (float (or (device-mm-width device) 293)))
328           (retval nil))
329       (cond
330        ;; the following string-match is broken, there will never be a
331        ;; left operand detected
332        ((string-match "^ *\\([-+*/]\\) *" spec) ; math!  whee!
333         (let ((math-func (intern (match-string 1 spec)))
334               (other (font-spatial-to-canonical
335                       (substring spec (match-end 0) nil)))
336               (default (font-spatial-to-canonical
337                         (font-default-size-for-device device))))
338           (if (fboundp math-func)
339               (setq type "px"
340                     spec (int-to-string (funcall math-func default other)))
341             (setq type "px"
342                   spec (int-to-string other)))))
343        ((string-match "[^0-9.]+$" spec)
344         (setq type (substring spec (match-beginning 0))
345               spec (substring spec 0 (match-beginning 0))))
346        (t
347         (setq type "px"
348               spec spec)))
349       (setq num (string-to-number spec))
350       (cond
351        ((member type '("pixel" "px" "pix"))
352         (setq retval (* num (/ pix-width mm-width) (/ 25.4 72.0))))
353        ((member type '("point" "pt"))
354         (setq retval num))
355        ((member type '("pica" "pa"))
356         (setq retval (* num 12.0)))
357        ((member type '("inch" "in"))
358         (setq retval (* num 72.0)))
359        ((string= type "mm")
360         (setq retval (* num (/ 72.0 25.4))))
361        ((string= type "cm")
362         (setq retval (* num 10 (/ 72.0 25.4))))
363        (t
364         (setq retval num))
365        )
366       retval))))
367
368 \f
369 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
370 ;;; The main interface routines - constructors and accessor functions
371 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
372 (defun make-font (&rest args)
373   (vector :family
374           (if (stringp (plist-get args :family))
375               (list (plist-get args :family))
376             (plist-get args :family))
377           :weight
378           (plist-get args :weight)
379           :style
380           (if (numberp (plist-get args :style))
381               (plist-get args :style)
382             0)
383           :size
384           (plist-get args :size)
385           :registry
386           (plist-get args :registry)
387           :encoding
388           (plist-get args :encoding)))
389
390 (defun font-create-name (fontobj &optional device)
391   "Return a font name constructed from FONTOBJ, appropriate for DEVICE."
392   (let* ((type (device-type device))
393          (func (car (cdr-safe (assq type font-window-system-mappings)))))
394     (and func (fboundp func) (funcall func fontobj device))))
395
396 ;;;###autoload
397 (defun font-create-object (fontname &optional device)
398   "Return a font descriptor object for FONTNAME, appropriate for DEVICE."
399   (let* ((type (device-type device))
400          (func (car (cdr (cdr-safe (assq type font-window-system-mappings))))))
401     (and func (fboundp func) (funcall func fontname device))))
402
403 (defun font-combine-fonts-internal (fontobj-1 fontobj-2)
404   (let ((retval (make-font))
405         (size-1 (and (font-size fontobj-1)
406                      (font-spatial-to-canonical (font-size fontobj-1))))
407         (size-2 (and (font-size fontobj-2)
408                      (font-spatial-to-canonical (font-size fontobj-2)))))
409     (set-font-weight retval (font-higher-weight (font-weight fontobj-1)
410                                                 (font-weight fontobj-2)))
411     (set-font-family retval (font-unique (append (font-family fontobj-1)
412                                                  (font-family fontobj-2))))
413     (set-font-style retval (| (font-style fontobj-1) (font-style fontobj-2)))
414     (set-font-registry retval (or (font-registry fontobj-1)
415                                   (font-registry fontobj-2)))
416     (set-font-encoding retval (or (font-encoding fontobj-1)
417                                   (font-encoding fontobj-2)))
418     (set-font-size retval (cond
419                            ((and size-1 size-2 (>= size-2 size-1))
420                             (font-size fontobj-2))
421                            ((and size-1 size-2)
422                             (font-size fontobj-1))
423                            (size-1
424                             (font-size fontobj-1))
425                            (size-2
426                             (font-size fontobj-2))
427                            (t nil)))
428
429     retval))
430
431 (defun font-combine-fonts (&rest args)
432   (cond
433    ((null args)
434     (error "Wrong number of arguments to font-combine-fonts"))
435    ((= (length args) 1)
436     (car args))
437    (t
438     (let ((retval (font-combine-fonts-internal (nth 0 args) (nth 1 args))))
439       (setq args (cdr (cdr args)))
440       (while args
441         (setq retval (font-combine-fonts-internal retval (car args))
442               args (cdr args)))
443       retval))))
444
445 \f
446 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
447 ;;; The window-system dependent code (TTY-style)
448 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
449 (defun tty-font-create-object (fontname &optional device)
450   "Return a font descriptor object for FONTNAME, appropriate for TTY devices."
451   (make-font :size "12pt"))
452
453 (defun tty-font-create-plist (fontobj &optional device)
454   "Return a font name constructed from FONTOBJ, appropriate for TTY devices."
455   (list
456    (cons 'underline (font-underline-p fontobj))
457    (cons 'highlight (if (or (font-bold-p fontobj)
458                             (memq (font-weight fontobj) '(:bold :demi-bold)))
459                         t))
460    (cons 'dim       (font-dim-p fontobj))
461    (cons 'blinking  (font-blink-p fontobj))
462    (cons 'reverse   (font-reverse-p fontobj))))
463
464 \f
465 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
466 ;;; The window-system dependent code (X-style)
467 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
468 (defvar font-x-font-regexp (or (and font-running-xemacs
469                                     (boundp 'x-font-regexp)
470                                     x-font-regexp)
471  (let
472      ((-                "[-?]")
473       (foundry          "[^-]*")
474       (family           "[^-]*")
475       (weight           "\\(bold\\|demibold\\|medium\\|black\\)")
476       (weight\?         "\\([^-]*\\)")
477       (slant            "\\([ior]\\)")
478       (slant\?          "\\([^-]?\\)")
479       (swidth           "\\([^-]*\\)")
480       (adstyle          "\\([^-]*\\)")
481       (pixelsize        "\\(\\*\\|[0-9]+\\)")
482       (pointsize        "\\(\\*\\|0\\|[0-9][0-9]+\\)")
483       (resx             "\\([*0]\\|[0-9][0-9]+\\)")
484       (resy             "\\([*0]\\|[0-9][0-9]+\\)")
485       (spacing          "[cmp?*]")
486       (avgwidth         "\\(\\*\\|[0-9]+\\)")
487       (registry         "[^-]*")
488       (encoding "[^-]+")
489       )
490    (concat "\\`\\*?[-?*]"
491            foundry - family - weight\? - slant\? - swidth - adstyle -
492            pixelsize - pointsize - resx - resy - spacing - avgwidth -
493            registry - encoding "\\'"
494            ))))
495
496 (defvar font-x-registry-and-encoding-regexp
497   (or (and font-running-xemacs
498            (boundp 'x-font-regexp-registry-and-encoding)
499            (symbol-value 'x-font-regexp-registry-and-encoding))
500       (let ((- "[-?]")
501             (registry "[^-]*")
502             (encoding "[^-]+"))
503         (concat - "\\(" registry "\\)" - "\\(" encoding "\\)\\'"))))
504
505 (defvar font-x-family-mappings
506   '(
507     ("serif"        . ("new century schoolbook"
508                        "utopia"
509                        "charter"
510                        "times"
511                        "lucidabright"
512                        "garamond"
513                        "palatino"
514                        "times new roman"
515                        "baskerville"
516                        "bookman"
517                        "bodoni"
518                        "computer modern"
519                        "rockwell"
520                        ))
521     ("sans-serif"   . ("lucida"
522                        "helvetica"
523                        "gills-sans"
524                        "avant-garde"
525                        "univers"
526                        "optima"))
527     ("elfin"        . ("tymes"))
528     ("monospace"    . ("courier"
529                        "fixed"
530                        "lucidatypewriter"
531                        "clean"
532                        "terminal"))
533     ("cursive"      . ("sirene"
534                        "zapf chancery"))
535     )
536   "A list of font family mappings on X devices.")
537
538 (defun x-font-create-object (fontname &optional device)
539   "Return a font descriptor object for FONTNAME, appropriate for X devices."
540   (let ((case-fold-search t))
541     (if (or (not (stringp fontname))
542             (not (string-match font-x-font-regexp fontname)))
543         (make-font)
544       (let ((family nil)
545             (style nil)
546             (size nil)
547             (weight  (match-string 1 fontname))
548             (slant   (match-string 2 fontname))
549             (swidth  (match-string 3 fontname))
550             (adstyle (match-string 4 fontname))
551             (pxsize  (match-string 5 fontname))
552             (ptsize  (match-string 6 fontname))
553             (retval nil)
554             (case-fold-search t)
555             )
556         (if (not (string-match x-font-regexp-foundry-and-family fontname))
557             nil
558           (setq family (list (downcase (match-string 1 fontname)))))
559         (if (string= "*" weight)  (setq weight  nil))
560         (if (string= "*" slant)   (setq slant   nil))
561         (if (string= "*" swidth)  (setq swidth  nil))
562         (if (string= "*" adstyle) (setq adstyle nil))
563         (if (string= "*" pxsize)  (setq pxsize  nil))
564         (if (string= "*" ptsize)  (setq ptsize  nil))
565         (if ptsize (setq size (/ (string-to-int ptsize) 10)))
566         (if (and (not size) pxsize) (setq size (concat pxsize "px")))
567         (if weight (setq weight (intern-soft (concat ":" (downcase weight)))))
568         (if (and adstyle (not (equal adstyle "")))
569             (setq family (append family (list (downcase adstyle)))))
570         (setq retval (make-font :family family
571                                 :weight weight
572                                 :size size))
573         (set-font-bold-p retval (eq :bold weight))
574         (cond
575          ((null slant) nil)
576          ((member slant '("i" "I"))
577           (set-font-italic-p retval t))
578          ((member slant '("o" "O"))
579           (set-font-oblique-p retval t)))
580         (when (string-match font-x-registry-and-encoding-regexp fontname)
581           (set-font-registry retval (match-string 1 fontname))
582           (set-font-encoding retval (match-string 2 fontname)))
583         retval))))
584
585 (defun x-font-families-for-device (&optional device no-resetp)
586   (ignore-errors (require 'x-font-menu))
587   (or device (setq device (selected-device)))
588   (if (boundp 'device-fonts-cache)
589       (let ((menu (or (cdr-safe (assq device device-fonts-cache)))))
590         (if (and (not menu) (not no-resetp))
591             (progn
592               (reset-device-font-menus device)
593               (x-font-families-for-device device t))
594           (let ((scaled (mapcar #'(lambda (x) (if x (aref x 0)))
595                                 (aref menu 0)))
596                 (normal (mapcar #'(lambda (x) (if x (aref x 0)))
597                                 (aref menu 1))))
598             (sort (font-unique (nconc scaled normal)) 'string-lessp))))
599     (cons "monospace" (mapcar 'car font-x-family-mappings))))
600
601 (defvar font-default-cache nil)
602
603 ;;;###autoload
604 (defun font-default-font-for-device (&optional device)
605   (or device (setq device (selected-device)))
606   (if font-running-xemacs
607       (font-truename
608        (make-font-specifier
609         (face-font-name 'default device)))
610     (let ((font (cdr-safe (assq 'font (frame-parameters device)))))
611       (if (and (fboundp 'fontsetp) (fontsetp font))
612           (aref (get-font-info (aref (cdr (get-fontset-info font)) 0)) 2)
613         font))))
614
615 ;;;###autoload
616 (defun font-default-object-for-device (&optional device)
617   (let ((font (font-default-font-for-device device)))
618     (or (cdr-safe (assoc font font-default-cache))
619         (let ((object (font-create-object font)))
620           (push (cons font object) font-default-cache)
621           object))))
622
623 ;;;###autoload
624 (defun font-default-family-for-device (&optional device)
625   (font-family (font-default-object-for-device (or device (selected-device)))))
626
627 ;;;###autoload
628 (defun font-default-registry-for-device (&optional device)
629   (font-registry (font-default-object-for-device (or device (selected-device)))))
630
631 ;;;###autoload
632 (defun font-default-encoding-for-device (&optional device)
633   (font-encoding (font-default-object-for-device (or device (selected-device)))))
634
635 ;;;###autoload
636 (defun font-default-size-for-device (&optional device)
637   ;; face-height isn't the right thing (always 1 pixel too high?)
638   ;; (if font-running-xemacs
639   ;;    (format "%dpx" (face-height 'default device))
640   (font-size (font-default-object-for-device (or device (selected-device)))))
641
642 (defun x-font-create-name (fontobj &optional device)
643   "Return a font name constructed from FONTOBJ, appropriate for X devices."
644   (if (and (not (or (font-family fontobj)
645                     (font-weight fontobj)
646                     (font-size fontobj)
647                     (font-registry fontobj)
648                     (font-encoding fontobj)))
649            (= (font-style fontobj) 0))
650       (face-font 'default)
651     (or device (setq device (selected-device)))
652     (let* ((default (font-default-object-for-device device))
653            (family (or (font-family fontobj)
654                        (font-family default)
655                        (x-font-families-for-device device)))
656            (weight (or (font-weight fontobj) :medium))
657            (style (font-style fontobj))
658            (size (or (if font-running-xemacs
659                          (font-size fontobj))
660                      (font-size default)))
661            (registry (or (font-registry fontobj)
662                          (font-registry default)
663                          "*"))
664            (encoding (or (font-encoding fontobj)
665                          (font-encoding default)
666                          "*")))
667       (if (stringp family)
668           (setq family (list family)))
669       (setq weight (font-higher-weight weight
670                                        (and (font-bold-p fontobj) :bold)))
671       (if (stringp size)
672           (setq size (truncate (font-spatial-to-canonical size device))))
673       (setq weight (or (cdr-safe (assq weight x-font-weight-mappings)) "*"))
674       (let ((done nil)                  ; Did we find a good font yet?
675             (font-name nil)             ; font name we are currently checking
676             (cur-family nil)            ; current family we are checking
677             )
678         (while (and family (not done))
679           (setq cur-family (car family)
680                 family (cdr family))
681           (if (assoc cur-family font-x-family-mappings)
682               ;; If the family name is an alias as defined by
683               ;; font-x-family-mappings, then append those families
684               ;; to the front of 'family' and continue in the loop.
685               (setq family (append
686                             (cdr-safe (assoc cur-family
687                                              font-x-family-mappings))
688                             family))
689             ;; Not an alias for a list of fonts, so we just check it.
690             ;; First, convert all '-' to spaces so that we don't screw up
691             ;; the oh-so wonderful X font model.  Wheee.
692             (let ((x (length cur-family)))
693               (while (> x 0)
694                 (if (= ?- (aref cur-family (1- x)))
695                     (aset cur-family (1- x) ? ))
696                 (setq x (1- x))))
697             ;; We treat oblique and italic as equivalent.  Don't ask.
698             (let ((slants '("o" "i")))
699               (while (and slants (not done))
700                 (setq font-name (format "-*-%s-%s-%s-*-*-*-%s-*-*-*-*-%s-%s"
701                                         cur-family weight
702                                         (if (or (font-italic-p fontobj)
703                                                 (font-oblique-p fontobj))
704                                             (car slants)
705                                           "r")
706                                         (if size
707                                             (int-to-string (* 10 size)) "*")
708                                         registry
709                                         encoding
710                                         )
711                       slants (cdr slants)
712                       done (try-font-name font-name device))))))
713         (if done font-name)))))
714
715 \f
716 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
717 ;;; The window-system dependent code (NS-style)
718 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
719 (defun ns-font-families-for-device (&optional device no-resetp)
720   ;; For right now, assume we are going to have the same storage for
721   ;; device fonts for NS as we do for X.  Is this a valid assumption?
722   (or device (setq device (selected-device)))
723   (if (boundp 'device-fonts-cache)
724       (let ((menu (or (cdr-safe (assq device device-fonts-cache)))))
725         (if (and (not menu) (not no-resetp))
726             (progn
727               (reset-device-font-menus device)
728               (ns-font-families-for-device device t))
729           (let ((scaled (mapcar #'(lambda (x) (if x (aref x 0)))
730                                 (aref menu 0)))
731                 (normal (mapcar #'(lambda (x) (if x (aref x 0)))
732                                 (aref menu 1))))
733             (sort (font-unique (nconc scaled normal)) 'string-lessp))))))
734
735 (defun ns-font-create-name (fontobj &optional device)
736   "Return a font name constructed from FONTOBJ, appropriate for NextSTEP devices."
737   (let ((family (or (font-family fontobj)
738                     (ns-font-families-for-device device)))
739         (weight (or (font-weight fontobj) :medium))
740         (style (or (font-style fontobj) (list :normal)))
741         (size (font-size fontobj))
742         (registry (or (font-registry fontobj) "*"))
743         (encoding (or (font-encoding fontobj) "*")))
744     ;; Create a font, wow!
745     (if (stringp family)
746         (setq family (list family)))
747     (if (or (symbolp style) (numberp style))
748         (setq style (list style)))
749     (setq weight (font-higher-weight weight (car-safe (memq :bold style))))
750     (if (stringp size)
751         (setq size (font-spatial-to-canonical size device)))
752     (setq weight (or (cdr-safe (assq weight ns-font-weight-mappings))
753                      "medium"))
754     (let ((done nil)                    ; Did we find a good font yet?
755           (font-name nil)               ; font name we are currently checking
756           (cur-family nil)              ; current family we are checking
757           )
758       (while (and family (not done))
759         (setq cur-family (car family)
760               family (cdr family))
761         (if (assoc cur-family font-x-family-mappings)
762             ;; If the family name is an alias as defined by
763             ;; font-x-family-mappings, then append those families
764             ;; to the front of 'family' and continue in the loop.
765             ;; #### jhar: I don't know about ns font names, so using X mappings
766             (setq family (append
767                           (cdr-safe (assoc cur-family
768                                            font-x-family-mappings))
769                           family))
770           ;; CARL: Need help here - I am not familiar with the NS font
771           ;; model
772           (setq font-name "UNKNOWN FORMULA GOES HERE"
773                 done (try-font-name font-name device))))
774       (if done font-name))))
775
776 \f
777 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
778 ;;; The window-system dependent code (mswindows-style)
779 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
780
781 ;;; mswindows fonts look like:
782 ;;;     fontname[:[weight][ style][:pointsize[:effects]]][:charset]
783 ;;; A minimal mswindows font spec looks like:
784 ;;;     Courier New
785 ;;; A maximal mswindows font spec looks like:
786 ;;;     Courier New:Bold Italic:10:underline strikeout:western
787 ;;; Missing parts of the font spec should be filled in with these values:
788 ;;;     Courier New:Regular:10::western
789 ;;  "^[a-zA-Z ]+:[a-zA-Z ]*:[0-9]+:[a-zA-Z ]*:[a-zA-Z 0-9]*$"
790 (defvar font-mswindows-font-regexp
791   (let
792       ((-               ":")
793        (fontname        "\\([a-zA-Z ]+\\)")
794        (weight          "\\([a-zA-Z]*\\)")
795        (style           "\\( [a-zA-Z]*\\)?")
796        (pointsize       "\\([0-9]+\\)")
797        (effects         "\\([a-zA-Z ]*\\)")
798        (charset         "\\([a-zA-Z 0-9]*\\)")
799        )
800     (concat "^"
801             fontname - weight style - pointsize - effects - charset "$")))
802
803 (defconst mswindows-font-weight-mappings
804   '((:extra-light . "Extralight")
805     (:light       . "Light")
806     (:demi-light  . "Demilight")
807     (:demi        . "Demi")
808     (:book        . "Book")
809     (:medium      . "Medium")
810     (:normal      . "Normal")
811     (:demi-bold   . "Demibold")
812     (:bold        . "Bold")
813     (:regular     . "Regular")
814     (:extra-bold  . "Extrabold"))
815   "An assoc list mapping keywords to actual mswindows specific strings
816 for use in the 'weight' field of an mswindows font string.")
817
818 (defvar font-mswindows-family-mappings
819   '(
820     ("serif"        . ("times new roman"
821                        "century schoolbook"
822                        "book antiqua"
823                        "bookman old style"))
824     ("sans-serif"   . ("arial"
825                        "verdana"
826                        "lucida sans unicode"))
827     ("monospace"    . ("courier new"
828                        "lucida console"
829                        "courier"
830                        "terminal"))
831     ("cursive"      . ("roman"
832                        "script"))
833     )
834   "A list of font family mappings on mswindows devices.")
835
836 (defun mswindows-font-create-object (fontname &optional device)
837   "Return a font descriptor object for FONTNAME, appropriate for MS Windows devices."
838   (let ((case-fold-search t)
839         (font (mswindows-font-canonicalize-name fontname)))
840     (if (or (not (stringp font))
841             (not (string-match font-mswindows-font-regexp font)))
842         (make-font)
843       (let ((family     (match-string 1 font))
844             (weight     (match-string 2 font))
845             (style      (match-string 3 font))
846             (pointsize  (match-string 4 font))
847             (effects    (match-string 5 font))
848             (charset    (match-string 6 font))
849             (retval nil)
850             (size nil)
851             (case-fold-search t)
852             )
853         (if pointsize (setq size (concat pointsize "pt")))
854         (if weight (setq weight (intern-soft (concat ":" (downcase weight)))))
855         (setq retval (make-font :family family
856                                 :weight weight
857                                 :size size
858                                 :encoding charset))
859         (set-font-bold-p retval (eq :bold weight))
860         (cond
861          ((null style) nil)
862          ((string-match "^ *[iI]talic" style)
863           (set-font-italic-p retval t)))
864         (cond
865          ((null effects) nil)
866          ((string-match "^[uU]nderline [sS]trikeout" effects)
867           (set-font-underline-p retval t)
868           (set-font-strikethru-p retval t))
869          ((string-match "[uU]nderline" effects)
870           (set-font-underline-p retval t))
871          ((string-match "[sS]trikeout" effects)
872           (set-font-strikethru-p retval t)))
873         retval))))
874
875 (defun mswindows-font-create-name (fontobj &optional device)
876   "Return a font name constructed from FONTOBJ, appropriate for MS Windows devices."
877   (if (and (not (or (font-family fontobj)
878                     (font-weight fontobj)
879                     (font-size fontobj)
880                     (font-registry fontobj)
881                     (font-encoding fontobj)))
882            (= (font-style fontobj) 0))
883       (face-font 'default)
884     (or device (setq device (selected-device)))
885     (let* ((default (font-default-object-for-device device))
886            (family (or (font-family fontobj)
887                        (font-family default)))
888            (weight (or (font-weight fontobj) :regular))
889            (style (font-style fontobj))
890            (size (or (if font-running-xemacs
891                          (font-size fontobj))
892                      (font-size default)))
893            (underline-p (font-underline-p fontobj))
894            (strikeout-p (font-strikethru-p fontobj))
895            (encoding (or (font-encoding fontobj)
896                          (font-encoding default))))
897       (if (stringp family)
898           (setq family (list family)))
899       (setq weight (font-higher-weight weight
900                                        (and (font-bold-p fontobj) :bold)))
901       (if (stringp size)
902           (setq size (truncate (font-spatial-to-canonical size device))))
903       (setq weight (or (cdr-safe
904                         (assq weight mswindows-font-weight-mappings)) ""))
905       (let ((done nil)                  ; Did we find a good font yet?
906             (font-name nil)             ; font name we are currently checking
907             (cur-family nil)            ; current family we are checking
908             )
909         (while (and family (not done))
910           (setq cur-family (car family)
911                 family (cdr family))
912           (if (assoc cur-family font-mswindows-family-mappings)
913               ;; If the family name is an alias as defined by
914               ;; font-mswindows-family-mappings, then append those families
915               ;; to the front of 'family' and continue in the loop.
916               (setq family (append
917                             (cdr-safe (assoc cur-family
918                                              font-mswindows-family-mappings))
919                             family))
920             ;; We treat oblique and italic as equivalent.  Don't ask.
921             ;; Courier New:Bold Italic:10:underline strikeout:western
922             (setq font-name (format "%s:%s%s:%s:%s:%s"
923                                     cur-family weight
924                                     (if (font-italic-p fontobj)
925                                         " Italic" "")
926                                     (if size
927                                         (int-to-string size) "10")
928                                     (if underline-p
929                                         (if strikeout-p
930                                             "underline strikeout"
931                                           "underline")
932                                       (if strikeout-p "strikeout" ""))
933                                     (if encoding
934                                         encoding ""))
935                   done (try-font-name font-name device))))
936         (if done font-name)))))
937
938 \f
939 ;;; Cache building code
940 ;;;###autoload
941 (defun x-font-build-cache (&optional device)
942   (let ((hash-table (make-hash-table :test 'equal :size 15))
943         (fonts (mapcar 'x-font-create-object
944                        (x-list-fonts "-*-*-*-*-*-*-*-*-*-*-*-*-*-*")))
945         (plist nil)
946         (cur nil))
947     (while fonts
948       (setq cur (car fonts)
949             fonts (cdr fonts)
950             plist (cl-gethash (car (font-family cur)) hash-table))
951       (if (not (memq (font-weight cur) (plist-get plist 'weights)))
952           (setq plist (plist-put plist 'weights (cons (font-weight cur)
953                                                       (plist-get plist 'weights)))))
954       (if (not (member (font-size cur) (plist-get plist 'sizes)))
955           (setq plist (plist-put plist 'sizes (cons (font-size cur)
956                                                     (plist-get plist 'sizes)))))
957       (if (and (font-oblique-p cur)
958                (not (memq 'oblique (plist-get plist 'styles))))
959           (setq plist (plist-put plist 'styles (cons 'oblique (plist-get plist 'styles)))))
960       (if (and (font-italic-p cur)
961                (not (memq 'italic (plist-get plist 'styles))))
962           (setq plist (plist-put plist 'styles (cons 'italic (plist-get plist 'styles)))))
963       (cl-puthash (car (font-family cur)) plist hash-table))
964     hash-table))
965
966 \f
967 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
968 ;;; Now overwrite the original copy of set-face-font with our own copy that
969 ;;; can deal with either syntax.
970 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
971 ;;; ###autoload
972 (defun font-set-face-font (&optional face font &rest args)
973   (cond
974    ((and (vectorp font) (= (length font) 12))
975     (let ((font-name (font-create-name font)))
976       (set-face-property face 'font-specification font)
977       (cond
978        ((null font-name)                ; No matching font!
979         nil)
980        ((listp font-name)               ; For TTYs
981         (let (cur)
982           (while font-name
983             (setq cur (car font-name)
984                   font-name (cdr font-name))
985             (apply 'set-face-property face (car cur) (cdr cur) args))))
986        (font-running-xemacs
987         (apply 'set-face-font face font-name args)
988         (apply 'set-face-underline-p face (font-underline-p font) args)
989         (if (and (or (font-smallcaps-p font) (font-bigcaps-p font))
990                  (fboundp 'set-face-display-table))
991             (apply 'set-face-display-table
992                    face font-caps-display-table args))
993         (apply 'set-face-property face 'strikethru (or
994                                                     (font-linethrough-p font)
995                                                     (font-strikethru-p font))
996                args))
997        (t
998         (condition-case nil
999             (apply 'set-face-font face font-name args)
1000           (error
1001            (let ((args (car-safe args)))
1002              (and (or (font-bold-p font)
1003                       (memq (font-weight font) '(:bold :demi-bold)))
1004                   (make-face-bold face args t))
1005              (and (font-italic-p font) (make-face-italic face args t)))))
1006         (apply 'set-face-underline-p face (font-underline-p font) args)))))
1007    (t
1008     ;; Let the original set-face-font signal any errors
1009     (set-face-property face 'font-specification nil)
1010     (apply 'set-face-font face font args))))
1011
1012 \f
1013 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1014 ;;; Now for emacsen specific stuff
1015 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1016 (defun font-update-device-fonts (device)
1017   ;; Update all faces that were created with the 'font' package
1018   ;; to appear correctly on the new device.  This should be in the
1019   ;; create-device-hook.  This is XEmacs 19.12+ specific
1020   (let ((faces (face-list 2))
1021         (cur nil)
1022         (font nil)
1023         (font-spec nil))
1024     (while faces
1025       (setq cur (car faces)
1026             faces (cdr faces)
1027             font-spec (face-property cur 'font-specification))
1028       (if font-spec
1029           (set-face-font cur font-spec device)))))
1030
1031 (defun font-update-one-face (face &optional device-list)
1032   ;; Update FACE on all devices in DEVICE-LIST
1033   ;; DEVICE_LIST defaults to a list of all active devices
1034   (setq device-list (or device-list (device-list)))
1035   (if (devicep device-list)
1036       (setq device-list (list device-list)))
1037   (let* ((cur-device nil)
1038          (font-spec (face-property face 'font-specification))
1039          (font nil))
1040     (if (not font-spec)
1041         ;; Hey!  Don't mess with fonts we didn't create in the
1042         ;; first place.
1043         nil
1044       (while device-list
1045         (setq cur-device (car device-list)
1046               device-list (cdr device-list))
1047         (if (not (device-live-p cur-device))
1048             ;; Whoah!
1049             nil
1050           (if font-spec
1051               (set-face-font face font-spec cur-device)))))))
1052
1053 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1054 ;;; Various color related things
1055 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1056 (cond
1057  ((fboundp 'display-warning)
1058   (fset 'font-warn 'display-warning))
1059  ((fboundp 'w3-warn)
1060   (fset 'font-warn 'w3-warn))
1061  ((fboundp 'url-warn)
1062   (fset 'font-warn 'url-warn))
1063  ((fboundp 'warn)
1064   (defun font-warn (class message &optional level)
1065     (warn "(%s/%s) %s" class (or level 'warning) message)))
1066  (t
1067   (defun font-warn (class message &optional level)
1068     (save-excursion
1069       (set-buffer (get-buffer-create "*W3-WARNINGS*"))
1070       (goto-char (point-max))
1071       (save-excursion
1072         (insert (format "(%s/%s) %s\n" class (or level 'warning) message)))
1073       (display-buffer (current-buffer))))))
1074
1075 (defun font-lookup-rgb-components (color)
1076   "Lookup COLOR (a color name) in rgb.txt and return a list of RGB values.
1077 The list (R G B) is returned, or an error is signaled if the lookup fails."
1078   (let ((lib-list (if (boundp 'x-library-search-path)
1079                       x-library-search-path
1080                     ;; This default is from XEmacs 19.13 - hope it covers
1081                     ;; everyone.
1082                     (list "/usr/X11R6/lib/X11/"
1083                           "/usr/X11R5/lib/X11/"
1084                           "/usr/lib/X11R6/X11/"
1085                           "/usr/lib/X11R5/X11/"
1086                           "/usr/local/X11R6/lib/X11/"
1087                           "/usr/local/X11R5/lib/X11/"
1088                           "/usr/local/lib/X11R6/X11/"
1089                           "/usr/local/lib/X11R5/X11/"
1090                           "/usr/X11/lib/X11/"
1091                           "/usr/lib/X11/"
1092                           "/usr/local/lib/X11/"
1093                           "/usr/X386/lib/X11/"
1094                           "/usr/x386/lib/X11/"
1095                           "/usr/XFree86/lib/X11/"
1096                           "/usr/unsupported/lib/X11/"
1097                           "/usr/athena/lib/X11/"
1098                           "/usr/local/x11r5/lib/X11/"
1099                           "/usr/lpp/Xamples/lib/X11/"
1100                           "/usr/openwin/lib/X11/"
1101                           "/usr/openwin/share/lib/X11/")))
1102         (file font-rgb-file)
1103         r g b)
1104     (if (not file)
1105         (while lib-list
1106           (setq file (expand-file-name "rgb.txt" (car lib-list)))
1107           (if (file-readable-p file)
1108               (setq lib-list nil
1109                     font-rgb-file file)
1110             (setq lib-list (cdr lib-list)
1111                   file nil))))
1112     (if (null file)
1113         (list 0 0 0)
1114       (save-excursion
1115         (set-buffer (find-file-noselect file))
1116         (if (not (= (aref (buffer-name) 0) ? ))
1117             (rename-buffer (generate-new-buffer-name " *rgb-tmp-buffer*")))
1118         (save-excursion
1119           (save-restriction
1120             (widen)
1121             (goto-char (point-min))
1122             (if (re-search-forward (format "\t%s$" (regexp-quote color)) nil t)
1123                 (progn
1124                   (beginning-of-line)
1125                   (setq r (* (read (current-buffer)) 256)
1126                         g (* (read (current-buffer)) 256)
1127                         b (* (read (current-buffer)) 256)))
1128               (font-warn 'color (format "No such color: %s" color))
1129               (setq r 0
1130                     g 0
1131                     b 0))
1132             (list r g b) ))))))
1133
1134 (defun font-hex-string-to-number (string)
1135   "Convert STRING to an integer by parsing it as a hexadecimal number."
1136   (let ((conv-list '((?0 . 0) (?a . 10) (?A . 10)
1137                      (?1 . 1) (?b . 11) (?B . 11)
1138                      (?2 . 2) (?c . 12) (?C . 12)
1139                      (?3 . 3) (?d . 13) (?D . 13)
1140                      (?4 . 4) (?e . 14) (?E . 14)
1141                      (?5 . 5) (?f . 15) (?F . 15)
1142                      (?6 . 6)
1143                      (?7 . 7)
1144                      (?8 . 8)
1145                      (?9 . 9)))
1146         (n 0)
1147         (i 0)
1148         (lim (length string)))
1149     (while (< i lim)
1150       (setq n (+ (* n 16) (or (cdr (assq (aref string i) conv-list)) 0))
1151             i (1+ i)))
1152     n ))
1153
1154 (defun font-parse-rgb-components (color)
1155   "Parse RGB color specification and return a list of integers (R G B).
1156 #FEFEFE and rgb:fe/fe/fe style specifications are parsed."
1157   (let ((case-fold-search t)
1158         r g b str)
1159   (cond ((string-match "^#[0-9a-f]+$" color)
1160          (cond
1161           ((= (length color) 4)
1162            (setq r (font-hex-string-to-number (substring color 1 2))
1163                  g (font-hex-string-to-number (substring color 2 3))
1164                  b (font-hex-string-to-number (substring color 3 4))
1165                  r (* r 4096)
1166                  g (* g 4096)
1167                  b (* b 4096)))
1168           ((= (length color) 7)
1169            (setq r (font-hex-string-to-number (substring color 1 3))
1170                  g (font-hex-string-to-number (substring color 3 5))
1171                  b (font-hex-string-to-number (substring color 5 7))
1172                  r (* r 256)
1173                  g (* g 256)
1174                  b (* b 256)))
1175           ((= (length color) 10)
1176            (setq r (font-hex-string-to-number (substring color 1 4))
1177                  g (font-hex-string-to-number (substring color 4 7))
1178                  b (font-hex-string-to-number (substring color 7 10))
1179                  r (* r 16)
1180                  g (* g 16)
1181                  b (* b 16)))
1182           ((= (length color) 13)
1183            (setq r (font-hex-string-to-number (substring color 1 5))
1184                  g (font-hex-string-to-number (substring color 5 9))
1185                  b (font-hex-string-to-number (substring color 9 13))))
1186           (t
1187            (font-warn 'color (format "Invalid RGB color specification: %s"
1188                                      color))
1189            (setq r 0
1190                  g 0
1191                  b 0))))
1192         ((string-match "rgb:\\([0-9a-f]+\\)/\\([0-9a-f]+\\)/\\([0-9a-f]+\\)"
1193                        color)
1194          (if (or (> (- (match-end 1) (match-beginning 1)) 4)
1195                  (> (- (match-end 2) (match-beginning 2)) 4)
1196                  (> (- (match-end 3) (match-beginning 3)) 4))
1197              (error "Invalid RGB color specification: %s" color)
1198            (setq str (match-string 1 color)
1199                  r (* (font-hex-string-to-number str)
1200                       (expt 16 (- 4 (length str))))
1201                  str (match-string 2 color)
1202                  g (* (font-hex-string-to-number str)
1203                       (expt 16 (- 4 (length str))))
1204                  str (match-string 3 color)
1205                  b (* (font-hex-string-to-number str)
1206                       (expt 16 (- 4 (length str)))))))
1207         (t
1208          (font-warn 'html (format "Invalid RGB color specification: %s"
1209                                 color))
1210          (setq r 0
1211                g 0
1212                b 0)))
1213   (list r g b) ))
1214
1215 (defsubst font-rgb-color-p (obj)
1216   (or (and (vectorp obj)
1217            (= (length obj) 4)
1218            (eq (aref obj 0) 'rgb))))
1219
1220 (defsubst font-rgb-color-red (obj) (aref obj 1))
1221 (defsubst font-rgb-color-green (obj) (aref obj 2))
1222 (defsubst font-rgb-color-blue (obj) (aref obj 3))
1223
1224 (defun font-color-rgb-components (color)
1225   "Return the RGB components of COLOR as a list of integers (R G B).
1226 16-bit values are always returned.
1227 #FEFEFE and rgb:fe/fe/fe style color specifications are parsed directly
1228 into their components.
1229 RGB values for color names are looked up in the rgb.txt file.
1230 The variable x-library-search-path is use to locate the rgb.txt file."
1231   (let ((case-fold-search t))
1232     (cond
1233      ((and (font-rgb-color-p color) (floatp (aref color 1)))
1234       (list (* 65535 (aref color 0))
1235             (* 65535 (aref color 1))
1236             (* 65535 (aref color 2))))
1237      ((font-rgb-color-p color)
1238       (list (font-rgb-color-red color)
1239             (font-rgb-color-green color)
1240             (font-rgb-color-blue color)))
1241      ((and (vectorp color) (= 3 (length color)))
1242       (list (aref color 0) (aref color 1) (aref color 2)))
1243      ((and (listp color) (= 3 (length color)) (floatp (car color)))
1244       (mapcar #'(lambda (x) (* x 65535)) color))
1245      ((and (listp color) (= 3 (length color)))
1246       color)
1247      ((or (string-match "^#" color)
1248           (string-match "^rgb:" color))
1249       (font-parse-rgb-components color))
1250      ((string-match "\\([0-9.]+\\)[ \t]\\([0-9.]+\\)[ \t]\\([0-9.]+\\)"
1251                     color)
1252       (let ((r (string-to-number (match-string 1 color)))
1253             (g (string-to-number (match-string 2 color)))
1254             (b (string-to-number (match-string 3 color))))
1255         (if (floatp r)
1256             (setq r (round (* 255 r))
1257                   g (round (* 255 g))
1258                   b (round (* 255 b))))
1259         (font-parse-rgb-components (format "#%02x%02x%02x" r g b))))
1260      (t
1261       (font-lookup-rgb-components color)))))
1262
1263 (defsubst font-tty-compute-color-delta (col1 col2)
1264   (+
1265    (* (- (aref col1 0) (aref col2 0))
1266       (- (aref col1 0) (aref col2 0)))
1267    (* (- (aref col1 1) (aref col2 1))
1268       (- (aref col1 1) (aref col2 1)))
1269    (* (- (aref col1 2) (aref col2 2))
1270       (- (aref col1 2) (aref col2 2)))))
1271
1272 (defun font-tty-find-closest-color (r g b)
1273   ;; This is basically just a lisp copy of allocate_nearest_color
1274   ;; from objects-x.c from Emacs 19
1275   ;; We really should just check tty-color-list, but unfortunately
1276   ;; that does not include any RGB information at all.
1277   ;; So for now we just hardwire in the default list and call it
1278   ;; good for now.
1279   (setq r (/ r 65535.0)
1280         g (/ g 65535.0)
1281         b (/ b 65535.0))
1282   (let* ((color_def (vector r g b))
1283          (colors [([1.0 1.0 1.0] . "white")
1284                   ([0.0 1.0 1.0] . "cyan")
1285                   ([1.0 0.0 1.0] . "magenta")
1286                   ([0.0 0.0 1.0] . "blue")
1287                   ([1.0 1.0 0.0] . "yellow")
1288                   ([0.0 1.0 0.0] . "green")
1289                   ([1.0 0.0 0.0] . "red")
1290                   ([0.0 0.0 0.0] . "black")])
1291          (no_cells (length colors))
1292          (x 1)
1293          (nearest 0)
1294          (nearest_delta 0)
1295          (trial_delta 0))
1296     (setq nearest_delta (font-tty-compute-color-delta (car (aref colors 0))
1297                                                       color_def))
1298     (while (/= no_cells x)
1299       (setq trial_delta (font-tty-compute-color-delta (car (aref colors x))
1300                                                       color_def))
1301       (if (< trial_delta nearest_delta)
1302           (setq nearest x
1303                 nearest_delta trial_delta))
1304       (setq x (1+ x)))
1305     (cdr-safe (aref colors nearest))))
1306
1307 (defun font-normalize-color (color &optional device)
1308   "Return an RGB tuple, given any form of input.  If an error occurs, black
1309 is returned."
1310   (case (device-type device)
1311    ((x pm)
1312     (apply 'format "#%02x%02x%02x" (font-color-rgb-components color)))
1313    (mswindows
1314     (let* ((rgb (font-color-rgb-components color))
1315            (color (apply 'format "#%02x%02x%02x" rgb)))
1316       (mswindows-define-rgb-color (nth 0 rgb) (nth 1 rgb) (nth 2 rgb) color)
1317       color))
1318    (tty
1319     (apply 'font-tty-find-closest-color (font-color-rgb-components color)))
1320    (ns
1321     (let ((vals (mapcar #'(lambda (x) (>> x 8))
1322                         (font-color-rgb-components color))))
1323       (apply 'format "RGB%02x%02x%02xff" vals)))
1324    (otherwise
1325     color)))
1326
1327 (defun font-set-face-background (&optional face color &rest args)
1328   (interactive)
1329   (condition-case nil
1330       (cond
1331        ((or (font-rgb-color-p color)
1332             (string-match "^#[0-9a-fA-F]+$" color))
1333         (apply 'set-face-background face
1334                (font-normalize-color color) args))
1335        (t
1336         (apply 'set-face-background face color args)))
1337     (error nil)))
1338
1339 (defun font-set-face-foreground (&optional face color &rest args)
1340   (interactive)
1341   (condition-case nil
1342       (cond
1343        ((or (font-rgb-color-p color)
1344             (string-match "^#[0-9a-fA-F]+$" color))
1345         (apply 'set-face-foreground face (font-normalize-color color) args))
1346        (t
1347         (apply 'set-face-foreground face color args)))
1348     (error nil)))
1349
1350 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1351 ;;; Support for 'blinking' fonts
1352 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1353 (defun font-map-windows (func &optional arg frame)
1354   (let* ((start (selected-window))
1355          (cur start)
1356          (result nil))
1357     (push (funcall func start arg) result)
1358     (while (not (eq start (setq cur (next-window cur))))
1359       (push (funcall func cur arg) result))
1360     result))
1361
1362 (defun font-face-visible-in-window-p (window face)
1363   (let ((st (window-start window))
1364         (nd (window-end window))
1365         (found nil)
1366         (face-at nil))
1367     (setq face-at (get-text-property st 'face (window-buffer window)))
1368     (if (or (eq face face-at) (and (listp face-at) (memq face face-at)))
1369         (setq found t))
1370     (while (and (not found)
1371                 (/= nd
1372                     (setq st (next-single-property-change
1373                               st 'face
1374                               (window-buffer window) nd))))
1375       (setq face-at (get-text-property st 'face (window-buffer window)))
1376       (if (or (eq face face-at) (and (listp face-at) (memq face face-at)))
1377           (setq found t)))
1378     found))
1379
1380 (defun font-blink-callback ()
1381   ;; Optimized to never invert the face unless one of the visible windows
1382   ;; is showing it.
1383   (let ((faces (if font-running-xemacs (face-list t) (face-list)))
1384         (obj nil))
1385     (while faces
1386       (if (and (setq obj (face-property (car faces) 'font-specification))
1387                (font-blink-p obj)
1388                (memq t
1389                      (font-map-windows 'font-face-visible-in-window-p (car faces))))
1390           (invert-face (car faces)))
1391       (pop faces))))
1392
1393 (defcustom font-blink-interval 0.5
1394   "How often to blink faces"
1395   :type 'number
1396   :group 'faces)
1397
1398 (defun font-blink-initialize ()
1399   (cond
1400    ((featurep 'itimer)
1401     (if (get-itimer "font-blinker")
1402         (delete-itimer (get-itimer "font-blinker")))
1403     (start-itimer "font-blinker" 'font-blink-callback
1404                   font-blink-interval
1405                   font-blink-interval))
1406    ((fboundp 'run-at-time)
1407     (cancel-function-timers 'font-blink-callback)
1408     (run-at-time font-blink-interval
1409                  font-blink-interval
1410                  'font-blink-callback))
1411    (t nil)))
1412
1413 (provide 'font)