doc-view.el 82.4 KB
Newer Older
1 2
;;; doc-view.el --- View PDF/PostScript/DVI files in Emacs -*- lexical-binding: t -*-

Paul Eggert's avatar
Paul Eggert committed
3
;; Copyright (C) 2007-2019 Free Software Foundation, Inc.
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
4
;;
5
;; Author: Tassilo Horn <tsdh@gnu.org>
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
6 7 8 9
;; Keywords: files, pdf, ps, dvi

;; This file is part of GNU Emacs.

10
;; GNU Emacs is free software: you can redistribute it and/or modify
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
11
;; it under the terms of the GNU General Public License as published by
12 13
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
14 15 16 17 18 19 20

;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
21
;; along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
22 23 24

;;; Requirements:

25
;; doc-view.el requires GNU Emacs 22.1 or newer.  You also need Ghostscript,
26 27 28
;; `dvipdf' (comes with Ghostscript) or `dvipdfm' (comes with teTeX or TeXLive)
;; and `pdftotext', which comes with xpdf (http://www.foolabs.com/xpdf/) or
;; poppler (http://poppler.freedesktop.org/).
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
29 30 31 32 33 34 35 36

;;; Commentary:

;; DocView is a document viewer for Emacs.  It converts PDF, PS and DVI files
;; to a set of PNG files, one PNG for each page, and displays the PNG images
;; inside an Emacs buffer.  This buffer uses `doc-view-mode' which provides
;; convenient key bindings for browsing the document.
;;
37
;; To use it simply open a document file with
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
38
;;
39
;;     C-x C-f ~/path/to/document RET
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
40
;;
41
;; and the document will be converted and displayed, if your emacs supports PNG
42
;; images.  With `C-c C-c' you can toggle between the rendered images
43
;; representation and the source text representation of the document.
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
44 45 46
;;
;; Since conversion may take some time all the PNG images are cached in a
;; subdirectory of `doc-view-cache-directory' and reused when you want to view
47 48
;; that file again.  To reconvert a document hit `g' (`doc-view-reconvert-doc')
;; when displaying the document.  To delete all cached files use
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
49 50 51
;; `doc-view-clear-cache'.  To open the cache with dired, so that you can tidy
;; it out use `doc-view-dired-cache'.
;;
52
;; When conversion is underway the first page will be displayed as soon as it
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
53 54 55 56 57
;; is available and the available pages are refreshed every
;; `doc-view-conversion-refresh-interval' seconds.  If that variable is nil the
;; pages won't be displayed before conversion of the document finished
;; completely.
;;
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
;; DocView lets you select a slice of the displayed pages.  This slice
;; will be remembered and applied to all pages of the current
;; document.  This enables you to cut away the margins of a document
;; to save some space.  To select a slice you can use
;; `doc-view-set-slice' (bound to `s s') which will query you for the
;; coordinates of the slice's top-left corner and its width and
;; height.  A much more convenient way to do the same is offered by
;; the command `doc-view-set-slice-using-mouse' (bound to `s m').
;; After invocation you only have to press mouse-1 at the top-left
;; corner and drag it to the bottom-right corner of the desired slice.
;; Even more accurate and convenient is to use
;; `doc-view-set-slice-from-bounding-box' (bound to `s b') which uses
;; the BoundingBox information of the current page to set an optimal
;; slice.  To reset the slice use `doc-view-reset-slice' (bound to `s
;; r').
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
73 74 75 76
;;
;; You can also search within the document.  The command `doc-view-search'
;; (bound to `C-s') queries for a search regexp and initializes a list of all
;; matching pages and messages how many match-pages were found.  After that you
77 78 79 80
;; can jump to the next page containing a match with an additional `C-s'.  With
;; `C-r' you can do the same, but backwards.  To search for a new regexp give a
;; prefix arg to one of the search functions, e.g. by typing `C-u C-s'.  The
;; searching works by using a plain text representation of the document.  If
Juanma Barranquero's avatar
Juanma Barranquero committed
81
;; that doesn't already exist the first invocation of `doc-view-search' (or
82 83 84
;; `doc-view-search-backward') starts the conversion.  When that finishes and
;; you're still viewing the document (i.e. you didn't switch to another buffer)
;; you're queried for the regexp then.
85 86 87 88
;;
;; Dired users can simply hit `v' on a document file.  If it's a PS, PDF or DVI
;; it will be opened using `doc-view-mode'.
;;
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
89 90 91

;;; Configuration:

92 93 94
;; If the images are too small or too big you should set the "-rXXX" option in
;; `doc-view-ghostscript-options' to another value.  (The bigger your screen,
;; the higher the value.)
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
95 96 97 98 99 100 101 102
;;
;; This and all other options can be set with the customization interface.
;; Simply do
;;
;;     M-x customize-group RET doc-view RET
;;
;; and modify them to your needs.

103
;;; Todo:
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
104

105 106
;; - add print command.
;; - share more code with image-mode.
107 108
;; - better menu.
;; - Bind slicing to a drag event.
109
;; - zoom the region around the cursor (like xdvi).
110 111
;; - get rid of the silly arrow in the fringe.
;; - improve anti-aliasing (pdf-utils gets it better).
112

113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
;;;; About isearch support

