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