(lisp-font-lock-keywords-2): Add save-selected-window-norecord.
[emacs.git] / lisp / image.el
blob2633ff283100541b847ab4afe8fd924f6e15a8f5
1 ;;; image.el --- image API
3 ;; Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003,
4 ;; 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
6 ;; Maintainer: FSF
7 ;; Keywords: multimedia
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24 ;;; Commentary:
26 ;;; Code:
29 (defgroup image ()
30 "Image support."
31 :group 'multimedia)
34 (defconst image-type-header-regexps
35 `(("\\`/[\t\n\r ]*\\*.*XPM.\\*/" . xpm)
36 ("\\`P[1-6][[:space:]]+\\(?:#.*[[:space:]]+\\)*[0-9]+[[:space:]]+[0-9]+" . pbm)
37 ("\\`GIF8[79]a" . gif)
38 ("\\`\x89PNG\r\n\x1a\n" . png)
39 ("\\`[\t\n\r ]*#define \\([a-z0-9]+\\)_width [0-9]+\n\
40 #define \\1_height [0-9]+\n\
41 static char \\1_bits" . xbm)
42 ("\\`\\(?:MM\0\\*\\|II\\*\0\\)" . tiff)
43 ("\\`[\t\n\r ]*%!PS" . postscript)
44 ("\\`\xff\xd8" . (image-jpeg-p . jpeg))
45 (,(let* ((incomment-re "\\(?:[^-]\\|-[^-]\\)")
46 (comment-re (concat "\\(?:!--" incomment-re "*-->[ \t\r\n]*<\\)")))
47 (concat "\\(?:<\\?xml[ \t\r\n]+[^>]*>\\)?[ \t\r\n]*<"
48 comment-re "*"
49 "\\(?:!DOCTYPE[ \t\r\n]+[^>]*>[ \t\r\n]*<[ \t\r\n]*" comment-re "*\\)?"
50 "[Ss][Vv][Gg]"))
51 . svg)
53 "Alist of (REGEXP . IMAGE-TYPE) pairs used to auto-detect image types.
54 When the first bytes of an image file match REGEXP, it is assumed to
55 be of image type IMAGE-TYPE if IMAGE-TYPE is a symbol. If not a symbol,
56 IMAGE-TYPE must be a pair (PREDICATE . TYPE). PREDICATE is called
57 with one argument, a string containing the image data. If PREDICATE returns
58 a non-nil value, TYPE is the image's type.")
60 (defconst image-type-file-name-regexps
61 '(("\\.png\\'" . png)
62 ("\\.gif\\'" . gif)
63 ("\\.jpe?g\\'" . jpeg)
64 ("\\.bmp\\'" . bmp)
65 ("\\.xpm\\'" . xpm)
66 ("\\.pbm\\'" . pbm)
67 ("\\.xbm\\'" . xbm)
68 ("\\.ps\\'" . postscript)
69 ("\\.tiff?\\'" . tiff)
70 ("\\.svgz?\\'" . svg)
72 "Alist of (REGEXP . IMAGE-TYPE) pairs used to identify image files.
73 When the name of an image file match REGEXP, it is assumed to
74 be of image type IMAGE-TYPE.")
76 ;; We rely on `auto-mode-alist' to detect xbm and xpm files, instead
77 ;; of content autodetection. Their contents are just C code, so it is
78 ;; easy to generate false matches.
79 (defvar image-type-auto-detectable
80 '((pbm . t)
81 (xbm . nil)
82 (bmp . maybe)
83 (gif . maybe)
84 (png . maybe)
85 (xpm . nil)
86 (jpeg . maybe)
87 (tiff . maybe)
88 (svg . maybe)
89 (postscript . nil))
90 "Alist of (IMAGE-TYPE . AUTODETECT) pairs used to auto-detect image files.
91 \(See `image-type-auto-detected-p').
93 AUTODETECT can be
94 - t always auto-detect.
95 - nil never auto-detect.
96 - maybe auto-detect only if the image type is available
97 (see `image-type-available-p').")
99 (defvar image-load-path nil
100 "List of locations in which to search for image files.
101 If an element is a string, it defines a directory to search.
102 If an element is a variable symbol whose value is a string, that
103 value defines a directory to search.
104 If an element is a variable symbol whose value is a list, the
105 value is used as a list of directories to search.")
107 (eval-at-startup
108 (setq image-load-path
109 (list (file-name-as-directory (expand-file-name "images" data-directory))
110 'data-directory 'load-path)))
113 (defun image-load-path-for-library (library image &optional path no-error)
114 "Return a suitable search path for images used by LIBRARY.
116 It searches for IMAGE in `image-load-path' (excluding
117 \"`data-directory'/images\") and `load-path', followed by a path
118 suitable for LIBRARY, which includes \"../../etc/images\" and
119 \"../etc/images\" relative to the library file itself, and then
120 in \"`data-directory'/images\".
122 Then this function returns a list of directories which contains
123 first the directory in which IMAGE was found, followed by the
124 value of `load-path'. If PATH is given, it is used instead of
125 `load-path'.
127 If NO-ERROR is non-nil and a suitable path can't be found, don't
128 signal an error. Instead, return a list of directories as before,
129 except that nil appears in place of the image directory.
131 Here is an example that uses a common idiom to provide
132 compatibility with versions of Emacs that lack the variable
133 `image-load-path':
135 ;; Shush compiler.
136 (defvar image-load-path)
138 (let* ((load-path (image-load-path-for-library \"mh-e\" \"mh-logo.xpm\"))
139 (image-load-path (cons (car load-path)
140 (when (boundp 'image-load-path)
141 image-load-path))))
142 (mh-tool-bar-folder-buttons-init))"
143 (unless library (error "No library specified"))
144 (unless image (error "No image specified"))
145 (let (image-directory image-directory-load-path)
146 ;; Check for images in image-load-path or load-path.
147 (let ((img image)
148 (dir (or
149 ;; Images in image-load-path.
150 (image-search-load-path image)
151 ;; Images in load-path.
152 (locate-library image)))
153 parent)
154 ;; Since the image might be in a nested directory (for
155 ;; example, mail/attach.pbm), adjust `image-directory'
156 ;; accordingly.
157 (when dir
158 (setq dir (file-name-directory dir))
159 (while (setq parent (file-name-directory img))
160 (setq img (directory-file-name parent)
161 dir (expand-file-name "../" dir))))
162 (setq image-directory-load-path dir))
164 ;; If `image-directory-load-path' isn't Emacs' image directory,
165 ;; it's probably a user preference, so use it. Then use a
166 ;; relative setting if possible; otherwise, use
167 ;; `image-directory-load-path'.
168 (cond
169 ;; User-modified image-load-path?
170 ((and image-directory-load-path
171 (not (equal image-directory-load-path
172 (file-name-as-directory
173 (expand-file-name "images" data-directory)))))
174 (setq image-directory image-directory-load-path))
175 ;; Try relative setting.
176 ((let (library-name d1ei d2ei)
177 ;; First, find library in the load-path.
178 (setq library-name (locate-library library))
179 (if (not library-name)
180 (error "Cannot find library %s in load-path" library))
181 ;; And then set image-directory relative to that.
182 (setq
183 ;; Go down 2 levels.
184 d2ei (file-name-as-directory
185 (expand-file-name
186 (concat (file-name-directory library-name) "../../etc/images")))
187 ;; Go down 1 level.
188 d1ei (file-name-as-directory
189 (expand-file-name
190 (concat (file-name-directory library-name) "../etc/images"))))
191 (setq image-directory
192 ;; Set it to nil if image is not found.
193 (cond ((file-exists-p (expand-file-name image d2ei)) d2ei)
194 ((file-exists-p (expand-file-name image d1ei)) d1ei)))))
195 ;; Use Emacs' image directory.
196 (image-directory-load-path
197 (setq image-directory image-directory-load-path))
198 (no-error
199 (message "Could not find image %s for library %s" image library))
201 (error "Could not find image %s for library %s" image library)))
203 ;; Return an augmented `path' or `load-path'.
204 (nconc (list image-directory)
205 (delete image-directory (copy-sequence (or path load-path))))))
208 (defun image-jpeg-p (data)
209 "Value is non-nil if DATA, a string, consists of JFIF image data.
210 We accept the tag Exif because that is the same format."
211 (setq data (ignore-errors (string-to-unibyte data)))
212 (when (and data (string-match-p "\\`\xff\xd8" data))
213 (catch 'jfif
214 (let ((len (length data)) (i 2))
215 (while (< i len)
216 (when (/= (aref data i) #xff)
217 (throw 'jfif nil))
218 (setq i (1+ i))
219 (when (>= (+ i 2) len)
220 (throw 'jfif nil))
221 (let ((nbytes (+ (lsh (aref data (+ i 1)) 8)
222 (aref data (+ i 2))))
223 (code (aref data i)))
224 (when (and (>= code #xe0) (<= code #xef))
225 ;; APP0 LEN1 LEN2 "JFIF\0"
226 (throw 'jfif
227 (string-match-p "JFIF\\|Exif"
228 (substring data i (min (+ i nbytes) len)))))
229 (setq i (+ i 1 nbytes))))))))
232 ;;;###autoload
233 (defun image-type-from-data (data)
234 "Determine the image type from image data DATA.
235 Value is a symbol specifying the image type or nil if type cannot
236 be determined."
237 (let ((types image-type-header-regexps)
238 type)
239 (while types
240 (let ((regexp (car (car types)))
241 (image-type (cdr (car types))))
242 (if (or (and (symbolp image-type)
243 (string-match-p regexp data))
244 (and (consp image-type)
245 (funcall (car image-type) data)
246 (setq image-type (cdr image-type))))
247 (setq type image-type
248 types nil)
249 (setq types (cdr types)))))
250 type))
253 ;;;###autoload
254 (defun image-type-from-buffer ()
255 "Determine the image type from data in the current buffer.
256 Value is a symbol specifying the image type or nil if type cannot
257 be determined."
258 (let ((types image-type-header-regexps)
259 type
260 (opoint (point)))
261 (goto-char (point-min))
262 (while types
263 (let ((regexp (car (car types)))
264 (image-type (cdr (car types)))
265 data)
266 (if (or (and (symbolp image-type)
267 (looking-at-p regexp))
268 (and (consp image-type)
269 (funcall (car image-type)
270 (or data
271 (setq data
272 (buffer-substring
273 (point-min)
274 (min (point-max)
275 (+ (point-min) 256))))))
276 (setq image-type (cdr image-type))))
277 (setq type image-type
278 types nil)
279 (setq types (cdr types)))))
280 (goto-char opoint)
281 type))
284 ;;;###autoload
285 (defun image-type-from-file-header (file)
286 "Determine the type of image file FILE from its first few bytes.
287 Value is a symbol specifying the image type, or nil if type cannot
288 be determined."
289 (unless (or (file-readable-p file)
290 (file-name-absolute-p file))
291 (setq file (image-search-load-path file)))
292 (and file
293 (file-readable-p file)
294 (with-temp-buffer
295 (set-buffer-multibyte nil)
296 (insert-file-contents-literally file nil 0 256)
297 (image-type-from-buffer))))
300 ;;;###autoload
301 (defun image-type-from-file-name (file)
302 "Determine the type of image file FILE from its name.
303 Value is a symbol specifying the image type, or nil if type cannot
304 be determined."
305 (assoc-default file image-type-file-name-regexps 'string-match-p))
308 ;;;###autoload
309 (defun image-type (source &optional type data-p)
310 "Determine and return image type.
311 SOURCE is an image file name or image data.
312 Optional TYPE is a symbol describing the image type. If TYPE is omitted
313 or nil, try to determine the image type from its first few bytes
314 of image data. If that doesn't work, and SOURCE is a file name,
315 use its file extension as image type.
316 Optional DATA-P non-nil means SOURCE is a string containing image data."
317 (when (and (not data-p) (not (stringp source)))
318 (error "Invalid image file name `%s'" source))
319 (unless type
320 (setq type (if data-p
321 (image-type-from-data source)
322 (or (image-type-from-file-header source)
323 (image-type-from-file-name source))))
324 (or type (error "Cannot determine image type")))
325 (or (memq type (and (boundp 'image-types) image-types))
326 (error "Invalid image type `%s'" type))
327 type)
330 (defvar image-library-alist)
332 ;;;###autoload
333 (defun image-type-available-p (type)
334 "Return non-nil if image type TYPE is available.
335 Image types are symbols like `xbm' or `jpeg'."
336 (and (fboundp 'init-image-library)
337 (init-image-library type image-library-alist)))
340 ;;;###autoload
341 (defun image-type-auto-detected-p ()
342 "Return t if the current buffer contains an auto-detectable image.
343 This function is intended to be used from `magic-fallback-mode-alist'.
345 The buffer is considered to contain an auto-detectable image if
346 its beginning matches an image type in `image-type-header-regexps',
347 and that image type is present in `image-type-auto-detectable' with a
348 non-nil value. If that value is non-nil, but not t, then the image type
349 must be available."
350 (let* ((type (image-type-from-buffer))
351 (auto (and type (cdr (assq type image-type-auto-detectable)))))
352 (and auto
353 (or (eq auto t) (image-type-available-p type)))))
356 ;;;###autoload
357 (defun create-image (file-or-data &optional type data-p &rest props)
358 "Create an image.
359 FILE-OR-DATA is an image file name or image data.
360 Optional TYPE is a symbol describing the image type. If TYPE is omitted
361 or nil, try to determine the image type from its first few bytes
362 of image data. If that doesn't work, and FILE-OR-DATA is a file name,
363 use its file extension as image type.
364 Optional DATA-P non-nil means FILE-OR-DATA is a string containing image data.
365 Optional PROPS are additional image attributes to assign to the image,
366 like, e.g. `:mask MASK'.
367 Value is the image created, or nil if images of type TYPE are not supported.
369 Images should not be larger than specified by `max-image-size'.
371 Image file names that are not absolute are searched for in the
372 \"images\" sub-directory of `data-directory' and
373 `x-bitmap-file-path' (in that order)."
374 ;; It is x_find_image_file in image.c that sets the search path.
375 (setq type (image-type file-or-data type data-p))
376 (when (image-type-available-p type)
377 (append (list 'image :type type (if data-p :data :file) file-or-data)
378 props)))
381 ;;;###autoload
382 (defun put-image (image pos &optional string area)
383 "Put image IMAGE in front of POS in the current buffer.
384 IMAGE must be an image created with `create-image' or `defimage'.
385 IMAGE is displayed by putting an overlay into the current buffer with a
386 `before-string' STRING that has a `display' property whose value is the
387 image. STRING is defaulted if you omit it.
388 POS may be an integer or marker.
389 AREA is where to display the image. AREA nil or omitted means
390 display it in the text area, a value of `left-margin' means
391 display it in the left marginal area, a value of `right-margin'
392 means display it in the right marginal area."
393 (unless string (setq string "x"))
394 (let ((buffer (current-buffer)))
395 (unless (eq (car-safe image) 'image)
396 (error "Not an image: %s" image))
397 (unless (or (null area) (memq area '(left-margin right-margin)))
398 (error "Invalid area %s" area))
399 (setq string (copy-sequence string))
400 (let ((overlay (make-overlay pos pos buffer))
401 (prop (if (null area) image (list (list 'margin area) image))))
402 (put-text-property 0 (length string) 'display prop string)
403 (overlay-put overlay 'put-image t)
404 (overlay-put overlay 'before-string string))))
407 ;;;###autoload
408 (defun insert-image (image &optional string area slice)
409 "Insert IMAGE into current buffer at point.
410 IMAGE is displayed by inserting STRING into the current buffer
411 with a `display' property whose value is the image. STRING is
412 defaulted if you omit it.
413 AREA is where to display the image. AREA nil or omitted means
414 display it in the text area, a value of `left-margin' means
415 display it in the left marginal area, a value of `right-margin'
416 means display it in the right marginal area.
417 SLICE specifies slice of IMAGE to insert. SLICE nil or omitted
418 means insert whole image. SLICE is a list (X Y WIDTH HEIGHT)
419 specifying the X and Y positions and WIDTH and HEIGHT of image area
420 to insert. A float value 0.0 - 1.0 means relative to the width or
421 height of the image; integer values are taken as pixel values."
422 ;; Use a space as least likely to cause trouble when it's a hidden
423 ;; character in the buffer.
424 (unless string (setq string " "))
425 (unless (eq (car-safe image) 'image)
426 (error "Not an image: %s" image))
427 (unless (or (null area) (memq area '(left-margin right-margin)))
428 (error "Invalid area %s" area))
429 (if area
430 (setq image (list (list 'margin area) image))
431 ;; Cons up a new spec equal but not eq to `image' so that
432 ;; inserting it twice in a row (adjacently) displays two copies of
433 ;; the image. Don't try to avoid this by looking at the display
434 ;; properties on either side so that we DTRT more often with
435 ;; cut-and-paste. (Yanking killed image text next to another copy
436 ;; of it loses anyway.)
437 (setq image (cons 'image (cdr image))))
438 (let ((start (point)))
439 (insert string)
440 (add-text-properties start (point)
441 `(display ,(if slice
442 (list (cons 'slice slice) image)
443 image) rear-nonsticky (display)))))
446 ;;;###autoload
447 (defun insert-sliced-image (image &optional string area rows cols)
448 "Insert IMAGE into current buffer at point.
449 IMAGE is displayed by inserting STRING into the current buffer
450 with a `display' property whose value is the image. STRING is
451 defaulted if you omit it.
452 AREA is where to display the image. AREA nil or omitted means
453 display it in the text area, a value of `left-margin' means
454 display it in the left marginal area, a value of `right-margin'
455 means display it in the right marginal area.
456 The image is automatically split into ROW x COLS slices."
457 (unless string (setq string " "))
458 (unless (eq (car-safe image) 'image)
459 (error "Not an image: %s" image))
460 (unless (or (null area) (memq area '(left-margin right-margin)))
461 (error "Invalid area %s" area))
462 (if area
463 (setq image (list (list 'margin area) image))
464 ;; Cons up a new spec equal but not eq to `image' so that
465 ;; inserting it twice in a row (adjacently) displays two copies of
466 ;; the image. Don't try to avoid this by looking at the display
467 ;; properties on either side so that we DTRT more often with
468 ;; cut-and-paste. (Yanking killed image text next to another copy
469 ;; of it loses anyway.)
470 (setq image (cons 'image (cdr image))))
471 (let ((x 0.0) (dx (/ 1.0001 (or cols 1)))
472 (y 0.0) (dy (/ 1.0001 (or rows 1))))
473 (while (< y 1.0)
474 (while (< x 1.0)
475 (let ((start (point)))
476 (insert string)
477 (add-text-properties start (point)
478 `(display ,(list (list 'slice x y dx dy) image)
479 rear-nonsticky (display)))
480 (setq x (+ x dx))))
481 (setq x 0.0
482 y (+ y dy))
483 (insert (propertize "\n" 'line-height t)))))
487 ;;;###autoload
488 (defun remove-images (start end &optional buffer)
489 "Remove images between START and END in BUFFER.
490 Remove only images that were put in BUFFER with calls to `put-image'.
491 BUFFER nil or omitted means use the current buffer."
492 (unless buffer
493 (setq buffer (current-buffer)))
494 (let ((overlays (overlays-in start end)))
495 (while overlays
496 (let ((overlay (car overlays)))
497 (when (overlay-get overlay 'put-image)
498 (delete-overlay overlay)))
499 (setq overlays (cdr overlays)))))
501 (defun image-search-load-path (file &optional path)
502 (unless path
503 (setq path image-load-path))
504 (let (element found filename)
505 (while (and (not found) (consp path))
506 (setq element (car path))
507 (cond
508 ((stringp element)
509 (setq found
510 (file-readable-p
511 (setq filename (expand-file-name file element)))))
512 ((and (symbolp element) (boundp element))
513 (setq element (symbol-value element))
514 (cond
515 ((stringp element)
516 (setq found
517 (file-readable-p
518 (setq filename (expand-file-name file element)))))
519 ((consp element)
520 (if (setq filename (image-search-load-path file element))
521 (setq found t))))))
522 (setq path (cdr path)))
523 (if found filename)))
525 ;;;###autoload
526 (defun find-image (specs)
527 "Find an image, choosing one of a list of image specifications.
529 SPECS is a list of image specifications.
531 Each image specification in SPECS is a property list. The contents of
532 a specification are image type dependent. All specifications must at
533 least contain the properties `:type TYPE' and either `:file FILE' or
534 `:data DATA', where TYPE is a symbol specifying the image type,
535 e.g. `xbm', FILE is the file to load the image from, and DATA is a
536 string containing the actual image data. The specification whose TYPE
537 is supported, and FILE exists, is used to construct the image
538 specification to be returned. Return nil if no specification is
539 satisfied.
541 The image is looked for in `image-load-path'.
543 Image files should not be larger than specified by `max-image-size'."
544 (let (image)
545 (while (and specs (null image))
546 (let* ((spec (car specs))
547 (type (plist-get spec :type))
548 (data (plist-get spec :data))
549 (file (plist-get spec :file))
550 found)
551 (when (image-type-available-p type)
552 (cond ((stringp file)
553 (if (setq found (image-search-load-path file))
554 (setq image
555 (cons 'image (plist-put (copy-sequence spec)
556 :file found)))))
557 ((not (null data))
558 (setq image (cons 'image spec)))))
559 (setq specs (cdr specs))))
560 image))
563 ;;;###autoload
564 (defmacro defimage (symbol specs &optional doc)
565 "Define SYMBOL as an image.
567 SPECS is a list of image specifications. DOC is an optional
568 documentation string.
570 Each image specification in SPECS is a property list. The contents of
571 a specification are image type dependent. All specifications must at
572 least contain the properties `:type TYPE' and either `:file FILE' or
573 `:data DATA', where TYPE is a symbol specifying the image type,
574 e.g. `xbm', FILE is the file to load the image from, and DATA is a
575 string containing the actual image data. The first image
576 specification whose TYPE is supported, and FILE exists, is used to
577 define SYMBOL.
579 Example:
581 (defimage test-image ((:type xpm :file \"~/test1.xpm\")
582 (:type xbm :file \"~/test1.xbm\")))"
583 (declare (doc-string 3))
584 `(defvar ,symbol (find-image ',specs) ,doc))
587 (provide 'image)
589 ;; arch-tag: 8e76a07b-eb48-4f3e-a7a0-1a7ba9f096b3
590 ;;; image.el ends here