Add more keymaps where S-SPC scrolls in the opposite direction to SPC.
[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.
72 (unless winprops
73 (setq winprops (cons window
74 (copy-alist (cdar image-mode-winprops-alist))))
75 (run-hook-with-args 'image-mode-new-window-functions winprops))
76 ;; Move window to front.
77 (setq image-mode-winprops-alist
78 (cons winprops (delq winprops image-mode-winprops-alist)))
79 winprops))
80
81(defun image-mode-window-get (prop &optional winprops)
f58e0fd5
SM
82 (declare (gv-setter (lambda (val)
83 `(image-mode-window-put ,prop ,val ,winprops))))
44e3c7c6
SM
84 (unless (consp winprops) (setq winprops (image-mode-winprops winprops)))
85 (cdr (assq prop (cdr winprops))))
86
44e3c7c6
SM
87(defun image-mode-window-put (prop val &optional winprops)
88 (unless (consp winprops) (setq winprops (image-mode-winprops winprops)))
89 (setcdr winprops (cons (cons prop val)
90 (delq (assq prop (cdr winprops)) (cdr winprops)))))
91
92(defun image-set-window-vscroll (vscroll)
93 (setf (image-mode-window-get 'vscroll) vscroll)
94 (set-window-vscroll (selected-window) vscroll))
95
96(defun image-set-window-hscroll (ncol)
60134fd4 97 (setf (image-mode-window-get 'hscroll) ncol)
44e3c7c6
SM
98 (set-window-hscroll (selected-window) ncol))
99
100(defun image-mode-reapply-winprops ()
6d401b4e
SM
101 ;; When set-window-buffer, set hscroll and vscroll to what they were
102 ;; last time the image was displayed in this window.
b81f0bab
CY
103 (when (and (image-get-display-property)
104 (listp image-mode-winprops-alist))
105 (let* ((winprops (image-mode-winprops nil t))
6d401b4e
SM
106 (hscroll (image-mode-window-get 'hscroll winprops))
107 (vscroll (image-mode-window-get 'vscroll winprops)))
c313b5fe
SM
108 (if hscroll (set-window-hscroll (selected-window) hscroll))
109 (if vscroll (set-window-vscroll (selected-window) vscroll)))))
36e1c289 110
44e3c7c6
SM
111(defun image-mode-setup-winprops ()
112 ;; Record current scroll settings.
113 (unless (listp image-mode-winprops-alist)
114 (setq image-mode-winprops-alist nil))
115 (add-hook 'window-configuration-change-hook
116 'image-mode-reapply-winprops nil t))
117
118;;; Image scrolling functions
119
91784462
SM
120(defun image-get-display-property ()
121 (get-char-property (point-min) 'display
122 ;; There might be different images for different displays.
123 (if (eq (window-buffer) (current-buffer))
124 (selected-window))))
125
aa360da1
GM
126(declare-function image-size "image.c" (spec &optional pixels frame))
127
c9088194 128(defun image-display-size (spec &optional pixels frame)
2f224f0b
CY
129 "Wrapper around `image-size', handling slice display properties.
130Like `image-size', the return value is (WIDTH . HEIGHT).
131WIDTH and HEIGHT are in canonical character units if PIXELS is
132nil, and in pixel units if PIXELS is non-nil.
133
134If SPEC is an image display property, this function is equivalent
135to `image-size'. If SPEC is a list of properties containing
136`image' and `slice' properties, return the display size taking
137the slice property into account. If the list contains `image'
138but not `slice', return the `image-size' of the specified image."
c9088194
SK
139 (if (eq (car spec) 'image)
140 (image-size spec pixels frame)
141 (let ((image (assoc 'image spec))
142 (slice (assoc 'slice spec)))
143 (cond ((and image slice)
144 (if pixels
145 (cons (nth 3 slice) (nth 4 slice))
146 (cons (/ (float (nth 3 slice)) (frame-char-width frame))
147 (/ (float (nth 4 slice)) (frame-char-height frame)))))
148 (image
149 (image-size image pixels frame))
150 (t
151 (error "Invalid image specification: %s" spec))))))
152
bb0cb417
CY
153(defun image-forward-hscroll (&optional n)
154 "Scroll image in current window to the left by N character widths.
155Stop if the right edge of the image is reached."
156 (interactive "p")
157 (cond ((= n 0) nil)
158 ((< n 0)
44e3c7c6 159 (image-set-window-hscroll (max 0 (+ (window-hscroll) n))))
bb0cb417 160 (t
91784462 161 (let* ((image (image-get-display-property))
bb0cb417
CY
162 (edges (window-inside-edges))
163 (win-width (- (nth 2 edges) (nth 0 edges)))
c9088194 164 (img-width (ceiling (car (image-display-size image)))))
44e3c7c6 165 (image-set-window-hscroll (min (max 0 (- img-width win-width))
36e1c289 166 (+ n (window-hscroll))))))))
bb0cb417
CY
167
168(defun image-backward-hscroll (&optional n)
169 "Scroll image in current window to the right by N character widths.
170Stop if the left edge of the image is reached."
171 (interactive "p")
172 (image-forward-hscroll (- n)))
173
77549ea8 174(defun image-next-line (n)
bb0cb417
CY
175 "Scroll image in current window upward by N lines.
176Stop if the bottom edge of the image is reached."
177 (interactive "p")
178 (cond ((= n 0) nil)
179 ((< n 0)
44e3c7c6 180 (image-set-window-vscroll (max 0 (+ (window-vscroll) n))))
bb0cb417 181 (t
91784462 182 (let* ((image (image-get-display-property))
bb0cb417
CY
183 (edges (window-inside-edges))
184 (win-height (- (nth 3 edges) (nth 1 edges)))
c9088194 185 (img-height (ceiling (cdr (image-display-size image)))))
44e3c7c6 186 (image-set-window-vscroll (min (max 0 (- img-height win-height))
36e1c289 187 (+ n (window-vscroll))))))))
bb0cb417
CY
188
189(defun image-previous-line (&optional n)
190 "Scroll image in current window downward by N lines.
191Stop if the top edge of the image is reached."
192 (interactive "p")
193 (image-next-line (- n)))
194
195(defun image-scroll-up (&optional n)
196 "Scroll image in current window upward by N lines.
197Stop if the bottom edge of the image is reached.
198If ARG is omitted or nil, scroll upward by a near full screen.
199A near full screen is `next-screen-context-lines' less than a full screen.
200Negative ARG means scroll downward.
201If ARG is the atom `-', scroll downward by nearly full screen.
202When calling from a program, supply as argument a number, nil, or `-'."
203 (interactive "P")
204 (cond ((null n)
205 (let* ((edges (window-inside-edges))
206 (win-height (- (nth 3 edges) (nth 1 edges))))
207 (image-next-line
208 (max 0 (- win-height next-screen-context-lines)))))
209 ((eq n '-)
210 (let* ((edges (window-inside-edges))
211 (win-height (- (nth 3 edges) (nth 1 edges))))
212 (image-next-line
213 (min 0 (- next-screen-context-lines win-height)))))
214 (t (image-next-line (prefix-numeric-value n)))))
215
216(defun image-scroll-down (&optional n)
3488c456 217 "Scroll image in current window downward by N lines.
bb0cb417
CY
218Stop if the top edge of the image is reached.
219If ARG is omitted or nil, scroll downward by a near full screen.
220A near full screen is `next-screen-context-lines' less than a full screen.
221Negative ARG means scroll upward.
222If ARG is the atom `-', scroll upward by nearly full screen.
223When calling from a program, supply as argument a number, nil, or `-'."
224 (interactive "P")
225 (cond ((null n)
226 (let* ((edges (window-inside-edges))
227 (win-height (- (nth 3 edges) (nth 1 edges))))
228 (image-next-line
229 (min 0 (- next-screen-context-lines win-height)))))
230 ((eq n '-)
231 (let* ((edges (window-inside-edges))
232 (win-height (- (nth 3 edges) (nth 1 edges))))
233 (image-next-line
234 (max 0 (- win-height next-screen-context-lines)))))
235 (t (image-next-line (- (prefix-numeric-value n))))))
236
237(defun image-bol (arg)
238 "Scroll horizontally to the left edge of the image in the current window.
239With argument ARG not nil or 1, move forward ARG - 1 lines first,
240stopping if the top or bottom edge of the image is reached."
241 (interactive "p")
242 (and arg
243 (/= (setq arg (prefix-numeric-value arg)) 1)
244 (image-next-line (- arg 1)))
44e3c7c6 245 (image-set-window-hscroll 0))
bb0cb417
CY
246
247(defun image-eol (arg)
248 "Scroll horizontally to the right edge of the image in the current window.
249With argument ARG not nil or 1, move forward ARG - 1 lines first,
250stopping if the top or bottom edge of the image is reached."
251 (interactive "p")
252 (and arg
253 (/= (setq arg (prefix-numeric-value arg)) 1)
254 (image-next-line (- arg 1)))
91784462 255 (let* ((image (image-get-display-property))
bb0cb417
CY
256 (edges (window-inside-edges))
257 (win-width (- (nth 2 edges) (nth 0 edges)))
c9088194 258 (img-width (ceiling (car (image-display-size image)))))
44e3c7c6 259 (image-set-window-hscroll (max 0 (- img-width win-width)))))
bb0cb417
CY
260
261(defun image-bob ()
262 "Scroll to the top-left corner of the image in the current window."
263 (interactive)
44e3c7c6
SM
264 (image-set-window-hscroll 0)
265 (image-set-window-vscroll 0))
bb0cb417
CY
266
267(defun image-eob ()
268 "Scroll to the bottom-right corner of the image in the current window."
269 (interactive)
91784462 270 (let* ((image (image-get-display-property))
bb0cb417
CY
271 (edges (window-inside-edges))
272 (win-width (- (nth 2 edges) (nth 0 edges)))
c9088194 273 (img-width (ceiling (car (image-display-size image))))
bb0cb417 274 (win-height (- (nth 3 edges) (nth 1 edges)))
c9088194 275 (img-height (ceiling (cdr (image-display-size image)))))
44e3c7c6
SM
276 (image-set-window-hscroll (max 0 (- img-width win-width)))
277 (image-set-window-vscroll (max 0 (- img-height win-height)))))
bb0cb417 278
bd1d6a63
SM
279;; Adjust frame and image size.
280
2a43515a
CY
281(defun image-mode-fit-frame (&optional frame toggle)
282 "Fit FRAME to the current image.
283If FRAME is omitted or nil, it defaults to the selected frame.
284All other windows on the frame are deleted.
285
286If called interactively, or if TOGGLE is non-nil, toggle between
287fitting FRAME to the current image and restoring the size and
288window configuration prior to the last `image-mode-fit-frame'
289call."
290 (interactive (list nil t))
291 (let* ((buffer (current-buffer))
bd1d6a63 292 (display (image-get-display-property))
2a43515a
CY
293 (size (image-display-size display))
294 (saved (frame-parameter frame 'image-mode-saved-params))
295 (window-configuration (current-window-configuration frame))
296 (width (frame-width frame))
297 (height (frame-height frame)))
298 (with-selected-frame (or frame (selected-frame))
299 (if (and toggle saved
300 (= (caar saved) width)
301 (= (cdar saved) height))
302 (progn
303 (set-frame-width frame (car (nth 1 saved)))
304 (set-frame-height frame (cdr (nth 1 saved)))
305 (set-window-configuration (nth 2 saved))
306 (set-frame-parameter frame 'image-mode-saved-params nil))
307 (delete-other-windows)
308 (switch-to-buffer buffer t t)
309 (let* ((edges (window-inside-edges))
310 (inner-width (- (nth 2 edges) (nth 0 edges)))
311 (inner-height (- (nth 3 edges) (nth 1 edges))))
312 (set-frame-width frame (+ (ceiling (car size))
313 width (- inner-width)))
314 (set-frame-height frame (+ (ceiling (cdr size))
315 height (- inner-height)))
316 ;; The frame size after the above `set-frame-*' calls may
317 ;; differ from what we specified, due to window manager
318 ;; interference. We have to call `frame-width' and
319 ;; `frame-height' to get the actual results.
320 (set-frame-parameter frame 'image-mode-saved-params
321 (list (cons (frame-width)
322 (frame-height))
323 (cons width height)
324 window-configuration)))))))
bd1d6a63 325
bb0cb417
CY
326;;; Image Mode setup
327
d487ca7d 328(defvar image-type nil
71d73c9c 329 "The image type for the current Image mode buffer.")
d487ca7d
JL
330(make-variable-buffer-local 'image-type)
331
9b9debd1
JL
332(defvar image-mode-previous-major-mode nil
333 "Internal variable to keep the previous non-image major mode.")
334
c7bd5d57 335(defvar image-mode-map
bb0cb417 336 (let ((map (make-sparse-keymap)))
abef340a 337 (set-keymap-parent map special-mode-map)
bb0cb417 338 (define-key map "\C-c\C-c" 'image-toggle-display)
42c27c2a 339 (define-key map (kbd "SPC") 'image-scroll-up)
9cec74cf 340 (define-key map (kbd "S-SPC") 'image-scroll-down)
42c27c2a 341 (define-key map (kbd "DEL") 'image-scroll-down)
18af70d0 342 (define-key map (kbd "RET") 'image-toggle-animation)
20de6ab6
CW
343 (define-key map "n" 'image-next-file)
344 (define-key map "p" 'image-previous-file)
bb0cb417
CY
345 (define-key map [remap forward-char] 'image-forward-hscroll)
346 (define-key map [remap backward-char] 'image-backward-hscroll)
d8b0cddd
SM
347 (define-key map [remap right-char] 'image-forward-hscroll)
348 (define-key map [remap left-char] 'image-backward-hscroll)
bb0cb417
CY
349 (define-key map [remap previous-line] 'image-previous-line)
350 (define-key map [remap next-line] 'image-next-line)
351 (define-key map [remap scroll-up] 'image-scroll-up)
352 (define-key map [remap scroll-down] 'image-scroll-down)
32129746
JL
353 (define-key map [remap scroll-up-command] 'image-scroll-up)
354 (define-key map [remap scroll-down-command] 'image-scroll-down)
bb0cb417
CY
355 (define-key map [remap move-beginning-of-line] 'image-bol)
356 (define-key map [remap move-end-of-line] 'image-eol)
357 (define-key map [remap beginning-of-buffer] 'image-bob)
358 (define-key map [remap end-of-buffer] 'image-eob)
359 map)
71d73c9c 360 "Mode keymap for `image-mode'.")
bb0cb417 361
9b9debd1 362(defvar image-minor-mode-map
c7bd5d57
RS
363 (let ((map (make-sparse-keymap)))
364 (define-key map "\C-c\C-c" 'image-toggle-display)
365 map)
71d73c9c 366 "Mode keymap for `image-minor-mode'.")
c7bd5d57 367
e0385bf4 368(defvar bookmark-make-record-function)
a47d49c0 369
0d17c4b9
JL
370(put 'image-mode 'mode-class 'special)
371
c7bd5d57
RS
372;;;###autoload
373(defun image-mode ()
374 "Major mode for image files.
375You can use \\<image-mode-map>\\[image-toggle-display]
376to toggle between display as an image and display as text."
377 (interactive)
9b9debd1
JL
378 (condition-case err
379 (progn
380 (unless (display-images-p)
381 (error "Display does not support images"))
382
383 (kill-all-local-variables)
384 (setq major-mode 'image-mode)
385
386 (if (not (image-get-display-property))
387 (progn
388 (image-toggle-display-image)
389 ;; If attempt to display the image fails.
390 (if (not (image-get-display-property))
391 (error "Invalid image")))
392 ;; Set next vars when image is already displayed but local
393 ;; variables were cleared by kill-all-local-variables
394 (setq cursor-type nil truncate-lines t
395 image-type (plist-get (cdr (image-get-display-property)) :type)))
396
397 (setq mode-name (if image-type (format "Image[%s]" image-type) "Image"))
bb43424b 398 (use-local-map image-mode-map)
9b9debd1
JL
399
400 ;; Use our own bookmarking function for images.
401 (set (make-local-variable 'bookmark-make-record-function)
402 'image-bookmark-make-record)
403
404 ;; Keep track of [vh]scroll when switching buffers
405 (image-mode-setup-winprops)
406
407 (add-hook 'change-major-mode-hook 'image-toggle-display-text nil t)
0fb1193d 408 (add-hook 'after-revert-hook 'image-after-revert-hook nil t)
9b9debd1 409 (run-mode-hooks 'image-mode-hook)
18af70d0
CY
410 (let ((image (image-get-display-property))
411 (msg1 (substitute-command-keys
412 "Type \\[image-toggle-display] to view the image as ")))
413 (cond
414 ((null image)
415 (message "%s" (concat msg1 "an image.")))
416 ((image-animated-p image)
417 (message "%s"
418 (concat msg1 "text, or "
419 (substitute-command-keys
420 "\\[image-toggle-animation] to animate."))))
421 (t
422 (message "%s" (concat msg1 "text."))))))
423
9b9debd1
JL
424 (error
425 (image-mode-as-text)
426 (funcall
427 (if (called-interactively-p 'any) 'error 'message)
428 "Cannot display image: %s" (cdr err)))))
18af70d0 429
d90e651e
JL
430;;;###autoload
431(define-minor-mode image-minor-mode
06e21633
CY
432 "Toggle Image minor mode in this buffer.
433With a prefix argument ARG, enable Image minor mode if ARG is
434positive, and disable it otherwise. If called from Lisp, enable
435the mode if ARG is omitted or nil.
436
437Image minor mode provides the key \\<image-mode-map>\\[image-toggle-display],
438to switch back to `image-mode' and display an image file as the
439actual image."
9b9debd1
JL
440 nil (:eval (if image-type (format " Image[%s]" image-type) " Image"))
441 image-minor-mode-map
d90e651e
JL
442 :group 'image
443 :version "22.1"
9b9debd1
JL
444 (if image-minor-mode
445 (add-hook 'change-major-mode-hook (lambda () (image-minor-mode -1)) nil t)))
d90e651e
JL
446
447;;;###autoload
9b9debd1
JL
448(defun image-mode-as-text ()
449 "Set a non-image mode as major mode in combination with image minor mode.
450A non-image major mode found from `auto-mode-alist' or Fundamental mode
451displays an image file as text. `image-minor-mode' provides the key
452\\<image-mode-map>\\[image-toggle-display] to switch back to `image-mode'
453to display an image file as the actual image.
454
455You can use `image-mode-as-text' in `auto-mode-alist' when you want
316d12fb 456to display an image file as text initially.
9b9debd1
JL
457
458See commands `image-mode' and `image-minor-mode' for more information
459on these modes."
d90e651e 460 (interactive)
9b9debd1
JL
461 ;; image-mode-as-text = normal-mode + image-minor-mode
462 (let ((previous-image-type image-type)) ; preserve `image-type'
463 (if image-mode-previous-major-mode
464 ;; Restore previous major mode that was already found by this
465 ;; function and cached in `image-mode-previous-major-mode'
466 (funcall image-mode-previous-major-mode)
467 (let ((auto-mode-alist
468 (delq nil (mapcar
469 (lambda (elt)
470 (unless (memq (or (car-safe (cdr elt)) (cdr elt))
471 '(image-mode image-mode-maybe image-mode-as-text))
472 elt))
473 auto-mode-alist)))
474 (magic-fallback-mode-alist
475 (delq nil (mapcar
476 (lambda (elt)
477 (unless (memq (or (car-safe (cdr elt)) (cdr elt))
478 '(image-mode image-mode-maybe image-mode-as-text))
479 elt))
480 magic-fallback-mode-alist))))
481 (normal-mode)
482 (set (make-local-variable 'image-mode-previous-major-mode) major-mode)))
483 ;; Restore `image-type' after `kill-all-local-variables' in `normal-mode'.
484 (setq image-type previous-image-type)
485 ;; Enable image minor mode with `C-c C-c'.
486 (image-minor-mode 1)
487 ;; Show the image file as text.
488 (image-toggle-display-text)
489 (message "%s" (concat
490 (substitute-command-keys
491 "Type \\[image-toggle-display] to view the image as ")
492 (if (image-get-display-property)
493 "text" "an image") "."))))
494
495(define-obsolete-function-alias 'image-mode-maybe 'image-mode "23.2")
d90e651e
JL
496
497(defun image-toggle-display-text ()
9b9debd1
JL
498 "Show the image file as text.
499Remove text properties that display the image."
500 (let ((inhibit-read-only t)
501 (buffer-undo-list t)
502 (modified (buffer-modified-p)))
503 (remove-list-of-text-properties (point-min) (point-max)
345083b2 504 '(display read-nonsticky ;; intangible
9b9debd1
JL
505 read-only front-sticky))
506 (set-buffer-modified-p modified)
507 (if (called-interactively-p 'any)
508 (message "Repeat this command to go back to displaying the image"))))
c7bd5d57 509
f2920ffe
RS
510(defvar archive-superior-buffer)
511(defvar tar-superior-buffer)
110683ad 512(declare-function image-flush "image.c" (spec &optional frame))
f2920ffe 513
9b9debd1
JL
514(defun image-toggle-display-image ()
515 "Show the image of the image file.
516Turn the image data into a real image, but only if the whole file
517was inserted."
953a8c3b 518 (unless (derived-mode-p 'image-mode)
a32d4040 519 (error "The buffer is not in Image mode"))
9b9debd1
JL
520 (let* ((filename (buffer-file-name))
521 (data-p (not (and filename
522 (file-readable-p filename)
523 (not (file-remote-p filename))
524 (not (buffer-modified-p))
525 (not (and (boundp 'archive-superior-buffer)
526 archive-superior-buffer))
527 (not (and (boundp 'tar-superior-buffer)
528 tar-superior-buffer)))))
529 (file-or-data (if data-p
530 (string-make-unibyte
531 (buffer-substring-no-properties (point-min) (point-max)))
532 filename))
533 (type (image-type file-or-data nil data-p))
e8cbec34
CY
534 (image (create-image file-or-data type data-p))
535 (inhibit-read-only t)
536 (buffer-undo-list t)
537 (modified (buffer-modified-p))
538 props)
539
18af70d0
CY
540 ;; Discard any stale image data before looking it up again.
541 (image-flush image)
e8cbec34
CY
542 (setq image (append image (image-transform-properties image)))
543 (setq props
9b9debd1 544 `(display ,image
345083b2
SM
545 ;; intangible ,image
546 rear-nonsticky (display) ;; intangible
9b9debd1 547 read-only t front-sticky (read-only)))
e8cbec34 548
9b9debd1
JL
549 (let ((buffer-file-truename nil)) ; avoid changing dir mtime by lock_file
550 (add-text-properties (point-min) (point-max) props)
551 (restore-buffer-modified-p modified))
552 ;; Inhibit the cursor when the buffer contains only an image,
553 ;; because cursors look very strange on top of images.
554 (setq cursor-type nil)
555 ;; This just makes the arrow displayed in the right fringe
556 ;; area look correct when the image is wider than the window.
557 (setq truncate-lines t)
4114ed61
EZ
558 ;; Disable adding a newline at the end of the image file when it
559 ;; is written with, e.g., C-x C-w.
560 (if (coding-system-equal (coding-system-base buffer-file-coding-system)
561 'no-conversion)
562 (set (make-local-variable 'find-file-literally) t))
9b9debd1
JL
563 ;; Allow navigation of large images
564 (set (make-local-variable 'auto-hscroll-mode) nil)
565 (setq image-type type)
566 (if (eq major-mode 'image-mode)
567 (setq mode-name (format "Image[%s]" type)))
2d21d7f6 568 (image-transform-check-size)
9b9debd1
JL
569 (if (called-interactively-p 'any)
570 (message "Repeat this command to go back to displaying the file as text"))))
571
c7bd5d57 572(defun image-toggle-display ()
71d73c9c
CY
573 "Toggle between image and text display.
574If the current buffer is displaying an image file as an image,
575call `image-mode-as-text' to switch to text. Otherwise, display
576the image by calling `image-mode'."
c7bd5d57 577 (interactive)
91784462 578 (if (image-get-display-property)
9b9debd1
JL
579 (image-mode-as-text)
580 (image-mode)))
0fb1193d
JL
581
582(defun image-after-revert-hook ()
583 (when (image-get-display-property)
584 (image-toggle-display-text)
585 ;; Update image display.
637d46ca
GM
586 (mapc (lambda (window) (redraw-frame (window-frame window)))
587 (get-buffer-window-list (current-buffer) 'nomini 'visible))
0fb1193d
JL
588 (image-toggle-display-image)))
589
97666703 590\f
18af70d0
CY
591;;; Animated images
592
593(defcustom image-animate-loop nil
eea14f31 594 "Non-nil means animated images loop forever, rather than playing once."
18af70d0
CY
595 :type 'boolean
596 :version "24.1"
597 :group 'image)
598
599(defun image-toggle-animation ()
eea14f31
GM
600 "Start or stop animating the current image.
601If `image-animate-loop' is non-nil, animation loops forever.
602Otherwise it plays once, then stops."
18af70d0
CY
603 (interactive)
604 (let ((image (image-get-display-property))
605 animation)
606 (cond
607 ((null image)
608 (error "No image is present"))
609 ((null (setq animation (image-animated-p image)))
610 (message "No image animation."))
611 (t
612 (let ((timer (image-animate-timer image)))
613 (if timer
614 (cancel-timer timer)
615 (let ((index (plist-get (cdr image) :index)))
616 ;; If we're at the end, restart.
617 (and index
618 (>= index (1- (car animation)))
619 (setq index nil))
620 (image-animate image index
621 (if image-animate-loop t)))))))))
622
623\f
20de6ab6
CW
624;;; Switching to the next/previous image
625
626(defun image-next-file (&optional n)
627 "Visit the next image in the same directory as the current image file.
628With optional argument N, visit the Nth image file after the
629current one, in cyclic alphabetical order.
630
631This command visits the specified file via `find-alternate-file',
632replacing the current Image mode buffer."
633 (interactive "p")
634 (unless (derived-mode-p 'image-mode)
635 (error "The buffer is not in Image mode"))
636 (unless buffer-file-name
637 (error "The current image is not associated with a file"))
638 (let* ((file (file-name-nondirectory buffer-file-name))
639 (images (image-mode--images-in-directory file))
640 (idx 0))
641 (catch 'image-visit-next-file
642 (dolist (f images)
643 (if (string= f file)
644 (throw 'image-visit-next-file (1+ idx)))
645 (setq idx (1+ idx))))
646 (setq idx (mod (+ idx (or n 1)) (length images)))
647 (find-alternate-file (nth idx images))))
648
649(defun image-previous-file (&optional n)
650 "Visit the preceding image in the same directory as the current file.
651With optional argument N, visit the Nth image file preceding the
652current one, in cyclic alphabetical order.
653
654This command visits the specified file via `find-alternate-file',
655replacing the current Image mode buffer."
656 (interactive "p")
657 (image-next-file (- n)))
658
659(defun image-mode--images-in-directory (file)
660 (let* ((dir (file-name-directory buffer-file-name))
661 (files (directory-files dir nil
662 (image-file-name-regexp) t)))
663 ;; Add the current file to the list of images if necessary, in
664 ;; case it does not match `image-file-name-regexp'.
665 (unless (member file files)
666 (push file files))
667 (sort files 'string-lessp)))
668
669\f
137187c8 670;;; Support for bookmark.el
e44fa724
KF
671(declare-function bookmark-make-record-default
672 "bookmark" (&optional no-file no-context posn))
43f8b275
SM
673(declare-function bookmark-prop-get "bookmark" (bookmark prop))
674(declare-function bookmark-default-handler "bookmark" (bmk))
137187c8 675
43f8b275 676(defun image-bookmark-make-record ()
f12492c8
TV
677 `(,@(bookmark-make-record-default nil 'no-context 0)
678 (image-type . ,image-type)
679 (handler . image-bookmark-jump)))
137187c8 680
137187c8
TH
681;;;###autoload
682(defun image-bookmark-jump (bmk)
03e26a79 683 ;; This implements the `handler' function interface for record type
e0385bf4 684 ;; returned by `bookmark-make-record-function', which see.
43f8b275
SM
685 (prog1 (bookmark-default-handler bmk)
686 (when (not (string= image-type (bookmark-prop-get bmk 'image-type)))
687 (image-toggle-display))))
97666703 688\f
c7f514b5 689
b4ac6e8c 690;; Not yet implemented.
7102e6d0
WJ
691;; (defvar image-transform-minor-mode-map
692;; (let ((map (make-sparse-keymap)))
693;; ;; (define-key map [(control ?+)] 'image-scale-in)
694;; ;; (define-key map [(control ?-)] 'image-scale-out)
695;; ;; (define-key map [(control ?=)] 'image-scale-none)
696;; ;; (define-key map "c f h" 'image-scale-fit-height)
697;; ;; (define-key map "c ]" 'image-rotate-right)
698;; map)
699;; "Minor mode keymap `image-transform-mode'.")
700;;
701;; (define-minor-mode image-transform-mode
702;; "Minor mode for scaling and rotating images.
703;; With a prefix argument ARG, enable the mode if ARG is positive,
704;; and disable it otherwise. If called from Lisp, enable the mode
705;; if ARG is omitted or nil. This minor mode requires Emacs to have
706;; been compiled with ImageMagick support."
707;; nil "image-transform" image-transform-minor-mode-map)
b4ac6e8c
GM
708
709
710;; FIXME this doesn't seem mature yet. Document in manual when it is.
a32d4040
CY
711(defvar image-transform-resize nil
712 "The image resize operation.
713Its value should be one of the following:
714 - nil, meaning no resizing.
715 - `fit-height', meaning to fit the image to the window height.
716 - `fit-width', meaning to fit the image to the window width.
7102e6d0 717 - A number, which is a scale factor (the default size is 1).")
c7f514b5 718
2d21d7f6
WJ
719(defvar image-transform-scale 1.0
720 "The scale factor of the image being displayed.")
721
18af70d0
CY
722(defvar image-transform-rotation 0.0
723 "Rotation angle for the image in the current Image mode buffer.")
c7f514b5 724
2d21d7f6
WJ
725(defvar image-transform-right-angle-fudge 0.0001
726 "Snap distance to a multiple of a right angle.
727There's no deep theory behind the default value, it should just
728be somewhat larger than ImageMagick's MagickEpsilon.")
729
730(defsubst image-transform-width (width height)
731 "Return the bounding box width of a rotated WIDTH x HEIGHT rectangle.
732The rotation angle is the value of `image-transform-rotation' in degrees."
733 (let ((angle (degrees-to-radians image-transform-rotation)))
734 ;; Assume, w.l.o.g., that the vertices of the rectangle have the
735 ;; coordinates (+-w/2, +-h/2) and that (0, 0) is the center of the
736 ;; rotation by the angle A. The projections onto the first axis
737 ;; of the vertices of the rotated rectangle are +- (w/2) cos A +-
738 ;; (h/2) sin A, and the difference between the largest and the
739 ;; smallest of the four values is the expression below.
740 (+ (* width (abs (cos angle))) (* height (abs (sin angle))))))
741
742;; The following comment and code snippet are from
743;; ImageMagick-6.7.4-4/magick/distort.c
744
c846da43 745;; /* Set the output image geometry to calculated 'best fit'.
2d21d7f6
WJ
746;; Yes this tends to 'over do' the file image size, ON PURPOSE!
747;; Do not do this for DePolar which needs to be exact for virtual tiling.
748;; */
749;; if ( fix_bounds ) {
750;; geometry.x = (ssize_t) floor(min.x-0.5);
751;; geometry.y = (ssize_t) floor(min.y-0.5);
752;; geometry.width=(size_t) ceil(max.x-geometry.x+0.5);
753;; geometry.height=(size_t) ceil(max.y-geometry.y+0.5);
754;; }
755
756;; Other parts of the same file show that here the origin is in the
757;; left lower corner of the image rectangle, the center of the
758;; rotation is the center of the rectangle and min.x and max.x
759;; (resp. min.y and max.y) are the smallest and the largest of the
760;; projections of the vertices onto the first (resp. second) axis.
761
762(defun image-transform-fit-width (width height length)
763 "Return (w . h) so that a rotated w x h image has exactly width LENGTH.
764The rotation angle is the value of `image-transform-rotation'.
765Write W for WIDTH and H for HEIGHT. Then the w x h rectangle is
766an \"approximately uniformly\" scaled W x H rectangle, which
767currently means that w is one of floor(s W) + {0, 1, -1} and h is
768floor(s H), where s can be recovered as the value of `image-transform-scale'.
769The value of `image-transform-rotation' may be replaced by
770a slightly different angle. Currently this is done for values
771close to a multiple of 90, see `image-transform-right-angle-fudge'."
772 (cond ((< (abs (- (mod (+ image-transform-rotation 90) 180) 90))
773 image-transform-right-angle-fudge)
f58e0fd5 774 (cl-assert (not (zerop width)) t)
2d21d7f6
WJ
775 (setq image-transform-rotation
776 (float (round image-transform-rotation))
777 image-transform-scale (/ (float length) width))
778 (cons length nil))
779 ((< (abs (- (mod (+ image-transform-rotation 45) 90) 45))
780 image-transform-right-angle-fudge)
f58e0fd5 781 (cl-assert (not (zerop height)) t)
2d21d7f6
WJ
782 (setq image-transform-rotation
783 (float (round image-transform-rotation))
784 image-transform-scale (/ (float length) height))
785 (cons nil length))
786 (t
f58e0fd5 787 (cl-assert (not (and (zerop width) (zerop height))) t)
2d21d7f6
WJ
788 (setq image-transform-scale
789 (/ (float (1- length)) (image-transform-width width height)))
790 ;; Assume we have a w x h image and an angle A, and let l =
791 ;; l(w, h) = w |cos A| + h |sin A|, which is the actual width
792 ;; of the bounding box of the rotated image, as calculated by
793 ;; `image-transform-width'. The code snippet quoted above
794 ;; means that ImageMagick puts the rotated image in
795 ;; a bounding box of width L = 2 ceil((w+l+1)/2) - w.
796 ;; Elementary considerations show that this is equivalent to
797 ;; L - w being even and L-3 < l(w, h) <= L-1. In our case, L is
798 ;; the given `length' parameter and our job is to determine
799 ;; reasonable values for w and h which satisfy these
800 ;; conditions.
801 (let ((w (floor (* image-transform-scale width)))
802 (h (floor (* image-transform-scale height))))
803 ;; Let w and h as bound above. Then l(w, h) <= l(s W, s H)
804 ;; = L-1 < l(w+1, h+1) = l(w, h) + l(1, 1) <= l(w, h) + 2,
805 ;; hence l(w, h) > (L-1) - 2 = L-3.
806 (cons
807 (cond ((= (mod w 2) (mod length 2))
808 w)
809 ;; l(w+1, h) >= l(w, h) > L-3, but does l(w+1, h) <=
810 ;; L-1 hold?
811 ((<= (image-transform-width (1+ w) h) (1- length))
812 (1+ w))
813 ;; No, it doesn't, but this implies that l(w-1, h) =
814 ;; l(w+1, h) - l(2, 0) >= l(w+1, h) - 2 > (L-1) -
815 ;; 2 = L-3. Clearly, l(w-1, h) <= l(w, h) <= L-1.
816 (t
817 (1- w)))
818 h)))))
819
820(defun image-transform-check-size ()
977f9325
WJ
821 "Check that the image exactly fits the width/height of the window.
822
823Do this for an image of type `imagemagick' to make sure that the
824elisp code matches the way ImageMagick computes the bounding box
825of a rotated image."
826 (when (and (not (numberp image-transform-resize))
827 (boundp 'image-type)
828 (eq image-type 'imagemagick))
2d21d7f6
WJ
829 (let ((size (image-display-size (image-get-display-property) t)))
830 (cond ((eq image-transform-resize 'fit-width)
f58e0fd5 831 (cl-assert (= (car size)
2d21d7f6
WJ
832 (- (nth 2 (window-inside-pixel-edges))
833 (nth 0 (window-inside-pixel-edges))))
834 t))
835 ((eq image-transform-resize 'fit-height)
f58e0fd5 836 (cl-assert (= (cdr size)
2d21d7f6
WJ
837 (- (nth 3 (window-inside-pixel-edges))
838 (nth 1 (window-inside-pixel-edges))))
839 t))))))
840
18af70d0
CY
841(defun image-transform-properties (spec)
842 "Return rescaling/rotation properties for image SPEC.
843These properties are determined by the Image mode variables
844`image-transform-resize' and `image-transform-rotation'. The
845return value is suitable for appending to an image spec.
e8cbec34 846
09e80d9f 847Rescaling and rotation properties only take effect if Emacs is
e8cbec34 848compiled with ImageMagick support."
2d21d7f6 849 (setq image-transform-scale 1.0)
18af70d0 850 (when (or image-transform-resize
2d21d7f6 851 (/= image-transform-rotation 0.0))
18af70d0
CY
852 ;; Note: `image-size' looks up and thus caches the untransformed
853 ;; image. There's no easy way to prevent that.
854 (let* ((size (image-size spec t))
2d21d7f6 855 (resized
18af70d0
CY
856 (cond
857 ((numberp image-transform-resize)
7102e6d0 858 (unless (= image-transform-resize 1)
2d21d7f6
WJ
859 (setq image-transform-scale image-transform-resize)
860 (cons nil (floor (* image-transform-resize (cdr size))))))
861 ((eq image-transform-resize 'fit-width)
862 (image-transform-fit-width
863 (car size) (cdr size)
864 (- (nth 2 (window-inside-pixel-edges))
865 (nth 0 (window-inside-pixel-edges)))))
18af70d0 866 ((eq image-transform-resize 'fit-height)
2d21d7f6
WJ
867 (let ((res (image-transform-fit-width
868 (cdr size) (car size)
869 (- (nth 3 (window-inside-pixel-edges))
870 (nth 1 (window-inside-pixel-edges))))))
871 (cons (cdr res) (car res)))))))
872 `(,@(when (car resized)
873 (list :width (car resized)))
874 ,@(when (cdr resized)
875 (list :height (cdr resized)))
876 ,@(unless (= 0.0 image-transform-rotation)
877 (list :rotation image-transform-rotation))))))
c7f514b5
JV
878
879(defun image-transform-set-scale (scale)
a32d4040
CY
880 "Prompt for a number, and resize the current image by that amount.
881This command has no effect unless Emacs is compiled with
882ImageMagick support."
883 (interactive "nScale: ")
c183f693 884 (setq image-transform-resize scale)
a32d4040 885 (image-toggle-display-image))
c7f514b5
JV
886
887(defun image-transform-fit-to-height ()
a32d4040
CY
888 "Fit the current image to the height of the current window.
889This command has no effect unless Emacs is compiled with
890ImageMagick support."
c7f514b5 891 (interactive)
a32d4040
CY
892 (setq image-transform-resize 'fit-height)
893 (image-toggle-display-image))
c7f514b5 894
3a50be51 895(defun image-transform-fit-to-width ()
a32d4040
CY
896 "Fit the current image to the width of the current window.
897This command has no effect unless Emacs is compiled with
898ImageMagick support."
3a50be51 899 (interactive)
a32d4040
CY
900 (setq image-transform-resize 'fit-width)
901 (image-toggle-display-image))
c7f514b5
JV
902
903(defun image-transform-set-rotation (rotation)
a32d4040
CY
904 "Prompt for an angle ROTATION, and rotate the image by that amount.
905ROTATION should be in degrees. This command has no effect unless
906Emacs is compiled with ImageMagick support."
907 (interactive "nRotation angle (in degrees): ")
2d21d7f6 908 (setq image-transform-rotation (float (mod rotation 360)))
a32d4040 909 (image-toggle-display-image))
c7f514b5 910
c7bd5d57
RS
911(provide 'image-mode)
912
913;;; image-mode.el ends here