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