;; I tried implementing isearch by setting
;; `isearch-search-fun-function' buffer-locally, but that didn't
;; work too good.  The function doing the real search was called
;; endlessly somehow.  But even if we'd get that working no real
;; isearch feeling comes up due to the missing match highlighting.
;; Currently I display all lines containing a match in a tooltip and
;; each C-s or C-r jumps directly to the next/previous page with a
;; match.  With isearch we could only display the current match.  So
;; we had to decide if another C-s jumps to the next page with a
;; match (thus only the first match in a page will be displayed in a
;; tooltip) or to the next match, which would do nothing visible
;; (except the tooltip) if the next match is on the same page.

;; And it's much slower than the current search facility, because
Paul Eggert's avatar
Paul Eggert committed
129
;; isearch really searches for each step forward or backward whereas
130 131 132 133 134 135 136 137
;; the current approach searches once and then it knows to which
;; pages to jump.

;; Anyway, if someone with better isearch knowledge wants to give it a try,
;; feel free to do it.  --Tassilo

;;; Code:

138
(require 'cl-lib)
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
139
(require 'dired)
140
(require 'image-mode)
141
(require 'jka-compr)
142
(eval-when-compile (require 'subr-x))
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
143 144 145 146

;;;; Customization Options

(defgroup doc-view nil
147
  "In-buffer viewer for PDF, PostScript, DVI, and DJVU files."
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
148 149 150
  :link '(function-link doc-view)
  :version "22.2"
  :group 'applications
151
  :group 'data
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
152 153 154
  :group 'multimedia
  :prefix "doc-view-")

155 156 157 158 159 160
(defcustom doc-view-ghostscript-program
  (cond
   ((memq system-type '(windows-nt ms-dos))
    "gswin32c")
   (t
    "gs"))
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
161
  "Program to convert PS and PDF files to PNG."
162 163
  :type 'file
  :version "27.1")
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
164

165 166 167
(defcustom doc-view-pdfdraw-program
  (cond
   ((executable-find "pdfdraw") "pdfdraw")
168 169
   ((executable-find "mudraw") "mudraw")
   ((executable-find "mutool") "mutool")
170 171
   (t "mudraw"))
  "Name of MuPDF's program to convert PDF files to PNG."
172 173 174 175
  :type 'file
  :version "24.4")

(defcustom doc-view-pdf->png-converter-function
176 177 178
  (if (executable-find doc-view-pdfdraw-program)
      #'doc-view-pdf->png-converter-mupdf
    #'doc-view-pdf->png-converter-ghostscript)
179 180 181 182 183 184 185 186 187
  "Function to call to convert a PDF file into a PNG file."
  :type '(radio
          (function-item doc-view-pdf->png-converter-ghostscript
                         :doc "Use ghostscript")
          (function-item doc-view-pdf->png-converter-mupdf
                         :doc "Use mupdf")
          function)
  :version "24.4")

Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
188
(defcustom doc-view-ghostscript-options
189
  '("-dSAFER" ;; Avoid security problems when rendering files from untrusted
190
    ;; sources.
191
    "-dNOPAUSE" "-dTextAlphaBits=4"
192
    "-dBATCH" "-dGraphicsAlphaBits=4" "-dQUIET")
193
  "A list of options to give to ghostscript."
194
  :type '(repeat string))
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
195

196 197 198 199 200
(defcustom doc-view-ghostscript-device "png16m"
  "Output device to give to ghostscript."
  :type 'string
  :version "27.1")

201 202 203
(defcustom doc-view-resolution 100
  "Dots per inch resolution used to render the documents.
Higher values result in larger images."
204
  :type 'number)
205

206 207 208 209 210
(defcustom doc-view-scale-internally t
  "Whether we should try to rescale images ourselves.
If nil, the document is re-rendered every time the scaling factor is modified.
This only has an effect if the image libraries linked with Emacs support
scaling."
211
  :version "24.4"
212 213
  :type 'boolean)

214 215
(defcustom doc-view-image-width 850
  "Default image width.
216 217
Has only an effect if `doc-view-scale-internally' is non-nil and support for
scaling is compiled into emacs."
218
  :version "24.1"
219
  :type 'number)
220

