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