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