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