221
(defcustom doc-view-dvipdfm-program "dvipdfm"
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
222 223 224
  "Program to convert DVI files to PDF.

DVI file will be converted to PDF before the resulting PDF is
225 226 227 228
converted to PNG.

If this and `doc-view-dvipdf-program' are set,
`doc-view-dvipdf-program' will be preferred."
229
  :type 'file)
230

231
(defcustom doc-view-dvipdf-program "dvipdf"
232 233 234 235 236 237 238
  "Program to convert DVI files to PDF.

DVI file will be converted to PDF before the resulting PDF is
converted to PNG.

If this and `doc-view-dvipdfm-program' are set,
`doc-view-dvipdf-program' will be preferred."
239
  :type 'file)
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
240

241 242 243 244 245 246 247 248 249
(define-obsolete-variable-alias 'doc-view-unoconv-program
                                'doc-view-odf->pdf-converter-program
                                "24.4")

(defcustom doc-view-odf->pdf-converter-program
  (cond
   ((executable-find "soffice") "soffice")
   ((executable-find "unoconv") "unoconv")
   (t "soffice"))
250 251 252
  "Program to convert any file type readable by OpenOffice.org to PDF.

Needed for viewing OpenOffice.org (and MS Office) files."
253
  :version "24.4"
254
  :type 'file)
255

256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
(defcustom doc-view-odf->pdf-converter-function
  (cond
   ((string-match "unoconv\\'" doc-view-odf->pdf-converter-program)
    #'doc-view-odf->pdf-converter-unoconv)
   ((string-match "soffice\\'" doc-view-odf->pdf-converter-program)
    #'doc-view-odf->pdf-converter-soffice))
  "Function to call to convert a ODF file into a PDF file."
  :type '(radio
          (function-item doc-view-odf->pdf-converter-unoconv
                         :doc "Use unoconv")
          (function-item doc-view-odf->pdf-converter-soffice
                         :doc "Use LibreOffice")
          function)
  :version "24.4")

271
(defcustom doc-view-ps2pdf-program "ps2pdf"
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
272 273 274
  "Program to convert PS files to PDF.

PS files will be converted to PDF before searching is possible."
275
  :type 'file)
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
276

277
(defcustom doc-view-pdftotext-program "pdftotext"
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
278 279 280
  "Program to convert PDF files to plain text.

Needed for searching."
281
  :type 'file)
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
282

283
(defcustom doc-view-cache-directory
284
  (expand-file-name (format "docview%d" (user-uid))
285
		    temporary-file-directory)
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
286
  "The base directory, where the PNG images will be saved."
287
  :type 'directory)
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
288

289 290
(defvar doc-view-conversion-buffer " *doc-view conversion output*"
  "The buffer where messages from the converter programs go to.")
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
291

292
(defcustom doc-view-conversion-refresh-interval 1
293 294
  "Interval in seconds between refreshes of the DocView buffer while converting.
After such a refresh newly converted pages will be available for
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
295 296 297
viewing.  If set to nil there won't be any refreshes and the
pages won't be displayed before conversion of the whole document
has finished."
298
  :type 'integer)
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
299

Juri Linkov's avatar
Juri Linkov committed
300
(defcustom doc-view-continuous nil
301 302 303 304 305 306 307
  "In Continuous mode reaching the page edge advances to next/previous page.
When non-nil, scrolling a line upward at the bottom edge of the page
moves to the next page, and scrolling a line downward at the top edge
of the page moves to the previous page."
  :type 'boolean
  :version "23.2")

Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
308 309
;;;; Internal Variables

310
(defvar-local doc-view--current-converter-processes nil
311 312
  "Only used internally.")

313
(defun doc-view-new-window-function (winprops)
314 315 316
  ;; (message "New window %s for buf %s" (car winprops) (current-buffer))
  (cl-assert (or (eq t (car winprops))
                 (eq (window-buffer (car winprops)) (current-buffer))))
317 318
  (let ((ol (image-mode-window-get 'overlay winprops)))
    (if ol
319
        (progn
320 321 322
          (setq ol (copy-overlay ol))
          ;; `ol' might actually be dead.
          (move-overlay ol (point-min) (point-max)))
323 324 325
      (setq ol (make-overlay (point-min) (point-max) nil t))
      (overlay-put ol 'doc-view t))
    (overlay-put ol 'window (car winprops))
326 327 328 329 330
    (unless (windowp (car winprops))
      ;; It's a pseudo entry.  Let's make sure it's not displayed (the
      ;; `window' property is only effective if its value is a window).
      (cl-assert (eq t (car winprops)))
      (delete-overlay ol))
Tassilo Horn's avatar
Tassilo Horn committed
331
    (image-mode-window-put 'overlay ol winprops)
332 333
    (when (and (windowp (car winprops))
               (stringp (overlay-get ol 'display))
334
               (null doc-view--current-converter-processes))
335 336 337 338 339
      ;; We're not displaying an image yet, so let's do so.  This happens when
      ;; the buffer is displayed for the first time.
      ;; Don't do it if there's a conversion is running, since in that case, it
      ;; will be done later.
      (with-selected-window (car winprops)
340
        (doc-view-goto-page (image-mode-window-get 'page t))))))
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
341

342
(defvar-local doc-view--current-files nil
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
343 344
  "Only used internally.")

345
(defvar-local doc-view--current-timer nil
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
346 347
  "Only used internally.")

348
(defvar-local doc-view--current-cache-dir nil
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
349 350
  "Only used internally.")

351
(defvar-local doc-view--current-search-matches nil
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
352 353
  "Only used internally.")

354
(defvar doc-view--pending-cache-flush nil
355
  "Only used internally.")
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
356

357
(defvar doc-view--buffer-file-name nil
358 359 360 361 362 363 364
  "Only used internally.
The file name used for conversion.  Normally it's the same as
`buffer-file-name', but for remote files, compressed files and
files inside an archive it is a temporary copy of
the (uncompressed, extracted) file residing in
`doc-view-cache-directory'.")

365 366 367 368
(defvar doc-view-doc-type nil
  "The type of document in the current buffer.
Can be `dvi', `pdf', or `ps'.")

369 370 371 372 373
(defvar doc-view-single-page-converter-function nil
  "Function to call to convert a single page of the document to a bitmap file.
May operate on the source document or on some intermediate (typically PDF)
conversion of it.")

374
(defvar-local doc-view--image-type nil
375 376 377
  "The type of image in the current buffer.
Can be `png' or `tiff'.")

378 379 380
(defvar-local doc-view--image-file-pattern nil
  "The `format' pattern of image file names.
Typically \"page-%s.png\".")
381

382
;;;; DocView Keymaps
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
383 384 385

(defvar doc-view-mode-map
  (let ((map (make-sparse-keymap)))
386
    (set-keymap-parent map image-mode-map)
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
387 388 389
    ;; Navigation in the document
    (define-key map (kbd "n")         'doc-view-next-page)
    (define-key map (kbd "p")         'doc-view-previous-page)
390 391 392 393
    (define-key map (kbd "<next>")    'forward-page)
    (define-key map (kbd "<prior>")   'backward-page)
    (define-key map [remap forward-page]  'doc-view-next-page)
    (define-key map [remap backward-page] 'doc-view-previous-page)
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
394
    (define-key map (kbd "SPC")       'doc-view-scroll-up-or-next-page)
395
    (define-key map (kbd "S-SPC")     'doc-view-scroll-down-or-previous-page)
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
396
    (define-key map (kbd "DEL")       'doc-view-scroll-down-or-previous-page)
397 398 399 400
    (define-key map (kbd "C-n")       'doc-view-next-line-or-next-page)
    (define-key map (kbd "<down>")    'doc-view-next-line-or-next-page)
    (define-key map (kbd "C-p")       'doc-view-previous-line-or-previous-page)
    (define-key map (kbd "<up>")      'doc-view-previous-line-or-previous-page)
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
401 402
    (define-key map (kbd "M-<")       'doc-view-first-page)
    (define-key map (kbd "M->")       'doc-view-last-page)
403
    (define-key map [remap goto-line] 'doc-view-goto-page)
404
    (define-key map (kbd "RET")       'image-next-line)
405 406
    ;; Zoom in/out.
    (define-key map "+"               'doc-view-enlarge)
407
    (define-key map "="               'doc-view-enlarge)
408
    (define-key map "-"               'doc-view-shrink)
409 410
    (define-key map "0"               'doc-view-scale-reset)
    (define-key map [remap text-scale-adjust] 'doc-view-scale-adjust)
411 412 413 414
    ;; Fit the image to the window
    (define-key map "W"               'doc-view-fit-width-to-window)
    (define-key map "H"               'doc-view-fit-height-to-window)
    (define-key map "P"               'doc-view-fit-page-to-window)
415
    (define-key map "F"               'doc-view-fit-window-to-page) ;F = frame
416
    ;; Killing the buffer (and the process)
417
    (define-key map (kbd "K")         'doc-view-kill-proc)
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
418 419 420
    ;; Slicing the image
    (define-key map (kbd "s s")       'doc-view-set-slice)
    (define-key map (kbd "s m")       'doc-view-set-slice-using-mouse)
421
    (define-key map (kbd "s b")       'doc-view-set-slice-from-bounding-box)
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
422 423 424 425
    (define-key map (kbd "s r")       'doc-view-reset-slice)
    ;; Searching
    (define-key map (kbd "C-s")       'doc-view-search)
    (define-key map (kbd "<find>")    'doc-view-search)
426
    (define-key map (kbd "C-r")       'doc-view-search-backward)
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
427 428
    ;; Show the tooltip
    (define-key map (kbd "C-t")       'doc-view-show-tooltip)
429 430
    ;; Toggle between text and image display or editing
    (define-key map (kbd "C-c C-c")   'doc-view-toggle-display)
431 432
    ;; Open a new buffer with doc's text contents
    (define-key map (kbd "C-c C-t")   'doc-view-open-text)
433
    (define-key map (kbd "r")         'revert-buffer)
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
434
    map)
435 436
  "Keymap used by `doc-view-mode' when displaying a doc as a set of images.")

437 438 439 440
(define-obsolete-function-alias 'doc-view-revert-buffer #'revert-buffer "27.1")
(defvar revert-buffer-preserve-modes)
(defun doc-view--revert-buffer (orig-fun &rest args)
  "Preserve the buffer's current mode and check PDF sanity."
441 442 443
  (if (< undo-outer-limit (* 2 (buffer-size)))
      ;; It's normal for this operation to result in a very large undo entry.
      (setq-local undo-outer-limit (* 2 (buffer-size))))
444
  (cl-labels ((revert ()
445 446
                      (let ((revert-buffer-preserve-modes t))
                        (apply orig-fun args))))
447 448 449
    (if (and (eq 'pdf doc-view-doc-type)
             (executable-find "pdfinfo"))
        ;; We don't want to revert if the PDF file is corrupted which
450
        ;; might happen when it is currently recompiled from a tex
451 452 453
        ;; file.  (TODO: We'd like to have something like that also
        ;; for other types, at least PS, but I don't know a good way
        ;; to test if a PS file is complete.)
454
        (if (= 0 (call-process "pdfinfo" nil nil nil
455 456 457 458 459
                               doc-view--buffer-file-name))
            (revert)
          (when (called-interactively-p 'interactive)
            (message "Can't revert right now because the file is corrupted.")))
      (revert))))
460 461


462 463 464
(easy-menu-define doc-view-menu doc-view-mode-map
  "Menu for Doc View mode."
  '("DocView"
Juri Linkov's avatar
Juri Linkov committed
465 466 467 468 469 470 471 472 473 474 475
    ["Toggle display"		doc-view-toggle-display]
    ("Continuous"
     ["Off"                     (setq doc-view-continuous nil)
      :style radio :selected    (eq doc-view-continuous nil)]
     ["On"		        (setq doc-view-continuous t)
      :style radio :selected    (eq doc-view-continuous t)]
     "---"
     ["Save as Default"
      (customize-save-variable 'doc-view-continuous doc-view-continuous) t]
     )
    "---"
476
    ["Set Slice"		doc-view-set-slice-using-mouse]
477
    ["Set Slice (BoundingBox)"  doc-view-set-slice-from-bounding-box]
478 479 480 481
    ["Set Slice (manual)"	doc-view-set-slice]
    ["Reset Slice"		doc-view-reset-slice]
    "---"
    ["Search"			doc-view-search]
482
    ["Search Backwards"         doc-view-search-backward]
483 484
    ))

485
(defvar doc-view-minor-mode-map
486 487 488 489
  (let ((map (make-sparse-keymap)))
    ;; Toggle between text and image display or editing
    (define-key map (kbd "C-c C-c") 'doc-view-toggle-display)
    map)
490
  "Keymap used by `doc-minor-view-mode'.")
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
491 492 493

;;;; Navigation Commands

494 495
;; FIXME: The doc-view-current-* definitions below are macros because they
;; map to accessors which we want to use via `setf' as well!
496 497
(defmacro doc-view-current-page (&optional win)
  `(image-mode-window-get 'page ,win))
498 499 500 501
(defmacro doc-view-current-info () '(image-mode-window-get 'info))
(defmacro doc-view-current-overlay () '(image-mode-window-get 'overlay))
(defmacro doc-view-current-image () '(image-mode-window-get 'image))
(defmacro doc-view-current-slice () '(image-mode-window-get 'slice))
502

503
(defun doc-view-last-page-number ()
504
  (length doc-view--current-files))
505

Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
506 507 508
(defun doc-view-goto-page (page)
  "View the page given by PAGE."
  (interactive "nPage: ")
509
  (let ((len (doc-view-last-page-number)))
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
510
    (if (< page 1)
511
	(setq page 1)
512 513 514
      (when (and (> page len)
                 ;; As long as the converter is running, we don't know
                 ;; how many pages will be available.
515
                 (null doc-view--current-converter-processes))
516
	(setq page len)))
517
    (force-mode-line-update)            ;To update `current-page'.
518 519
    (setf (doc-view-current-page) page
	  (doc-view-current-info)
520 521
	  (concat
	   (propertize
522
	    (format "Page %d of %d." page len) 'face 'bold)
523
	   ;; Tell user if converting isn't finished yet
524
	   (if doc-view--current-converter-processes
525 526 527
	       " (still converting...)\n"
	     "\n")
	   ;; Display context infos if this page matches the last search
528 529
	   (when (and doc-view--current-search-matches
		      (assq page doc-view--current-search-matches))
530 531
	     (concat (propertize "Search matches:\n" 'face 'bold)
		     (let ((contexts ""))
532
		       (dolist (m (cdr (assq page
533
					     doc-view--current-search-matches)))
534 535
			 (setq contexts (concat contexts "  - \"" m "\"\n")))
		       contexts)))))
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
536
    ;; Update the buffer
537
    ;; We used to find the file name from doc-view--current-files but
538
    ;; that's not right if the pages are not generated sequentially
539
    ;; or if the page isn't in doc-view--current-files yet.
540
    (let ((file (expand-file-name
541
                 (format doc-view--image-file-pattern page)
542
                 (doc-view--current-cache-dir))))
543 544
      (doc-view-insert-image file :pointer 'arrow)
      (when (and (not (file-exists-p file))
545
                 doc-view--current-converter-processes)
546
        ;; The PNG file hasn't been generated yet.
547
        (funcall doc-view-single-page-converter-function
548
		 doc-view--buffer-file-name file page
549 550 551 552 553 554 555 556 557 558
		 (let ((win (selected-window)))
		   (lambda ()
		     (and (eq (current-buffer) (window-buffer win))
			  ;; If we changed page in the mean
			  ;; time, don't mess things up.
			  (eq (doc-view-current-page win) page)
			  ;; Make sure we don't infloop.
			  (file-readable-p file)
			  (with-selected-window win
			    (doc-view-goto-page page))))))))
559
    (overlay-put (doc-view-current-overlay)
Tassilo Horn's avatar
Tassilo Horn committed
560
		 'help-echo (doc-view-current-info))))
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
561 562 563 564

(defun doc-view-next-page (&optional arg)
  "Browse ARG pages forward."
  (interactive "p")
565
  (doc-view-goto-page (+ (doc-view-current-page) (or arg 1))))
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
566 567 568 569

(defun doc-view-previous-page (&optional arg)
  "Browse ARG pages backward."
  (interactive "p")
570
  (doc-view-goto-page (- (doc-view-current-page) (or arg 1))))
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
571 572 573 574 575 576 577 578 579

(defun doc-view-first-page ()
  "View the first page."
  (interactive)
  (doc-view-goto-page 1))

(defun doc-view-last-page ()
  "View the last page."
  (interactive)
580
  (doc-view-goto-page (doc-view-last-page-number)))
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
581

582 583
(defun doc-view-scroll-up-or-next-page (&optional arg)
  "Scroll page up ARG lines if possible, else goto next page.
Juri Linkov's avatar
Juri Linkov committed
584
When `doc-view-continuous' is non-nil, scrolling upward
585 586 587
at the bottom edge of the page moves to the next page.
Otherwise, goto next page only on typing SPC (ARG is nil)."
  (interactive "P")
Juri Linkov's avatar
Juri Linkov committed
588
  (if (or doc-view-continuous (null arg))
589 590 591 592 593 594 595 596 597 598 599 600
      (let ((hscroll (window-hscroll))
	    (cur-page (doc-view-current-page)))
	(when (= (window-vscroll) (image-scroll-up arg))
	  (doc-view-next-page)
	  (when (/= cur-page (doc-view-current-page))
	    (image-bob)
	    (image-bol 1))
	  (set-window-hscroll (selected-window) hscroll)))
    (image-scroll-up arg)))

(defun doc-view-scroll-down-or-previous-page (&optional arg)
  "Scroll page down ARG lines if possible, else goto previous page.
Juri Linkov's avatar
Juri Linkov committed
601
When `doc-view-continuous' is non-nil, scrolling downward
602 603 604
at the top edge of the page moves to the previous page.
Otherwise, goto previous page only on typing DEL (ARG is nil)."
  (interactive "P")
Juri Linkov's avatar
Juri Linkov committed
605
  (if (or doc-view-continuous (null arg))
606 607 608 609 610 611 612 613 614 615 616 617
      (let ((hscroll (window-hscroll))
	    (cur-page (doc-view-current-page)))
	(when (= (window-vscroll) (image-scroll-down arg))
	  (doc-view-previous-page)
	  (when (/= cur-page (doc-view-current-page))
	    (image-eob)
	    (image-bol 1))
	  (set-window-hscroll (selected-window) hscroll)))
    (image-scroll-down arg)))

(defun doc-view-next-line-or-next-page (&optional arg)
  "Scroll upward by ARG lines if possible, else goto next page.
Juri Linkov's avatar
Juri Linkov committed
618
When `doc-view-continuous' is non-nil, scrolling a line upward
619
at the bottom edge of the page moves to the next page."
620
  (interactive "p")
Juri Linkov's avatar
Juri Linkov committed
621
  (if doc-view-continuous
622 623
      (let ((hscroll (window-hscroll))
	    (cur-page (doc-view-current-page)))
624
	(when (= (window-vscroll) (image-next-line arg))
625 626 627 628 629
	  (doc-view-next-page)
	  (when (/= cur-page (doc-view-current-page))
	    (image-bob)
	    (image-bol 1))
	  (set-window-hscroll (selected-window) hscroll)))
630
    (image-next-line arg)))
631

632 633
(defun doc-view-previous-line-or-previous-page (&optional arg)
  "Scroll downward by ARG lines if possible, else goto previous page.
Juri Linkov's avatar
Juri Linkov committed
634
When `doc-view-continuous' is non-nil, scrolling a line downward
635 636
at the top edge of the page moves to the previous page."
  (interactive "p")
Juri Linkov's avatar
Juri Linkov committed
637
  (if doc-view-continuous
638 639
      (let ((hscroll (window-hscroll))
	    (cur-page (doc-view-current-page)))
640
	(when (= (window-vscroll) (image-previous-line arg))
641 642 643 644 645
	  (doc-view-previous-page)
	  (when (/= cur-page (doc-view-current-page))
	    (image-eob)
	    (image-bol 1))
	  (set-window-hscroll (selected-window) hscroll)))
646
    (image-previous-line arg)))
647

648 649
;;;; Utility Functions

650
(defun doc-view-kill-proc ()
651
  "Kill the current converter process(es)."
652
  (interactive)
653
  (while (consp doc-view--current-converter-processes)
654 655
    (ignore-errors ;; Some entries might not be processes, and maybe
		   ;; some are dead already?
656 657 658 659
      (kill-process (pop doc-view--current-converter-processes))))
  (when doc-view--current-timer
    (cancel-timer doc-view--current-timer)
    (setq doc-view--current-timer nil))
660 661
  (setq mode-line-process nil))

662 663
(define-obsolete-function-alias 'doc-view-kill-proc-and-buffer
  #'image-kill-buffer "25.1")
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
664

665 666
(defun doc-view-make-safe-dir (dir)
  (condition-case nil
667 668 669 670
      ;; Create temp files with strict access rights.  It's easy to
      ;; loosen them later, whereas it's impossible to close the
      ;; time-window of loose permissions otherwise.
      (with-file-modes #o0700 (make-directory dir))
671
    (file-already-exists
672 673
     (when (file-symlink-p dir)
       (error "Danger: %s points to a symbolic link" dir))
674 675 676 677 678 679 680 681
     ;; In case it was created earlier with looser rights.
     ;; We could check the mode info returned by file-attributes, but it's
     ;; a pain to parse and it may not tell you what we want under
     ;; non-standard file-systems.  So let's just say what we want and let
     ;; the underlying C code and file-system figure it out.
     ;; This also ends up checking a bunch of useful conditions: it makes
     ;; sure we have write-access to the directory and that we own it, thus
     ;; closing a bunch of security holes.
682 683 684 685 686
     (condition-case error
	 (set-file-modes dir #o0700)
       (file-error
	(error
	 (format "Unable to use temporary directory %s: %s"
687
		 dir (mapconcat #'identity (cdr error) " "))))))))
688

689
(defun doc-view--current-cache-dir ()
690 691
  "Return the directory where the png files of the current doc should be saved.
It's a subdirectory of `doc-view-cache-directory'."
692 693
  (if doc-view--current-cache-dir
      doc-view--current-cache-dir
694 695 696
    ;; Try and make sure doc-view-cache-directory exists and is safe.
    (doc-view-make-safe-dir doc-view-cache-directory)
    ;; Now compute the subdirectory to use.
697
    (setq doc-view--current-cache-dir
698
	  (file-name-as-directory
699
	   (expand-file-name
700 701
	    (concat (thread-last
                        (file-name-nondirectory doc-view--buffer-file-name)
702 703
                      ;; bug#13679
                      (subst-char-in-string ?% ?_)
Paul Eggert's avatar
Paul Eggert committed
704
                      ;; arc-mode concatenates archive name and file name
705
                      ;; with colon, which isn't allowed on MS-Windows.
706 707 708 709 710 711 712
                      (subst-char-in-string ?: ?_))
                    "-"
                    (let ((file doc-view--buffer-file-name))
                      (with-temp-buffer
                        (set-buffer-multibyte nil)
                        (insert-file-contents-literally file)
                        (md5 (current-buffer)))))
713
            doc-view-cache-directory)))))
714

715 716
;;;###autoload
(defun doc-view-mode-p (type)
717 718 719
  "Return non-nil if document type TYPE is available for `doc-view'.
Document types are symbols like `dvi', `ps', `pdf', or `odf' (any
OpenDocument format)."
720
  (and (display-graphic-p)
721 722
       (or (image-type-available-p 'imagemagick)
	   (image-type-available-p 'png))
723 724 725
       (cond
	((eq type 'dvi)
	 (and (doc-view-mode-p 'pdf)
726 727 728 729
	      (or (and doc-view-dvipdf-program
		       (executable-find doc-view-dvipdf-program))
		  (and doc-view-dvipdfm-program
		       (executable-find doc-view-dvipdfm-program)))))
730
	((memq type '(postscript ps eps pdf))
731
	 ;; FIXME: allow mupdf here
732 733
	 (and doc-view-ghostscript-program
	      (executable-find doc-view-ghostscript-program)))
734
	((eq type 'odf)
735 736
	 (and doc-view-odf->pdf-converter-program
	      (executable-find doc-view-odf->pdf-converter-program)
737
	      (doc-view-mode-p 'pdf)))
738 739
	((eq type 'djvu)
	 (executable-find "ddjvu"))
740 741 742
	(t ;; unknown image type
	 nil))))

Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
743 744
;;;; Conversion Functions

745 746 747
(defvar doc-view-shrink-factor 1.125)

(defun doc-view-enlarge (factor)
748
  "Enlarge the document by FACTOR."
749
  (interactive (list doc-view-shrink-factor))
750 751 752
  (if (and doc-view-scale-internally
           (eq (plist-get (cdr (doc-view-current-image)) :type)
               'imagemagick))
753 754 755
      ;; ImageMagick supports on-the-fly-rescaling.
      (let ((new (ceiling (* factor doc-view-image-width))))
        (unless (equal new doc-view-image-width)
756
          (setq-local doc-view-image-width new)
757 758 759 760 761
          (doc-view-insert-image
           (plist-get (cdr (doc-view-current-image)) :file)
           :width doc-view-image-width)))
    (let ((new (ceiling (* factor doc-view-resolution))))
      (unless (equal new doc-view-resolution)
762
        (setq-local doc-view-resolution new)
763
        (doc-view-reconvert-doc)))))
764 765 766 767 768 769

(defun doc-view-shrink (factor)
  "Shrink the document."
  (interactive (list doc-view-shrink-factor))
  (doc-view-enlarge (/ 1.0 factor)))

770
(defun doc-view-scale-reset ()
771 772 773 774 775 776 777 778 779 780 781 782 783
  "Reset the document size/zoom level to the initial one."
  (interactive)
  (if (and doc-view-scale-internally
           (eq (plist-get (cdr (doc-view-current-image)) :type)
               'imagemagick))
      (progn
	(kill-local-variable 'doc-view-image-width)
	(doc-view-insert-image
	 (plist-get (cdr (doc-view-current-image)) :file)
	 :width doc-view-image-width))
    (kill-local-variable 'doc-view-resolution)
    (doc-view-reconvert-doc)))

784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801
(defun doc-view-scale-adjust (factor)
  "Adjust the scale of the DocView page images by FACTOR.
FACTOR defaults to `doc-view-shrink-factor'.

The actual adjustment made depends on the final component of the
key-binding used to invoke the command, with all modifiers removed:

   +, =   Increase the image scale by FACTOR
   -      Decrease the image scale by FACTOR
   0      Reset the image scale to the initial scale"
  (interactive (list doc-view-shrink-factor))
  (let ((ev last-command-event)
	(echo-keystrokes nil))
    (pcase (event-basic-type ev)
      ((or ?+ ?=) (doc-view-enlarge factor))
      (?-         (doc-view-shrink factor))
      (?0         (doc-view-scale-reset)))))

802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862
(defun doc-view-fit-width-to-window ()
  "Fit the image width to the window width."
  (interactive)
  (let ((win-width (- (nth 2 (window-inside-pixel-edges))
                      (nth 0 (window-inside-pixel-edges))))
        (slice (doc-view-current-slice)))
    (if (not slice)
        (let ((img-width (car (image-display-size
                               (image-get-display-property) t))))
          (doc-view-enlarge (/ (float win-width) (float img-width))))

      ;; If slice is set
      (let* ((slice-width (nth 2 slice))
             (scale-factor (/ (float win-width) (float slice-width)))
             (new-slice (mapcar (lambda (x) (ceiling (* scale-factor x))) slice)))

        (doc-view-enlarge scale-factor)
        (setf (doc-view-current-slice) new-slice)
        (doc-view-goto-page (doc-view-current-page))))))

(defun doc-view-fit-height-to-window ()
  "Fit the image height to the window height."
  (interactive)
  (let ((win-height (- (nth 3 (window-inside-pixel-edges))
                       (nth 1 (window-inside-pixel-edges))))
        (slice (doc-view-current-slice)))
    (if (not slice)
        (let ((img-height (cdr (image-display-size
                                (image-get-display-property) t))))
          ;; When users call 'doc-view-fit-height-to-window',
          ;; they might want to go to next page by typing SPC
          ;; ONLY once. So I used '(- win-height 1)' instead of
          ;; 'win-height'
          (doc-view-enlarge (/ (float (- win-height 1)) (float img-height))))

      ;; If slice is set
      (let* ((slice-height (nth 3 slice))
             (scale-factor (/ (float (- win-height 1)) (float slice-height)))
             (new-slice (mapcar (lambda (x) (ceiling (* scale-factor x))) slice)))

        (doc-view-enlarge scale-factor)
        (setf (doc-view-current-slice) new-slice)
        (doc-view-goto-page (doc-view-current-page))))))

(defun doc-view-fit-page-to-window ()
  "Fit the image to the window.
More specifically, this function enlarges image by:

min {(window-width / image-width), (window-height / image-height)} times."
  (interactive)
  (let ((win-width (- (nth 2 (window-inside-pixel-edges))
                      (nth 0 (window-inside-pixel-edges))))
        (win-height (- (nth 3 (window-inside-pixel-edges))
                       (nth 1 (window-inside-pixel-edges))))
        (slice (doc-view-current-slice)))
    (if (not slice)
        (let ((img-width (car (image-display-size
                               (image-get-display-property) t)))
              (img-height (cdr (image-display-size
                                (image-get-display-property) t))))
          (doc-view-enlarge (min (/ (float win-width) (float img-width))
863 864
                                 (/ (float (- win-height 1))
                                    (float img-height)))))
865 866 867 868
      ;; If slice is set
      (let* ((slice-width (nth 2 slice))
             (slice-height (nth 3 slice))
             (scale-factor (min (/ (float win-width) (float slice-width))
869 870
                                (/ (float (- win-height 1))
                                   (float slice-height))))
871 872 873 874 875
             (new-slice (mapcar (lambda (x) (ceiling (* scale-factor x))) slice)))
        (doc-view-enlarge scale-factor)
        (setf (doc-view-current-slice) new-slice)
        (doc-view-goto-page (doc-view-current-page))))))

876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907
(defun doc-view-fit-window-to-page ()
  "Resize selected window so it just fits the current page.
Resize the containing frame if needed."
  (interactive)
  (let* ((slice (doc-view-current-slice))
         (img-width  (if slice (nth 2 slice)
                       (car (image-display-size
                             (image-get-display-property) t))))
         (img-height (if slice (nth 3 slice)
                       (cdr (image-display-size
                             (image-get-display-property) t))))
         (win-width  (- (nth 2 (window-inside-pixel-edges))
                        (nth 0 (window-inside-pixel-edges))))
         (win-height (- (nth 3 (window-inside-pixel-edges))
                        (nth 1 (window-inside-pixel-edges))))
         (width-diff  (- img-width  win-width))
         (height-diff (- img-height win-height))
         (new-frame-params
          (append
           (if (= (window-width) (frame-width))
               `((width  . (text-pixels
                            . ,(+ (frame-text-width) width-diff))))
             (enlarge-window (/ width-diff (frame-char-width)) 'horiz)
             nil)
           (if (= (window-height) (frame-height))
               `((height  . (text-pixels
                             . ,(+ (frame-text-height) height-diff))))
             (enlarge-window (/ height-diff (frame-char-height)) nil)
             nil))))
    (when new-frame-params
      (modify-frame-parameters (selected-frame) new-frame-params))))

908
(defun doc-view-reconvert-doc ()
909 910 911
  "Reconvert the current document.
Should be invoked when the cached images aren't up-to-date."
  (interactive)
912 913
  (doc-view-kill-proc)
  ;; Clear the old cached files
914 915
  (when (file-exists-p (doc-view--current-cache-dir))
    (delete-directory (doc-view--current-cache-dir) 'recursive))
916
  (kill-local-variable 'doc-view-last-page-number)
917
  (doc-view-initiate-display))
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
918

919 920
(defun doc-view-sentinel (proc event)
  "Generic sentinel for doc-view conversion processes."
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
921
  (if (not (string-match "finished" event))
922
      (message "DocView: process %s changed status to %s."
923 924 925 926
               (process-name proc)
	       (if (string-match "\\(.+\\)\n?\\'" event)
		   (match-string 1 event)
		 event))
927 928
    (when (buffer-live-p (process-get proc 'buffer))
      (with-current-buffer (process-get proc 'buffer)
929 930
        (setq doc-view--current-converter-processes
              (delq proc doc-view--current-converter-processes))
931
        (setq mode-line-process
932 933
              (if doc-view--current-converter-processes
                  (format ":%s" (car doc-view--current-converter-processes))))
934 935 936
        (funcall (process-get proc 'callback))))))

(defun doc-view-start-process (name program args callback)
937 938
  ;; Make sure the process is started in an existing directory, (rather than
  ;; some file-name-handler-managed dir, for example).
939 940
  (let* ((default-directory (or (unhandled-file-name-directory
                                 default-directory)
941
			      (expand-file-name "~/")))
942
         (proc (apply #'start-process name doc-view-conversion-buffer
943
                      program args)))
944
    (push proc doc-view--current-converter-processes)
945 946 947 948
    (setq mode-line-process (list (format ":%s" proc)))
    (set-process-sentinel proc 'doc-view-sentinel)
    (process-put proc 'buffer   (current-buffer))
    (process-put proc 'callback callback)))
949 950 951

(defun doc-view-dvi->pdf (dvi pdf callback)
  "Convert DVI to PDF asynchronously and call CALLBACK when finished."
952 953 954 955 956
  ;; Prefer dvipdf over dvipdfm, because the latter has problems if the DVI
  ;; references and includes other PS files.
  (if (and doc-view-dvipdf-program
	   (executable-find doc-view-dvipdf-program))
      (doc-view-start-process "dvi->pdf" doc-view-dvipdf-program
957 958
			      (list dvi pdf)
			      callback)
959 960 961
    (doc-view-start-process "dvi->pdf" doc-view-dvipdfm-program
			    (list "-o" pdf dvi)
			    callback)))
962

963 964 965 966 967 968 969 970 971 972 973
(defun doc-view-pdf-password-protected-ghostscript-p (pdf)
  "Return non-nil if a PDF file is password-protected.
The test is performed using `doc-view-ghostscript-program'."
  (with-temp-buffer
    (apply #'call-process doc-view-ghostscript-program nil (current-buffer)
           nil `(,@doc-view-ghostscript-options
                 "-sNODISPLAY"
                 ,pdf))
    (goto-char (point-min))
    (search-forward "This file requires a password for access." nil t)))

974
(defun doc-view-pdf->png-converter-ghostscript (pdf png page callback)
975 976 977 978 979 980 981 982 983 984 985 986 987
  (let ((pdf-passwd (if (doc-view-pdf-password-protected-ghostscript-p pdf)
                        (read-passwd "Enter password for PDF file: "))))
    (doc-view-start-process
     "pdf/ps->png" doc-view-ghostscript-program
     `(,@doc-view-ghostscript-options
       ,(concat "-sDEVICE=" doc-view-ghostscript-device)
       ,(format "-r%d" (round doc-view-resolution))
       ,@(if page `(,(format "-dFirstPage=%d" page)))
       ,@(if page `(,(format "-dLastPage=%d" page)))
       ,@(if pdf-passwd `(,(format "-sPDFPassword=%s" pdf-passwd)))
       ,(concat "-sOutputFile=" png)
       ,pdf)
     callback)))
988 989 990 991

(defalias 'doc-view-ps->png-converter-ghostscript
  'doc-view-pdf->png-converter-ghostscript)

992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007
(defun doc-view-djvu->tiff-converter-ddjvu (djvu tiff page callback)
  "Convert PAGE of a DJVU file to bitmap(s) asynchronously.
Call CALLBACK with no arguments when done.
If PAGE is nil, convert the whole document."
  (doc-view-start-process
   "djvu->tiff" "ddjvu"
   `("-format=tiff"
     ;; ddjvu only accepts the range 1-999.
     ,(format "-scale=%d" (round doc-view-resolution))
     ;; -eachpage was only added after djvulibre-3.5.25.3!
     ,@(unless page '("-eachpage"))
     ,@(if page `(,(format "-page=%d" page)))
     ,djvu
     ,tiff)
   callback))

1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
(defun doc-view-pdfdraw-program-subcommand ()
  "Return the mutool subcommand replacing mudraw.
Recent MuPDF distributions replaced 'mudraw' with 'mutool draw'."
  (when (string-match "mutool[^/\\]*$" doc-view-pdfdraw-program)
    '("draw")))

(defun doc-view-pdf-password-protected-pdfdraw-p (pdf)
  "Return non-nil if a PDF file is password-protected.
The test is performed using `doc-view-pdfdraw-program'."
  (with-temp-buffer
    (apply #'call-process doc-view-pdfdraw-program nil (current-buffer) nil
           `(,@(doc-view-pdfdraw-program-subcommand)
             ,(concat "-o" null-device)
             ;; In case PDF isn't password-protected, "draw" only one page.
             ,pdf "1"))
    (goto-char (point-min))
    (search-forward "error: cannot authenticate password" nil t)))

1026
(defun doc-view-pdf->png-converter-mupdf (pdf png page callback)
1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
  (let ((pdf-passwd (if (doc-view-pdf-password-protected-pdfdraw-p pdf)
                        (read-passwd "Enter password for PDF file: "))))
    (doc-view-start-process
     "pdf->png" doc-view-pdfdraw-program
     `(,@(doc-view-pdfdraw-program-subcommand)
       ,(concat "-o" png)
       ,(format "-r%d" (round doc-view-resolution))
       ,@(if pdf-passwd `("-p" ,pdf-passwd))
       ,pdf
       ,@(if page `(,(format "%d" page))))
     callback)))
1038

1039
(defun doc-view-odf->pdf-converter-unoconv (odf callback)
1040 1041 1042
  "Convert ODF to PDF asynchronously and call CALLBACK when finished.
The converted PDF is put into the current cache directory, and it
is named like ODF with the extension turned to pdf."
1043
  (doc-view-start-process "odf->pdf" doc-view-odf->pdf-converter-program
1044
			  (list "-f" "pdf" "-o" (doc-view--current-cache-dir) odf)
1045
			  callback))
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
1046

1047 1048 1049 1050
(defun doc-view-odf->pdf-converter-soffice (odf callback)
  "Convert ODF to PDF asynchronously and call CALLBACK when finished.
The converted PDF is put into the current cache directory, and it
is named like ODF with the extension turned to pdf."
1051 1052 1053 1054 1055 1056 1057 1058 1059
  ;; FIXME: soffice doesn't work when there's another running
  ;; LibreOffice instance, in which case it returns success without
  ;; actually doing anything.  See LibreOffice bug
  ;; https://bugs.freedesktop.org/show_bug.cgi?id=37531.  A workaround
  ;; is to start soffice with a separate UserInstallation directory.
  (let ((tmp-user-install-dir (make-temp-file "libreoffice-docview" t)))
    (doc-view-start-process "odf->pdf" doc-view-odf->pdf-converter-program
			    (list
			     (concat "-env:UserInstallation=file://"
1060 1061 1062 1063 1064
                                     ;; The URL must be
                                     ;; file:///C:/tmp/dir on Windows.
                                     ;; https://wiki.documentfoundation.org/UserProfile.
                                     (when (eq system-type 'windows-nt)
                                       "/")
1065 1066
				     tmp-user-install-dir)
			     "--headless" "--convert-to" "pdf"
1067
			     "--outdir" (doc-view--current-cache-dir) odf)
1068 1069 1070
			    (lambda ()
			      (delete-directory tmp-user-install-dir t)
			      (funcall callback)))))
1071

Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
1072
(defun doc-view-pdf/ps->png (pdf-ps png)
1073
  ;; FIXME: Fix name and docstring to account for djvu&tiff.
1074
  "Convert PDF-PS to PNG asynchronously."
1075 1076
  (funcall
   (pcase doc-view-doc-type
1077 1078
     ('pdf doc-view-pdf->png-converter-function)
     ('djvu #'doc-view-djvu->tiff-converter-ddjvu)
1079 1080
     (_ #'doc-view-ps->png-converter-ghostscript))
   pdf-ps png nil
1081
   (let ((resolution doc-view-resolution))
1082 1083 1084 1085 1086
     (lambda ()
       ;; Only create the resolution file when it's all done, so it also
       ;; serves as a witness that the conversion is complete.
       (write-region (prin1-to-string resolution) nil
                     (expand-file-name "resolution.el"
1087
                                       (doc-view--current-cache-dir))
1088
                     nil 'silently)
1089 1090 1091
       (when doc-view--current-timer
         (cancel-timer doc-view--current-timer)
         (setq doc-view--current-timer nil))
1092 1093
       (doc-view-display (current-buffer) 'force))))

1094
  ;; Update the displayed pages as soon as they're done generating.
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
1095
  (when doc-view-conversion-refresh-interval
1096
    (setq doc-view--current-timer
1097 1098 1099 1100
          (run-at-time "1 secs" doc-view-conversion-refresh-interval
                       'doc-view-display
                       (current-buffer)))))

1101 1102
(declare-function clear-image-cache "image.c" (&optional filter))

1103
(defun doc-view-document->bitmap (pdf png pages)
1104
  "Convert a document file to bitmap images asynchronously.
1105 1106 1107 1108 1109 1110 1111
Start by converting PAGES, and then the rest."
  (if (null pages)
      (doc-view-pdf/ps->png pdf png)
    ;; We could render several `pages' with a single process if they're
    ;; (almost) consecutive, but since in 99% of the cases, there'll be only
    ;; a single page anyway, and of the remaining 1%, few cases will have
    ;; consecutive pages, it's not worth the trouble.
1112
    (let ((rest (cdr pages)))
1113
      (funcall doc-view-single-page-converter-function
1114
	       pdf (format png (car pages)) (car pages)
1115 1116
       (lambda ()
         (if rest
1117
             (doc-view-document->bitmap pdf png rest)
1118 1119
           ;; Yippie, the important pages are done, update the display.
           (clear-image-cache)
1120 1121 1122 1123 1124
           ;; For the windows that have a message (like "Welcome to
           ;; DocView") display property, clearing the image cache is
           ;; not sufficient.
           (dolist (win (get-buffer-window-list (current-buffer) nil 'visible))
             (with-selected-window win
1125
	       (when (stringp (overlay-get (doc-view-current-overlay) 'display))
1126
		 (doc-view-goto-page (doc-view-current-page)))))
1127 1128
           ;; Convert the rest of the pages.
           (doc-view-pdf/ps->png pdf png)))))))
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
1129

1130 1131
(defun doc-view-pdf->txt (pdf txt callback)
  "Convert PDF to TXT asynchronously and call CALLBACK when finished."
1132
  (or (executable-find doc-view-pdftotext-program)
1133
      (error "You need the `pdftotext' program to convert a PDF to text"))
1134 1135 1136
  (doc-view-start-process "pdf->txt" doc-view-pdftotext-program
                          (list "-raw" pdf txt)
                          callback))
1137

1138 1139 1140
(defun doc-view-current-cache-doc-pdf ()
  "Return the name of the doc.pdf in the current cache dir.
  This file exists only if the current document isn't a PDF or PS file already."
1141
  (expand-file-name "doc.pdf" (doc-view--current-cache-dir)))
1142

1143 1144
(defun doc-view-doc->txt (txt callback)
  "Convert the current document to text and call CALLBACK when done."
1145
  (make-directory (doc-view--current-cache-dir) t)
1146
  (pcase doc-view-doc-type
1147
    ('pdf