Merge from trunk
[bpt/emacs.git] / lisp / doc-view.el
CommitLineData
b38b1ec0
SM
1;;; doc-view.el --- View PDF/PostScript/DVI files in Emacs -*- lexical-binding: t -*-
2
94dbe99c 3
acaf905b 4;; Copyright (C) 2007-2012 Free Software Foundation, Inc.
94dbe99c 5;;
db8a5a18
TH
6;; Author: Tassilo Horn <tsdh@gnu.org>
7;; Maintainer: Tassilo Horn <tsdh@gnu.org>
94dbe99c 8;; Keywords: files, pdf, ps, dvi
94dbe99c
TTN
9
10;; This file is part of GNU Emacs.
11
eb3fa2cf 12;; GNU Emacs is free software: you can redistribute it and/or modify
94dbe99c 13;; it under the terms of the GNU General Public License as published by
eb3fa2cf
GM
14;; the Free Software Foundation, either version 3 of the License, or
15;; (at your option) any later version.
94dbe99c
TTN
16
17;; GNU Emacs is distributed in the hope that it will be useful,
18;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20;; GNU General Public License for more details.
21
22;; You should have received a copy of the GNU General Public License
eb3fa2cf 23;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
94dbe99c
TTN
24
25;;; Requirements:
26
4b378e75 27;; doc-view.el requires GNU Emacs 22.1 or newer. You also need Ghostscript,
1ecc9da7
TH
28;; `dvipdf' (comes with Ghostscript) or `dvipdfm' (comes with teTeX or TeXLive)
29;; and `pdftotext', which comes with xpdf (http://www.foolabs.com/xpdf/) or
30;; poppler (http://poppler.freedesktop.org/).
94dbe99c
TTN
31
32;;; Commentary:
33
34;; DocView is a document viewer for Emacs. It converts PDF, PS and DVI files
35;; to a set of PNG files, one PNG for each page, and displays the PNG images
36;; inside an Emacs buffer. This buffer uses `doc-view-mode' which provides
37;; convenient key bindings for browsing the document.
38;;
640602f7 39;; To use it simply open a document file with
94dbe99c 40;;
640602f7 41;; C-x C-f ~/path/to/document RET
94dbe99c 42;;
640602f7
RS
43;; and the document will be converted and displayed, if your emacs supports png
44;; images. With `C-c C-c' you can toggle between the rendered images
1f75e53d 45;; representation and the source text representation of the document.
94dbe99c
TTN
46;;
47;; Since conversion may take some time all the PNG images are cached in a
48;; subdirectory of `doc-view-cache-directory' and reused when you want to view
640602f7
RS
49;; that file again. To reconvert a document hit `g' (`doc-view-reconvert-doc')
50;; when displaying the document. To delete all cached files use
94dbe99c
TTN
51;; `doc-view-clear-cache'. To open the cache with dired, so that you can tidy
52;; it out use `doc-view-dired-cache'.
53;;
54;; When conversion in underway the first page will be displayed as soon as it
55;; is available and the available pages are refreshed every
56;; `doc-view-conversion-refresh-interval' seconds. If that variable is nil the
57;; pages won't be displayed before conversion of the document finished
58;; completely.
59;;
db8a5a18
TH
60;; DocView lets you select a slice of the displayed pages. This slice
61;; will be remembered and applied to all pages of the current
62;; document. This enables you to cut away the margins of a document
63;; to save some space. To select a slice you can use
64;; `doc-view-set-slice' (bound to `s s') which will query you for the
65;; coordinates of the slice's top-left corner and its width and
66;; height. A much more convenient way to do the same is offered by
67;; the command `doc-view-set-slice-using-mouse' (bound to `s m').
68;; After invocation you only have to press mouse-1 at the top-left
69;; corner and drag it to the bottom-right corner of the desired slice.
70;; Even more accurate and convenient is to use
71;; `doc-view-set-slice-from-bounding-box' (bound to `s b') which uses
72;; the BoundingBox information of the current page to set an optimal
73;; slice. To reset the slice use `doc-view-reset-slice' (bound to `s
74;; r').
94dbe99c 75;;
94dbe99c
TTN
76;; You can also search within the document. The command `doc-view-search'
77;; (bound to `C-s') queries for a search regexp and initializes a list of all
78;; matching pages and messages how many match-pages were found. After that you
7baca0fa
JL
79;; can jump to the next page containing a match with an additional `C-s'. With
80;; `C-r' you can do the same, but backwards. To search for a new regexp give a
81;; prefix arg to one of the search functions, e.g. by typing `C-u C-s'. The
82;; searching works by using a plain text representation of the document. If
a8ce3d17 83;; that doesn't already exist the first invocation of `doc-view-search' (or
7baca0fa
JL
84;; `doc-view-search-backward') starts the conversion. When that finishes and
85;; you're still viewing the document (i.e. you didn't switch to another buffer)
86;; you're queried for the regexp then.
640602f7
RS
87;;
88;; Dired users can simply hit `v' on a document file. If it's a PS, PDF or DVI
89;; it will be opened using `doc-view-mode'.
90;;
94dbe99c
TTN
91
92;;; Configuration:
93
640602f7
RS
94;; If the images are too small or too big you should set the "-rXXX" option in
95;; `doc-view-ghostscript-options' to another value. (The bigger your screen,
96;; the higher the value.)
94dbe99c
TTN
97;;
98;; This and all other options can be set with the customization interface.
99;; Simply do
100;;
101;; M-x customize-group RET doc-view RET
102;;
103;; and modify them to your needs.
104
34065e5e 105;;; Todo:
94dbe99c 106
56741510
SM
107;; - add print command.
108;; - share more code with image-mode.
f4c75497 109;; - better menu.
f4c75497 110;; - Bind slicing to a drag event.
cec1df02 111;; - zoom the region around the cursor (like xdvi).
c17587fe
SM
112;; - get rid of the silly arrow in the fringe.
113;; - improve anti-aliasing (pdf-utils gets it better).
f4c75497 114
34065e5e
JL
115;;;; About isearch support
116
117;; I tried implementing isearch by setting
118;; `isearch-search-fun-function' buffer-locally, but that didn't
119;; work too good. The function doing the real search was called
120;; endlessly somehow. But even if we'd get that working no real
121;; isearch feeling comes up due to the missing match highlighting.
122;; Currently I display all lines containing a match in a tooltip and
123;; each C-s or C-r jumps directly to the next/previous page with a
124;; match. With isearch we could only display the current match. So
125;; we had to decide if another C-s jumps to the next page with a
126;; match (thus only the first match in a page will be displayed in a
127;; tooltip) or to the next match, which would do nothing visible
128;; (except the tooltip) if the next match is on the same page.
129
130;; And it's much slower than the current search facility, because
ee7683eb 131;; isearch really searches for each step forward or backward whereas
34065e5e
JL
132;; the current approach searches once and then it knows to which
133;; pages to jump.
134
135;; Anyway, if someone with better isearch knowledge wants to give it a try,
136;; feel free to do it. --Tassilo
137
138;;; Code:
139
f58e0fd5 140(eval-when-compile (require 'cl-lib))
94dbe99c 141(require 'dired)
414dd971 142(require 'image-mode)
7baca0fa 143(require 'jka-compr)
94dbe99c
TTN
144
145;;;; Customization Options
146
147(defgroup doc-view nil
148 "In-buffer viewer for PDF, PostScript and DVI files."
149 :link '(function-link doc-view)
150 :version "22.2"
151 :group 'applications
ff90f4b0 152 :group 'data
94dbe99c
TTN
153 :group 'multimedia
154 :prefix "doc-view-")
155
d0af9f77 156(defcustom doc-view-ghostscript-program "gs"
94dbe99c 157 "Program to convert PS and PDF files to PNG."
c9a9a5e3 158 :type 'file
94dbe99c
TTN
159 :group 'doc-view)
160
161(defcustom doc-view-ghostscript-options
6a658a30 162 '("-dSAFER" ;; Avoid security problems when rendering files from untrusted
94d11cb5 163 ;; sources.
6a658a30 164 "-dNOPAUSE" "-sDEVICE=png16m" "-dTextAlphaBits=4"
05477667 165 "-dBATCH" "-dGraphicsAlphaBits=4" "-dQUIET")
4b378e75 166 "A list of options to give to ghostscript."
c9a9a5e3 167 :type '(repeat string)
94dbe99c
TTN
168 :group 'doc-view)
169
05477667
SM
170(defcustom doc-view-resolution 100
171 "Dots per inch resolution used to render the documents.
172Higher values result in larger images."
9efa445f
DN
173 :type 'number
174 :group 'doc-view)
05477667 175
875c044a
TH
176(defcustom doc-view-image-width 850
177 "Default image width.
178Has only an effect if imagemagick support is compiled into emacs."
2bed3f04 179 :version "24.1"
875c044a
TH
180 :type 'number
181 :group 'doc-view)
182
d0af9f77 183(defcustom doc-view-dvipdfm-program "dvipdfm"
94dbe99c
TTN
184 "Program to convert DVI files to PDF.
185
186DVI file will be converted to PDF before the resulting PDF is
53d4c024
TH
187converted to PNG.
188
189If this and `doc-view-dvipdf-program' are set,
190`doc-view-dvipdf-program' will be preferred."
191 :type 'file
192 :group 'doc-view)
193
d0af9f77 194(defcustom doc-view-dvipdf-program "dvipdf"
53d4c024
TH
195 "Program to convert DVI files to PDF.
196
197DVI file will be converted to PDF before the resulting PDF is
198converted to PNG.
199
200If this and `doc-view-dvipdfm-program' are set,
201`doc-view-dvipdf-program' will be preferred."
c9a9a5e3 202 :type 'file
94dbe99c
TTN
203 :group 'doc-view)
204
d0af9f77 205(defcustom doc-view-unoconv-program "unoconv"
95e16d17
TH
206 "Program to convert any file type readable by OpenOffice.org to PDF.
207
208Needed for viewing OpenOffice.org (and MS Office) files."
2bed3f04 209 :version "24.1"
95e16d17
TH
210 :type 'file
211 :group 'doc-view)
212
d0af9f77 213(defcustom doc-view-ps2pdf-program "ps2pdf"
94dbe99c
TTN
214 "Program to convert PS files to PDF.
215
216PS files will be converted to PDF before searching is possible."
c9a9a5e3 217 :type 'file
94dbe99c
TTN
218 :group 'doc-view)
219
d0af9f77 220(defcustom doc-view-pdftotext-program "pdftotext"
94dbe99c
TTN
221 "Program to convert PDF files to plain text.
222
223Needed for searching."
c9a9a5e3 224 :type 'file
94dbe99c
TTN
225 :group 'doc-view)
226
c17587fe 227(defcustom doc-view-cache-directory
8aafd651 228 (expand-file-name (format "docview%d" (user-uid))
bce6be12 229 temporary-file-directory)
94dbe99c 230 "The base directory, where the PNG images will be saved."
c9a9a5e3 231 :type 'directory
94dbe99c
TTN
232 :group 'doc-view)
233
56741510
SM
234(defvar doc-view-conversion-buffer " *doc-view conversion output*"
235 "The buffer where messages from the converter programs go to.")
94dbe99c 236
56741510 237(defcustom doc-view-conversion-refresh-interval 1
1f75e53d
GM
238 "Interval in seconds between refreshes of the DocView buffer while converting.
239After such a refresh newly converted pages will be available for
94dbe99c
TTN
240viewing. If set to nil there won't be any refreshes and the
241pages won't be displayed before conversion of the whole document
242has finished."
c9a9a5e3 243 :type 'integer
94dbe99c
TTN
244 :group 'doc-view)
245
0a745733 246(defcustom doc-view-continuous nil
aefcadb6
JL
247 "In Continuous mode reaching the page edge advances to next/previous page.
248When non-nil, scrolling a line upward at the bottom edge of the page
249moves to the next page, and scrolling a line downward at the top edge
250of the page moves to the previous page."
251 :type 'boolean
252 :group 'doc-view
253 :version "23.2")
254
94dbe99c
TTN
255;;;; Internal Variables
256
de171465 257(defun doc-view-new-window-function (winprops)
83600dc8
SM
258 ;; (message "New window %s for buf %s" (car winprops) (current-buffer))
259 (cl-assert (or (eq t (car winprops))
260 (eq (window-buffer (car winprops)) (current-buffer))))
de171465
SM
261 (let ((ol (image-mode-window-get 'overlay winprops)))
262 (if ol
0bca393f 263 (progn
83600dc8
SM
264 (setq ol (copy-overlay ol))
265 ;; `ol' might actually be dead.
266 (move-overlay ol (point-min) (point-max)))
de171465
SM
267 (setq ol (make-overlay (point-min) (point-max) nil t))
268 (overlay-put ol 'doc-view t))
269 (overlay-put ol 'window (car winprops))
83600dc8
SM
270 (unless (windowp (car winprops))
271 ;; It's a pseudo entry. Let's make sure it's not displayed (the
272 ;; `window' property is only effective if its value is a window).
273 (cl-assert (eq t (car winprops)))
274 (delete-overlay ol))
de171465 275 (image-mode-window-put 'overlay ol winprops)))
94dbe99c 276
de171465 277(defvar doc-view-current-files nil
94dbe99c 278 "Only used internally.")
ec4853ab 279(make-variable-buffer-local 'doc-view-current-files)
94dbe99c 280
ec4853ab 281(defvar doc-view-current-converter-processes nil
94dbe99c 282 "Only used internally.")
ec4853ab 283(make-variable-buffer-local 'doc-view-current-converter-processes)
94dbe99c
TTN
284
285(defvar doc-view-current-timer nil
286 "Only used internally.")
ec4853ab 287(make-variable-buffer-local 'doc-view-current-timer)
94dbe99c 288
94dbe99c
TTN
289(defvar doc-view-current-cache-dir nil
290 "Only used internally.")
ec4853ab 291(make-variable-buffer-local 'doc-view-current-cache-dir)
94dbe99c
TTN
292
293(defvar doc-view-current-search-matches nil
294 "Only used internally.")
ec4853ab 295(make-variable-buffer-local 'doc-view-current-search-matches)
94dbe99c 296
d99abf1b
RS
297(defvar doc-view-pending-cache-flush nil
298 "Only used internally.")
94dbe99c 299
937cb3fb 300(defvar doc-view-previous-major-mode nil
640602f7
RS
301 "Only used internally.")
302
39a402e3
TH
303(defvar doc-view-buffer-file-name nil
304 "Only used internally.
305The file name used for conversion. Normally it's the same as
306`buffer-file-name', but for remote files, compressed files and
307files inside an archive it is a temporary copy of
308the (uncompressed, extracted) file residing in
309`doc-view-cache-directory'.")
310
eb79098b
SM
311(defvar doc-view-doc-type nil
312 "The type of document in the current buffer.
313Can be `dvi', `pdf', or `ps'.")
314
640602f7 315;;;; DocView Keymaps
94dbe99c
TTN
316
317(defvar doc-view-mode-map
318 (let ((map (make-sparse-keymap)))
d2d7e96c 319 (set-keymap-parent map image-mode-map)
94dbe99c
TTN
320 ;; Navigation in the document
321 (define-key map (kbd "n") 'doc-view-next-page)
322 (define-key map (kbd "p") 'doc-view-previous-page)
eb8d0216
SM
323 (define-key map (kbd "<next>") 'forward-page)
324 (define-key map (kbd "<prior>") 'backward-page)
325 (define-key map [remap forward-page] 'doc-view-next-page)
326 (define-key map [remap backward-page] 'doc-view-previous-page)
94dbe99c
TTN
327 (define-key map (kbd "SPC") 'doc-view-scroll-up-or-next-page)
328 (define-key map (kbd "DEL") 'doc-view-scroll-down-or-previous-page)
aefcadb6
JL
329 (define-key map (kbd "C-n") 'doc-view-next-line-or-next-page)
330 (define-key map (kbd "<down>") 'doc-view-next-line-or-next-page)
331 (define-key map (kbd "C-p") 'doc-view-previous-line-or-previous-page)
332 (define-key map (kbd "<up>") 'doc-view-previous-line-or-previous-page)
94dbe99c
TTN
333 (define-key map (kbd "M-<") 'doc-view-first-page)
334 (define-key map (kbd "M->") 'doc-view-last-page)
7656fe61 335 (define-key map [remap goto-line] 'doc-view-goto-page)
4376876e 336 (define-key map (kbd "RET") 'image-next-line)
05477667
SM
337 ;; Zoom in/out.
338 (define-key map "+" 'doc-view-enlarge)
339 (define-key map "-" 'doc-view-shrink)
d7b89879
TH
340 ;; Fit the image to the window
341 (define-key map "W" 'doc-view-fit-width-to-window)
342 (define-key map "H" 'doc-view-fit-height-to-window)
343 (define-key map "P" 'doc-view-fit-page-to-window)
d2d7e96c 344 ;; Killing the buffer (and the process)
94dbe99c 345 (define-key map (kbd "k") 'doc-view-kill-proc-and-buffer)
937cb3fb 346 (define-key map (kbd "K") 'doc-view-kill-proc)
94dbe99c
TTN
347 ;; Slicing the image
348 (define-key map (kbd "s s") 'doc-view-set-slice)
349 (define-key map (kbd "s m") 'doc-view-set-slice-using-mouse)
db8a5a18 350 (define-key map (kbd "s b") 'doc-view-set-slice-from-bounding-box)
94dbe99c
TTN
351 (define-key map (kbd "s r") 'doc-view-reset-slice)
352 ;; Searching
353 (define-key map (kbd "C-s") 'doc-view-search)
354 (define-key map (kbd "<find>") 'doc-view-search)
7baca0fa 355 (define-key map (kbd "C-r") 'doc-view-search-backward)
94dbe99c
TTN
356 ;; Show the tooltip
357 (define-key map (kbd "C-t") 'doc-view-show-tooltip)
640602f7
RS
358 ;; Toggle between text and image display or editing
359 (define-key map (kbd "C-c C-c") 'doc-view-toggle-display)
515357c2
TH
360 ;; Open a new buffer with doc's text contents
361 (define-key map (kbd "C-c C-t") 'doc-view-open-text)
0bca393f
SM
362 ;; Reconvert the current document. Don't just use revert-buffer
363 ;; because that resets the scale factor, the page number, ...
364 (define-key map (kbd "g") 'doc-view-revert-buffer)
365 (define-key map (kbd "r") 'doc-view-revert-buffer)
94dbe99c 366 map)
640602f7
RS
367 "Keymap used by `doc-view-mode' when displaying a doc as a set of images.")
368
0bca393f
SM
369(defun doc-view-revert-buffer (&optional ignore-auto noconfirm)
370 "Like `revert-buffer', but preserves the buffer's current modes."
371 ;; FIXME: this should probably be moved to files.el and used for
372 ;; most/all "g" bindings to revert-buffer.
373 (interactive (list (not current-prefix-arg)))
374 (revert-buffer ignore-auto noconfirm 'preserve-modes))
375
376
f4c75497
SM
377(easy-menu-define doc-view-menu doc-view-mode-map
378 "Menu for Doc View mode."
379 '("DocView"
0a745733
JL
380 ["Toggle display" doc-view-toggle-display]
381 ("Continuous"
382 ["Off" (setq doc-view-continuous nil)
383 :style radio :selected (eq doc-view-continuous nil)]
384 ["On" (setq doc-view-continuous t)
385 :style radio :selected (eq doc-view-continuous t)]
386 "---"
387 ["Save as Default"
388 (customize-save-variable 'doc-view-continuous doc-view-continuous) t]
389 )
390 "---"
f4c75497 391 ["Set Slice" doc-view-set-slice-using-mouse]
db8a5a18 392 ["Set Slice (BoundingBox)" doc-view-set-slice-from-bounding-box]
f4c75497
SM
393 ["Set Slice (manual)" doc-view-set-slice]
394 ["Reset Slice" doc-view-reset-slice]
395 "---"
396 ["Search" doc-view-search]
7baca0fa 397 ["Search Backwards" doc-view-search-backward]
f4c75497
SM
398 ))
399
937cb3fb 400(defvar doc-view-minor-mode-map
640602f7
RS
401 (let ((map (make-sparse-keymap)))
402 ;; Toggle between text and image display or editing
403 (define-key map (kbd "C-c C-c") 'doc-view-toggle-display)
640602f7 404 map)
937cb3fb 405 "Keymap used by `doc-minor-view-mode'.")
94dbe99c
TTN
406
407;;;; Navigation Commands
408
160dfe43
SM
409(defmacro doc-view-current-page (&optional win)
410 `(image-mode-window-get 'page ,win))
de171465
SM
411(defmacro doc-view-current-info () `(image-mode-window-get 'info))
412(defmacro doc-view-current-overlay () `(image-mode-window-get 'overlay))
413(defmacro doc-view-current-image () `(image-mode-window-get 'image))
414(defmacro doc-view-current-slice () `(image-mode-window-get 'slice))
415
bdd42899
SM
416(defun doc-view-last-page-number ()
417 (length doc-view-current-files))
418
94dbe99c
TTN
419(defun doc-view-goto-page (page)
420 "View the page given by PAGE."
421 (interactive "nPage: ")
bdd42899 422 (let ((len (doc-view-last-page-number))
bc19637d 423 (hscroll (window-hscroll)))
94dbe99c 424 (if (< page 1)
1ca678aa 425 (setq page 1)
56741510
SM
426 (when (and (> page len)
427 ;; As long as the converter is running, we don't know
428 ;; how many pages will be available.
ec4853ab 429 (null doc-view-current-converter-processes))
1ca678aa 430 (setq page len)))
de171465
SM
431 (setf (doc-view-current-page) page
432 (doc-view-current-info)
1ca678aa
MC
433 (concat
434 (propertize
de171465 435 (format "Page %d of %d." page len) 'face 'bold)
1ca678aa 436 ;; Tell user if converting isn't finished yet
ec4853ab 437 (if doc-view-current-converter-processes
1ca678aa
MC
438 " (still converting...)\n"
439 "\n")
440 ;; Display context infos if this page matches the last search
441 (when (and doc-view-current-search-matches
de171465 442 (assq page doc-view-current-search-matches))
1ca678aa
MC
443 (concat (propertize "Search matches:\n" 'face 'bold)
444 (let ((contexts ""))
de171465 445 (dolist (m (cdr (assq page
1ca678aa
MC
446 doc-view-current-search-matches)))
447 (setq contexts (concat contexts " - \"" m "\"\n")))
448 contexts)))))
94dbe99c 449 ;; Update the buffer
56741510
SM
450 ;; We used to find the file name from doc-view-current-files but
451 ;; that's not right if the pages are not generated sequentially
452 ;; or if the page isn't in doc-view-current-files yet.
ec4853ab
SM
453 (let ((file (expand-file-name (format "page-%d.png" page)
454 (doc-view-current-cache-dir))))
455 (doc-view-insert-image file :pointer 'arrow)
bc19637d 456 (set-window-hscroll (selected-window) hscroll)
ec4853ab
SM
457 (when (and (not (file-exists-p file))
458 doc-view-current-converter-processes)
459 ;; The PNG file hasn't been generated yet.
460 (doc-view-pdf->png-1 doc-view-buffer-file-name file page
94d11cb5 461 (let ((win (selected-window)))
ec4853ab
SM
462 (lambda ()
463 (and (eq (current-buffer) (window-buffer win))
464 ;; If we changed page in the mean
465 ;; time, don't mess things up.
466 (eq (doc-view-current-page win) page)
bdd42899
SM
467 ;; Make sure we don't infloop.
468 (file-readable-p file)
ec4853ab 469 (with-selected-window win
94d11cb5 470 (doc-view-goto-page page))))))))
de171465
SM
471 (overlay-put (doc-view-current-overlay)
472 'help-echo (doc-view-current-info))))
94dbe99c
TTN
473
474(defun doc-view-next-page (&optional arg)
475 "Browse ARG pages forward."
476 (interactive "p")
de171465 477 (doc-view-goto-page (+ (doc-view-current-page) (or arg 1))))
94dbe99c
TTN
478
479(defun doc-view-previous-page (&optional arg)
480 "Browse ARG pages backward."
481 (interactive "p")
de171465 482 (doc-view-goto-page (- (doc-view-current-page) (or arg 1))))
94dbe99c
TTN
483
484(defun doc-view-first-page ()
485 "View the first page."
486 (interactive)
487 (doc-view-goto-page 1))
488
489(defun doc-view-last-page ()
490 "View the last page."
491 (interactive)
bdd42899 492 (doc-view-goto-page (doc-view-last-page-number)))
94dbe99c 493
7d6b4d3c
JL
494(defun doc-view-scroll-up-or-next-page (&optional arg)
495 "Scroll page up ARG lines if possible, else goto next page.
0a745733 496When `doc-view-continuous' is non-nil, scrolling upward
7d6b4d3c
JL
497at the bottom edge of the page moves to the next page.
498Otherwise, goto next page only on typing SPC (ARG is nil)."
499 (interactive "P")
0a745733 500 (if (or doc-view-continuous (null arg))
7d6b4d3c
JL
501 (let ((hscroll (window-hscroll))
502 (cur-page (doc-view-current-page)))
503 (when (= (window-vscroll) (image-scroll-up arg))
504 (doc-view-next-page)
505 (when (/= cur-page (doc-view-current-page))
506 (image-bob)
507 (image-bol 1))
508 (set-window-hscroll (selected-window) hscroll)))
509 (image-scroll-up arg)))
510
511(defun doc-view-scroll-down-or-previous-page (&optional arg)
512 "Scroll page down ARG lines if possible, else goto previous page.
0a745733 513When `doc-view-continuous' is non-nil, scrolling downward
7d6b4d3c
JL
514at the top edge of the page moves to the previous page.
515Otherwise, goto previous page only on typing DEL (ARG is nil)."
516 (interactive "P")
0a745733 517 (if (or doc-view-continuous (null arg))
7d6b4d3c
JL
518 (let ((hscroll (window-hscroll))
519 (cur-page (doc-view-current-page)))
520 (when (= (window-vscroll) (image-scroll-down arg))
521 (doc-view-previous-page)
522 (when (/= cur-page (doc-view-current-page))
523 (image-eob)
524 (image-bol 1))
525 (set-window-hscroll (selected-window) hscroll)))
526 (image-scroll-down arg)))
527
528(defun doc-view-next-line-or-next-page (&optional arg)
529 "Scroll upward by ARG lines if possible, else goto next page.
0a745733 530When `doc-view-continuous' is non-nil, scrolling a line upward
7d6b4d3c 531at the bottom edge of the page moves to the next page."
aefcadb6 532 (interactive "p")
0a745733 533 (if doc-view-continuous
aefcadb6
JL
534 (let ((hscroll (window-hscroll))
535 (cur-page (doc-view-current-page)))
7d6b4d3c 536 (when (= (window-vscroll) (image-next-line arg))
aefcadb6
JL
537 (doc-view-next-page)
538 (when (/= cur-page (doc-view-current-page))
539 (image-bob)
540 (image-bol 1))
541 (set-window-hscroll (selected-window) hscroll)))
542 (image-next-line 1)))
543
7d6b4d3c
JL
544(defun doc-view-previous-line-or-previous-page (&optional arg)
545 "Scroll downward by ARG lines if possible, else goto previous page.
0a745733 546When `doc-view-continuous' is non-nil, scrolling a line downward
aefcadb6
JL
547at the top edge of the page moves to the previous page."
548 (interactive "p")
0a745733 549 (if doc-view-continuous
aefcadb6
JL
550 (let ((hscroll (window-hscroll))
551 (cur-page (doc-view-current-page)))
7d6b4d3c 552 (when (= (window-vscroll) (image-previous-line arg))
aefcadb6
JL
553 (doc-view-previous-page)
554 (when (/= cur-page (doc-view-current-page))
555 (image-eob)
556 (image-bol 1))
557 (set-window-hscroll (selected-window) hscroll)))
7d6b4d3c 558 (image-previous-line arg)))
aefcadb6 559
937cb3fb
GM
560;;;; Utility Functions
561
640602f7 562(defun doc-view-kill-proc ()
ec4853ab 563 "Kill the current converter process(es)."
640602f7 564 (interactive)
bdd42899 565 (while (consp doc-view-current-converter-processes)
83600dc8
SM
566 (ignore-errors ;; Some entries might not be processes, and maybe
567 ;; some are dead already?
ec4853ab 568 (kill-process (pop doc-view-current-converter-processes))))
640602f7
RS
569 (when doc-view-current-timer
570 (cancel-timer doc-view-current-timer)
571 (setq doc-view-current-timer nil))
572 (setq mode-line-process nil))
573
94dbe99c
TTN
574(defun doc-view-kill-proc-and-buffer ()
575 "Kill the current converter process and buffer."
576 (interactive)
640602f7 577 (doc-view-kill-proc)
94dbe99c 578 (when (eq major-mode 'doc-view-mode)
94dbe99c
TTN
579 (kill-buffer (current-buffer))))
580
c17587fe
SM
581(defun doc-view-make-safe-dir (dir)
582 (condition-case nil
583 (let ((umask (default-file-modes)))
c82f64de
LMI
584 (unwind-protect
585 (progn
586 ;; Create temp files with strict access rights. It's easy to
587 ;; loosen them later, whereas it's impossible to close the
588 ;; time-window of loose permissions otherwise.
589 (set-default-file-modes #o0700)
590 (make-directory dir))
591 ;; Reset the umask.
592 (set-default-file-modes umask)))
c17587fe 593 (file-already-exists
c82f64de
LMI
594 (when (file-symlink-p dir)
595 (error "Danger: %s points to a symbolic link" dir))
c17587fe
SM
596 ;; In case it was created earlier with looser rights.
597 ;; We could check the mode info returned by file-attributes, but it's
598 ;; a pain to parse and it may not tell you what we want under
599 ;; non-standard file-systems. So let's just say what we want and let
600 ;; the underlying C code and file-system figure it out.
601 ;; This also ends up checking a bunch of useful conditions: it makes
602 ;; sure we have write-access to the directory and that we own it, thus
603 ;; closing a bunch of security holes.
c82f64de
LMI
604 (condition-case error
605 (set-file-modes dir #o0700)
606 (file-error
607 (error
608 (format "Unable to use temporary directory %s: %s"
609 dir (mapconcat 'identity (cdr error) " "))))))))
c17587fe 610
937cb3fb
GM
611(defun doc-view-current-cache-dir ()
612 "Return the directory where the png files of the current doc should be saved.
613It's a subdirectory of `doc-view-cache-directory'."
614 (if doc-view-current-cache-dir
615 doc-view-current-cache-dir
c17587fe
SM
616 ;; Try and make sure doc-view-cache-directory exists and is safe.
617 (doc-view-make-safe-dir doc-view-cache-directory)
618 ;; Now compute the subdirectory to use.
937cb3fb
GM
619 (setq doc-view-current-cache-dir
620 (file-name-as-directory
c17587fe 621 (expand-file-name
5e9fde5e 622 (concat (file-name-nondirectory doc-view-buffer-file-name)
39a402e3
TH
623 "-"
624 (let ((file doc-view-buffer-file-name))
625 (with-temp-buffer
86903c81 626 (set-buffer-multibyte nil)
39a402e3
TH
627 (insert-file-contents-literally file)
628 (md5 (current-buffer)))))
c17587fe 629 doc-view-cache-directory)))))
937cb3fb
GM
630
631(defun doc-view-remove-if (predicate list)
632 "Return LIST with all items removed that satisfy PREDICATE."
633 (let (new-list)
8eda563d 634 (dolist (item list)
937cb3fb 635 (when (not (funcall predicate item))
8eda563d
JB
636 (setq new-list (cons item new-list))))
637 (nreverse new-list)))
937cb3fb 638
789ab9d4
RS
639;;;###autoload
640(defun doc-view-mode-p (type)
95e16d17
TH
641 "Return non-nil if document type TYPE is available for `doc-view'.
642Document types are symbols like `dvi', `ps', `pdf', or `odf' (any
643OpenDocument format)."
789ab9d4 644 (and (display-graphic-p)
c44d54b3
TH
645 (or (image-type-available-p 'imagemagick)
646 (image-type-available-p 'png))
789ab9d4
RS
647 (cond
648 ((eq type 'dvi)
649 (and (doc-view-mode-p 'pdf)
53d4c024
TH
650 (or (and doc-view-dvipdf-program
651 (executable-find doc-view-dvipdf-program))
652 (and doc-view-dvipdfm-program
653 (executable-find doc-view-dvipdfm-program)))))
622face2 654 ((or (eq type 'postscript) (eq type 'ps) (eq type 'eps)
789ab9d4
RS
655 (eq type 'pdf))
656 (and doc-view-ghostscript-program
657 (executable-find doc-view-ghostscript-program)))
95e16d17
TH
658 ((eq type 'odf)
659 (and doc-view-unoconv-program
660 (executable-find doc-view-unoconv-program)
661 (doc-view-mode-p 'pdf)))
789ab9d4
RS
662 (t ;; unknown image type
663 nil))))
664
94dbe99c
TTN
665;;;; Conversion Functions
666
05477667
SM
667(defvar doc-view-shrink-factor 1.125)
668
669(defun doc-view-enlarge (factor)
83600dc8 670 "Enlarge the document by FACTOR."
05477667 671 (interactive (list doc-view-shrink-factor))
875c044a
TH
672 (if (eq (plist-get (cdr (doc-view-current-image)) :type)
673 'imagemagick)
83600dc8
SM
674 ;; ImageMagick supports on-the-fly-rescaling.
675 (let ((new (ceiling (* factor doc-view-image-width))))
676 (unless (equal new doc-view-image-width)
677 (set (make-local-variable 'doc-view-image-width) new)
678 (doc-view-insert-image
679 (plist-get (cdr (doc-view-current-image)) :file)
680 :width doc-view-image-width)))
681 (let ((new (ceiling (* factor doc-view-resolution))))
682 (unless (equal new doc-view-resolution)
683 (set (make-local-variable 'doc-view-resolution) new)
684 (doc-view-reconvert-doc)))))
05477667
SM
685
686(defun doc-view-shrink (factor)
687 "Shrink the document."
688 (interactive (list doc-view-shrink-factor))
689 (doc-view-enlarge (/ 1.0 factor)))
690
d7b89879
TH
691(defun doc-view-fit-width-to-window ()
692 "Fit the image width to the window width."
693 (interactive)
694 (let ((win-width (- (nth 2 (window-inside-pixel-edges))
695 (nth 0 (window-inside-pixel-edges))))
696 (slice (doc-view-current-slice)))
697 (if (not slice)
698 (let ((img-width (car (image-display-size
699 (image-get-display-property) t))))
700 (doc-view-enlarge (/ (float win-width) (float img-width))))
701
702 ;; If slice is set
703 (let* ((slice-width (nth 2 slice))
704 (scale-factor (/ (float win-width) (float slice-width)))
705 (new-slice (mapcar (lambda (x) (ceiling (* scale-factor x))) slice)))
706
707 (doc-view-enlarge scale-factor)
708 (setf (doc-view-current-slice) new-slice)
709 (doc-view-goto-page (doc-view-current-page))))))
710
711(defun doc-view-fit-height-to-window ()
712 "Fit the image height to the window height."
713 (interactive)
714 (let ((win-height (- (nth 3 (window-inside-pixel-edges))
715 (nth 1 (window-inside-pixel-edges))))
716 (slice (doc-view-current-slice)))
717 (if (not slice)
718 (let ((img-height (cdr (image-display-size
719 (image-get-display-property) t))))
720 ;; When users call 'doc-view-fit-height-to-window',
721 ;; they might want to go to next page by typing SPC
722 ;; ONLY once. So I used '(- win-height 1)' instead of
723 ;; 'win-height'
724 (doc-view-enlarge (/ (float (- win-height 1)) (float img-height))))
725
726 ;; If slice is set
727 (let* ((slice-height (nth 3 slice))
728 (scale-factor (/ (float (- win-height 1)) (float slice-height)))
729 (new-slice (mapcar (lambda (x) (ceiling (* scale-factor x))) slice)))
730
731 (doc-view-enlarge scale-factor)
732 (setf (doc-view-current-slice) new-slice)
733 (doc-view-goto-page (doc-view-current-page))))))
734
735(defun doc-view-fit-page-to-window ()
736 "Fit the image to the window.
737More specifically, this function enlarges image by:
738
739min {(window-width / image-width), (window-height / image-height)} times."
740 (interactive)
741 (let ((win-width (- (nth 2 (window-inside-pixel-edges))
742 (nth 0 (window-inside-pixel-edges))))
743 (win-height (- (nth 3 (window-inside-pixel-edges))
744 (nth 1 (window-inside-pixel-edges))))
745 (slice (doc-view-current-slice)))
746 (if (not slice)
747 (let ((img-width (car (image-display-size
748 (image-get-display-property) t)))
749 (img-height (cdr (image-display-size
750 (image-get-display-property) t))))
751 (doc-view-enlarge (min (/ (float win-width) (float img-width))
83600dc8
SM
752 (/ (float (- win-height 1))
753 (float img-height)))))
d7b89879
TH
754 ;; If slice is set
755 (let* ((slice-width (nth 2 slice))
756 (slice-height (nth 3 slice))
757 (scale-factor (min (/ (float win-width) (float slice-width))
83600dc8
SM
758 (/ (float (- win-height 1))
759 (float slice-height))))
d7b89879
TH
760 (new-slice (mapcar (lambda (x) (ceiling (* scale-factor x))) slice)))
761 (doc-view-enlarge scale-factor)
762 (setf (doc-view-current-slice) new-slice)
763 (doc-view-goto-page (doc-view-current-page))))))
764
c17587fe 765(defun doc-view-reconvert-doc ()
640602f7
RS
766 "Reconvert the current document.
767Should be invoked when the cached images aren't up-to-date."
768 (interactive)
f4c75497
SM
769 (doc-view-kill-proc)
770 ;; Clear the old cached files
771 (when (file-exists-p (doc-view-current-cache-dir))
bdd42899 772 (delete-directory (doc-view-current-cache-dir) 'recursive))
83600dc8 773 (kill-local-variable 'doc-view-last-page-number)
c17587fe 774 (doc-view-initiate-display))
94dbe99c 775
b4cb319f
SM
776(defun doc-view-sentinel (proc event)
777 "Generic sentinel for doc-view conversion processes."
94dbe99c 778 (if (not (string-match "finished" event))
b4cb319f 779 (message "DocView: process %s changed status to %s."
405ee48d
CY
780 (process-name proc)
781 (if (string-match "\\(.+\\)\n?\\'" event)
782 (match-string 1 event)
783 event))
ec4853ab
SM
784 (when (buffer-live-p (process-get proc 'buffer))
785 (with-current-buffer (process-get proc 'buffer)
786 (setq doc-view-current-converter-processes
787 (delq proc doc-view-current-converter-processes))
788 (setq mode-line-process
789 (if doc-view-current-converter-processes
790 (format ":%s" (car doc-view-current-converter-processes))))
791 (funcall (process-get proc 'callback))))))
792
793(defun doc-view-start-process (name program args callback)
3c03f2ce
TH
794 ;; Make sure the process is started in an existing directory, (rather than
795 ;; some file-name-handler-managed dir, for example).
796 (let* ((default-directory (if (file-readable-p default-directory)
797 default-directory
798 (expand-file-name "~/")))
ec4853ab
SM
799 (proc (apply 'start-process name doc-view-conversion-buffer
800 program args)))
801 (push proc doc-view-current-converter-processes)
802 (setq mode-line-process (list (format ":%s" proc)))
803 (set-process-sentinel proc 'doc-view-sentinel)
804 (process-put proc 'buffer (current-buffer))
805 (process-put proc 'callback callback)))
b4cb319f
SM
806
807(defun doc-view-dvi->pdf (dvi pdf callback)
808 "Convert DVI to PDF asynchronously and call CALLBACK when finished."
53d4c024
TH
809 ;; Prefer dvipdf over dvipdfm, because the latter has problems if the DVI
810 ;; references and includes other PS files.
811 (if (and doc-view-dvipdf-program
812 (executable-find doc-view-dvipdf-program))
813 (doc-view-start-process "dvi->pdf" doc-view-dvipdf-program
94d11cb5
IK
814 (list dvi pdf)
815 callback)
53d4c024
TH
816 (doc-view-start-process "dvi->pdf" doc-view-dvipdfm-program
817 (list "-o" pdf dvi)
818 callback)))
ec4853ab 819
95e16d17
TH
820(defun doc-view-odf->pdf (odf callback)
821 "Convert ODF to PDF asynchronously and call CALLBACK when finished.
822The converted PDF is put into the current cache directory, and it
823is named like ODF with the extension turned to pdf."
824 (doc-view-start-process "odf->pdf" doc-view-unoconv-program
825 (list "-f" "pdf" "-o" (doc-view-current-cache-dir) odf)
826 callback))
94dbe99c
TTN
827
828(defun doc-view-pdf/ps->png (pdf-ps png)
1f75e53d 829 "Convert PDF-PS to PNG asynchronously."
ec4853ab
SM
830 (doc-view-start-process
831 "pdf/ps->png" doc-view-ghostscript-program
832 (append doc-view-ghostscript-options
833 (list (format "-r%d" (round doc-view-resolution))
834 (concat "-sOutputFile=" png)
835 pdf-ps))
94d11cb5 836 (let ((resolution doc-view-resolution))
bdd42899
SM
837 (lambda ()
838 ;; Only create the resolution file when it's all done, so it also
839 ;; serves as a witness that the conversion is complete.
840 (write-region (prin1-to-string resolution) nil
841 (expand-file-name "resolution.el"
842 (doc-view-current-cache-dir))
843 nil 'silently)
844 (when doc-view-current-timer
845 (cancel-timer doc-view-current-timer)
846 (setq doc-view-current-timer nil))
847 (doc-view-display (current-buffer) 'force))))
ec4853ab 848 ;; Update the displayed pages as soon as they're done generating.
94dbe99c
TTN
849 (when doc-view-conversion-refresh-interval
850 (setq doc-view-current-timer
ec4853ab
SM
851 (run-at-time "1 secs" doc-view-conversion-refresh-interval
852 'doc-view-display
853 (current-buffer)))))
854
855(defun doc-view-pdf->png-1 (pdf png page callback)
856 "Convert a PAGE of a PDF file to PNG asynchronously.
857Call CALLBACK with no arguments when done."
858 (doc-view-start-process
859 "pdf->png-1" doc-view-ghostscript-program
860 (append doc-view-ghostscript-options
861 (list (format "-r%d" (round doc-view-resolution))
862 ;; Sadly, `gs' only supports the page-range
863 ;; for PDF files.
864 (format "-dFirstPage=%d" page)
865 (format "-dLastPage=%d" page)
866 (concat "-sOutputFile=" png)
867 pdf))
868 callback))
869
aa360da1
GM
870(declare-function clear-image-cache "image.c" (&optional filter))
871
ec4853ab
SM
872(defun doc-view-pdf->png (pdf png pages)
873 "Convert a PDF file to PNG asynchronously.
874Start by converting PAGES, and then the rest."
875 (if (null pages)
876 (doc-view-pdf/ps->png pdf png)
877 ;; We could render several `pages' with a single process if they're
878 ;; (almost) consecutive, but since in 99% of the cases, there'll be only
879 ;; a single page anyway, and of the remaining 1%, few cases will have
880 ;; consecutive pages, it's not worth the trouble.
94d11cb5 881 (let ((rest (cdr pages)))
ec4853ab
SM
882 (doc-view-pdf->png-1
883 pdf (format png (car pages)) (car pages)
884 (lambda ()
885 (if rest
886 (doc-view-pdf->png pdf png rest)
887 ;; Yippie, the important pages are done, update the display.
888 (clear-image-cache)
bdd42899
SM
889 ;; For the windows that have a message (like "Welcome to
890 ;; DocView") display property, clearing the image cache is
891 ;; not sufficient.
892 (dolist (win (get-buffer-window-list (current-buffer) nil 'visible))
893 (with-selected-window win
94d11cb5
IK
894 (when (stringp (get-char-property (point-min) 'display))
895 (doc-view-goto-page (doc-view-current-page)))))
ec4853ab
SM
896 ;; Convert the rest of the pages.
897 (doc-view-pdf/ps->png pdf png)))))))
94dbe99c 898
b4cb319f
SM
899(defun doc-view-pdf->txt (pdf txt callback)
900 "Convert PDF to TXT asynchronously and call CALLBACK when finished."
d0af9f77 901 (or (executable-find doc-view-pdftotext-program)
ca32d854 902 (error "You need the `pdftotext' program to convert a PDF to text"))
ec4853ab
SM
903 (doc-view-start-process "pdf->txt" doc-view-pdftotext-program
904 (list "-raw" pdf txt)
905 callback))
515357c2 906
c00ebc98
TH
907(defun doc-view-current-cache-doc-pdf ()
908 "Return the name of the doc.pdf in the current cache dir.
909 This file exists only if the current document isn't a PDF or PS file already."
910 (expand-file-name "doc.pdf" (doc-view-current-cache-dir)))
911
b4cb319f
SM
912(defun doc-view-doc->txt (txt callback)
913 "Convert the current document to text and call CALLBACK when done."
7edd6b92 914 (make-directory (doc-view-current-cache-dir) t)
f58e0fd5
SM
915 (pcase doc-view-doc-type
916 (`pdf
b4cb319f
SM
917 ;; Doc is a PDF, so convert it to TXT
918 (doc-view-pdf->txt doc-view-buffer-file-name txt callback))
f58e0fd5 919 (`ps
b4cb319f
SM
920 ;; Doc is a PS, so convert it to PDF (which will be converted to
921 ;; TXT thereafter).
c00ebc98 922 (let ((pdf (doc-view-current-cache-doc-pdf)))
b4cb319f
SM
923 (doc-view-ps->pdf doc-view-buffer-file-name pdf
924 (lambda () (doc-view-pdf->txt pdf txt callback)))))
f58e0fd5 925 (`dvi
b4cb319f
SM
926 ;; Doc is a DVI. This means that a doc.pdf already exists in its
927 ;; cache subdirectory.
c00ebc98 928 (doc-view-pdf->txt (doc-view-current-cache-doc-pdf) txt callback))
f58e0fd5 929 (`odf
b71b7803
TH
930 ;; Doc is some ODF (or MS Office) doc. This means that a doc.pdf
931 ;; already exists in its cache subdirectory.
c00ebc98 932 (doc-view-pdf->txt (doc-view-current-cache-doc-pdf) txt callback))
f58e0fd5 933 (_ (error "DocView doesn't know what to do"))))
b4cb319f
SM
934
935(defun doc-view-ps->pdf (ps pdf callback)
936 "Convert PS to PDF asynchronously and call CALLBACK when finished."
d0af9f77 937 (or (executable-find doc-view-ps2pdf-program)
ca32d854 938 (error "You need the `ps2pdf' program to convert PS to PDF"))
ec4853ab
SM
939 (doc-view-start-process "ps->pdf" doc-view-ps2pdf-program
940 (list
941 ;; Avoid security problems when rendering files from
942 ;; untrusted sources.
943 "-dSAFER"
944 ;; in-file and out-file
945 ps pdf)
946 callback))
947
948(defun doc-view-active-pages ()
949 (let ((pages ()))
950 (dolist (win (get-buffer-window-list (current-buffer) nil 'visible))
951 (let ((page (image-mode-window-get 'page win)))
952 (unless (memq page pages) (push page pages))))
953 pages))
94dbe99c 954
640602f7 955(defun doc-view-convert-current-doc ()
39a402e3 956 "Convert `doc-view-buffer-file-name' to a set of png files, one file per page.
640602f7
RS
957Those files are saved in the directory given by the function
958`doc-view-current-cache-dir'."
c17587fe
SM
959 ;; Let stale files still display while we recompute the new ones, so only
960 ;; flush the cache when the conversion is over. One of the reasons why it
961 ;; is important to keep displaying the stale page is so that revert-buffer
962 ;; preserves the horizontal/vertical scroll settings (which are otherwise
963 ;; resets during the redisplay).
964 (setq doc-view-pending-cache-flush t)
965 (let ((png-file (expand-file-name "page-%d.png"
966 (doc-view-current-cache-dir))))
7edd6b92 967 (make-directory (doc-view-current-cache-dir) t)
f58e0fd5
SM
968 (pcase doc-view-doc-type
969 (`dvi
eb79098b
SM
970 ;; DVI files have to be converted to PDF before Ghostscript can process
971 ;; it.
c00ebc98 972 (let ((pdf (doc-view-current-cache-doc-pdf)))
b4cb319f
SM
973 (doc-view-dvi->pdf doc-view-buffer-file-name pdf
974 (lambda () (doc-view-pdf/ps->png pdf png-file)))))
f58e0fd5 975 (`odf
95e16d17
TH
976 ;; ODF files have to be converted to PDF before Ghostscript can
977 ;; process it.
c00ebc98 978 (let ((pdf (doc-view-current-cache-doc-pdf))
d2c32364 979 (opdf (expand-file-name (concat (file-name-base doc-view-buffer-file-name)
e95a67dc
SM
980 ".pdf")
981 doc-view-current-cache-dir))
982 (png-file png-file))
95e16d17
TH
983 ;; The unoconv tool only supports a output directory, but no
984 ;; file name. It's named like the input file with the
985 ;; extension replaced by pdf.
986 (doc-view-odf->pdf doc-view-buffer-file-name
987 (lambda ()
988 ;; Rename to doc.pdf
989 (rename-file opdf pdf)
990 (doc-view-pdf/ps->png pdf png-file)))))
f58e0fd5 991 (`pdf
bdd42899
SM
992 (let ((pages (doc-view-active-pages)))
993 ;; Convert PDF to PNG images starting with the active pages.
994 (doc-view-pdf->png doc-view-buffer-file-name png-file pages)))
f58e0fd5 995 (_
eb79098b
SM
996 ;; Convert to PNG images.
997 (doc-view-pdf/ps->png doc-view-buffer-file-name png-file)))))
94dbe99c 998
94dbe99c
TTN
999;;;; Slicing
1000
aa360da1
GM
1001(declare-function image-size "image.c" (spec &optional pixels frame))
1002
94dbe99c
TTN
1003(defun doc-view-set-slice (x y width height)
1004 "Set the slice of the images that should be displayed.
1005You can use this function to tell doc-view not to display the
1006margins of the document. It prompts for the top-left corner (X
1007and Y) of the slice to display and its WIDTH and HEIGHT.
1008
db8a5a18
TH
1009See `doc-view-set-slice-using-mouse' and
1010`doc-view-set-slice-from-bounding-box' for more convenient ways
1011to do that. To reset the slice use `doc-view-reset-slice'."
94dbe99c 1012 (interactive
de171465 1013 (let* ((size (image-size (doc-view-current-image) t))
1ca678aa
MC
1014 (a (read-number (format "Top-left X (0..%d): " (car size))))
1015 (b (read-number (format "Top-left Y (0..%d): " (cdr size))))
1016 (c (read-number (format "Width (0..%d): " (- (car size) a))))
1017 (d (read-number (format "Height (0..%d): " (- (cdr size) b)))))
94dbe99c 1018 (list a b c d)))
de171465 1019 (setf (doc-view-current-slice) (list x y width height))
94dbe99c 1020 ;; Redisplay
de171465 1021 (doc-view-goto-page (doc-view-current-page)))
94dbe99c
TTN
1022
1023(defun doc-view-set-slice-using-mouse ()
1024 "Set the slice of the images that should be displayed.
1025You set the slice by pressing mouse-1 at its top-left corner and
1026dragging it to its bottom-right corner. See also
1027`doc-view-set-slice' and `doc-view-reset-slice'."
1028 (interactive)
1029 (let (x y w h done)
1030 (while (not done)
1031 (let ((e (read-event
1ca678aa
MC
1032 (concat "Press mouse-1 at the top-left corner and "
1033 "drag it to the bottom-right corner!"))))
1034 (when (eq (car e) 'drag-mouse-1)
1035 (setq x (car (posn-object-x-y (event-start e))))
1036 (setq y (cdr (posn-object-x-y (event-start e))))
1037 (setq w (- (car (posn-object-x-y (event-end e))) x))
1038 (setq h (- (cdr (posn-object-x-y (event-end e))) y))
1039 (setq done t))))
94dbe99c
TTN
1040 (doc-view-set-slice x y w h)))
1041
db8a5a18
TH
1042(defun doc-view-get-bounding-box ()
1043 "Get the BoundingBox information of the current page."
1044 (let* ((page (doc-view-current-page))
c00ebc98
TH
1045 (doc (let ((cache-doc (doc-view-current-cache-doc-pdf)))
1046 (if (file-exists-p cache-doc)
1047 cache-doc
1048 doc-view-buffer-file-name)))
db8a5a18
TH
1049 (o (shell-command-to-string
1050 (concat doc-view-ghostscript-program
1051 " -dSAFER -dBATCH -dNOPAUSE -q -sDEVICE=bbox "
1052 (format "-dFirstPage=%s -dLastPage=%s %s"
c00ebc98 1053 page page doc)))))
db8a5a18
TH
1054 (save-match-data
1055 (when (string-match (concat "%%BoundingBox: "
1056 "\\([[:digit:]]+\\) \\([[:digit:]]+\\) "
1057 "\\([[:digit:]]+\\) \\([[:digit:]]+\\)") o)
1058 (mapcar #'string-to-number
1059 (list (match-string 1 o)
1060 (match-string 2 o)
1061 (match-string 3 o)
1062 (match-string 4 o)))))))
1063
1064(defvar doc-view-paper-sizes
1065 '((a4 595 842)
1066 (a4-landscape 842 595)
1067 (letter 612 792)
1068 (letter-landscape 792 612)
1069 (legal 612 1008)
1070 (legal-landscape 1008 612)
1071 (a3 842 1191)
1072 (a3-landscape 1191 842)
1073 (tabloid 792 1224)
1074 (ledger 1224 792))
1075 "An alist from paper size names to dimensions.")
1076
1077(defun doc-view-guess-paper-size (iw ih)
1078 "Guess the paper size according to the aspect ratio."
1079 (cl-labels ((div (x y)
1080 (round (/ (* 100.0 x) y))))
1081 (let ((ar (div iw ih))
1082 (al (mapcar (lambda (l)
46624b4f 1083 (list (div (nth 1 l) (nth 2 l)) (car l)))
db8a5a18
TH
1084 doc-view-paper-sizes)))
1085 (cadr (assoc ar al)))))
1086
1087(defun doc-view-scale-bounding-box (ps iw ih bb)
46624b4f
SM
1088 (list (/ (* (nth 0 bb) iw) (nth 1 (assoc ps doc-view-paper-sizes)))
1089 (/ (* (nth 1 bb) ih) (nth 2 (assoc ps doc-view-paper-sizes)))
1090 (/ (* (nth 2 bb) iw) (nth 1 (assoc ps doc-view-paper-sizes)))
1091 (/ (* (nth 3 bb) ih) (nth 2 (assoc ps doc-view-paper-sizes)))))
db8a5a18
TH
1092
1093(defun doc-view-set-slice-from-bounding-box (&optional force-paper-size)
1094 "Set the slice from the document's BoundingBox information.
1095The result is that the margins are almost completely cropped,
1096much more accurate than could be done manually using
1097`doc-view-set-slice-using-mouse'."
1098 (interactive "P")
1099 (let ((bb (doc-view-get-bounding-box)))
1100 (if (not bb)
1101 (message "BoundingBox couldn't be determined")
1102 (let* ((is (image-size (doc-view-current-image) t))
1103 (iw (car is))
1104 (ih (cdr is))
1105 (ps (or (and (null force-paper-size) (doc-view-guess-paper-size iw ih))
1106 (intern (completing-read "Paper size: "
1107 (mapcar #'car doc-view-paper-sizes)
1108 nil t))))
1109 (bb (doc-view-scale-bounding-box ps iw ih bb))
1110 (x1 (nth 0 bb))
1111 (y1 (nth 1 bb))
1112 (x2 (nth 2 bb))
1113 (y2 (nth 3 bb)))
1114 ;; We keep a 2 pixel margin.
1115 (doc-view-set-slice (- x1 2) (- ih y2 2)
1116 (+ (- x2 x1) 4) (+ (- y2 y1) 4))))))
1117
94dbe99c 1118(defun doc-view-reset-slice ()
e48a5bf9 1119 "Reset the current slice.
1f75e53d 1120After calling this function whole pages will be visible again."
94dbe99c 1121 (interactive)
de171465 1122 (setf (doc-view-current-slice) nil)
94dbe99c 1123 ;; Redisplay
de171465 1124 (doc-view-goto-page (doc-view-current-page)))
94dbe99c
TTN
1125
1126;;;; Display
1127
1128(defun doc-view-insert-image (file &rest args)
1129 "Insert the given png FILE.
e48a5bf9 1130ARGS is a list of image descriptors."
c17587fe
SM
1131 (when doc-view-pending-cache-flush
1132 (clear-image-cache)
1133 (setq doc-view-pending-cache-flush nil))
de171465 1134 (let ((ol (doc-view-current-overlay))
56741510 1135 (image (if (and file (file-readable-p file))
875c044a
TH
1136 (if (not (fboundp 'imagemagick-types))
1137 (apply 'create-image file 'png nil args)
1138 (unless (member :width args)
1139 (setq args (append args (list :width doc-view-image-width))))
1140 (apply 'create-image file 'imagemagick nil args))))
de171465
SM
1141 (slice (doc-view-current-slice)))
1142 (setf (doc-view-current-image) image)
56741510 1143 (move-overlay ol (point-min) (point-max))
de171465 1144 (overlay-put ol 'display
56741510
SM
1145 (cond
1146 (image
de171465
SM
1147 (if slice
1148 (list (cons 'slice slice) image)
56741510
SM
1149 image))
1150 ;; We're trying to display a page that doesn't exist.
ec4853ab 1151 (doc-view-current-converter-processes
56741510
SM
1152 ;; Maybe the page doesn't exist *yet*.
1153 "Cannot display this page (yet)!")
1154 (t
1155 ;; Typically happens if the conversion process somehow
1156 ;; failed. Better not signal an error here because it
1157 ;; could prevent a subsequent reconversion from fixing
1158 ;; the problem.
1159 (concat "Cannot display this page!\n"
1160 "Maybe because of a conversion failure!"))))
1161 (let ((win (overlay-get ol 'window)))
1162 (if (stringp (overlay-get ol 'display))
1163 (progn ;Make sure the text is not scrolled out of view.
1164 (set-window-hscroll win 0)
1165 (set-window-vscroll win 0))
1166 (let ((hscroll (image-mode-window-get 'hscroll win))
1167 (vscroll (image-mode-window-get 'vscroll win)))
1168 ;; Reset scroll settings, in case they were changed.
1169 (if hscroll (set-window-hscroll win hscroll))
1170 (if vscroll (set-window-vscroll win vscroll)))))))
94dbe99c
TTN
1171
1172(defun doc-view-sort (a b)
1173 "Return non-nil if A should be sorted before B.
1174Predicate for sorting `doc-view-current-files'."
f4c75497
SM
1175 (or (< (length a) (length b))
1176 (and (= (length a) (length b))
1177 (string< a b))))
94dbe99c 1178
65073003
SM
1179(defun doc-view-display (buffer &optional force)
1180 "Start viewing the document in BUFFER.
214abdd4
SM
1181If FORCE is non-nil, start viewing even if the document does not
1182have the page we want to view."
65073003 1183 (with-current-buffer buffer
83600dc8 1184 (let ((prev-pages doc-view-current-files))
56741510
SM
1185 (setq doc-view-current-files
1186 (sort (directory-files (doc-view-current-cache-dir) t
1187 "page-[0-9]+\\.png" t)
1188 'doc-view-sort))
83600dc8
SM
1189 (dolist (win (or (get-buffer-window-list buffer nil t)
1190 (list t)))
10b6e7c1
CY
1191 (let* ((page (doc-view-current-page win))
1192 (pagefile (expand-file-name (format "page-%d.png" page)
1193 (doc-view-current-cache-dir))))
1194 (when (or force
1195 (and (not (member pagefile prev-pages))
1196 (member pagefile doc-view-current-files)))
83600dc8
SM
1197 (if (windowp win)
1198 (with-selected-window win
1199 (cl-assert (eq (current-buffer) buffer) t)
1200 (doc-view-goto-page page))
db8a5a18 1201 (doc-view-goto-page page))))))))
94dbe99c
TTN
1202
1203(defun doc-view-buffer-message ()
c17587fe
SM
1204 ;; Only show this message initially, not when refreshing the buffer (in which
1205 ;; case it's better to keep displaying the "stale" page while computing
1206 ;; the fresh new ones).
de171465
SM
1207 (unless (overlay-get (doc-view-current-overlay) 'display)
1208 (overlay-put (doc-view-current-overlay) 'display
c17587fe
SM
1209 (concat (propertize "Welcome to DocView!" 'face 'bold)
1210 "\n"
1211 "
1f75e53d 1212If you see this buffer it means that the document you want to view is being
f4c75497 1213converted to PNG and the conversion of the first page hasn't finished yet or
94dbe99c
TTN
1214`doc-view-conversion-refresh-interval' is set to nil.
1215
1216For now these keys are useful:
1217
1ca678aa 1218`q' : Bury this buffer. Conversion will go on in background.
937cb3fb 1219`k' : Kill the conversion process and this buffer.
c17587fe 1220`K' : Kill the conversion process.\n"))))
94dbe99c 1221
aa360da1
GM
1222(declare-function tooltip-show "tooltip" (text &optional use-echo-area))
1223
94dbe99c
TTN
1224(defun doc-view-show-tooltip ()
1225 (interactive)
de171465 1226 (tooltip-show (doc-view-current-info)))
94dbe99c 1227
515357c2
TH
1228(defun doc-view-open-text ()
1229 "Open a buffer with the current doc's contents as text."
1230 (interactive)
ec4853ab 1231 (if doc-view-current-converter-processes
515357c2
TH
1232 (message "DocView: please wait till conversion finished.")
1233 (let ((txt (expand-file-name "doc.txt" (doc-view-current-cache-dir))))
1234 (if (file-readable-p txt)
5b355315
TH
1235 (let ((name (concat "Text contents of "
1236 (file-name-nondirectory buffer-file-name)))
1237 (dir (file-name-directory buffer-file-name)))
1238 (with-current-buffer (find-file txt)
1239 (rename-buffer name)
1240 (setq default-directory dir)))
b4cb319f 1241 (doc-view-doc->txt txt 'doc-view-open-text)))))
515357c2 1242
937cb3fb 1243;;;;; Toggle between editing and viewing
640602f7 1244
83600dc8
SM
1245(defvar-local doc-view-saved-settings nil
1246 "Doc-view settings saved while in some other mode.")
1247(put 'doc-view-saved-settings 'permanent-local t)
1248
640602f7 1249(defun doc-view-toggle-display ()
937cb3fb 1250 "Toggle between editing a document as text or viewing it."
640602f7 1251 (interactive)
937cb3fb
GM
1252 (if (eq major-mode 'doc-view-mode)
1253 ;; Switch to editing mode
1254 (progn
1255 (doc-view-kill-proc)
1256 (setq buffer-read-only nil)
515357c2
TH
1257 (remove-overlays (point-min) (point-max) 'doc-view t)
1258 (set (make-local-variable 'image-mode-winprops-alist) t)
ad727c81
TH
1259 ;; Switch to the previously used major mode or fall back to
1260 ;; normal mode.
291cc045 1261 (doc-view-fallback-mode)
c17587fe 1262 (doc-view-minor-mode 1))
937cb3fb
GM
1263 ;; Switch to doc-view-mode
1264 (when (and (buffer-modified-p)
1265 (y-or-n-p "The buffer has been modified. Save the changes? "))
1266 (save-buffer))
937cb3fb 1267 (doc-view-mode)))
640602f7 1268
94dbe99c
TTN
1269;;;; Searching
1270
515357c2 1271
94dbe99c
TTN
1272(defun doc-view-search-internal (regexp file)
1273 "Return a list of FILE's pages that contain text matching REGEXP.
1ca678aa
MC
1274The value is an alist of the form (PAGE CONTEXTS) where PAGE is
1275the pagenumber and CONTEXTS are all lines of text containing a match."
94dbe99c
TTN
1276 (with-temp-buffer
1277 (insert-file-contents file)
1278 (let ((page 1)
1ca678aa
MC
1279 (lastpage 1)
1280 matches)
94dbe99c 1281 (while (re-search-forward (concat "\\(?:\\([\f]\\)\\|\\("
1ca678aa 1282 regexp "\\)\\)") nil t)
069b4ce3 1283 (when (match-string 1) (setq page (1+ page)))
1ca678aa
MC
1284 (when (match-string 2)
1285 (if (/= page lastpage)
c17587fe 1286 (push (cons page
515357c2
TH
1287 (list (buffer-substring
1288 (line-beginning-position)
1289 (line-end-position))))
1290 matches)
1ca678aa
MC
1291 (setq matches (cons
1292 (append
1293 (or
1294 ;; This page already is a match.
1295 (car matches)
1296 ;; This is the first match on page.
1297 (list page))
1298 (list (buffer-substring
1299 (line-beginning-position)
1300 (line-end-position))))
1301 (cdr matches))))
1302 (setq lastpage page)))
94dbe99c
TTN
1303 (nreverse matches))))
1304
1305(defun doc-view-search-no-of-matches (list)
1306 "Extract the number of matches from the search result LIST."
1307 (let ((no 0))
1308 (dolist (p list)
1309 (setq no (+ no (1- (length p)))))
1310 no))
1311
7baca0fa
JL
1312(defun doc-view-search-backward (new-query)
1313 "Call `doc-view-search' for backward search.
1314If prefix NEW-QUERY is given, ask for a new regexp."
1315 (interactive "P")
da99b369 1316 (doc-view-search new-query t))
7baca0fa
JL
1317
1318(defun doc-view-search (new-query &optional backward)
1319 "Jump to the next match or initiate a new search if NEW-QUERY is given.
94dbe99c 1320If the current document hasn't been transformed to plain text
7baca0fa
JL
1321till now do that first.
1322If BACKWARD is non-nil, jump to the previous match."
1323 (interactive "P")
da99b369 1324 (if (and (not new-query)
7baca0fa
JL
1325 doc-view-current-search-matches)
1326 (if backward
1327 (doc-view-search-previous-match 1)
1328 (doc-view-search-next-match 1))
1329 ;; New search, so forget the old results.
1330 (setq doc-view-current-search-matches nil)
1331 (let ((txt (expand-file-name "doc.txt"
1332 (doc-view-current-cache-dir))))
1333 (if (file-readable-p txt)
1334 (progn
1335 (setq doc-view-current-search-matches
1336 (doc-view-search-internal
1337 (read-from-minibuffer "Regexp: ")
1338 txt))
1339 (message "DocView: search yielded %d matches."
1340 (doc-view-search-no-of-matches
1341 doc-view-current-search-matches)))
1342 ;; We must convert to TXT first!
ec4853ab 1343 (if doc-view-current-converter-processes
7baca0fa 1344 (message "DocView: please wait till conversion finished.")
b4cb319f 1345 (doc-view-doc->txt txt (lambda () (doc-view-search nil))))))))
94dbe99c
TTN
1346
1347(defun doc-view-search-next-match (arg)
1348 "Go to the ARGth next matching page."
1349 (interactive "p")
937cb3fb 1350 (let* ((next-pages (doc-view-remove-if
de171465 1351 (lambda (i) (<= (car i) (doc-view-current-page)))
937cb3fb 1352 doc-view-current-search-matches))
1ca678aa 1353 (page (car (nth (1- arg) next-pages))))
94dbe99c 1354 (if page
1ca678aa 1355 (doc-view-goto-page page)
94dbe99c 1356 (when (and
1ca678aa
MC
1357 doc-view-current-search-matches
1358 (y-or-n-p "No more matches after current page. Wrap to first match? "))
1359 (doc-view-goto-page (caar doc-view-current-search-matches))))))
94dbe99c
TTN
1360
1361(defun doc-view-search-previous-match (arg)
1362 "Go to the ARGth previous matching page."
1363 (interactive "p")
937cb3fb 1364 (let* ((prev-pages (doc-view-remove-if
de171465 1365 (lambda (i) (>= (car i) (doc-view-current-page)))
937cb3fb 1366 doc-view-current-search-matches))
1ca678aa 1367 (page (car (nth (1- arg) (nreverse prev-pages)))))
94dbe99c 1368 (if page
1ca678aa 1369 (doc-view-goto-page page)
94dbe99c 1370 (when (and
1ca678aa
MC
1371 doc-view-current-search-matches
1372 (y-or-n-p "No more matches before current page. Wrap to last match? "))
1373 (doc-view-goto-page (caar (last doc-view-current-search-matches)))))))
94dbe99c 1374
640602f7 1375;;;; User interface commands and the mode
94dbe99c 1376
0d17c4b9 1377(put 'doc-view-mode 'mode-class 'special)
c17587fe 1378
515357c2
TH
1379(defun doc-view-already-converted-p ()
1380 "Return non-nil if the current doc was already converted."
1381 (and (file-exists-p (doc-view-current-cache-dir))
bdd42899
SM
1382 ;; Check that the resolution info is there, otherwise it means
1383 ;; the conversion is incomplete.
1384 (file-readable-p (expand-file-name "resolution.el"
1385 (doc-view-current-cache-dir)))
1386 (> (length (directory-files (doc-view-current-cache-dir)
1387 nil "\\.png\\'"))
1388 0)))
515357c2 1389
c17587fe
SM
1390(defun doc-view-initiate-display ()
1391 ;; Switch to image display if possible
322f4559 1392 (if (doc-view-mode-p doc-view-doc-type)
c17587fe
SM
1393 (progn
1394 (doc-view-buffer-message)
de171465 1395 (setf (doc-view-current-page) (or (doc-view-current-page) 1))
515357c2 1396 (if (doc-view-already-converted-p)
c17587fe
SM
1397 (progn
1398 (message "DocView: using cached files!")
cde4c3f1 1399 ;; Load the saved resolution
bdd42899
SM
1400 (let* ((res-file (expand-file-name "resolution.el"
1401 (doc-view-current-cache-dir)))
1402 (res
1403 (with-temp-buffer
1404 (when (file-readable-p res-file)
1405 (insert-file-contents res-file)
1406 (read (current-buffer))))))
1407 (when (numberp res)
cde4c3f1 1408 (set (make-local-variable 'doc-view-resolution) res)))
65073003 1409 (doc-view-display (current-buffer) 'force))
c17587fe
SM
1410 (doc-view-convert-current-doc))
1411 (message
1412 "%s"
1413 (substitute-command-keys
1414 (concat "Type \\[doc-view-toggle-display] to toggle between "
1415 "editing or viewing the document."))))
1416 (message
1417 "%s"
0855c2ca
CY
1418 (concat "No PNG support is available, or some conversion utility for "
1419 (file-name-extension doc-view-buffer-file-name)
1420 " files is missing."))
1281bd51
TH
1421 (when (and (executable-find doc-view-pdftotext-program)
1422 (y-or-n-p
1423 "Unable to render file. View extracted text instead? "))
1424 (doc-view-open-text))
1425 (doc-view-toggle-display)))
94dbe99c 1426
e0385bf4 1427(defvar bookmark-make-record-function)
069b4ce3 1428
65073003
SM
1429(defun doc-view-clone-buffer-hook ()
1430 ;; FIXME: There are several potential problems linked with reconversion
1431 ;; and auto-revert when we have indirect buffers because they share their
1432 ;; /tmp cache directory. This sharing is good (you'd rather not reconvert
1433 ;; for each clone), but that means that clones need to collaborate a bit.
1434 ;; I guess it mostly means: detect when a reconversion process is already
1435 ;; running, and run the sentinel in all clones.
515357c2 1436 ;;
de171465 1437 ;; Maybe the clones should really have a separate /tmp directory
65073003
SM
1438 ;; so they could have a different resolution and you could use clones
1439 ;; for zooming.
de171465
SM
1440 (remove-overlays (point-min) (point-max) 'doc-view t)
1441 (if (consp image-mode-winprops-alist) (setq image-mode-winprops-alist nil)))
65073003 1442
eb79098b
SM
1443(defun doc-view-intersection (l1 l2)
1444 (let ((l ()))
1445 (dolist (x l1) (if (memq x l2) (push x l)))
1446 l))
1447
291cc045
TH
1448(defun doc-view-set-doc-type ()
1449 "Figure out the current document type (`doc-view-doc-type')."
1450 (let ((name-types
1451 (when buffer-file-name
1452 (cdr (assoc (file-name-extension buffer-file-name)
1453 '(
1454 ;; DVI
1455 ("dvi" dvi)
1456 ;; PDF
1457 ("pdf" pdf) ("epdf" pdf)
1458 ;; PostScript
1459 ("ps" ps) ("eps" ps)
1460 ;; OpenDocument formats
1461 ("odt" odf) ("ods" odf) ("odp" odf) ("odg" odf)
1462 ("odc" odf) ("odi" odf) ("odm" odf) ("ott" odf)
1463 ("ots" odf) ("otp" odf) ("otg" odf)
1464 ;; Microsoft Office formats (also handled
1465 ;; by the odf conversion chain)
1466 ("doc" odf) ("docx" odf) ("xls" odf) ("xlsx" odf)
1467 ("ppt" odf) ("pptx" odf))))))
1468 (content-types
1469 (save-excursion
1470 (goto-char (point-min))
1471 (cond
1472 ((looking-at "%!") '(ps))
1473 ((looking-at "%PDF") '(pdf))
1474 ((looking-at "\367\002") '(dvi))))))
1475 (set (make-local-variable 'doc-view-doc-type)
1476 (car (or (doc-view-intersection name-types content-types)
1477 (when (and name-types content-types)
1478 (error "Conflicting types: name says %s but content says %s"
1479 name-types content-types))
1480 name-types content-types
1481 (error "Cannot determine the document type"))))))
1482
640602f7 1483;;;###autoload
937cb3fb 1484(defun doc-view-mode ()
640602f7 1485 "Major mode in DocView buffers.
06a21f70
TH
1486
1487DocView Mode is an Emacs document viewer. It displays PDF, PS
1488and DVI files (as PNG images) in Emacs buffers.
1489
640602f7 1490You can use \\<doc-view-mode-map>\\[doc-view-toggle-display] to
5c1f16b0
SM
1491toggle between displaying the document or editing it as text.
1492\\{doc-view-mode-map}"
937cb3fb 1493 (interactive)
f9adf05b 1494
96fe38a8 1495 (if (= (point-min) (point-max))
85699772 1496 ;; The doc is empty or doesn't exist at all, so fallback to
96fe38a8
SM
1497 ;; another mode. We used to also check file-exists-p, but this
1498 ;; returns nil for tar members.
291cc045 1499 (doc-view-fallback-mode)
06a21f70 1500
83600dc8 1501 (let* ((prev-major-mode (if (derived-mode-p 'doc-view-mode)
06a21f70 1502 doc-view-previous-major-mode
83600dc8 1503 (unless (eq major-mode 'fundamental-mode)
ad727c81 1504 major-mode))))
06a21f70 1505 (kill-all-local-variables)
83600dc8
SM
1506 (set (make-local-variable 'doc-view-previous-major-mode)
1507 prev-major-mode))
1508
1509 (dolist (var doc-view-saved-settings)
1510 (set (make-local-variable (car var)) (cdr var)))
bc19637d 1511
06a21f70 1512 ;; Figure out the document type.
291cc045
TH
1513 (unless doc-view-doc-type
1514 (doc-view-set-doc-type))
bc19637d 1515
06a21f70
TH
1516 (doc-view-make-safe-dir doc-view-cache-directory)
1517 ;; Handle compressed files, remote files, files inside archives
1518 (set (make-local-variable 'doc-view-buffer-file-name)
1519 (cond
1520 (jka-compr-really-do-compress
5e9fde5e 1521 ;; FIXME: there's a risk of name conflicts here.
06a21f70
TH
1522 (expand-file-name
1523 (file-name-nondirectory
1524 (file-name-sans-extension buffer-file-name))
1525 doc-view-cache-directory))
1526 ;; Is the file readable by local processes?
1527 ;; We used to use `file-remote-p' but it's unclear what it's
1528 ;; supposed to return nil for things like local files accessed via
1529 ;; `su' or via file://...
1530 ((let ((file-name-handler-alist nil))
5e9fde5e
SM
1531 (not (and buffer-file-name (file-readable-p buffer-file-name))))
1532 ;; FIXME: there's a risk of name conflicts here.
06a21f70 1533 (expand-file-name
5e9fde5e
SM
1534 (if buffer-file-name
1535 (file-name-nondirectory buffer-file-name)
1536 (buffer-name))
1537 doc-view-cache-directory))
06a21f70
TH
1538 (t buffer-file-name)))
1539 (when (not (string= doc-view-buffer-file-name buffer-file-name))
1540 (write-region nil nil doc-view-buffer-file-name))
bc19637d 1541
06a21f70
TH
1542 (add-hook 'change-major-mode-hook
1543 (lambda ()
1544 (doc-view-kill-proc)
1545 (remove-overlays (point-min) (point-max) 'doc-view t))
1546 nil t)
1547 (add-hook 'clone-indirect-buffer-hook 'doc-view-clone-buffer-hook nil t)
1548 (add-hook 'kill-buffer-hook 'doc-view-kill-proc nil t)
bc19637d 1549
06a21f70
TH
1550 (remove-overlays (point-min) (point-max) 'doc-view t) ;Just in case.
1551 ;; Keep track of display info ([vh]scroll, page number, overlay,
1552 ;; ...) for each window in which this document is shown.
1553 (add-hook 'image-mode-new-window-functions
1554 'doc-view-new-window-function nil t)
1555 (image-mode-setup-winprops)
bc19637d 1556
06a21f70
TH
1557 (set (make-local-variable 'mode-line-position)
1558 '(" P" (:eval (number-to-string (doc-view-current-page)))
bdd42899 1559 "/" (:eval (number-to-string (doc-view-last-page-number)))))
06a21f70
TH
1560 ;; Don't scroll unless the user specifically asked for it.
1561 (set (make-local-variable 'auto-hscroll-mode) nil)
7d6b4d3c
JL
1562 (set (make-local-variable 'mwheel-scroll-up-function)
1563 'doc-view-scroll-up-or-next-page)
1564 (set (make-local-variable 'mwheel-scroll-down-function)
1565 'doc-view-scroll-down-or-previous-page)
06a21f70
TH
1566 (set (make-local-variable 'cursor-type) nil)
1567 (use-local-map doc-view-mode-map)
1568 (set (make-local-variable 'after-revert-hook) 'doc-view-reconvert-doc)
1569 (set (make-local-variable 'bookmark-make-record-function)
1570 'doc-view-bookmark-make-record)
1571 (setq mode-name "DocView"
1572 buffer-read-only t
1573 major-mode 'doc-view-mode)
1574 (doc-view-initiate-display)
d1d33062
TH
1575 ;; Switch off view-mode explicitly, because doc-view-mode is the
1576 ;; canonical view mode for PDF/PS/DVI files. This could be
1577 ;; switched on automatically depending on the value of
1578 ;; `view-read-only'.
bde04ea9 1579 (set (make-local-variable 'view-read-only) nil)
06a21f70 1580 (run-mode-hooks 'doc-view-mode-hook)))
937cb3fb 1581
291cc045
TH
1582(defun doc-view-fallback-mode ()
1583 "Fallback to the previous or next best major mode."
83600dc8
SM
1584 (let ((vars (if (derived-mode-p 'doc-view-mode)
1585 (mapcar (lambda (var) (cons var (symbol-value var)))
1586 '(doc-view-resolution
1587 image-mode-winprops-alist)))))
1588 (if doc-view-previous-major-mode
1589 (funcall doc-view-previous-major-mode)
1590 (let ((auto-mode-alist
1591 (rassq-delete-all
1592 'doc-view-mode-maybe
1593 (rassq-delete-all 'doc-view-mode
1594 (copy-alist auto-mode-alist)))))
1595 (normal-mode)))
1596 (when vars
1597 (setq-local doc-view-saved-settings vars))))
291cc045
TH
1598
1599;;;###autoload
1600(defun doc-view-mode-maybe ()
1601 "Switch to `doc-view-mode' if possible.
1602If the required external tools are not available, then fallback
1603to the next best mode."
1604 (condition-case nil
1605 (doc-view-set-doc-type)
1606 (error (doc-view-fallback-mode)))
1607 (if (doc-view-mode-p doc-view-doc-type)
1608 (doc-view-mode)
1609 (doc-view-fallback-mode)))
1610
937cb3fb
GM
1611;;;###autoload
1612(define-minor-mode doc-view-minor-mode
06e21633
CY
1613 "Toggle displaying buffer via Doc View (Doc View minor mode).
1614With a prefix argument ARG, enable Doc View minor mode if ARG is
1615positive, and disable it otherwise. If called from Lisp, enable
1616the mode if ARG is omitted or nil.
1617
937cb3fb
GM
1618See the command `doc-view-mode' for more information on this mode."
1619 nil " DocView" doc-view-minor-mode-map
1620 :group 'doc-view
1621 (when doc-view-minor-mode
1622 (add-hook 'change-major-mode-hook (lambda () (doc-view-minor-mode -1)) nil t)
1623 (message
1624 "%s"
1625 (substitute-command-keys
1626 "Type \\[doc-view-toggle-display] to toggle between editing or viewing the document."))))
94dbe99c
TTN
1627
1628(defun doc-view-clear-cache ()
1629 "Delete the whole cache (`doc-view-cache-directory')."
1630 (interactive)
515357c2 1631 (dired-delete-file doc-view-cache-directory 'always))
94dbe99c
TTN
1632
1633(defun doc-view-dired-cache ()
1634 "Open `dired' in `doc-view-cache-directory'."
1635 (interactive)
1636 (dired doc-view-cache-directory))
1637
94dbe99c 1638
1666a6b3
TH
1639;;;; Bookmark integration
1640
e44fa724
KF
1641(declare-function bookmark-make-record-default
1642 "bookmark" (&optional no-file no-context posn))
a9f8b49b 1643(declare-function bookmark-prop-get "bookmark" (bookmark prop))
43f8b275 1644(declare-function bookmark-default-handler "bookmark" (bmk))
a9f8b49b 1645
32a091dd 1646(defun doc-view-bookmark-make-record ()
43f8b275
SM
1647 (nconc (bookmark-make-record-default)
1648 `((page . ,(doc-view-current-page))
1649 (handler . doc-view-bookmark-jump))))
1666a6b3 1650
069b4ce3 1651
1666a6b3
TH
1652;;;###autoload
1653(defun doc-view-bookmark-jump (bmk)
03e26a79 1654 ;; This implements the `handler' function interface for record type
e0385bf4 1655 ;; returned by `doc-view-bookmark-make-record', which see.
43f8b275
SM
1656 (prog1 (bookmark-default-handler bmk)
1657 (let ((page (bookmark-prop-get bmk 'page)))
1666a6b3 1658 (when (not (eq major-mode 'doc-view-mode))
43f8b275 1659 (doc-view-toggle-display))
a9f8b49b 1660 (with-selected-window
94d11cb5
IK
1661 (or (get-buffer-window (current-buffer) 0)
1662 (selected-window))
1663 (doc-view-goto-page page)))))
1666a6b3 1664
069b4ce3
GM
1665
1666(provide 'doc-view)
1667
1668;; Local Variables:
f0da764a 1669;; eval: (outline-minor-mode 1)
069b4ce3
GM
1670;; End:
1671
94dbe99c 1672;;; doc-view.el ends here