* lisp/ibuffer.el (ibuffer): Improve 'other-window' case. (Bug#23617)
[emacs.git] / lisp / image-mode.el
bloba18b07ebe6a9b2dd3e528af54e8131f665015ef6
1 ;;; image-mode.el --- support for visiting image files -*- lexical-binding: t -*-
2 ;;
3 ;; Copyright (C) 2005-2016 Free Software Foundation, Inc.
4 ;;
5 ;; Author: Richard Stallman <rms@gnu.org>
6 ;; Keywords: multimedia
7 ;; Package: emacs
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 ;; Defines a major mode for visiting image files
27 ;; that allows conversion between viewing the text of the file,
28 ;; hex of the file and viewing the file as an image. Viewing the image
29 ;; works by putting a `display' text-property on the
30 ;; image data, with the image-data still present underneath; if the
31 ;; resulting buffer file is saved to another name it will correctly save
32 ;; the image data to the new file.
34 ;; Todo:
36 ;; Consolidate with doc-view to make them work on directories of images or on
37 ;; image files containing various "pages".
39 ;;; Code:
41 (require 'image)
42 (eval-when-compile (require 'cl-lib))
44 ;;; Image mode window-info management.
46 (defvar-local image-mode-winprops-alist t)
48 (defvar image-mode-new-window-functions nil
49 "Special hook run when image data is requested in a new window.
50 It is called with one argument, the initial WINPROPS.")
52 ;; FIXME this doesn't seem mature yet. Document in manual when it is.
53 (defvar image-transform-resize nil
54 "The image resize operation.
55 Its value should be one of the following:
56 - nil, meaning no resizing.
57 - `fit-height', meaning to fit the image to the window height.
58 - `fit-width', meaning to fit the image to the window width.
59 - A number, which is a scale factor (the default size is 1).")
61 (defvar image-transform-scale 1.0
62 "The scale factor of the image being displayed.")
64 (defvar image-transform-rotation 0.0
65 "Rotation angle for the image in the current Image mode buffer.")
67 (defvar image-transform-right-angle-fudge 0.0001
68 "Snap distance to a multiple of a right angle.
69 There's no deep theory behind the default value, it should just
70 be somewhat larger than ImageMagick's MagickEpsilon.")
72 (defun image-mode-winprops (&optional window cleanup)
73 "Return winprops of WINDOW.
74 A winprops object has the shape (WINDOW . ALIST).
75 WINDOW defaults to `selected-window' if it displays the current buffer, and
76 otherwise it defaults to t, used for times when the buffer is not displayed."
77 (cond ((null window)
78 (setq window
79 (if (eq (current-buffer) (window-buffer)) (selected-window) t)))
80 ((eq window t))
81 ((not (windowp window))
82 (error "Not a window: %s" window)))
83 (when cleanup
84 (setq image-mode-winprops-alist
85 (delq nil (mapcar (lambda (winprop)
86 (let ((w (car-safe winprop)))
87 (if (or (not (windowp w)) (window-live-p w))
88 winprop)))
89 image-mode-winprops-alist))))
90 (let ((winprops (assq window image-mode-winprops-alist)))
91 ;; For new windows, set defaults from the latest.
92 (if winprops
93 ;; Move window to front.
94 (setq image-mode-winprops-alist
95 (cons winprops (delq winprops image-mode-winprops-alist)))
96 (setq winprops (cons window
97 (copy-alist (cdar image-mode-winprops-alist))))
98 ;; Add winprops before running the hook, to avoid inf-loops if the hook
99 ;; triggers window-configuration-change-hook.
100 (setq image-mode-winprops-alist
101 (cons winprops image-mode-winprops-alist))
102 (run-hook-with-args 'image-mode-new-window-functions winprops))
103 winprops))
105 (defun image-mode-window-get (prop &optional winprops)
106 (declare (gv-setter (lambda (val)
107 `(image-mode-window-put ,prop ,val ,winprops))))
108 (unless (consp winprops) (setq winprops (image-mode-winprops winprops)))
109 (cdr (assq prop (cdr winprops))))
111 (defun image-mode-window-put (prop val &optional winprops)
112 (unless (consp winprops) (setq winprops (image-mode-winprops winprops)))
113 (unless (eq t (car winprops))
114 (image-mode-window-put prop val t))
115 (setcdr winprops (cons (cons prop val)
116 (delq (assq prop (cdr winprops)) (cdr winprops)))))
118 (defun image-set-window-vscroll (vscroll)
119 (setf (image-mode-window-get 'vscroll) vscroll)
120 (set-window-vscroll (selected-window) vscroll))
122 (defun image-set-window-hscroll (ncol)
123 (setf (image-mode-window-get 'hscroll) ncol)
124 (set-window-hscroll (selected-window) ncol))
126 (defun image-mode-reapply-winprops ()
127 ;; When set-window-buffer, set hscroll and vscroll to what they were
128 ;; last time the image was displayed in this window.
129 (when (listp image-mode-winprops-alist)
130 ;; Beware: this call to image-mode-winprops can't be optimized away,
131 ;; because it not only gets the winprops data but sets it up if needed
132 ;; (e.g. it's used by doc-view to display the image in a new window).
133 (let* ((winprops (image-mode-winprops nil t))
134 (hscroll (image-mode-window-get 'hscroll winprops))
135 (vscroll (image-mode-window-get 'vscroll winprops)))
136 (when (image-get-display-property) ;Only do it if we display an image!
137 (if hscroll (set-window-hscroll (selected-window) hscroll))
138 (if vscroll (set-window-vscroll (selected-window) vscroll))))))
140 (defun image-mode-setup-winprops ()
141 ;; Record current scroll settings.
142 (unless (listp image-mode-winprops-alist)
143 (setq image-mode-winprops-alist nil))
144 (add-hook 'window-configuration-change-hook
145 'image-mode-reapply-winprops nil t))
147 ;;; Image scrolling functions
149 (defun image-get-display-property ()
150 (get-char-property (point-min) 'display
151 ;; There might be different images for different displays.
152 (if (eq (window-buffer) (current-buffer))
153 (selected-window))))
155 (declare-function image-size "image.c" (spec &optional pixels frame))
156 (declare-function xwidget-info "xwidget.c" (xwidget))
157 (declare-function xwidget-at "xwidget.el" (pos))
159 (defun image-display-size (spec &optional pixels frame)
160 "Wrapper around `image-size', handling slice display properties.
161 Like `image-size', the return value is (WIDTH . HEIGHT).
162 WIDTH and HEIGHT are in canonical character units if PIXELS is
163 nil, and in pixel units if PIXELS is non-nil.
165 If SPEC is an image display property, this function is equivalent to
166 `image-size'. If SPEC represents an xwidget object, defer to `xwidget-info'.
167 If SPEC is a list of properties containing `image' and `slice' properties,
168 return the display size taking the slice property into account. If the list
169 contains `image' but not `slice', return the `image-size' of the specified
170 image."
171 (cond ((eq (car spec) 'xwidget)
172 (let ((xwi (xwidget-info (xwidget-at (point-min)))))
173 (cons (aref xwi 2) (aref xwi 3))))
174 ((eq (car spec) 'image)
175 (image-size spec pixels frame))
176 (t (let ((image (assoc 'image spec))
177 (slice (assoc 'slice spec)))
178 (cond ((and image slice)
179 (if pixels
180 (cons (nth 3 slice) (nth 4 slice))
181 (cons (/ (float (nth 3 slice)) (frame-char-width frame))
182 (/ (float (nth 4 slice))
183 (frame-char-height frame)))))
184 (image
185 (image-size image pixels frame))
187 (error "Invalid image specification: %s" spec)))))))
189 (defun image-forward-hscroll (&optional n)
190 "Scroll image in current window to the left by N character widths.
191 Stop if the right edge of the image is reached."
192 (interactive "p")
193 (cond ((= n 0) nil)
194 ((< n 0)
195 (image-set-window-hscroll (max 0 (+ (window-hscroll) n))))
197 (let* ((image (image-get-display-property))
198 (edges (window-inside-edges))
199 (win-width (- (nth 2 edges) (nth 0 edges)))
200 (img-width (ceiling (car (image-display-size image)))))
201 (image-set-window-hscroll (min (max 0 (- img-width win-width))
202 (+ n (window-hscroll))))))))
204 (defun image-backward-hscroll (&optional n)
205 "Scroll image in current window to the right by N character widths.
206 Stop if the left edge of the image is reached."
207 (interactive "p")
208 (image-forward-hscroll (- n)))
210 (defun image-next-line (n)
211 "Scroll image in current window upward by N lines.
212 Stop if the bottom edge of the image is reached."
213 (interactive "p")
214 (cond ((= n 0) nil)
215 ((< n 0)
216 (image-set-window-vscroll (max 0 (+ (window-vscroll) n))))
218 (let* ((image (image-get-display-property))
219 (edges (window-inside-edges))
220 (win-height (- (nth 3 edges) (nth 1 edges)))
221 (img-height (ceiling (cdr (image-display-size image)))))
222 (image-set-window-vscroll (min (max 0 (- img-height win-height))
223 (+ n (window-vscroll))))))))
225 (defun image-previous-line (&optional n)
226 "Scroll image in current window downward by N lines.
227 Stop if the top edge of the image is reached."
228 (interactive "p")
229 (image-next-line (- n)))
231 (defun image-scroll-up (&optional n)
232 "Scroll image in current window upward by N lines.
233 Stop if the bottom edge of the image is reached.
234 If ARG is omitted or nil, scroll upward by a near full screen.
235 A near full screen is `next-screen-context-lines' less than a full screen.
236 Negative ARG means scroll downward.
237 If ARG is the atom `-', scroll downward by nearly full screen.
238 When calling from a program, supply as argument a number, nil, or `-'."
239 (interactive "P")
240 (cond ((null n)
241 (let* ((edges (window-inside-edges))
242 (win-height (- (nth 3 edges) (nth 1 edges))))
243 (image-next-line
244 (max 0 (- win-height next-screen-context-lines)))))
245 ((eq n '-)
246 (let* ((edges (window-inside-edges))
247 (win-height (- (nth 3 edges) (nth 1 edges))))
248 (image-next-line
249 (min 0 (- next-screen-context-lines win-height)))))
250 (t (image-next-line (prefix-numeric-value n)))))
252 (defun image-scroll-down (&optional n)
253 "Scroll image in current window downward by N lines.
254 Stop if the top edge of the image is reached.
255 If ARG is omitted or nil, scroll downward by a near full screen.
256 A near full screen is `next-screen-context-lines' less than a full screen.
257 Negative ARG means scroll upward.
258 If ARG is the atom `-', scroll upward by nearly full screen.
259 When calling from a program, supply as argument a number, nil, or `-'."
260 (interactive "P")
261 (cond ((null n)
262 (let* ((edges (window-inside-edges))
263 (win-height (- (nth 3 edges) (nth 1 edges))))
264 (image-next-line
265 (min 0 (- next-screen-context-lines win-height)))))
266 ((eq n '-)
267 (let* ((edges (window-inside-edges))
268 (win-height (- (nth 3 edges) (nth 1 edges))))
269 (image-next-line
270 (max 0 (- win-height next-screen-context-lines)))))
271 (t (image-next-line (- (prefix-numeric-value n))))))
273 (defun image-bol (arg)
274 "Scroll horizontally to the left edge of the image in the current window.
275 With argument ARG not nil or 1, move forward ARG - 1 lines first,
276 stopping if the top or bottom edge of the image is reached."
277 (interactive "p")
278 (and arg
279 (/= (setq arg (prefix-numeric-value arg)) 1)
280 (image-next-line (- arg 1)))
281 (image-set-window-hscroll 0))
283 (defun image-eol (arg)
284 "Scroll horizontally to the right edge of the image in the current window.
285 With argument ARG not nil or 1, move forward ARG - 1 lines first,
286 stopping if the top or bottom edge of the image is reached."
287 (interactive "p")
288 (and arg
289 (/= (setq arg (prefix-numeric-value arg)) 1)
290 (image-next-line (- arg 1)))
291 (let* ((image (image-get-display-property))
292 (edges (window-inside-edges))
293 (win-width (- (nth 2 edges) (nth 0 edges)))
294 (img-width (ceiling (car (image-display-size image)))))
295 (image-set-window-hscroll (max 0 (- img-width win-width)))))
297 (defun image-bob ()
298 "Scroll to the top-left corner of the image in the current window."
299 (interactive)
300 (image-set-window-hscroll 0)
301 (image-set-window-vscroll 0))
303 (defun image-eob ()
304 "Scroll to the bottom-right corner of the image in the current window."
305 (interactive)
306 (let* ((image (image-get-display-property))
307 (edges (window-inside-edges))
308 (win-width (- (nth 2 edges) (nth 0 edges)))
309 (img-width (ceiling (car (image-display-size image))))
310 (win-height (- (nth 3 edges) (nth 1 edges)))
311 (img-height (ceiling (cdr (image-display-size image)))))
312 (image-set-window-hscroll (max 0 (- img-width win-width)))
313 (image-set-window-vscroll (max 0 (- img-height win-height)))))
315 ;; Adjust frame and image size.
317 (defun image-mode-fit-frame (&optional frame toggle)
318 "Fit FRAME to the current image.
319 If FRAME is omitted or nil, it defaults to the selected frame.
320 All other windows on the frame are deleted.
322 If called interactively, or if TOGGLE is non-nil, toggle between
323 fitting FRAME to the current image and restoring the size and
324 window configuration prior to the last `image-mode-fit-frame'
325 call."
326 (interactive (list nil t))
327 (let* ((buffer (current-buffer))
328 (display (image-get-display-property))
329 (size (image-display-size display))
330 (saved (frame-parameter frame 'image-mode-saved-params))
331 (window-configuration (current-window-configuration frame))
332 (width (frame-width frame))
333 (height (frame-height frame)))
334 (with-selected-frame (or frame (selected-frame))
335 (if (and toggle saved
336 (= (caar saved) width)
337 (= (cdar saved) height))
338 (progn
339 (set-frame-width frame (car (nth 1 saved)))
340 (set-frame-height frame (cdr (nth 1 saved)))
341 (set-window-configuration (nth 2 saved))
342 (set-frame-parameter frame 'image-mode-saved-params nil))
343 (delete-other-windows)
344 (switch-to-buffer buffer t t)
345 (let* ((edges (window-inside-edges))
346 (inner-width (- (nth 2 edges) (nth 0 edges)))
347 (inner-height (- (nth 3 edges) (nth 1 edges))))
348 (set-frame-width frame (+ (ceiling (car size))
349 width (- inner-width)))
350 (set-frame-height frame (+ (ceiling (cdr size))
351 height (- inner-height)))
352 ;; The frame size after the above `set-frame-*' calls may
353 ;; differ from what we specified, due to window manager
354 ;; interference. We have to call `frame-width' and
355 ;; `frame-height' to get the actual results.
356 (set-frame-parameter frame 'image-mode-saved-params
357 (list (cons (frame-width)
358 (frame-height))
359 (cons width height)
360 window-configuration)))))))
362 ;;; Image Mode setup
364 (defvar-local image-type nil
365 "The image type for the current Image mode buffer.")
367 (defvar-local image-multi-frame nil
368 "Non-nil if image for the current Image mode buffer has multiple frames.")
370 (defvar image-mode-previous-major-mode nil
371 "Internal variable to keep the previous non-image major mode.")
373 (defvar image-mode-map
374 (let ((map (make-sparse-keymap)))
375 (define-key map "\C-c\C-c" 'image-toggle-display)
376 (define-key map "\C-c\C-x" 'image-toggle-hex-display)
377 (define-key map (kbd "SPC") 'image-scroll-up)
378 (define-key map (kbd "S-SPC") 'image-scroll-down)
379 (define-key map (kbd "DEL") 'image-scroll-down)
380 (define-key map (kbd "RET") 'image-toggle-animation)
381 (define-key map "F" 'image-goto-frame)
382 (define-key map "f" 'image-next-frame)
383 (define-key map "b" 'image-previous-frame)
384 (define-key map "n" 'image-next-file)
385 (define-key map "p" 'image-previous-file)
386 (define-key map "a+" 'image-increase-speed)
387 (define-key map "a-" 'image-decrease-speed)
388 (define-key map "a0" 'image-reset-speed)
389 (define-key map "ar" 'image-reverse-speed)
390 (define-key map "k" 'image-kill-buffer)
391 (define-key map [remap forward-char] 'image-forward-hscroll)
392 (define-key map [remap backward-char] 'image-backward-hscroll)
393 (define-key map [remap right-char] 'image-forward-hscroll)
394 (define-key map [remap left-char] 'image-backward-hscroll)
395 (define-key map [remap previous-line] 'image-previous-line)
396 (define-key map [remap next-line] 'image-next-line)
397 (define-key map [remap scroll-up] 'image-scroll-up)
398 (define-key map [remap scroll-down] 'image-scroll-down)
399 (define-key map [remap scroll-up-command] 'image-scroll-up)
400 (define-key map [remap scroll-down-command] 'image-scroll-down)
401 (define-key map [remap move-beginning-of-line] 'image-bol)
402 (define-key map [remap move-end-of-line] 'image-eol)
403 (define-key map [remap beginning-of-buffer] 'image-bob)
404 (define-key map [remap end-of-buffer] 'image-eob)
405 (easy-menu-define image-mode-menu map "Menu for Image mode."
406 '("Image"
407 ["Show as Text" image-toggle-display :active t
408 :help "Show image as text"]
409 ["Show as Hex" image-toggle-hex-display :active t
410 :help "Show image as hex"]
411 "--"
412 ["Fit to Window Height" image-transform-fit-to-height
413 :visible (eq image-type 'imagemagick)
414 :help "Resize image to match the window height"]
415 ["Fit to Window Width" image-transform-fit-to-width
416 :visible (eq image-type 'imagemagick)
417 :help "Resize image to match the window width"]
418 ["Rotate Image..." image-transform-set-rotation
419 :visible (eq image-type 'imagemagick)
420 :help "Rotate the image"]
421 ["Reset Transformations" image-transform-reset
422 :visible (eq image-type 'imagemagick)
423 :help "Reset all image transformations"]
424 "--"
425 ["Show Thumbnails"
426 (lambda ()
427 (interactive)
428 (image-dired default-directory))
429 :active default-directory
430 :help "Show thumbnails for all images in this directory"]
431 ["Next Image" image-next-file :active buffer-file-name
432 :help "Move to next image in this directory"]
433 ["Previous Image" image-previous-file :active buffer-file-name
434 :help "Move to previous image in this directory"]
435 "--"
436 ["Fit Frame to Image" image-mode-fit-frame :active t
437 :help "Resize frame to match image"]
438 "--"
439 ["Animate Image" image-toggle-animation :style toggle
440 :selected (let ((image (image-get-display-property)))
441 (and image (image-animate-timer image)))
442 :active image-multi-frame
443 :help "Toggle image animation"]
444 ["Loop Animation"
445 (lambda () (interactive)
446 (setq image-animate-loop (not image-animate-loop))
447 ;; FIXME this is a hacky way to make it affect a currently
448 ;; animating image.
449 (when (let ((image (image-get-display-property)))
450 (and image (image-animate-timer image)))
451 (image-toggle-animation)
452 (image-toggle-animation)))
453 :style toggle :selected image-animate-loop
454 :active image-multi-frame
455 :help "Animate images once, or forever?"]
456 ["Reverse Animation" image-reverse-speed
457 :style toggle :selected (let ((image (image-get-display-property)))
458 (and image (<
459 (image-animate-get-speed image)
460 0)))
461 :active image-multi-frame
462 :help "Reverse direction of this image's animation?"]
463 ["Speed Up Animation" image-increase-speed
464 :active image-multi-frame
465 :help "Speed up this image's animation"]
466 ["Slow Down Animation" image-decrease-speed
467 :active image-multi-frame
468 :help "Slow down this image's animation"]
469 ["Reset Animation Speed" image-reset-speed
470 :active image-multi-frame
471 :help "Reset the speed of this image's animation"]
472 ["Next Frame" image-next-frame :active image-multi-frame
473 :help "Show the next frame of this image"]
474 ["Previous Frame" image-previous-frame :active image-multi-frame
475 :help "Show the previous frame of this image"]
476 ["Goto Frame..." image-goto-frame :active image-multi-frame
477 :help "Show a specific frame of this image"]
479 (make-composed-keymap (list map image-map) special-mode-map))
480 "Mode keymap for `image-mode'.")
482 (defvar image-minor-mode-map
483 (let ((map (make-sparse-keymap)))
484 (define-key map "\C-c\C-c" 'image-toggle-display)
485 (define-key map "\C-c\C-x" 'image-toggle-hex-display)
486 map)
487 "Mode keymap for `image-minor-mode'.")
489 (defvar bookmark-make-record-function)
491 (put 'image-mode 'mode-class 'special)
493 ;;;###autoload
494 (defun image-mode ()
495 "Major mode for image files.
496 You can use \\<image-mode-map>\\[image-toggle-display] or \\<image-mode-map>\\[image-toggle-hex-display]
497 to toggle between display as an image and display as text or hex.
499 Key bindings:
500 \\{image-mode-map}"
501 (interactive)
502 (condition-case err
503 (progn
504 (unless (display-images-p)
505 (error "Display does not support images"))
507 (kill-all-local-variables)
508 (setq major-mode 'image-mode)
510 (if (not (image-get-display-property))
511 (progn
512 (image-toggle-display-image)
513 ;; If attempt to display the image fails.
514 (if (not (image-get-display-property))
515 (error "Invalid image")))
516 ;; Set next vars when image is already displayed but local
517 ;; variables were cleared by kill-all-local-variables
518 (setq cursor-type nil truncate-lines t
519 image-type (plist-get (cdr (image-get-display-property)) :type)))
521 (setq mode-name (if image-type (format "Image[%s]" image-type) "Image"))
522 (use-local-map image-mode-map)
524 ;; Use our own bookmarking function for images.
525 (setq-local bookmark-make-record-function
526 #'image-bookmark-make-record)
528 ;; Keep track of [vh]scroll when switching buffers
529 (image-mode-setup-winprops)
531 (add-hook 'change-major-mode-hook 'image-toggle-display-text nil t)
532 (add-hook 'after-revert-hook 'image-after-revert-hook nil t)
533 (run-mode-hooks 'image-mode-hook)
534 (let ((image (image-get-display-property))
535 (msg1 (substitute-command-keys
536 "Type \\[image-toggle-display] or \\[image-toggle-hex-display] to view the image as "))
537 animated)
538 (cond
539 ((null image)
540 (message "%s" (concat msg1 "an image.")))
541 ((setq animated (image-multi-frame-p image))
542 (setq image-multi-frame t
543 mode-line-process
544 `(:eval
545 (concat " "
546 (propertize
547 (format "[%s/%s]"
548 (1+ (image-current-frame ',image))
549 ,(car animated))
550 'help-echo "Frames
551 mouse-1: Next frame
552 mouse-3: Previous frame"
553 'mouse-face 'mode-line-highlight
554 'local-map
555 '(keymap
556 (mode-line
557 keymap
558 (down-mouse-1 . image-next-frame)
559 (down-mouse-3 . image-previous-frame)))))))
560 (message "%s"
561 (concat msg1 "text. This image has multiple frames.")))
562 ;;; (substitute-command-keys
563 ;;; "\\[image-toggle-animation] to animate."))))
565 (message "%s" (concat msg1 "text or hex."))))))
567 (error
568 (image-mode-as-text)
569 (funcall
570 (if (called-interactively-p 'any) 'error 'message)
571 "Cannot display image: %s" (cdr err)))))
573 ;;;###autoload
574 (define-minor-mode image-minor-mode
575 "Toggle Image minor mode in this buffer.
576 With a prefix argument ARG, enable Image minor mode if ARG is
577 positive, and disable it otherwise. If called from Lisp, enable
578 the mode if ARG is omitted or nil.
580 Image minor mode provides the key \\<image-mode-map>\\[image-toggle-display],
581 to switch back to `image-mode' and display an image file as the
582 actual image."
583 nil (:eval (if image-type (format " Image[%s]" image-type) " Image"))
584 image-minor-mode-map
585 :group 'image
586 :version "22.1"
587 (if image-minor-mode
588 (add-hook 'change-major-mode-hook (lambda () (image-minor-mode -1)) nil t)))
590 ;;;###autoload
591 (defun image-mode-to-text ()
592 "Set a non-image mode as major mode in combination with image minor mode.
593 A non-mage major mode found from `auto-mode-alist' or fundamental mode
594 displays an image file as text."
595 ;; image-mode-as-text = normal-mode + image-minor-mode
596 (let ((previous-image-type image-type)) ; preserve `image-type'
597 (if image-mode-previous-major-mode
598 ;; Restore previous major mode that was already found by this
599 ;; function and cached in `image-mode-previous-major-mode'
600 (funcall image-mode-previous-major-mode)
601 (let ((auto-mode-alist
602 (delq nil (mapcar
603 (lambda (elt)
604 (unless (memq (or (car-safe (cdr elt)) (cdr elt))
605 '(image-mode image-mode-maybe image-mode-as-text))
606 elt))
607 auto-mode-alist)))
608 (magic-fallback-mode-alist
609 (delq nil (mapcar
610 (lambda (elt)
611 (unless (memq (or (car-safe (cdr elt)) (cdr elt))
612 '(image-mode image-mode-maybe image-mode-as-text))
613 elt))
614 magic-fallback-mode-alist))))
615 (normal-mode)
616 (setq-local image-mode-previous-major-mode major-mode)))
617 ;; Restore `image-type' after `kill-all-local-variables' in `normal-mode'.
618 (setq image-type previous-image-type)
619 ;; Enable image minor mode with `C-c C-c'.
620 (image-minor-mode 1)
621 ;; Show the image file as text.
622 (image-toggle-display-text)))
624 (defun image-mode-as-hex ()
625 "Set a non-image mode as major mode in combination with image minor mode.
626 A non-mage major mode found from `auto-mode-alist' or fundamental mode
627 displays an image file as hex. `image-minor-mode' provides the key
628 \\<image-mode-map>\\[image-toggle-hex-display] to switch back to `image-mode'
629 to display an image file as the actual image.
631 You can use `image-mode-as-hex' in `auto-mode-alist' when you want to
632 to display an image file as hex initially.
634 See commands `image-mode' and `image-minor-mode' for more information
635 on these modes."
636 (interactive)
637 (image-mode-to-text)
638 ;; Turn on hexl-mode
639 (hexl-mode)
640 (message "%s" (concat
641 (substitute-command-keys
642 "Type \\[image-toggle-hex-display] or \\[image-toggle-display] to view the image as ")
643 (if (image-get-display-property)
644 "hex" "an image or text") ".")))
646 (defun image-mode-as-text ()
647 "Set a non-image mode as major mode in combination with image minor mode.
648 A non-image major mode found from `auto-mode-alist' or Fundamental mode
649 displays an image file as text. `image-minor-mode' provides the key
650 \\<image-mode-map>\\[image-toggle-display] to switch back to `image-mode'
651 to display an image file as the actual image.
653 You can use `image-mode-as-text' in `auto-mode-alist' when you want
654 to display an image file as text initially.
656 See commands `image-mode' and `image-minor-mode' for more information
657 on these modes."
658 (interactive)
659 (image-mode-to-text)
660 (message "%s" (concat
661 (substitute-command-keys
662 "Type \\[image-toggle-display] or \\[image-toggle-hex-display] to view the image as ")
663 (if (image-get-display-property)
664 "text" "an image or hex") ".")))
666 (define-obsolete-function-alias 'image-mode-maybe 'image-mode "23.2")
668 (defun image-toggle-display-text ()
669 "Show the image file as text.
670 Remove text properties that display the image."
671 (let ((inhibit-read-only t)
672 (buffer-undo-list t)
673 (modified (buffer-modified-p)))
674 (remove-list-of-text-properties (point-min) (point-max)
675 '(display read-nonsticky ;; intangible
676 read-only front-sticky))
677 (set-buffer-modified-p modified)
678 (if (called-interactively-p 'any)
679 (message "Repeat this command to go back to displaying the image"))))
681 (defvar archive-superior-buffer)
682 (defvar tar-superior-buffer)
683 (declare-function image-flush "image.c" (spec &optional frame))
685 (defun image-toggle-display-image ()
686 "Show the image of the image file.
687 Turn the image data into a real image, but only if the whole file
688 was inserted."
689 (unless (derived-mode-p 'image-mode)
690 (error "The buffer is not in Image mode"))
691 (let* ((filename (buffer-file-name))
692 (data-p (not (and filename
693 (file-readable-p filename)
694 (not (file-remote-p filename))
695 (not (buffer-modified-p))
696 (not (and (boundp 'archive-superior-buffer)
697 archive-superior-buffer))
698 (not (and (boundp 'tar-superior-buffer)
699 tar-superior-buffer))
700 ;; This means the buffer holds the
701 ;; decrypted content (bug#21870).
702 (not (and (boundp 'epa-file-encrypt-to)
703 (local-variable-p
704 'epa-file-encrypt-to))))))
705 (file-or-data (if data-p
706 (string-make-unibyte
707 (buffer-substring-no-properties (point-min) (point-max)))
708 filename))
709 ;; If we have a `fit-width' or a `fit-height', don't limit
710 ;; the size of the image to the window size.
711 (edges (and (null image-transform-resize)
712 (window-inside-pixel-edges
713 (get-buffer-window (current-buffer)))))
714 (type (if (fboundp 'imagemagick-types)
715 'imagemagick
716 (image-type file-or-data nil data-p)))
717 (image (if (not edges)
718 (create-image file-or-data type data-p)
719 (create-image file-or-data type data-p
720 :max-width (- (nth 2 edges) (nth 0 edges))
721 :max-height (- (nth 3 edges) (nth 1 edges)))))
722 (inhibit-read-only t)
723 (buffer-undo-list t)
724 (modified (buffer-modified-p))
725 props)
727 ;; Discard any stale image data before looking it up again.
728 (image-flush image)
729 (setq image (append image (image-transform-properties image)))
730 (setq props
731 `(display ,image
732 ;; intangible ,image
733 rear-nonsticky (display) ;; intangible
734 read-only t front-sticky (read-only)))
736 (let ((buffer-file-truename nil)) ; avoid changing dir mtime by lock_file
737 (add-text-properties (point-min) (point-max) props)
738 (restore-buffer-modified-p modified))
739 ;; Inhibit the cursor when the buffer contains only an image,
740 ;; because cursors look very strange on top of images.
741 (setq cursor-type nil)
742 ;; This just makes the arrow displayed in the right fringe
743 ;; area look correct when the image is wider than the window.
744 (setq truncate-lines t)
745 ;; Disable adding a newline at the end of the image file when it
746 ;; is written with, e.g., C-x C-w.
747 (if (coding-system-equal (coding-system-base buffer-file-coding-system)
748 'no-conversion)
749 (setq-local find-file-literally t))
750 ;; Allow navigation of large images.
751 (setq-local auto-hscroll-mode nil)
752 (setq image-type type)
753 (if (eq major-mode 'image-mode)
754 (setq mode-name (format "Image[%s]" type)))
755 (image-transform-check-size)
756 (if (called-interactively-p 'any)
757 (message "Repeat this command to go back to displaying the file as text"))))
759 (defun image-toggle-hex-display ()
760 "Toggle between image and hex display."
761 (interactive)
762 (if (image-get-display-property)
763 (image-mode-as-hex)
764 (if (eq major-mode 'fundamental-mode)
765 (image-mode-as-hex)
766 (image-mode))))
768 (defun image-toggle-display ()
769 "Toggle between image and text display.
771 If the current buffer is displaying an image file as an image,
772 call `image-mode-as-text' to switch to text or hex display.
773 Otherwise, display the image by calling `image-mode'"
774 (interactive)
775 (if (image-get-display-property)
776 (image-mode-as-text)
777 (if (eq major-mode 'hexl-mode)
778 (image-mode-as-text)
779 (image-mode))))
781 (defun image-kill-buffer ()
782 "Kill the current buffer."
783 (interactive)
784 (kill-buffer (current-buffer)))
786 (defun image-after-revert-hook ()
787 (when (image-get-display-property)
788 (image-toggle-display-text)
789 ;; Update image display.
790 (mapc (lambda (window) (redraw-frame (window-frame window)))
791 (get-buffer-window-list (current-buffer) 'nomini 'visible))
792 (image-toggle-display-image)))
795 ;;; Animated images
797 (defcustom image-animate-loop nil
798 "Non-nil means animated images loop forever, rather than playing once."
799 :type 'boolean
800 :version "24.1"
801 :group 'image)
803 (defun image-toggle-animation ()
804 "Start or stop animating the current image.
805 If `image-animate-loop' is non-nil, animation loops forever.
806 Otherwise it plays once, then stops."
807 (interactive)
808 (let ((image (image-get-display-property))
809 animation)
810 (cond
811 ((null image)
812 (error "No image is present"))
813 ((null (setq animation (image-multi-frame-p image)))
814 (message "No image animation."))
816 (let ((timer (image-animate-timer image)))
817 (if timer
818 (cancel-timer timer)
819 (let ((index (plist-get (cdr image) :index)))
820 ;; If we're at the end, restart.
821 (and index
822 (>= index (1- (car animation)))
823 (setq index nil))
824 (image-animate image index
825 (if image-animate-loop t)))))))))
827 (defun image--set-speed (speed &optional multiply)
828 "Set speed of an animated image to SPEED.
829 If MULTIPLY is non-nil, treat SPEED as a multiplication factor.
830 If SPEED is `reset', reset the magnitude of the speed to 1."
831 (let ((image (image-get-display-property)))
832 (cond
833 ((null image)
834 (error "No image is present"))
835 ((null image-multi-frame)
836 (message "No image animation."))
838 (if (eq speed 'reset)
839 (setq speed (if (< (image-animate-get-speed image) 0)
840 -1 1)
841 multiply nil))
842 (image-animate-set-speed image speed multiply)
843 ;; FIXME Hack to refresh an active image.
844 (when (image-animate-timer image)
845 (image-toggle-animation)
846 (image-toggle-animation))
847 (message "Image speed is now %s" (image-animate-get-speed image))))))
849 (defun image-increase-speed ()
850 "Increase the speed of current animated image by a factor of 2."
851 (interactive)
852 (image--set-speed 2 t))
854 (defun image-decrease-speed ()
855 "Decrease the speed of current animated image by a factor of 2."
856 (interactive)
857 (image--set-speed 0.5 t))
859 (defun image-reverse-speed ()
860 "Reverse the animation of the current image."
861 (interactive)
862 (image--set-speed -1 t))
864 (defun image-reset-speed ()
865 "Reset the animation speed of the current image."
866 (interactive)
867 (image--set-speed 'reset))
869 (defun image-goto-frame (n &optional relative)
870 "Show frame N of a multi-frame image.
871 Optional argument OFFSET non-nil means interpret N as relative to the
872 current frame. Frames are indexed from 1."
873 (interactive
874 (list (or current-prefix-arg
875 (read-number "Show frame number: "))))
876 (let ((image (image-get-display-property)))
877 (cond
878 ((null image)
879 (error "No image is present"))
880 ((null image-multi-frame)
881 (message "No image animation."))
883 (image-show-frame image
884 (if relative
885 (+ n (image-current-frame image))
886 (1- n)))))))
888 (defun image-next-frame (&optional n)
889 "Switch to the next frame of a multi-frame image.
890 With optional argument N, switch to the Nth frame after the current one.
891 If N is negative, switch to the Nth frame before the current one."
892 (interactive "p")
893 (image-goto-frame n t))
895 (defun image-previous-frame (&optional n)
896 "Switch to the previous frame of a multi-frame image.
897 With optional argument N, switch to the Nth frame before the current one.
898 If N is negative, switch to the Nth frame after the current one."
899 (interactive "p")
900 (image-next-frame (- n)))
903 ;;; Switching to the next/previous image
905 (defun image-next-file (&optional n)
906 "Visit the next image in the same directory as the current image file.
907 With optional argument N, visit the Nth image file after the
908 current one, in cyclic alphabetical order.
910 This command visits the specified file via `find-alternate-file',
911 replacing the current Image mode buffer."
912 (interactive "p")
913 (unless (derived-mode-p 'image-mode)
914 (error "The buffer is not in Image mode"))
915 (unless buffer-file-name
916 (error "The current image is not associated with a file"))
917 (let* ((file (file-name-nondirectory buffer-file-name))
918 (images (image-mode--images-in-directory file))
919 (idx 0))
920 (catch 'image-visit-next-file
921 (dolist (f images)
922 (if (string= f file)
923 (throw 'image-visit-next-file (1+ idx)))
924 (setq idx (1+ idx))))
925 (setq idx (mod (+ idx (or n 1)) (length images)))
926 (find-alternate-file (nth idx images))))
928 (defun image-previous-file (&optional n)
929 "Visit the preceding image in the same directory as the current file.
930 With optional argument N, visit the Nth image file preceding the
931 current one, in cyclic alphabetical order.
933 This command visits the specified file via `find-alternate-file',
934 replacing the current Image mode buffer."
935 (interactive "p")
936 (image-next-file (- n)))
938 (defun image-mode--images-in-directory (file)
939 (let* ((dir (file-name-directory buffer-file-name))
940 (files (directory-files dir nil
941 (image-file-name-regexp) t)))
942 ;; Add the current file to the list of images if necessary, in
943 ;; case it does not match `image-file-name-regexp'.
944 (unless (member file files)
945 (push file files))
946 (sort files 'string-lessp)))
949 ;;; Support for bookmark.el
950 (declare-function bookmark-make-record-default
951 "bookmark" (&optional no-file no-context posn))
952 (declare-function bookmark-prop-get "bookmark" (bookmark prop))
953 (declare-function bookmark-default-handler "bookmark" (bmk))
955 (defun image-bookmark-make-record ()
956 `(,@(bookmark-make-record-default nil 'no-context 0)
957 (image-type . ,image-type)
958 (handler . image-bookmark-jump)))
960 ;;;###autoload
961 (defun image-bookmark-jump (bmk)
962 ;; This implements the `handler' function interface for record type
963 ;; returned by `bookmark-make-record-function', which see.
964 (prog1 (bookmark-default-handler bmk)
965 (when (not (string= image-type (bookmark-prop-get bmk 'image-type)))
966 (image-toggle-display))))
969 ;; Not yet implemented.
970 ;; (defvar image-transform-minor-mode-map
971 ;; (let ((map (make-sparse-keymap)))
972 ;; ;; (define-key map [(control ?+)] 'image-scale-in)
973 ;; ;; (define-key map [(control ?-)] 'image-scale-out)
974 ;; ;; (define-key map [(control ?=)] 'image-scale-none)
975 ;; ;; (define-key map "c f h" 'image-scale-fit-height)
976 ;; ;; (define-key map "c ]" 'image-rotate-right)
977 ;; map)
978 ;; "Minor mode keymap `image-transform-mode'.")
980 ;; (define-minor-mode image-transform-mode
981 ;; "Minor mode for scaling and rotating images.
982 ;; With a prefix argument ARG, enable the mode if ARG is positive,
983 ;; and disable it otherwise. If called from Lisp, enable the mode
984 ;; if ARG is omitted or nil. This minor mode requires Emacs to have
985 ;; been compiled with ImageMagick support."
986 ;; nil "image-transform" image-transform-minor-mode-map)
989 (defsubst image-transform-width (width height)
990 "Return the bounding box width of a rotated WIDTH x HEIGHT rectangle.
991 The rotation angle is the value of `image-transform-rotation' in degrees."
992 (let ((angle (degrees-to-radians image-transform-rotation)))
993 ;; Assume, w.l.o.g., that the vertices of the rectangle have the
994 ;; coordinates (+-w/2, +-h/2) and that (0, 0) is the center of the
995 ;; rotation by the angle A. The projections onto the first axis
996 ;; of the vertices of the rotated rectangle are +- (w/2) cos A +-
997 ;; (h/2) sin A, and the difference between the largest and the
998 ;; smallest of the four values is the expression below.
999 (+ (* width (abs (cos angle))) (* height (abs (sin angle))))))
1001 ;; The following comment and code snippet are from
1002 ;; ImageMagick-6.7.4-4/magick/distort.c
1004 ;; /* Set the output image geometry to calculated 'best fit'.
1005 ;; Yes this tends to 'over do' the file image size, ON PURPOSE!
1006 ;; Do not do this for DePolar which needs to be exact for virtual tiling.
1007 ;; */
1008 ;; if ( fix_bounds ) {
1009 ;; geometry.x = (ssize_t) floor(min.x-0.5);
1010 ;; geometry.y = (ssize_t) floor(min.y-0.5);
1011 ;; geometry.width=(size_t) ceil(max.x-geometry.x+0.5);
1012 ;; geometry.height=(size_t) ceil(max.y-geometry.y+0.5);
1013 ;; }
1015 ;; Other parts of the same file show that here the origin is in the
1016 ;; left lower corner of the image rectangle, the center of the
1017 ;; rotation is the center of the rectangle and min.x and max.x
1018 ;; (resp. min.y and max.y) are the smallest and the largest of the
1019 ;; projections of the vertices onto the first (resp. second) axis.
1021 (defun image-transform-fit-width (width height length)
1022 "Return (w . h) so that a rotated w x h image has exactly width LENGTH.
1023 The rotation angle is the value of `image-transform-rotation'.
1024 Write W for WIDTH and H for HEIGHT. Then the w x h rectangle is
1025 an \"approximately uniformly\" scaled W x H rectangle, which
1026 currently means that w is one of floor(s W) + {0, 1, -1} and h is
1027 floor(s H), where s can be recovered as the value of `image-transform-scale'.
1028 The value of `image-transform-rotation' may be replaced by
1029 a slightly different angle. Currently this is done for values
1030 close to a multiple of 90, see `image-transform-right-angle-fudge'."
1031 (cond ((< (abs (- (mod (+ image-transform-rotation 90) 180) 90))
1032 image-transform-right-angle-fudge)
1033 (cl-assert (not (zerop width)) t)
1034 (setq image-transform-rotation
1035 (float (round image-transform-rotation))
1036 image-transform-scale (/ (float length) width))
1037 (cons length nil))
1038 ((< (abs (- (mod (+ image-transform-rotation 45) 90) 45))
1039 image-transform-right-angle-fudge)
1040 (cl-assert (not (zerop height)) t)
1041 (setq image-transform-rotation
1042 (float (round image-transform-rotation))
1043 image-transform-scale (/ (float length) height))
1044 (cons nil length))
1046 (cl-assert (not (and (zerop width) (zerop height))) t)
1047 (setq image-transform-scale
1048 (/ (float (1- length)) (image-transform-width width height)))
1049 ;; Assume we have a w x h image and an angle A, and let l =
1050 ;; l(w, h) = w |cos A| + h |sin A|, which is the actual width
1051 ;; of the bounding box of the rotated image, as calculated by
1052 ;; `image-transform-width'. The code snippet quoted above
1053 ;; means that ImageMagick puts the rotated image in
1054 ;; a bounding box of width L = 2 ceil((w+l+1)/2) - w.
1055 ;; Elementary considerations show that this is equivalent to
1056 ;; L - w being even and L-3 < l(w, h) <= L-1. In our case, L is
1057 ;; the given `length' parameter and our job is to determine
1058 ;; reasonable values for w and h which satisfy these
1059 ;; conditions.
1060 (let ((w (floor (* image-transform-scale width)))
1061 (h (floor (* image-transform-scale height))))
1062 ;; Let w and h as bound above. Then l(w, h) <= l(s W, s H)
1063 ;; = L-1 < l(w+1, h+1) = l(w, h) + l(1, 1) <= l(w, h) + 2,
1064 ;; hence l(w, h) > (L-1) - 2 = L-3.
1065 (cons
1066 (cond ((= (mod w 2) (mod length 2))
1068 ;; l(w+1, h) >= l(w, h) > L-3, but does l(w+1, h) <=
1069 ;; L-1 hold?
1070 ((<= (image-transform-width (1+ w) h) (1- length))
1071 (1+ w))
1072 ;; No, it doesn't, but this implies that l(w-1, h) =
1073 ;; l(w+1, h) - l(2, 0) >= l(w+1, h) - 2 > (L-1) -
1074 ;; 2 = L-3. Clearly, l(w-1, h) <= l(w, h) <= L-1.
1076 (1- w)))
1077 h)))))
1079 (defun image-transform-check-size ()
1080 "Check that the image exactly fits the width/height of the window.
1082 Do this for an image of type `imagemagick' to make sure that the
1083 elisp code matches the way ImageMagick computes the bounding box
1084 of a rotated image."
1085 (when (and (not (numberp image-transform-resize))
1086 (boundp 'image-type)
1087 (eq image-type 'imagemagick))
1088 (let ((size (image-display-size (image-get-display-property) t)))
1089 (cond ((eq image-transform-resize 'fit-width)
1090 (cl-assert (= (car size)
1091 (- (nth 2 (window-inside-pixel-edges))
1092 (nth 0 (window-inside-pixel-edges))))
1094 ((eq image-transform-resize 'fit-height)
1095 (cl-assert (= (cdr size)
1096 (- (nth 3 (window-inside-pixel-edges))
1097 (nth 1 (window-inside-pixel-edges))))
1098 t))))))
1100 (defun image-transform-properties (spec)
1101 "Return rescaling/rotation properties for image SPEC.
1102 These properties are determined by the Image mode variables
1103 `image-transform-resize' and `image-transform-rotation'. The
1104 return value is suitable for appending to an image spec.
1106 Rescaling and rotation properties only take effect if Emacs is
1107 compiled with ImageMagick support."
1108 (setq image-transform-scale 1.0)
1109 (when (or image-transform-resize
1110 (/= image-transform-rotation 0.0))
1111 ;; Note: `image-size' looks up and thus caches the untransformed
1112 ;; image. There's no easy way to prevent that.
1113 (let* ((size (image-size spec t))
1114 (resized
1115 (cond
1116 ((numberp image-transform-resize)
1117 (unless (= image-transform-resize 1)
1118 (setq image-transform-scale image-transform-resize)
1119 (cons nil (floor (* image-transform-resize (cdr size))))))
1120 ((eq image-transform-resize 'fit-width)
1121 (image-transform-fit-width
1122 (car size) (cdr size)
1123 (- (nth 2 (window-inside-pixel-edges))
1124 (nth 0 (window-inside-pixel-edges)))))
1125 ((eq image-transform-resize 'fit-height)
1126 (let ((res (image-transform-fit-width
1127 (cdr size) (car size)
1128 (- (nth 3 (window-inside-pixel-edges))
1129 (nth 1 (window-inside-pixel-edges))))))
1130 (cons (cdr res) (car res)))))))
1131 `(,@(when (car resized)
1132 (list :width (car resized)))
1133 ,@(when (cdr resized)
1134 (list :height (cdr resized)))
1135 ,@(unless (= 0.0 image-transform-rotation)
1136 (list :rotation image-transform-rotation))))))
1138 (defun image-transform-set-scale (scale)
1139 "Prompt for a number, and resize the current image by that amount.
1140 This command has no effect unless Emacs is compiled with
1141 ImageMagick support."
1142 (interactive "nScale: ")
1143 (setq image-transform-resize scale)
1144 (image-toggle-display-image))
1146 (defun image-transform-fit-to-height ()
1147 "Fit the current image to the height of the current window.
1148 This command has no effect unless Emacs is compiled with
1149 ImageMagick support."
1150 (interactive)
1151 (setq image-transform-resize 'fit-height)
1152 (image-toggle-display-image))
1154 (defun image-transform-fit-to-width ()
1155 "Fit the current image to the width of the current window.
1156 This command has no effect unless Emacs is compiled with
1157 ImageMagick support."
1158 (interactive)
1159 (setq image-transform-resize 'fit-width)
1160 (image-toggle-display-image))
1162 (defun image-transform-set-rotation (rotation)
1163 "Prompt for an angle ROTATION, and rotate the image by that amount.
1164 ROTATION should be in degrees. This command has no effect unless
1165 Emacs is compiled with ImageMagick support."
1166 (interactive "nRotation angle (in degrees): ")
1167 (setq image-transform-rotation (float (mod rotation 360)))
1168 (image-toggle-display-image))
1170 (defun image-transform-reset ()
1171 "Display the current image with the default size and rotation.
1172 This command has no effect unless Emacs is compiled with
1173 ImageMagick support."
1174 (interactive)
1175 (setq image-transform-resize nil
1176 image-transform-rotation 0.0
1177 image-transform-scale 1)
1178 (image-toggle-display-image))
1180 (provide 'image-mode)
1182 ;;; image-mode.el ends here