* sym-comp.el (symbol-complete): Replace obsolete completion-annotate-function.
[bpt/emacs.git] / lisp / image-mode.el
CommitLineData
83600dc8 1;;; image-mode.el --- support for visiting image files -*- lexical-binding: t -*-
c7bd5d57 2;;
ab422c4d 3;; Copyright (C) 2005-2013 Free Software Foundation, Inc.
c7bd5d57
RS
4;;
5;; Author: Richard Stallman <rms@gnu.org>
6;; Keywords: multimedia
bd78fa1d 7;; Package: emacs
c7bd5d57
RS
8
9;; This file is part of GNU Emacs.
10
eb3fa2cf 11;; GNU Emacs is free software: you can redistribute it and/or modify
c7bd5d57 12;; it under the terms of the GNU General Public License as published by
eb3fa2cf
GM
13;; the Free Software Foundation, either version 3 of the License, or
14;; (at your option) any later version.
c7bd5d57
RS
15
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.
20
21;; You should have received a copy of the GNU General Public License
eb3fa2cf 22;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
c7bd5d57
RS
23
24;;; Commentary:
25
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.
33
83600dc8
SM
34;; Todo:
35
36;; Consolidate with doc-view to make them work on directories of images or on
37;; image files containing various "pages".
38
c7bd5d57
RS
39;;; Code:
40
41(require 'image)
f58e0fd5 42(eval-when-compile (require 'cl-lib))
c7bd5d57 43
44e3c7c6
SM
44;;; Image mode window-info management.
45
83600dc8 46(defvar-local image-mode-winprops-alist t)
44e3c7c6
SM
47
48(defvar image-mode-new-window-functions nil
49 "Special hook run when image data is requested in a new window.
50It is called with one argument, the initial WINPROPS.")
51
b81f0bab 52(defun image-mode-winprops (&optional window cleanup)
44e3c7c6 53 "Return winprops of WINDOW.
83600dc8
SM
54A winprops object has the shape (WINDOW . ALIST).
55WINDOW defaults to `selected-window' if it displays the current buffer, and
56otherwise it defaults to t, used for times when the buffer is not displayed."
b81f0bab 57 (cond ((null window)
83600dc8
SM
58 (setq window
59 (if (eq (current-buffer) (window-buffer)) (selected-window) t)))
60 ((eq window t))
b81f0bab
CY
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)
08ce64e6
SM
66 (let ((w (car-safe winprop)))
67 (if (or (not (windowp w)) (window-live-p w))
68 winprop)))
b81f0bab 69 image-mode-winprops-alist))))
44e3c7c6
SM
70 (let ((winprops (assq window image-mode-winprops-alist)))
71 ;; For new windows, set defaults from the latest.
50105835
SM
72 (if winprops
73 ;; Move window to front.
74 (setq image-mode-winprops-alist
75 (cons winprops (delq winprops image-mode-winprops-alist)))
44e3c7c6
SM
76 (setq winprops (cons window
77 (copy-alist (cdar image-mode-winprops-alist))))
50105835
SM
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))
44e3c7c6 82 (run-hook-with-args 'image-mode-new-window-functions winprops))
44e3c7c6
SM
83 winprops))
84
85(defun image-mode-window-get (prop &optional winprops)
f58e0fd5
SM
86 (declare (gv-setter (lambda (val)
87 `(image-mode-window-put ,prop ,val ,winprops))))
44e3c7c6
SM
88 (unless (consp winprops) (setq winprops (image-mode-winprops winprops)))
89 (cdr (assq prop (cdr winprops))))
90
44e3c7c6
SM
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)))))
95
96(defun image-set-window-vscroll (vscroll)
97 (setf (image-mode-window-get 'vscroll) vscroll)
98 (set-window-vscroll (selected-window) vscroll))
99
100(defun image-set-window-hscroll (ncol)
60134fd4 101 (setf (image-mode-window-get 'hscroll) ncol)
44e3c7c6
SM
102 (set-window-hscroll (selected-window) ncol))
103
104(defun image-mode-reapply-winprops ()
6d401b4e
SM
105 ;; When set-window-buffer, set hscroll and vscroll to what they were
106 ;; last time the image was displayed in this window.
4fd996b3
SM
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).
b81f0bab 111 (let* ((winprops (image-mode-winprops nil t))
6d401b4e
SM
112 (hscroll (image-mode-window-get 'hscroll winprops))
113 (vscroll (image-mode-window-get 'vscroll winprops)))
4fd996b3
SM
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))))))
36e1c289 117
44e3c7c6
SM
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))
124
125;;; Image scrolling functions
126
91784462
SM
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))))
132
aa360da1
GM
133(declare-function image-size "image.c" (spec &optional pixels frame))
134
c9088194 135(defun image-display-size (spec &optional pixels frame)
2f224f0b
CY
136 "Wrapper around `image-size', handling slice display properties.
137Like `image-size', the return value is (WIDTH . HEIGHT).
138WIDTH and HEIGHT are in canonical character units if PIXELS is
139nil, and in pixel units if PIXELS is non-nil.
140
141If SPEC is an image display property, this function is equivalent
142to `image-size'. If SPEC is a list of properties containing
143`image' and `slice' properties, return the display size taking
144the slice property into account. If the list contains `image'
145but not `slice', return the `image-size' of the specified image."
c9088194
SK
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))
157 (t
158 (error "Invalid image specification: %s" spec))))))
159
bb0cb417
CY
160(defun image-forward-hscroll (&optional n)
161 "Scroll image in current window to the left by N character widths.
162Stop if the right edge of the image is reached."
163 (interactive "p")
164 (cond ((= n 0) nil)
165 ((< n 0)
44e3c7c6 166 (image-set-window-hscroll (max 0 (+ (window-hscroll) n))))
bb0cb417 167 (t
91784462 168 (let* ((image (image-get-display-property))
bb0cb417
CY
169 (edges (window-inside-edges))
170 (win-width (- (nth 2 edges) (nth 0 edges)))
c9088194 171 (img-width (ceiling (car (image-display-size image)))))
44e3c7c6 172 (image-set-window-hscroll (min (max 0 (- img-width win-width))
36e1c289 173 (+ n (window-hscroll))))))))
bb0cb417
CY
174
175(defun image-backward-hscroll (&optional n)
176 "Scroll image in current window to the right by N character widths.
177Stop if the left edge of the image is reached."
178 (interactive "p")
179 (image-forward-hscroll (- n)))
180
77549ea8 181(defun image-next-line (n)
bb0cb417
CY
182 "Scroll image in current window upward by N lines.
183Stop if the bottom edge of the image is reached."
184 (interactive "p")
185 (cond ((= n 0) nil)
186 ((< n 0)
44e3c7c6 187 (image-set-window-vscroll (max 0 (+ (window-vscroll) n))))
bb0cb417 188 (t
91784462 189 (let* ((image (image-get-display-property))
bb0cb417
CY
190 (edges (window-inside-edges))
191 (win-height (- (nth 3 edges) (nth 1 edges)))
c9088194 192 (img-height (ceiling (cdr (image-display-size image)))))
44e3c7c6 193 (image-set-window-vscroll (min (max 0 (- img-height win-height))
36e1c289 194 (+ n (window-vscroll))))))))
bb0cb417
CY
195
196(defun image-previous-line (&optional n)
197 "Scroll image in current window downward by N lines.
198Stop if the top edge of the image is reached."
199 (interactive "p")
200 (image-next-line (- n)))
201
202(defun image-scroll-up (&optional n)
203 "Scroll image in current window upward by N lines.
204Stop if the bottom edge of the image is reached.
205If ARG is omitted or nil, scroll upward by a near full screen.
206A near full screen is `next-screen-context-lines' less than a full screen.
207Negative ARG means scroll downward.
208If ARG is the atom `-', scroll downward by nearly full screen.
209When 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)))))
222
223(defun image-scroll-down (&optional n)
3488c456 224 "Scroll image in current window downward by N lines.
bb0cb417
CY
225Stop if the top edge of the image is reached.
226If ARG is omitted or nil, scroll downward by a near full screen.
227A near full screen is `next-screen-context-lines' less than a full screen.
228Negative ARG means scroll upward.
229If ARG is the atom `-', scroll upward by nearly full screen.
230When 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))))))
243
244(defun image-bol (arg)
245 "Scroll horizontally to the left edge of the image in the current window.
246With argument ARG not nil or 1, move forward ARG - 1 lines first,
247stopping 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)))
44e3c7c6 252 (image-set-window-hscroll 0))
bb0cb417
CY
253
254(defun image-eol (arg)
255 "Scroll horizontally to the right edge of the image in the current window.
256With argument ARG not nil or 1, move forward ARG - 1 lines first,
257stopping 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)))
91784462 262 (let* ((image (image-get-display-property))
bb0cb417
CY
263 (edges (window-inside-edges))
264 (win-width (- (nth 2 edges) (nth 0 edges)))
c9088194 265 (img-width (ceiling (car (image-display-size image)))))
44e3c7c6 266 (image-set-window-hscroll (max 0 (- img-width win-width)))))
bb0cb417
CY
267
268(defun image-bob ()
269 "Scroll to the top-left corner of the image in the current window."
270 (interactive)
44e3c7c6
SM
271 (image-set-window-hscroll 0)
272 (image-set-window-vscroll 0))
bb0cb417
CY
273
274(defun image-eob ()
275 "Scroll to the bottom-right corner of the image in the current window."
276 (interactive)
91784462 277 (let* ((image (image-get-display-property))
bb0cb417
CY
278 (edges (window-inside-edges))
279 (win-width (- (nth 2 edges) (nth 0 edges)))
c9088194 280 (img-width (ceiling (car (image-display-size image))))
bb0cb417 281 (win-height (- (nth 3 edges) (nth 1 edges)))
c9088194 282 (img-height (ceiling (cdr (image-display-size image)))))
44e3c7c6
SM
283 (image-set-window-hscroll (max 0 (- img-width win-width)))
284 (image-set-window-vscroll (max 0 (- img-height win-height)))))
bb0cb417 285
bd1d6a63
SM
286;; Adjust frame and image size.
287
2a43515a
CY
288(defun image-mode-fit-frame (&optional frame toggle)
289 "Fit FRAME to the current image.
290If FRAME is omitted or nil, it defaults to the selected frame.
291All other windows on the frame are deleted.
292
293If called interactively, or if TOGGLE is non-nil, toggle between
294fitting FRAME to the current image and restoring the size and
295window configuration prior to the last `image-mode-fit-frame'
296call."
297 (interactive (list nil t))
298 (let* ((buffer (current-buffer))
bd1d6a63 299 (display (image-get-display-property))
2a43515a
CY
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)))))))
bd1d6a63 332
bb0cb417
CY
333;;; Image Mode setup
334
4fd996b3 335(defvar-local image-type nil
71d73c9c 336 "The image type for the current Image mode buffer.")
d487ca7d 337
dc504515
GM
338(defvar-local image-multi-frame nil
339 "Non-nil if image for the current Image mode buffer has multiple frames.")
340
9b9debd1
JL
341(defvar image-mode-previous-major-mode nil
342 "Internal variable to keep the previous non-image major mode.")
343
c7bd5d57 344(defvar image-mode-map
bb0cb417 345 (let ((map (make-sparse-keymap)))
abef340a 346 (set-keymap-parent map special-mode-map)
bb0cb417 347 (define-key map "\C-c\C-c" 'image-toggle-display)
42c27c2a 348 (define-key map (kbd "SPC") 'image-scroll-up)
9cec74cf 349 (define-key map (kbd "S-SPC") 'image-scroll-down)
42c27c2a 350 (define-key map (kbd "DEL") 'image-scroll-down)
18af70d0 351 (define-key map (kbd "RET") 'image-toggle-animation)
c0211c4e
GM
352 (define-key map "F" 'image-goto-frame)
353 (define-key map "f" 'image-next-frame)
354 (define-key map "b" 'image-previous-frame)
20de6ab6
CW
355 (define-key map "n" 'image-next-file)
356 (define-key map "p" 'image-previous-file)
bb0cb417
CY
357 (define-key map [remap forward-char] 'image-forward-hscroll)
358 (define-key map [remap backward-char] 'image-backward-hscroll)
d8b0cddd
SM
359 (define-key map [remap right-char] 'image-forward-hscroll)
360 (define-key map [remap left-char] 'image-backward-hscroll)
bb0cb417
CY
361 (define-key map [remap previous-line] 'image-previous-line)
362 (define-key map [remap next-line] 'image-next-line)
363 (define-key map [remap scroll-up] 'image-scroll-up)
364 (define-key map [remap scroll-down] 'image-scroll-down)
32129746
JL
365 (define-key map [remap scroll-up-command] 'image-scroll-up)
366 (define-key map [remap scroll-down-command] 'image-scroll-down)
bb0cb417
CY
367 (define-key map [remap move-beginning-of-line] 'image-bol)
368 (define-key map [remap move-end-of-line] 'image-eol)
369 (define-key map [remap beginning-of-buffer] 'image-bob)
370 (define-key map [remap end-of-buffer] 'image-eob)
783b7b75
GM
371 (easy-menu-define image-mode-menu map "Menu for Image mode."
372 '("Image"
373 ["Show as Text" image-toggle-display :active t
374 :help "Show image as text"]
375 "--"
376 ["Fit Frame to Image" image-mode-fit-frame :active t
377 :help "Resize frame to match image"]
378 ["Fit to Window Height" image-transform-fit-to-height
379 :visible (eq image-type 'imagemagick)
380 :help "Resize image to match the window height"]
381 ["Fit to Window Width" image-transform-fit-to-width
382 :visible (eq image-type 'imagemagick)
383 :help "Resize image to match the window width"]
384 ["Rotate Image..." image-transform-set-rotation
385 :visible (eq image-type 'imagemagick)
386 :help "Rotate the image"]
387 "--"
f05e2ff2
GM
388 ["Show Thumbnails"
389 (lambda ()
390 (interactive)
391 (image-dired default-directory))
392 :active default-directory
393 :help "Show thumbnails for all images in this directory"]
394 ["Next Image" image-next-file :active buffer-file-name
783b7b75 395 :help "Move to next image in this directory"]
f05e2ff2 396 ["Previous Image" image-previous-file :active buffer-file-name
783b7b75
GM
397 :help "Move to previous image in this directory"]
398 "--"
399 ["Animate Image" image-toggle-animation :style toggle
400 :selected (let ((image (image-get-display-property)))
401 (and image (image-animate-timer image)))
dc504515 402 :active image-multi-frame
783b7b75
GM
403 :help "Toggle image animation"]
404 ["Loop Animation"
405 (lambda () (interactive)
783b7b75
GM
406 (setq image-animate-loop (not image-animate-loop))
407 ;; FIXME this is a hacky way to make it affect a currently
408 ;; animating image.
409 (when (let ((image (image-get-display-property)))
410 (and image (image-animate-timer image)))
411 (image-toggle-animation)
412 (image-toggle-animation)))
413 :style toggle :selected image-animate-loop
dc504515 414 :active image-multi-frame
783b7b75 415 :help "Animate images once, or forever?"]
dc504515 416 ["Next Frame" image-next-frame :active image-multi-frame
783b7b75 417 :help "Show the next frame of this image"]
dc504515 418 ["Previous Frame" image-previous-frame :active image-multi-frame
783b7b75 419 :help "Show the previous frame of this image"]
dc504515 420 ["Goto Frame..." image-goto-frame :active image-multi-frame
783b7b75
GM
421 :help "Show a specific frame of this image"]
422 ))
bb0cb417 423 map)
71d73c9c 424 "Mode keymap for `image-mode'.")
bb0cb417 425
9b9debd1 426(defvar image-minor-mode-map
c7bd5d57
RS
427 (let ((map (make-sparse-keymap)))
428 (define-key map "\C-c\C-c" 'image-toggle-display)
429 map)
71d73c9c 430 "Mode keymap for `image-minor-mode'.")
c7bd5d57 431
e0385bf4 432(defvar bookmark-make-record-function)
a47d49c0 433
0d17c4b9
JL
434(put 'image-mode 'mode-class 'special)
435
c7bd5d57
RS
436;;;###autoload
437(defun image-mode ()
438 "Major mode for image files.
439You can use \\<image-mode-map>\\[image-toggle-display]
440to toggle between display as an image and display as text."
441 (interactive)
9b9debd1
JL
442 (condition-case err
443 (progn
444 (unless (display-images-p)
445 (error "Display does not support images"))
446
447 (kill-all-local-variables)
448 (setq major-mode 'image-mode)
449
450 (if (not (image-get-display-property))
451 (progn
452 (image-toggle-display-image)
453 ;; If attempt to display the image fails.
454 (if (not (image-get-display-property))
455 (error "Invalid image")))
456 ;; Set next vars when image is already displayed but local
457 ;; variables were cleared by kill-all-local-variables
458 (setq cursor-type nil truncate-lines t
459 image-type (plist-get (cdr (image-get-display-property)) :type)))
460
461 (setq mode-name (if image-type (format "Image[%s]" image-type) "Image"))
bb43424b 462 (use-local-map image-mode-map)
9b9debd1
JL
463
464 ;; Use our own bookmarking function for images.
4fd996b3
SM
465 (setq-local bookmark-make-record-function
466 #'image-bookmark-make-record)
9b9debd1
JL
467
468 ;; Keep track of [vh]scroll when switching buffers
469 (image-mode-setup-winprops)
470
471 (add-hook 'change-major-mode-hook 'image-toggle-display-text nil t)
0fb1193d 472 (add-hook 'after-revert-hook 'image-after-revert-hook nil t)
9b9debd1 473 (run-mode-hooks 'image-mode-hook)
18af70d0
CY
474 (let ((image (image-get-display-property))
475 (msg1 (substitute-command-keys
bb9dfee1
GM
476 "Type \\[image-toggle-display] to view the image as "))
477 animated)
18af70d0
CY
478 (cond
479 ((null image)
480 (message "%s" (concat msg1 "an image.")))
ed8d7fca 481 ((setq animated (image-multi-frame-p image))
dc504515 482 (setq image-multi-frame t
bb9dfee1 483 mode-line-process
5db881d0
GM
484 `(:eval
485 (concat " "
486 (propertize
487 (format "[%s/%s]"
488 (1+ (image-current-frame ',image))
489 ,(car animated))
490 'help-echo "Frames
491mouse-1: Next frame
492mouse-3: Previous frame"
493 'mouse-face 'mode-line-highlight
494 'local-map
495 '(keymap
496 (mode-line
497 keymap
498 (down-mouse-1 . image-next-frame)
499 (down-mouse-3 . image-previous-frame)))))))
18af70d0 500 (message "%s"
ed8d7fca
GM
501 (concat msg1 "text. This image has multiple frames.")))
502;;; (substitute-command-keys
503;;; "\\[image-toggle-animation] to animate."))))
18af70d0
CY
504 (t
505 (message "%s" (concat msg1 "text."))))))
506
9b9debd1
JL
507 (error
508 (image-mode-as-text)
509 (funcall
510 (if (called-interactively-p 'any) 'error 'message)
511 "Cannot display image: %s" (cdr err)))))
18af70d0 512
d90e651e
JL
513;;;###autoload
514(define-minor-mode image-minor-mode
06e21633
CY
515 "Toggle Image minor mode in this buffer.
516With a prefix argument ARG, enable Image minor mode if ARG is
517positive, and disable it otherwise. If called from Lisp, enable
518the mode if ARG is omitted or nil.
519
520Image minor mode provides the key \\<image-mode-map>\\[image-toggle-display],
521to switch back to `image-mode' and display an image file as the
522actual image."
9b9debd1
JL
523 nil (:eval (if image-type (format " Image[%s]" image-type) " Image"))
524 image-minor-mode-map
d90e651e
JL
525 :group 'image
526 :version "22.1"
9b9debd1
JL
527 (if image-minor-mode
528 (add-hook 'change-major-mode-hook (lambda () (image-minor-mode -1)) nil t)))
d90e651e
JL
529
530;;;###autoload
9b9debd1
JL
531(defun image-mode-as-text ()
532 "Set a non-image mode as major mode in combination with image minor mode.
533A non-image major mode found from `auto-mode-alist' or Fundamental mode
534displays an image file as text. `image-minor-mode' provides the key
535\\<image-mode-map>\\[image-toggle-display] to switch back to `image-mode'
536to display an image file as the actual image.
537
538You can use `image-mode-as-text' in `auto-mode-alist' when you want
316d12fb 539to display an image file as text initially.
9b9debd1
JL
540
541See commands `image-mode' and `image-minor-mode' for more information
542on these modes."
d90e651e 543 (interactive)
9b9debd1
JL
544 ;; image-mode-as-text = normal-mode + image-minor-mode
545 (let ((previous-image-type image-type)) ; preserve `image-type'
546 (if image-mode-previous-major-mode
547 ;; Restore previous major mode that was already found by this
548 ;; function and cached in `image-mode-previous-major-mode'
549 (funcall image-mode-previous-major-mode)
550 (let ((auto-mode-alist
551 (delq nil (mapcar
552 (lambda (elt)
553 (unless (memq (or (car-safe (cdr elt)) (cdr elt))
554 '(image-mode image-mode-maybe image-mode-as-text))
555 elt))
556 auto-mode-alist)))
557 (magic-fallback-mode-alist
558 (delq nil (mapcar
559 (lambda (elt)
560 (unless (memq (or (car-safe (cdr elt)) (cdr elt))
561 '(image-mode image-mode-maybe image-mode-as-text))
562 elt))
563 magic-fallback-mode-alist))))
564 (normal-mode)
4fd996b3 565 (setq-local image-mode-previous-major-mode major-mode)))
9b9debd1
JL
566 ;; Restore `image-type' after `kill-all-local-variables' in `normal-mode'.
567 (setq image-type previous-image-type)
568 ;; Enable image minor mode with `C-c C-c'.
569 (image-minor-mode 1)
570 ;; Show the image file as text.
571 (image-toggle-display-text)
572 (message "%s" (concat
573 (substitute-command-keys
574 "Type \\[image-toggle-display] to view the image as ")
575 (if (image-get-display-property)
576 "text" "an image") "."))))
577
578(define-obsolete-function-alias 'image-mode-maybe 'image-mode "23.2")
d90e651e
JL
579
580(defun image-toggle-display-text ()
9b9debd1
JL
581 "Show the image file as text.
582Remove text properties that display the image."
583 (let ((inhibit-read-only t)
584 (buffer-undo-list t)
585 (modified (buffer-modified-p)))
586 (remove-list-of-text-properties (point-min) (point-max)
345083b2 587 '(display read-nonsticky ;; intangible
9b9debd1
JL
588 read-only front-sticky))
589 (set-buffer-modified-p modified)
590 (if (called-interactively-p 'any)
591 (message "Repeat this command to go back to displaying the image"))))
c7bd5d57 592
f2920ffe
RS
593(defvar archive-superior-buffer)
594(defvar tar-superior-buffer)
110683ad 595(declare-function image-flush "image.c" (spec &optional frame))
f2920ffe 596
9b9debd1
JL
597(defun image-toggle-display-image ()
598 "Show the image of the image file.
599Turn the image data into a real image, but only if the whole file
600was inserted."
953a8c3b 601 (unless (derived-mode-p 'image-mode)
a32d4040 602 (error "The buffer is not in Image mode"))
9b9debd1
JL
603 (let* ((filename (buffer-file-name))
604 (data-p (not (and filename
605 (file-readable-p filename)
606 (not (file-remote-p filename))
607 (not (buffer-modified-p))
608 (not (and (boundp 'archive-superior-buffer)
609 archive-superior-buffer))
610 (not (and (boundp 'tar-superior-buffer)
611 tar-superior-buffer)))))
612 (file-or-data (if data-p
613 (string-make-unibyte
614 (buffer-substring-no-properties (point-min) (point-max)))
615 filename))
616 (type (image-type file-or-data nil data-p))
e8cbec34
CY
617 (image (create-image file-or-data type data-p))
618 (inhibit-read-only t)
619 (buffer-undo-list t)
620 (modified (buffer-modified-p))
621 props)
622
18af70d0
CY
623 ;; Discard any stale image data before looking it up again.
624 (image-flush image)
e8cbec34
CY
625 (setq image (append image (image-transform-properties image)))
626 (setq props
9b9debd1 627 `(display ,image
345083b2
SM
628 ;; intangible ,image
629 rear-nonsticky (display) ;; intangible
9b9debd1 630 read-only t front-sticky (read-only)))
e8cbec34 631
9b9debd1
JL
632 (let ((buffer-file-truename nil)) ; avoid changing dir mtime by lock_file
633 (add-text-properties (point-min) (point-max) props)
634 (restore-buffer-modified-p modified))
635 ;; Inhibit the cursor when the buffer contains only an image,
636 ;; because cursors look very strange on top of images.
637 (setq cursor-type nil)
638 ;; This just makes the arrow displayed in the right fringe
639 ;; area look correct when the image is wider than the window.
640 (setq truncate-lines t)
4114ed61
EZ
641 ;; Disable adding a newline at the end of the image file when it
642 ;; is written with, e.g., C-x C-w.
643 (if (coding-system-equal (coding-system-base buffer-file-coding-system)
644 'no-conversion)
4fd996b3
SM
645 (setq-local find-file-literally t))
646 ;; Allow navigation of large images.
647 (setq-local auto-hscroll-mode nil)
9b9debd1
JL
648 (setq image-type type)
649 (if (eq major-mode 'image-mode)
650 (setq mode-name (format "Image[%s]" type)))
2d21d7f6 651 (image-transform-check-size)
9b9debd1
JL
652 (if (called-interactively-p 'any)
653 (message "Repeat this command to go back to displaying the file as text"))))
654
c7bd5d57 655(defun image-toggle-display ()
71d73c9c
CY
656 "Toggle between image and text display.
657If the current buffer is displaying an image file as an image,
658call `image-mode-as-text' to switch to text. Otherwise, display
659the image by calling `image-mode'."
c7bd5d57 660 (interactive)
91784462 661 (if (image-get-display-property)
9b9debd1
JL
662 (image-mode-as-text)
663 (image-mode)))
0fb1193d
JL
664
665(defun image-after-revert-hook ()
666 (when (image-get-display-property)
667 (image-toggle-display-text)
668 ;; Update image display.
637d46ca
GM
669 (mapc (lambda (window) (redraw-frame (window-frame window)))
670 (get-buffer-window-list (current-buffer) 'nomini 'visible))
0fb1193d
JL
671 (image-toggle-display-image)))
672
97666703 673\f
18af70d0
CY
674;;; Animated images
675
676(defcustom image-animate-loop nil
eea14f31 677 "Non-nil means animated images loop forever, rather than playing once."
18af70d0
CY
678 :type 'boolean
679 :version "24.1"
680 :group 'image)
681
682(defun image-toggle-animation ()
eea14f31
GM
683 "Start or stop animating the current image.
684If `image-animate-loop' is non-nil, animation loops forever.
685Otherwise it plays once, then stops."
18af70d0
CY
686 (interactive)
687 (let ((image (image-get-display-property))
688 animation)
689 (cond
690 ((null image)
691 (error "No image is present"))
ed8d7fca 692 ((null (setq animation (image-multi-frame-p image)))
18af70d0
CY
693 (message "No image animation."))
694 (t
695 (let ((timer (image-animate-timer image)))
696 (if timer
697 (cancel-timer timer)
698 (let ((index (plist-get (cdr image) :index)))
699 ;; If we're at the end, restart.
700 (and index
701 (>= index (1- (car animation)))
702 (setq index nil))
703 (image-animate image index
704 (if image-animate-loop t)))))))))
705
c0211c4e
GM
706(defun image-goto-frame (n &optional relative)
707 "Show frame N of a multi-frame image.
708Optional argument OFFSET non-nil means interpret N as relative to the
709current frame. Frames are indexed from 1."
710 (interactive
711 (list (or current-prefix-arg
712 (read-number "Show frame number: "))))
783b7b75 713 (let ((image (image-get-display-property)))
c0211c4e
GM
714 (cond
715 ((null image)
716 (error "No image is present"))
dc504515 717 ((null image-multi-frame)
c0211c4e
GM
718 (message "No image animation."))
719 (t
dc504515
GM
720 (image-show-frame image
721 (if relative
722 (+ n (image-current-frame image))
723 (1- n)))))))
c0211c4e
GM
724
725(defun image-next-frame (&optional n)
726 "Switch to the next frame of a multi-frame image.
727With optional argument N, switch to the Nth frame after the current one.
728If N is negative, switch to the Nth frame before the current one."
729 (interactive "p")
730 (image-goto-frame n t))
731
732(defun image-previous-frame (&optional n)
733 "Switch to the previous frame of a multi-frame image.
734With optional argument N, switch to the Nth frame before the current one.
735If N is negative, switch to the Nth frame after the current one."
736 (interactive "p")
737 (image-next-frame (- n)))
738
18af70d0 739\f
20de6ab6
CW
740;;; Switching to the next/previous image
741
742(defun image-next-file (&optional n)
743 "Visit the next image in the same directory as the current image file.
744With optional argument N, visit the Nth image file after the
745current one, in cyclic alphabetical order.
746
747This command visits the specified file via `find-alternate-file',
748replacing the current Image mode buffer."
749 (interactive "p")
750 (unless (derived-mode-p 'image-mode)
751 (error "The buffer is not in Image mode"))
752 (unless buffer-file-name
753 (error "The current image is not associated with a file"))
754 (let* ((file (file-name-nondirectory buffer-file-name))
755 (images (image-mode--images-in-directory file))
756 (idx 0))
757 (catch 'image-visit-next-file
758 (dolist (f images)
759 (if (string= f file)
760 (throw 'image-visit-next-file (1+ idx)))
761 (setq idx (1+ idx))))
762 (setq idx (mod (+ idx (or n 1)) (length images)))
763 (find-alternate-file (nth idx images))))
764
765(defun image-previous-file (&optional n)
766 "Visit the preceding image in the same directory as the current file.
767With optional argument N, visit the Nth image file preceding the
768current one, in cyclic alphabetical order.
769
770This command visits the specified file via `find-alternate-file',
771replacing the current Image mode buffer."
772 (interactive "p")
773 (image-next-file (- n)))
774
775(defun image-mode--images-in-directory (file)
776 (let* ((dir (file-name-directory buffer-file-name))
777 (files (directory-files dir nil
778 (image-file-name-regexp) t)))
779 ;; Add the current file to the list of images if necessary, in
780 ;; case it does not match `image-file-name-regexp'.
781 (unless (member file files)
782 (push file files))
783 (sort files 'string-lessp)))
784
785\f
137187c8 786;;; Support for bookmark.el
e44fa724
KF
787(declare-function bookmark-make-record-default
788 "bookmark" (&optional no-file no-context posn))
43f8b275
SM
789(declare-function bookmark-prop-get "bookmark" (bookmark prop))
790(declare-function bookmark-default-handler "bookmark" (bmk))
137187c8 791
43f8b275 792(defun image-bookmark-make-record ()
f12492c8
TV
793 `(,@(bookmark-make-record-default nil 'no-context 0)
794 (image-type . ,image-type)
795 (handler . image-bookmark-jump)))
137187c8 796
137187c8
TH
797;;;###autoload
798(defun image-bookmark-jump (bmk)
03e26a79 799 ;; This implements the `handler' function interface for record type
e0385bf4 800 ;; returned by `bookmark-make-record-function', which see.
43f8b275
SM
801 (prog1 (bookmark-default-handler bmk)
802 (when (not (string= image-type (bookmark-prop-get bmk 'image-type)))
803 (image-toggle-display))))
97666703 804\f
c7f514b5 805
b4ac6e8c 806;; Not yet implemented.
7102e6d0
WJ
807;; (defvar image-transform-minor-mode-map
808;; (let ((map (make-sparse-keymap)))
809;; ;; (define-key map [(control ?+)] 'image-scale-in)
810;; ;; (define-key map [(control ?-)] 'image-scale-out)
811;; ;; (define-key map [(control ?=)] 'image-scale-none)
812;; ;; (define-key map "c f h" 'image-scale-fit-height)
813;; ;; (define-key map "c ]" 'image-rotate-right)
814;; map)
815;; "Minor mode keymap `image-transform-mode'.")
816;;
817;; (define-minor-mode image-transform-mode
818;; "Minor mode for scaling and rotating images.
819;; With a prefix argument ARG, enable the mode if ARG is positive,
820;; and disable it otherwise. If called from Lisp, enable the mode
821;; if ARG is omitted or nil. This minor mode requires Emacs to have
822;; been compiled with ImageMagick support."
823;; nil "image-transform" image-transform-minor-mode-map)
b4ac6e8c
GM
824
825
826;; FIXME this doesn't seem mature yet. Document in manual when it is.
a32d4040
CY
827(defvar image-transform-resize nil
828 "The image resize operation.
829Its value should be one of the following:
830 - nil, meaning no resizing.
831 - `fit-height', meaning to fit the image to the window height.
832 - `fit-width', meaning to fit the image to the window width.
7102e6d0 833 - A number, which is a scale factor (the default size is 1).")
c7f514b5 834
2d21d7f6
WJ
835(defvar image-transform-scale 1.0
836 "The scale factor of the image being displayed.")
837
18af70d0
CY
838(defvar image-transform-rotation 0.0
839 "Rotation angle for the image in the current Image mode buffer.")
c7f514b5 840
2d21d7f6
WJ
841(defvar image-transform-right-angle-fudge 0.0001
842 "Snap distance to a multiple of a right angle.
843There's no deep theory behind the default value, it should just
844be somewhat larger than ImageMagick's MagickEpsilon.")
845
846(defsubst image-transform-width (width height)
847 "Return the bounding box width of a rotated WIDTH x HEIGHT rectangle.
848The rotation angle is the value of `image-transform-rotation' in degrees."
849 (let ((angle (degrees-to-radians image-transform-rotation)))
850 ;; Assume, w.l.o.g., that the vertices of the rectangle have the
851 ;; coordinates (+-w/2, +-h/2) and that (0, 0) is the center of the
852 ;; rotation by the angle A. The projections onto the first axis
853 ;; of the vertices of the rotated rectangle are +- (w/2) cos A +-
854 ;; (h/2) sin A, and the difference between the largest and the
855 ;; smallest of the four values is the expression below.
856 (+ (* width (abs (cos angle))) (* height (abs (sin angle))))))
857
858;; The following comment and code snippet are from
859;; ImageMagick-6.7.4-4/magick/distort.c
860
c846da43 861;; /* Set the output image geometry to calculated 'best fit'.
2d21d7f6
WJ
862;; Yes this tends to 'over do' the file image size, ON PURPOSE!
863;; Do not do this for DePolar which needs to be exact for virtual tiling.
864;; */
865;; if ( fix_bounds ) {
866;; geometry.x = (ssize_t) floor(min.x-0.5);
867;; geometry.y = (ssize_t) floor(min.y-0.5);
868;; geometry.width=(size_t) ceil(max.x-geometry.x+0.5);
869;; geometry.height=(size_t) ceil(max.y-geometry.y+0.5);
870;; }
871
872;; Other parts of the same file show that here the origin is in the
873;; left lower corner of the image rectangle, the center of the
874;; rotation is the center of the rectangle and min.x and max.x
875;; (resp. min.y and max.y) are the smallest and the largest of the
876;; projections of the vertices onto the first (resp. second) axis.
877
878(defun image-transform-fit-width (width height length)
879 "Return (w . h) so that a rotated w x h image has exactly width LENGTH.
880The rotation angle is the value of `image-transform-rotation'.
881Write W for WIDTH and H for HEIGHT. Then the w x h rectangle is
882an \"approximately uniformly\" scaled W x H rectangle, which
883currently means that w is one of floor(s W) + {0, 1, -1} and h is
884floor(s H), where s can be recovered as the value of `image-transform-scale'.
885The value of `image-transform-rotation' may be replaced by
886a slightly different angle. Currently this is done for values
887close to a multiple of 90, see `image-transform-right-angle-fudge'."
888 (cond ((< (abs (- (mod (+ image-transform-rotation 90) 180) 90))
889 image-transform-right-angle-fudge)
f58e0fd5 890 (cl-assert (not (zerop width)) t)
2d21d7f6
WJ
891 (setq image-transform-rotation
892 (float (round image-transform-rotation))
893 image-transform-scale (/ (float length) width))
894 (cons length nil))
895 ((< (abs (- (mod (+ image-transform-rotation 45) 90) 45))
896 image-transform-right-angle-fudge)
f58e0fd5 897 (cl-assert (not (zerop height)) t)
2d21d7f6
WJ
898 (setq image-transform-rotation
899 (float (round image-transform-rotation))
900 image-transform-scale (/ (float length) height))
901 (cons nil length))
902 (t
f58e0fd5 903 (cl-assert (not (and (zerop width) (zerop height))) t)
2d21d7f6
WJ
904 (setq image-transform-scale
905 (/ (float (1- length)) (image-transform-width width height)))
906 ;; Assume we have a w x h image and an angle A, and let l =
907 ;; l(w, h) = w |cos A| + h |sin A|, which is the actual width
908 ;; of the bounding box of the rotated image, as calculated by
909 ;; `image-transform-width'. The code snippet quoted above
910 ;; means that ImageMagick puts the rotated image in
911 ;; a bounding box of width L = 2 ceil((w+l+1)/2) - w.
912 ;; Elementary considerations show that this is equivalent to
913 ;; L - w being even and L-3 < l(w, h) <= L-1. In our case, L is
914 ;; the given `length' parameter and our job is to determine
915 ;; reasonable values for w and h which satisfy these
916 ;; conditions.
917 (let ((w (floor (* image-transform-scale width)))
918 (h (floor (* image-transform-scale height))))
919 ;; Let w and h as bound above. Then l(w, h) <= l(s W, s H)
920 ;; = L-1 < l(w+1, h+1) = l(w, h) + l(1, 1) <= l(w, h) + 2,
921 ;; hence l(w, h) > (L-1) - 2 = L-3.
922 (cons
923 (cond ((= (mod w 2) (mod length 2))
924 w)
925 ;; l(w+1, h) >= l(w, h) > L-3, but does l(w+1, h) <=
926 ;; L-1 hold?
927 ((<= (image-transform-width (1+ w) h) (1- length))
928 (1+ w))
929 ;; No, it doesn't, but this implies that l(w-1, h) =
930 ;; l(w+1, h) - l(2, 0) >= l(w+1, h) - 2 > (L-1) -
931 ;; 2 = L-3. Clearly, l(w-1, h) <= l(w, h) <= L-1.
932 (t
933 (1- w)))
934 h)))))
935
936(defun image-transform-check-size ()
977f9325
WJ
937 "Check that the image exactly fits the width/height of the window.
938
939Do this for an image of type `imagemagick' to make sure that the
940elisp code matches the way ImageMagick computes the bounding box
941of a rotated image."
942 (when (and (not (numberp image-transform-resize))
943 (boundp 'image-type)
944 (eq image-type 'imagemagick))
2d21d7f6
WJ
945 (let ((size (image-display-size (image-get-display-property) t)))
946 (cond ((eq image-transform-resize 'fit-width)
f58e0fd5 947 (cl-assert (= (car size)
2d21d7f6
WJ
948 (- (nth 2 (window-inside-pixel-edges))
949 (nth 0 (window-inside-pixel-edges))))
950 t))
951 ((eq image-transform-resize 'fit-height)
f58e0fd5 952 (cl-assert (= (cdr size)
2d21d7f6
WJ
953 (- (nth 3 (window-inside-pixel-edges))
954 (nth 1 (window-inside-pixel-edges))))
955 t))))))
956
18af70d0
CY
957(defun image-transform-properties (spec)
958 "Return rescaling/rotation properties for image SPEC.
959These properties are determined by the Image mode variables
960`image-transform-resize' and `image-transform-rotation'. The
961return value is suitable for appending to an image spec.
e8cbec34 962
09e80d9f 963Rescaling and rotation properties only take effect if Emacs is
e8cbec34 964compiled with ImageMagick support."
2d21d7f6 965 (setq image-transform-scale 1.0)
18af70d0 966 (when (or image-transform-resize
2d21d7f6 967 (/= image-transform-rotation 0.0))
18af70d0
CY
968 ;; Note: `image-size' looks up and thus caches the untransformed
969 ;; image. There's no easy way to prevent that.
970 (let* ((size (image-size spec t))
2d21d7f6 971 (resized
18af70d0
CY
972 (cond
973 ((numberp image-transform-resize)
7102e6d0 974 (unless (= image-transform-resize 1)
2d21d7f6
WJ
975 (setq image-transform-scale image-transform-resize)
976 (cons nil (floor (* image-transform-resize (cdr size))))))
977 ((eq image-transform-resize 'fit-width)
978 (image-transform-fit-width
979 (car size) (cdr size)
980 (- (nth 2 (window-inside-pixel-edges))
981 (nth 0 (window-inside-pixel-edges)))))
18af70d0 982 ((eq image-transform-resize 'fit-height)
2d21d7f6
WJ
983 (let ((res (image-transform-fit-width
984 (cdr size) (car size)
985 (- (nth 3 (window-inside-pixel-edges))
986 (nth 1 (window-inside-pixel-edges))))))
987 (cons (cdr res) (car res)))))))
988 `(,@(when (car resized)
989 (list :width (car resized)))
990 ,@(when (cdr resized)
991 (list :height (cdr resized)))
992 ,@(unless (= 0.0 image-transform-rotation)
993 (list :rotation image-transform-rotation))))))
c7f514b5
JV
994
995(defun image-transform-set-scale (scale)
a32d4040
CY
996 "Prompt for a number, and resize the current image by that amount.
997This command has no effect unless Emacs is compiled with
998ImageMagick support."
999 (interactive "nScale: ")
c183f693 1000 (setq image-transform-resize scale)
a32d4040 1001 (image-toggle-display-image))
c7f514b5
JV
1002
1003(defun image-transform-fit-to-height ()
a32d4040
CY
1004 "Fit the current image to the height of the current window.
1005This command has no effect unless Emacs is compiled with
1006ImageMagick support."
c7f514b5 1007 (interactive)
a32d4040
CY
1008 (setq image-transform-resize 'fit-height)
1009 (image-toggle-display-image))
c7f514b5 1010
3a50be51 1011(defun image-transform-fit-to-width ()
a32d4040
CY
1012 "Fit the current image to the width of the current window.
1013This command has no effect unless Emacs is compiled with
1014ImageMagick support."
3a50be51 1015 (interactive)
a32d4040
CY
1016 (setq image-transform-resize 'fit-width)
1017 (image-toggle-display-image))
c7f514b5
JV
1018
1019(defun image-transform-set-rotation (rotation)
a32d4040
CY
1020 "Prompt for an angle ROTATION, and rotate the image by that amount.
1021ROTATION should be in degrees. This command has no effect unless
1022Emacs is compiled with ImageMagick support."
1023 (interactive "nRotation angle (in degrees): ")
2d21d7f6 1024 (setq image-transform-rotation (float (mod rotation 360)))
a32d4040 1025 (image-toggle-display-image))
c7f514b5 1026
c7bd5d57
RS
1027(provide 'image-mode)
1028
1029;;; image-mode.el ends here