All of SXEmacs' http URLs are now https. WooHoo!
[sxemacs] / 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 SXEmacs.
12 ;;;
13 ;; SXEmacs 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 3 of the License, or
16 ;; (at your option) any later version.
17
18 ;; SXEmacs 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 this program.  If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
26 (require 'cus-face)
27
28 (globally-declare-fboundp
29  '(x-list-fonts internal-facep fontsetp
30                 get-font-info get-fontset-info font-color-rgb-components
31                 font-rgb-color-p cancel-function-timers run-at-time
32                 set-font-oblique-p set-font-italic-p set-font-bold-p
33                 font-dropcaps-p font-bigcaps-p font-smallcaps-p font-blink-p
34                 font-reverse-p font-strikethru-p font-linethrough-p
35                 font-overline-p font-underline-p font-dim-p font-oblique-p
36                 font-italic-p font-bold-p))
37
38 (globally-declare-boundp 'global-face-data)
39
40 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
41 ;;; The emacsen compatibility package - load it up before anything else
42 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
43 (require 'cl)
44
45 (eval-and-compile
46   (defvar device-fonts-cache)
47   (condition-case ()
48       (require 'custom)
49     (error nil))
50   (if (and (featurep 'custom) (fboundp 'custom-declare-variable))
51       nil ;; We've got what we needed
52     ;; We have the old custom-library, hack around it!
53     (defmacro defgroup (&rest args)
54       nil)
55     (defmacro defcustom (var value doc &rest args)
56       `(defvar ,var ,value ,doc))))
57
58 (if (not (fboundp 'try-font-name))
59     (defun try-font-name (fontname &rest args)
60       (case window-system
61         ((x) (car-safe (x-list-fonts fontname)))
62         (otherwise nil))))
63
64 (if (not (fboundp 'facep))
65     (defun facep (face)
66       "Return t if X is a face name or an internal face vector."
67       (if (not window-system)
68           nil                           ; FIXME if FSF ever does TTY faces
69         (and (or (internal-facep face)
70                  (and (symbolp face) (assq face global-face-data)))
71              t))))
72
73 (if (not (fboundp 'set-face-property))
74     (defun set-face-property (face property value &optional locale
75                                    tag-set how-to-add)
76       "Change a property of FACE."
77       (and (symbolp face)
78            (put face property value))))
79
80 (if (not (fboundp 'face-property))
81     (defun face-property (face property &optional locale tag-set exact-p)
82       "Return FACE's value of the given PROPERTY."
83       (and (symbolp face) (get face property))))
84
85 (require 'disp-table)
86
87 (eval-and-compile
88   (unless (fboundp #'<<)
89     (fset #'<< #'lsh))
90   (unless (fboundp #'&)
91     (fset #'& #'logand))
92   (unless (fboundp #'|)
93     (fset #'| #'logior))
94   (unless (fboundp #'~)
95     (fset #'~ #'lognot))
96   (unless (fboundp #'>>)
97     (defun >> (value count)
98       (<< value (- count)))))
99
100 \f
101 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
102 ;;; Lots of variables / keywords for use later in the program
103 ;;; Not much should need to be modified
104 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
105 (defconst font-running-xemacs (string-match "XEmacs" (emacs-version))
106   "Whether we are running in XEmacs or not.")
107
108 (defmacro define-font-keywords (&rest keys)
109   `(eval-and-compile
110      (let ((keywords (quote ,keys)))
111        (while keywords
112          (or (boundp (car keywords))
113              (set (car keywords) (car keywords)))
114          (setq keywords (cdr keywords))))))
115
116 (defconst font-window-system-mappings
117   '((x         . (x-font-create-name x-font-create-object))
118     (tty       . (tty-font-create-plist tty-font-create-object)))
119   "An assoc list mapping device types to a list of translations.
120
121 The first function creates a font name from a font descriptor object.
122 The second performs the reverse translation.")
123
124 (defconst x-font-weight-mappings
125   '((:extra-light . "extralight")
126     (:light       . "light")
127     (:demi-light  . "demilight")
128     (:demi        . "demi")
129     (:book        . "book")
130     (:medium      . "medium")
131     (:normal      . "medium")
132     (:demi-bold   . "demibold")
133     (:bold        . "bold")
134     (:extra-bold  . "extrabold"))
135   "An assoc list mapping keywords to actual Xwindow specific strings
136 for use in the 'weight' field of an X font string.")
137
138 (defconst font-possible-weights
139   (mapcar 'car x-font-weight-mappings))
140
141 (defvar font-rgb-file nil
142   "Where the RGB file was found.")
143
144 (defvar font-maximum-slippage "1pt"
145   "How much a font is allowed to vary from the desired size.")
146
147 ;; Canonical (internal) sizes are in points.
148 ;; Registry
149 (define-font-keywords :family :style :size :registry :encoding)
150
151 (define-font-keywords
152   :weight :extra-light :light :demi-light :medium :normal :demi-bold
153   :bold :extra-bold)
154
155 (defvar font-style-keywords nil)
156
157 (defsubst set-font-family (fontobj family)
158   (aset fontobj 1 family))
159
160 (defsubst set-font-weight (fontobj weight)
161   (aset fontobj 3 weight))
162
163 (defsubst set-font-style (fontobj style)
164   (aset fontobj 5 style))
165
166 (defsubst set-font-size (fontobj size)
167   (aset fontobj 7 size))
168
169 (defsubst set-font-registry (fontobj reg)
170   (aset fontobj 9 reg))
171
172 (defsubst set-font-encoding (fontobj enc)
173   (aset fontobj 11 enc))
174
175 (defsubst font-family (fontobj)
176   (aref fontobj 1))
177
178 (defsubst font-weight (fontobj)
179   (aref fontobj 3))
180
181 (defsubst font-style (fontobj)
182   (aref fontobj 5))
183
184 (defsubst font-size (fontobj)
185   (aref fontobj 7))
186
187 (defsubst font-registry (fontobj)
188   (aref fontobj 9))
189
190 (defsubst font-encoding (fontobj)
191   (aref fontobj 11))
192
193 (eval-when-compile
194   (defmacro define-new-mask (attr mask)
195     `(progn
196        (setq font-style-keywords
197              (cons (cons (quote ,attr)
198                          (cons
199                           (quote ,(intern (format "set-font-%s-p" attr)))
200                           (quote ,(intern (format "font-%s-p" attr)))))
201                    font-style-keywords))
202        (defconst ,(intern (format "font-%s-mask" attr)) (<< 1 ,mask)
203          ,(format
204            "Bitmask for whether a font is to be rendered in %s or not."
205            attr))
206        (defun ,(intern (format "font-%s-p" attr)) (fontobj)
207          ,(format "Whether FONTOBJ will be renderd in `%s' or not." attr)
208          (if (/= 0 (& (font-style fontobj)
209                       ,(intern (format "font-%s-mask" attr))))
210              t
211            nil))
212        (defun ,(intern (format "set-font-%s-p" attr)) (fontobj val)
213          ,(format "Set whether FONTOBJ will be renderd in `%s' or not."
214                   attr)
215          (cond
216           (val
217            (set-font-style fontobj (| (font-style fontobj)
218                                       ,(intern
219                                         (format "font-%s-mask" attr)))))
220           ((,(intern (format "font-%s-p" attr)) fontobj)
221            (set-font-style fontobj (- (font-style fontobj)
222                                       ,(intern
223                                         (format "font-%s-mask" attr)))))))
224        )))
225
226 (let ((mask 0))
227   (define-new-mask bold        (setq mask (1+ mask)))
228   (define-new-mask italic      (setq mask (1+ mask)))
229   (define-new-mask oblique     (setq mask (1+ mask)))
230   (define-new-mask dim         (setq mask (1+ mask)))
231   (define-new-mask underline   (setq mask (1+ mask)))
232   (define-new-mask overline    (setq mask (1+ mask)))
233   (define-new-mask linethrough (setq mask (1+ mask)))
234   (define-new-mask strikethru  (setq mask (1+ mask)))
235   (define-new-mask reverse     (setq mask (1+ mask)))
236   (define-new-mask blink       (setq mask (1+ mask)))
237   (define-new-mask smallcaps   (setq mask (1+ mask)))
238   (define-new-mask bigcaps     (setq mask (1+ mask)))
239   (define-new-mask dropcaps    (setq mask (1+ mask))))
240
241 (defvar font-caps-display-table
242   (let ((table (make-display-table))
243         (i 0))
244     ;; Standard ASCII characters
245     (while (< i 26)
246       (aset table (+ i ?a) (+ i ?A))
247       (setq i (1+ i)))
248     ;; Now ISO translations
249     (setq i 224)
250     (while (< i 247)                    ;; Agrave - Ouml
251       (aset table i (- i 32))
252       (setq i (1+ i)))
253     (setq i 248)
254     (while (< i 255)                    ;; Oslash - Thorn
255       (aset table i (- i 32))
256       (setq i (1+ i)))
257     table))
258 \f
259 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
260 ;;; Utility functions
261 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
262 (defsubst set-font-style-by-keywords (fontobj styles)
263   (make-local-variable 'font-func)
264   (declare (special font-func))
265   (if (listp styles)
266       (while styles
267         (setq font-func (car-safe (cdr-safe (assq (car styles) font-style-keywords)))
268               styles (cdr styles))
269         (and (fboundp font-func) (funcall font-func fontobj t)))
270     (setq font-func (car-safe (cdr-safe (assq styles font-style-keywords))))
271     (and (fboundp font-func) (funcall font-func fontobj t))))
272
273 (defsubst font-properties-from-style (fontobj)
274   (let (;(style (font-style fontobj))
275         (todo font-style-keywords)
276         type func retval)
277     (while todo
278       (setq func (cdr (cdr (car todo)))
279             type (car (pop todo)))
280       (if (funcall func fontobj)
281           (setq retval (cons type retval))))
282     retval))
283
284 (defun font-unique (list)
285   (let ((retval)
286         (cur))
287     (while list
288       (setq cur (car list)
289             list (cdr list))
290       (if (member cur retval)
291           nil
292         (setq retval (cons cur retval))))
293     (nreverse retval)))
294
295 (defun font-higher-weight (w1 w2)
296   (let ((index1 (length (memq w1 font-possible-weights)))
297         (index2 (length (memq w2 font-possible-weights))))
298     (cond
299      ((<= index1 index2)
300       (or w1 w2))
301      ((not w2)
302       w1)
303      (t
304       w2))))
305
306 (defun font-spatial-to-canonical (spec &optional device)
307   "Convert SPEC (in inches, millimeters, points, picas, or pixels) into points.
308
309 Canonical sizes are in points.  If SPEC is null, nil is returned.  If SPEC is
310 a number, it is interpreted as the desired point size and returned unchanged.
311 Otherwise SPEC must be a string consisting of a number and an optional type.
312 The type may be the strings \"px\", \"pix\", or \"pixel\" (pixels), \"pt\" or
313 \"point\" (points), \"pa\" or \"pica\" (picas), \"in\" or \"inch\" (inches), \"cm\"
314 (centimeters), or \"mm\" (millimeters).
315
316 1 in = 2.54 cm = 6 pa = 25.4 mm = 72 pt.  Pixel size is device-dependent."
317   (cond
318    ((numberp spec)
319     spec)
320    ((null spec)
321     nil)
322    (t
323     (let ((num nil)
324           (type nil)
325           ;; If for any reason we get null for any of this, default
326           ;; to 1024x768 resolution on a 17" screen
327           (pix-width (float (or (device-pixel-width device) 1024)))
328           (mm-width (float (or (device-mm-width device) 293)))
329           (retval nil))
330       (cond
331        ;; the following string-match is broken, there will never be a
332        ;; left operand detected
333        ((string-match #r"^ *\([-+*/]\) *" spec) ; math!  whee!
334         (let ((math-func (intern (match-string 1 spec)))
335               (other (font-spatial-to-canonical
336                       (substring spec (match-end 0) nil)))
337               (default (font-spatial-to-canonical
338                         (font-default-size-for-device device))))
339           (if (fboundp math-func)
340               (setq type "px"
341                     spec (int-to-string (funcall math-func default other)))
342             (setq type "px"
343                   spec (int-to-string other)))))
344        ((string-match "[^0-9.]+$" spec)
345         (setq type (substring spec (match-beginning 0))
346               spec (substring spec 0 (match-beginning 0))))
347        (t
348         (setq type "px"
349               spec spec)))
350       (setq num (string-to-number spec))
351       (cond
352        ((member type '("pixel" "px" "pix"))
353         (setq retval (* num (/ pix-width mm-width) (/ 25.4 72.0))))
354        ((member type '("point" "pt"))
355         (setq retval num))
356        ((member type '("pica" "pa"))
357         (setq retval (* num 12.0)))
358        ((member type '("inch" "in"))
359         (setq retval (* num 72.0)))
360        ((string= type "mm")
361         (setq retval (* num (/ 72.0 25.4))))
362        ((string= type "cm")
363         (setq retval (* num 10 (/ 72.0 25.4))))
364        (t
365         (setq retval num))
366        )
367       retval))))
368
369 \f
370 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
371 ;;; The main interface routines - constructors and accessor functions
372 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
373 (defun make-font (&rest args)
374   (vector :family
375           (if (stringp (plist-get args :family))
376               (list (plist-get args :family))
377             (plist-get args :family))
378           :weight
379           (plist-get args :weight)
380           :style
381           (if (numberp (plist-get args :style))
382               (plist-get args :style)
383             0)
384           :size
385           (plist-get args :size)
386           :registry
387           (plist-get args :registry)
388           :encoding
389           (plist-get args :encoding)))
390
391 (defun font-create-name (fontobj &optional device)
392   "Return a font name constructed from FONTOBJ, appropriate for DEVICE."
393   (let* ((type (device-type device))
394          (func (car (cdr-safe (assq type font-window-system-mappings)))))
395     (and func (fboundp func) (funcall func fontobj device))))
396
397 ;;;###autoload
398 (defun font-create-object (fontname &optional device)
399   "Return a font descriptor object for FONTNAME, appropriate for DEVICE."
400   (let* ((type (device-type device))
401          (func (car (cdr (cdr-safe (assq type font-window-system-mappings))))))
402     (and func (fboundp func) (funcall func fontname device))))
403
404 (defun font-combine-fonts-internal (fontobj-1 fontobj-2)
405   (let ((retval (make-font))
406         (size-1 (and (font-size fontobj-1)
407                      (font-spatial-to-canonical (font-size fontobj-1))))
408         (size-2 (and (font-size fontobj-2)
409                      (font-spatial-to-canonical (font-size fontobj-2)))))
410     (set-font-weight retval (font-higher-weight (font-weight fontobj-1)
411                                                 (font-weight fontobj-2)))
412     (set-font-family retval (font-unique (append (font-family fontobj-1)
413                                                  (font-family fontobj-2))))
414     (set-font-style retval (| (font-style fontobj-1) (font-style fontobj-2)))
415     (set-font-registry retval (or (font-registry fontobj-1)
416                                   (font-registry fontobj-2)))
417     (set-font-encoding retval (or (font-encoding fontobj-1)
418                                   (font-encoding fontobj-2)))
419     (set-font-size retval (cond
420                            ((and size-1 size-2 (>= size-2 size-1))
421                             (font-size fontobj-2))
422                            ((and size-1 size-2)
423                             (font-size fontobj-1))
424                            (size-1
425                             (font-size fontobj-1))
426                            (size-2
427                             (font-size fontobj-2))
428                            (t nil)))
429
430     retval))
431
432 (defun font-combine-fonts (&rest args)
433   (cond
434    ((null args)
435     (error "Wrong number of arguments to font-combine-fonts"))
436    ((= (length args) 1)
437     (car args))
438    (t
439     (let ((retval (font-combine-fonts-internal (nth 0 args) (nth 1 args))))
440       (setq args (cdr (cdr args)))
441       (while args
442         (setq retval (font-combine-fonts-internal retval (car args))
443               args (cdr args)))
444       retval))))
445
446 \f
447 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
448 ;;; The window-system dependent code (TTY-style)
449 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
450 (defun tty-font-create-object (fontname &optional device)
451   "Return a font descriptor object for FONTNAME, appropriate for TTY devices."
452   (make-font :size "12pt"))
453
454 (defun tty-font-create-plist (fontobj &optional device)
455   "Return a font name constructed from FONTOBJ, appropriate for TTY devices."
456   (list
457    (cons 'underline (font-underline-p fontobj))
458    (cons 'highlight (if (or (font-bold-p fontobj)
459                             (memq (font-weight fontobj) '(:bold :demi-bold)))
460                         t))
461    (cons 'dim       (font-dim-p fontobj))
462    (cons 'blinking  (font-blink-p fontobj))
463    (cons 'reverse   (font-reverse-p fontobj))))
464
465 \f
466 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
467 ;;; The window-system dependent code (X-style)
468 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
469 (defvar font-x-font-regexp (or (and font-running-xemacs
470                                     (boundp 'x-font-regexp)
471                                     x-font-regexp)
472  (let
473      ((-                "[-?]")
474       (foundry          "[^-]*")
475       (family           "[^-]*")
476       ;(weight          #r"\(bold\|demibold\|medium\|black\)")
477       (weight\?         #r"\([^-]*\)")
478       ;(slant           #r"\([ior]\)")
479       (slant\?          #r"\([^-]?\)")
480       (swidth           #r"\([^-]*\)")
481       (adstyle          #r"\([^-]*\)")
482       (pixelsize        #r"\(\*\|[0-9]+\)")
483       (pointsize        #r"\(\*\|0\|[0-9][0-9]+\)")
484       (resx             #r"\([*0]\|[0-9][0-9]+\)")
485       (resy             #r"\([*0]\|[0-9][0-9]+\)")
486       (spacing          "[cmp?*]")
487       (avgwidth         #r"\(\*\|[0-9]+\)")
488       (registry         "[^-]*")
489       (encoding "[^-]+")
490       )
491    (concat #r"\`\*?[-?*]"
492            foundry - family - weight\? - slant\? - swidth - adstyle -
493            pixelsize - pointsize - resx - resy - spacing - avgwidth -
494            registry - encoding "\\'"
495            ))))
496
497 (defvar font-x-registry-and-encoding-regexp
498   (or (and font-running-xemacs
499            (boundp 'x-font-regexp-registry-and-encoding)
500            (symbol-value 'x-font-regexp-registry-and-encoding))
501       (let ((- "[-?]")
502             (registry "[^-]*")
503             (encoding "[^-]+"))
504         (concat - "\\(" registry "\\)" - "\\(" encoding "\\)\\'"))))
505
506 (defvar font-x-family-mappings
507   '(
508     ("serif"        . ("new century schoolbook"
509                        "utopia"
510                        "charter"
511                        "times"
512                        "lucidabright"
513                        "garamond"
514                        "palatino"
515                        "times new roman"
516                        "baskerville"
517                        "bookman"
518                        "bodoni"
519                        "computer modern"
520                        "rockwell"
521                        ))
522     ("sans-serif"   . ("lucida"
523                        "helvetica"
524                        "gills-sans"
525                        "avant-garde"
526                        "univers"
527                        "optima"))
528     ("elfin"        . ("tymes"))
529     ("monospace"    . ("courier"
530                        "fixed"
531                        "lucidatypewriter"
532                        "clean"
533                        "terminal"))
534     ("cursive"      . ("sirene"
535                        "zapf chancery"))
536     )
537   "A list of font family mappings on X devices.")
538
539 (defun x-font-create-object (fontname &optional device)
540   "Return a font descriptor object for FONTNAME, appropriate for X devices."
541   (let ((case-fold-search t))
542     (if (or (not (stringp fontname))
543             (not (string-match font-x-font-regexp fontname)))
544         (make-font)
545       (let ((family nil)
546             ;(style nil)
547             (size nil)
548             (weight  (match-string 1 fontname))
549             (slant   (match-string 2 fontname))
550             (swidth  (match-string 3 fontname))
551             (adstyle (match-string 4 fontname))
552             (pxsize  (match-string 5 fontname))
553             (ptsize  (match-string 6 fontname))
554             (retval nil)
555             (case-fold-search t)
556             )
557         (if (not (string-match x-font-regexp-foundry-and-family fontname))
558             nil
559           (setq family (list (downcase (match-string 1 fontname)))))
560         (if (string= "*" weight)  (setq weight  nil))
561         (if (string= "*" slant)   (setq slant   nil))
562         (if (string= "*" swidth)  (setq swidth  nil))
563         (if (string= "*" adstyle) (setq adstyle nil))
564         (if (string= "*" pxsize)  (setq pxsize  nil))
565         (if (string= "*" ptsize)  (setq ptsize  nil))
566         (if ptsize (setq size (/ (string-to-int ptsize) 10)))
567         (if (and (not size) pxsize) (setq size (concat pxsize "px")))
568         (if weight (setq weight (intern-soft (concat ":" (downcase weight)))))
569         (if (and adstyle (not (equal adstyle "")))
570             (setq family (append family (list (downcase adstyle)))))
571         (setq retval (make-font :family family
572                                 :weight weight
573                                 :size size))
574         (set-font-bold-p retval (eq :bold weight))
575         (cond
576          ((null slant) nil)
577          ((member slant '("i" "I"))
578           (set-font-italic-p retval t))
579          ((member slant '("o" "O"))
580           (set-font-oblique-p retval t)))
581         (when (string-match font-x-registry-and-encoding-regexp fontname)
582           (set-font-registry retval (match-string 1 fontname))
583           (set-font-encoding retval (match-string 2 fontname)))
584         retval))))
585
586 (defun x-font-families-for-device (&optional device no-resetp)
587   (ignore-errors (require 'x-font-menu))
588   (or device (setq device (selected-device)))
589   (if (boundp 'device-fonts-cache)
590       (let ((menu (or (cdr-safe (assq device device-fonts-cache)))))
591         (if (and (not menu) (not no-resetp))
592             (progn
593               (declare-fboundp (reset-device-font-menus device))
594               (x-font-families-for-device device t))
595           (let ((scaled (mapcar #'(lambda (x) (if x (aref x 0)))
596                                 (aref menu 0)))
597                 (normal (mapcar #'(lambda (x) (if x (aref x 0)))
598                                 (aref menu 1))))
599             (sort (font-unique (nconc scaled normal)) 'string-lessp))))
600     (cons "monospace" (mapcar 'car font-x-family-mappings))))
601
602 (defvar font-default-cache nil)
603
604 ;;;###autoload
605 (defun font-default-font-for-device (&optional device)
606   (or device (setq device (selected-device)))
607   (if font-running-xemacs
608       (font-truename
609        (make-font-specifier
610         (face-font-name 'default device)))
611     (let ((font (cdr-safe (assq 'font (frame-parameters device)))))
612       (if (and (fboundp 'fontsetp) (fontsetp font))
613           (aref (get-font-info (aref (cdr (get-fontset-info font)) 0)) 2)
614         font))))
615
616 ;;;###autoload
617 (defun font-default-object-for-device (&optional device)
618   (let ((font (font-default-font-for-device device)))
619     (or (cdr-safe (assoc font font-default-cache))
620         (let ((object (font-create-object font)))
621           (push (cons font object) font-default-cache)
622           object))))
623
624 ;;;###autoload
625 (defun font-default-family-for-device (&optional device)
626   (font-family (font-default-object-for-device (or device (selected-device)))))
627
628 ;;;###autoload
629 (defun font-default-registry-for-device (&optional device)
630   (font-registry (font-default-object-for-device (or device (selected-device)))))
631
632 ;;;###autoload
633 (defun font-default-encoding-for-device (&optional device)
634   (font-encoding (font-default-object-for-device (or device (selected-device)))))
635
636 ;;;###autoload
637 (defun font-default-size-for-device (&optional device)
638   ;; face-height isn't the right thing (always 1 pixel too high?)
639   ;; (if font-running-xemacs
640   ;;    (format "%dpx" (face-height 'default device))
641   (font-size (font-default-object-for-device (or device (selected-device)))))
642
643 (defun x-font-create-name (fontobj &optional device)
644   "Return a font name constructed from FONTOBJ, appropriate for X devices."
645   (if (and (not (or (font-family fontobj)
646                     (font-weight fontobj)
647                     (font-size fontobj)
648                     (font-registry fontobj)
649                     (font-encoding fontobj)))
650            (= (font-style fontobj) 0))
651       (face-font 'default)
652     (or device (setq device (selected-device)))
653     (let* ((default (font-default-object-for-device device))
654            (family (or (font-family fontobj)
655                        (font-family default)
656                        (x-font-families-for-device device)))
657            (weight (or (font-weight fontobj) :medium))
658            ;(style (font-style fontobj))
659            (size (or (if font-running-xemacs
660                          (font-size fontobj))
661                      (font-size default)))
662            (registry (or (font-registry fontobj)
663                          (font-registry default)
664                          "*"))
665            (encoding (or (font-encoding fontobj)
666                          (font-encoding default)
667                          "*")))
668       (if (stringp family)
669           (setq family (list family)))
670       (setq weight (font-higher-weight weight
671                                        (and (font-bold-p fontobj) :bold)))
672       (if (stringp size)
673           (setq size (truncate (font-spatial-to-canonical size device))))
674       (setq weight (or (cdr-safe (assq weight x-font-weight-mappings)) "*"))
675       (let ((done nil)                  ; Did we find a good font yet?
676             (font-name nil)             ; font name we are currently checking
677             (cur-family nil)            ; current family we are checking
678             )
679         (while (and family (not done))
680           (setq cur-family (car family)
681                 family (cdr family))
682           (if (assoc cur-family font-x-family-mappings)
683               ;; If the family name is an alias as defined by
684               ;; font-x-family-mappings, then append those families
685               ;; to the front of 'family' and continue in the loop.
686               (setq family (append
687                             (cdr-safe (assoc cur-family
688                                              font-x-family-mappings))
689                             family))
690             ;; Not an alias for a list of fonts, so we just check it.
691             ;; First, convert all '-' to spaces so that we don't screw up
692             ;; the oh-so wonderful X font model.  Wheee.
693             (let ((x (length cur-family)))
694               (while (> x 0)
695                 (if (= ?- (aref cur-family (1- x)))
696                     (aset cur-family (1- x) ? ))
697                 (setq x (1- x))))
698             ;; We treat oblique and italic as equivalent.  Don't ask.
699             (let ((slants '("o" "i")))
700               (while (and slants (not done))
701                 (setq font-name (format "-*-%s-%s-%s-*-*-*-%s-*-*-*-*-%s-%s"
702                                         cur-family weight
703                                         (if (or (font-italic-p fontobj)
704                                                 (font-oblique-p fontobj))
705                                             (car slants)
706                                           "r")
707                                         (if size
708                                             (int-to-string (* 10 size)) "*")
709                                         registry
710                                         encoding
711                                         )
712                       slants (cdr slants)
713                       done (try-font-name font-name device))))))
714         (if done font-name)))))
715
716 \f
717 ;;; Cache building code
718 ;;;###autoload
719 (defun x-font-build-cache (&optional device)
720   (let ((hash-table (make-hash-table :test 'equal :size 15))
721         (fonts (mapcar 'x-font-create-object
722                        (x-list-fonts "-*-*-*-*-*-*-*-*-*-*-*-*-*-*")))
723         (plist nil)
724         (cur nil))
725     (while fonts
726       (setq cur (car fonts)
727             fonts (cdr fonts)
728             plist (cl-gethash (car (font-family cur)) hash-table))
729       (if (not (memq (font-weight cur) (plist-get plist 'weights)))
730           (setq plist (plist-put plist 'weights (cons (font-weight cur)
731                                                       (plist-get plist 'weights)))))
732       (if (not (member (font-size cur) (plist-get plist 'sizes)))
733           (setq plist (plist-put plist 'sizes (cons (font-size cur)
734                                                     (plist-get plist 'sizes)))))
735       (if (and (font-oblique-p cur)
736                (not (memq 'oblique (plist-get plist 'styles))))
737           (setq plist (plist-put plist 'styles (cons 'oblique (plist-get plist 'styles)))))
738       (if (and (font-italic-p cur)
739                (not (memq 'italic (plist-get plist 'styles))))
740           (setq plist (plist-put plist 'styles (cons 'italic (plist-get plist 'styles)))))
741       (cl-puthash (car (font-family cur)) plist hash-table))
742     hash-table))
743
744 \f
745 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
746 ;;; Now overwrite the original copy of set-face-font with our own copy that
747 ;;; can deal with either syntax.
748 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
749 ;;; ###autoload
750 (defun font-set-face-font (&optional face font &rest args)
751   (cond
752    ((and (vectorp font) (= (length font) 12))
753     (let ((font-name (font-create-name font)))
754       (set-face-property face 'font-specification font)
755       (cond
756        ((null font-name)                ; No matching font!
757         nil)
758        ((listp font-name)               ; For TTYs
759         (let (cur)
760           (while font-name
761             (setq cur (car font-name)
762                   font-name (cdr font-name))
763             (apply 'set-face-property face (car cur) (cdr cur) args))))
764        (font-running-xemacs
765         (apply 'set-face-font face font-name args)
766         (apply 'set-face-underline-p face (font-underline-p font) args)
767         (if (and (or (font-smallcaps-p font) (font-bigcaps-p font))
768                  (fboundp 'set-face-display-table))
769             (apply 'set-face-display-table
770                    face font-caps-display-table args))
771         (apply 'set-face-property face 'strikethru (or
772                                                     (font-linethrough-p font)
773                                                     (font-strikethru-p font))
774                args))
775        (t
776         (condition-case nil
777             (apply 'set-face-font face font-name args)
778           (error
779            (let ((args (car-safe args)))
780              (and (or (font-bold-p font)
781                       (memq (font-weight font) '(:bold :demi-bold)))
782                   (make-face-bold face args t))
783              (and (font-italic-p font) (make-face-italic face args t)))))
784         (apply 'set-face-underline-p face (font-underline-p font) args)))))
785    (t
786     ;; Let the original set-face-font signal any errors
787     (set-face-property face 'font-specification nil)
788     (apply 'set-face-font face font args))))
789
790 \f
791 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
792 ;;; Now for emacsen specific stuff
793 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
794 (defun font-update-device-fonts (device)
795   ;; Update all faces that were created with the 'font' package
796   ;; to appear correctly on the new device.  This should be in the
797   ;; create-device-hook.  This is XEmacs 19.12+ specific
798   (let ((faces (face-list 2))
799         (cur nil)
800         ;(font nil)
801         (font-spec nil))
802     (while faces
803       (setq cur (car faces)
804             faces (cdr faces)
805             font-spec (face-property cur 'font-specification))
806       (if font-spec
807           (set-face-font cur font-spec device)))))
808
809 (defun font-update-one-face (face &optional device-list)
810   ;; Update FACE on all devices in DEVICE-LIST
811   ;; DEVICE_LIST defaults to a list of all active devices
812   (setq device-list (or device-list (device-list)))
813   (if (devicep device-list)
814       (setq device-list (list device-list)))
815   (let* ((cur-device nil)
816          (font-spec (face-property face 'font-specification))
817          ;(font nil))
818          )
819     (if (not font-spec)
820         ;; Hey!  Don't mess with fonts we didn't create in the
821         ;; first place.
822         nil
823       (while device-list
824         (setq cur-device (car device-list)
825               device-list (cdr device-list))
826         (if (not (device-live-p cur-device))
827             ;; Whoah!
828             nil
829           (if font-spec
830               (set-face-font face font-spec cur-device)))))))
831
832 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
833 ;;; Various color related things
834 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
835 (cond
836  ((fboundp 'display-warning)
837   (fset 'font-warn 'display-warning))
838  ((fboundp 'w3-warn)
839   (fset 'font-warn 'w3-warn))
840  ((fboundp 'url-warn)
841   (fset 'font-warn 'url-warn))
842  ((fboundp 'warn)
843   (defun font-warn (class message &optional level)
844     (warn "(%s/%s) %s" class (or level 'warning) message)))
845  (t
846   (defun font-warn (class message &optional level)
847     (save-excursion
848       (set-buffer (get-buffer-create "*W3-WARNINGS*"))
849       (goto-char (point-max))
850       (save-excursion
851         (insert (format "(%s/%s) %s\n" class (or level 'warning) message)))
852       (display-buffer (current-buffer))))))
853
854 (require 'x-color)
855
856
857
858 (defun font-normalize-color (color &optional device)
859   "Return an RGB tuple, given any form of input.  If an error occurs, black
860 is returned."
861   (case (device-type device)
862    ((x tty)
863     (apply 'format "#%02x%02x%02x" (font-color-rgb-components color)))
864    (otherwise
865     color)))
866
867 (defun font-set-face-background (&optional face color &rest args)
868   (interactive)
869   (condition-case nil
870       (cond
871        ((or (font-rgb-color-p color)
872             (string-match "^#[0-9a-fA-F]+$" color))
873         (apply 'set-face-background face
874                (font-normalize-color color) args))
875        (t
876         (apply 'set-face-background face color args)))
877     (error nil)))
878
879 (defun font-set-face-foreground (&optional face color &rest args)
880   (interactive)
881   (condition-case nil
882       (cond
883        ((or (font-rgb-color-p color)
884             (string-match "^#[0-9a-fA-F]+$" color))
885         (apply 'set-face-foreground face (font-normalize-color color) args))
886        (t
887         (apply 'set-face-foreground face color args)))
888     (error nil)))
889
890 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
891 ;;; Support for 'blinking' fonts
892 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
893 (defun font-map-windows (func &optional arg frame)
894   (let* ((start (selected-window))
895          (cur start)
896          (result nil))
897     (push (funcall func start arg) result)
898     (while (not (eq start (setq cur (next-window cur))))
899       (push (funcall func cur arg) result))
900     result))
901
902 (defun font-face-visible-in-window-p (window face)
903   (let ((st (window-start window))
904         (nd (window-end window))
905         (found nil)
906         (face-at nil))
907     (setq face-at (get-text-property st 'face (window-buffer window)))
908     (if (or (eq face face-at) (and (listp face-at) (memq face face-at)))
909         (setq found t))
910     (while (and (not found)
911                 (/= nd
912                     (setq st (next-single-property-change
913                               st 'face
914                               (window-buffer window) nd))))
915       (setq face-at (get-text-property st 'face (window-buffer window)))
916       (if (or (eq face face-at) (and (listp face-at) (memq face face-at)))
917           (setq found t)))
918     found))
919
920 (defun font-blink-callback ()
921   ;; Optimized to never invert the face unless one of the visible windows
922   ;; is showing it.
923   (let ((faces (if font-running-xemacs (face-list t) (face-list)))
924         (obj nil))
925     (while faces
926       (if (and (setq obj (face-property (car faces) 'font-specification))
927                (font-blink-p obj)
928                (memq t
929                      (font-map-windows 'font-face-visible-in-window-p (car faces))))
930           (invert-face (car faces)))
931       (pop faces))))
932
933 (defcustom font-blink-interval 0.5
934   "How often to blink faces"
935   :type 'number
936   :group 'faces)
937
938 (defun font-blink-initialize ()
939   (cond
940    ((featurep 'itimer)
941     (if (get-itimer "font-blinker")
942         (delete-itimer (get-itimer "font-blinker")))
943     (start-itimer "font-blinker" 'font-blink-callback
944                   font-blink-interval
945                   font-blink-interval))
946    ((fboundp 'run-at-time)
947     (cancel-function-timers 'font-blink-callback)
948     (run-at-time font-blink-interval
949                  font-blink-interval
950                  'font-blink-callback))
951    (t nil)))
952
953 (provide 'font)