; Merge from origin/emacs-25
[emacs.git] / lisp / doc-view.el
blob223565cedb6a639d66ba6d152cf73ea58ec6026a
1 ;;; doc-view.el --- View PDF/PostScript/DVI files in Emacs -*- lexical-binding: t -*-
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
9 ;; This file is part of GNU Emacs.
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.
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.
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/>.
24 ;;; Requirements:
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/).
31 ;;; Commentary:
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.
38 ;; To use it simply open a document file with
40 ;; C-x C-f ~/path/to/document RET
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.
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'.
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.
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').
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.
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'.
91 ;;; Configuration:
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.)
97 ;; This and all other options can be set with the customization interface.
98 ;; Simply do
100 ;; M-x customize-group RET doc-view RET
102 ;; and modify them to your needs.
104 ;;; Todo:
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).
114 ;;;; About isearch support
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.
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.
134 ;; Anyway, if someone with better isearch knowledge wants to give it a try,
135 ;; feel free to do it. --Tassilo
137 ;;; Code:
139 (require 'cl-lib)
140 (require 'dired)
141 (require 'image-mode)
142 (require 'jka-compr)
143 (require 'subr-x)
145 ;;;; Customization Options
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-")
156 (defcustom doc-view-ghostscript-program "gs"
157 "Program to convert PS and PDF files to PNG."
158 :type 'file
159 :group 'doc-view)
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")
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")
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)
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)
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)
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)
213 (defcustom doc-view-dvipdfm-program "dvipdfm"
214 "Program to convert DVI files to PDF.
216 DVI file will be converted to PDF before the resulting PDF is
217 converted to PNG.
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)
224 (defcustom doc-view-dvipdf-program "dvipdf"
225 "Program to convert DVI files to PDF.
227 DVI file will be converted to PDF before the resulting PDF is
228 converted to PNG.
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)
235 (define-obsolete-variable-alias 'doc-view-unoconv-program
236 'doc-view-odf->pdf-converter-program
237 "24.4")
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.
246 Needed for viewing OpenOffice.org (and MS Office) files."
247 :version "24.4"
248 :type 'file
249 :group 'doc-view)
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")
266 (defcustom doc-view-ps2pdf-program "ps2pdf"
267 "Program to convert PS files to PDF.
269 PS files will be converted to PDF before searching is possible."
270 :type 'file
271 :group 'doc-view)
273 (defcustom doc-view-pdftotext-program "pdftotext"
274 "Program to convert PDF files to plain text.
276 Needed for searching."
277 :type 'file
278 :group 'doc-view)
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)
287 (defvar doc-view-conversion-buffer " *doc-view conversion output*"
288 "The buffer where messages from the converter programs go to.")
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)
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")
308 ;;;; Internal Variables
310 (defvar-local doc-view--current-converter-processes nil
311 "Only used internally.")
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))))))
342 (defvar-local doc-view--current-files nil
343 "Only used internally.")
345 (defvar-local doc-view--current-timer nil
346 "Only used internally.")
348 (defvar-local doc-view--current-cache-dir nil
349 "Only used internally.")
351 (defvar-local doc-view--current-search-matches nil
352 "Only used internally.")
354 (defvar doc-view--pending-cache-flush nil
355 "Only used internally.")
357 (defvar doc-view--previous-major-mode nil
358 "Only used internally.")
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'.")
368 (defvar doc-view-doc-type nil
369 "The type of document in the current buffer.
370 Can be `dvi', `pdf', or `ps'.")
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.")
377 (defvar-local doc-view--image-type nil
378 "The type of image in the current buffer.
379 Can be `png' or `tiff'.")
381 (defvar-local doc-view--image-file-pattern nil
382 "The `format' pattern of image file names.
383 Typically \"page-%s.png\".")
385 ;;;; DocView Keymaps
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.")
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))))
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]
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]
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'.")
493 ;;;; Navigation Commands
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))
502 (defun doc-view-last-page-number ()
503 (length doc-view--current-files))
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))))
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))))
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))))
571 (defun doc-view-first-page ()
572 "View the first page."
573 (interactive)
574 (doc-view-goto-page 1))
576 (defun doc-view-last-page ()
577 "View the last page."
578 (interactive)
579 (doc-view-goto-page (doc-view-last-page-number)))
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)))
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)))
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 arg)))
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)))
647 ;;;; Utility Functions
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))
661 (define-obsolete-function-alias 'doc-view-kill-proc-and-buffer
662 #'image-kill-buffer "25.1")
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) " "))))))))
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
700 (file-name-nondirectory doc-view--buffer-file-name)
701 ;; bug#13679
702 (subst-char-in-string ?% ?_)
703 ;; arc-mode concatenates archive name and file name
704 ;; with colon, which isn't allowed on MS-Windows.
705 (subst-char-in-string ?: ?_))
707 (let ((file doc-view--buffer-file-name))
708 (with-temp-buffer
709 (set-buffer-multibyte nil)
710 (insert-file-contents-literally file)
711 (md5 (current-buffer)))))
712 doc-view-cache-directory)))))
714 ;;;###autoload
715 (defun doc-view-mode-p (type)
716 "Return non-nil if document type TYPE is available for `doc-view'.
717 Document types are symbols like `dvi', `ps', `pdf', or `odf' (any
718 OpenDocument format)."
719 (and (display-graphic-p)
720 (or (image-type-available-p 'imagemagick)
721 (image-type-available-p 'png))
722 (cond
723 ((eq type 'dvi)
724 (and (doc-view-mode-p 'pdf)
725 (or (and doc-view-dvipdf-program
726 (executable-find doc-view-dvipdf-program))
727 (and doc-view-dvipdfm-program
728 (executable-find doc-view-dvipdfm-program)))))
729 ((memq type '(postscript ps eps pdf))
730 ;; FIXME: allow mupdf here
731 (and doc-view-ghostscript-program
732 (executable-find doc-view-ghostscript-program)))
733 ((eq type 'odf)
734 (and doc-view-odf->pdf-converter-program
735 (executable-find doc-view-odf->pdf-converter-program)
736 (doc-view-mode-p 'pdf)))
737 ((eq type 'djvu)
738 (executable-find "ddjvu"))
739 (t ;; unknown image type
740 nil))))
742 ;;;; Conversion Functions
744 (defvar doc-view-shrink-factor 1.125)
746 (defun doc-view-enlarge (factor)
747 "Enlarge the document by FACTOR."
748 (interactive (list doc-view-shrink-factor))
749 (if (and doc-view-scale-internally
750 (eq (plist-get (cdr (doc-view-current-image)) :type)
751 'imagemagick))
752 ;; ImageMagick supports on-the-fly-rescaling.
753 (let ((new (ceiling (* factor doc-view-image-width))))
754 (unless (equal new doc-view-image-width)
755 (setq-local doc-view-image-width new)
756 (doc-view-insert-image
757 (plist-get (cdr (doc-view-current-image)) :file)
758 :width doc-view-image-width)))
759 (let ((new (ceiling (* factor doc-view-resolution))))
760 (unless (equal new doc-view-resolution)
761 (setq-local doc-view-resolution new)
762 (doc-view-reconvert-doc)))))
764 (defun doc-view-shrink (factor)
765 "Shrink the document."
766 (interactive (list doc-view-shrink-factor))
767 (doc-view-enlarge (/ 1.0 factor)))
769 (defun doc-view-scale-reset ()
770 "Reset the document size/zoom level to the initial one."
771 (interactive)
772 (if (and doc-view-scale-internally
773 (eq (plist-get (cdr (doc-view-current-image)) :type)
774 'imagemagick))
775 (progn
776 (kill-local-variable 'doc-view-image-width)
777 (doc-view-insert-image
778 (plist-get (cdr (doc-view-current-image)) :file)
779 :width doc-view-image-width))
780 (kill-local-variable 'doc-view-resolution)
781 (doc-view-reconvert-doc)))
783 (defun doc-view-scale-adjust (factor)
784 "Adjust the scale of the DocView page images by FACTOR.
785 FACTOR defaults to `doc-view-shrink-factor'.
787 The actual adjustment made depends on the final component of the
788 key-binding used to invoke the command, with all modifiers removed:
790 +, = Increase the image scale by FACTOR
791 - Decrease the image scale by FACTOR
792 0 Reset the image scale to the initial scale"
793 (interactive (list doc-view-shrink-factor))
794 (let ((ev last-command-event)
795 (echo-keystrokes nil))
796 (pcase (event-basic-type ev)
797 ((or ?+ ?=) (doc-view-enlarge factor))
798 (?- (doc-view-shrink factor))
799 (?0 (doc-view-scale-reset)))))
801 (defun doc-view-fit-width-to-window ()
802 "Fit the image width to the window width."
803 (interactive)
804 (let ((win-width (- (nth 2 (window-inside-pixel-edges))
805 (nth 0 (window-inside-pixel-edges))))
806 (slice (doc-view-current-slice)))
807 (if (not slice)
808 (let ((img-width (car (image-display-size
809 (image-get-display-property) t))))
810 (doc-view-enlarge (/ (float win-width) (float img-width))))
812 ;; If slice is set
813 (let* ((slice-width (nth 2 slice))
814 (scale-factor (/ (float win-width) (float slice-width)))
815 (new-slice (mapcar (lambda (x) (ceiling (* scale-factor x))) slice)))
817 (doc-view-enlarge scale-factor)
818 (setf (doc-view-current-slice) new-slice)
819 (doc-view-goto-page (doc-view-current-page))))))
821 (defun doc-view-fit-height-to-window ()
822 "Fit the image height to the window height."
823 (interactive)
824 (let ((win-height (- (nth 3 (window-inside-pixel-edges))
825 (nth 1 (window-inside-pixel-edges))))
826 (slice (doc-view-current-slice)))
827 (if (not slice)
828 (let ((img-height (cdr (image-display-size
829 (image-get-display-property) t))))
830 ;; When users call 'doc-view-fit-height-to-window',
831 ;; they might want to go to next page by typing SPC
832 ;; ONLY once. So I used '(- win-height 1)' instead of
833 ;; 'win-height'
834 (doc-view-enlarge (/ (float (- win-height 1)) (float img-height))))
836 ;; If slice is set
837 (let* ((slice-height (nth 3 slice))
838 (scale-factor (/ (float (- win-height 1)) (float slice-height)))
839 (new-slice (mapcar (lambda (x) (ceiling (* scale-factor x))) slice)))
841 (doc-view-enlarge scale-factor)
842 (setf (doc-view-current-slice) new-slice)
843 (doc-view-goto-page (doc-view-current-page))))))
845 (defun doc-view-fit-page-to-window ()
846 "Fit the image to the window.
847 More specifically, this function enlarges image by:
849 min {(window-width / image-width), (window-height / image-height)} times."
850 (interactive)
851 (let ((win-width (- (nth 2 (window-inside-pixel-edges))
852 (nth 0 (window-inside-pixel-edges))))
853 (win-height (- (nth 3 (window-inside-pixel-edges))
854 (nth 1 (window-inside-pixel-edges))))
855 (slice (doc-view-current-slice)))
856 (if (not slice)
857 (let ((img-width (car (image-display-size
858 (image-get-display-property) t)))
859 (img-height (cdr (image-display-size
860 (image-get-display-property) t))))
861 (doc-view-enlarge (min (/ (float win-width) (float img-width))
862 (/ (float (- win-height 1))
863 (float img-height)))))
864 ;; If slice is set
865 (let* ((slice-width (nth 2 slice))
866 (slice-height (nth 3 slice))
867 (scale-factor (min (/ (float win-width) (float slice-width))
868 (/ (float (- win-height 1))
869 (float slice-height))))
870 (new-slice (mapcar (lambda (x) (ceiling (* scale-factor x))) slice)))
871 (doc-view-enlarge scale-factor)
872 (setf (doc-view-current-slice) new-slice)
873 (doc-view-goto-page (doc-view-current-page))))))
875 (defun doc-view-reconvert-doc ()
876 "Reconvert the current document.
877 Should be invoked when the cached images aren't up-to-date."
878 (interactive)
879 (doc-view-kill-proc)
880 ;; Clear the old cached files
881 (when (file-exists-p (doc-view--current-cache-dir))
882 (delete-directory (doc-view--current-cache-dir) 'recursive))
883 (kill-local-variable 'doc-view-last-page-number)
884 (doc-view-initiate-display))
886 (defun doc-view-sentinel (proc event)
887 "Generic sentinel for doc-view conversion processes."
888 (if (not (string-match "finished" event))
889 (message "DocView: process %s changed status to %s."
890 (process-name proc)
891 (if (string-match "\\(.+\\)\n?\\'" event)
892 (match-string 1 event)
893 event))
894 (when (buffer-live-p (process-get proc 'buffer))
895 (with-current-buffer (process-get proc 'buffer)
896 (setq doc-view--current-converter-processes
897 (delq proc doc-view--current-converter-processes))
898 (setq mode-line-process
899 (if doc-view--current-converter-processes
900 (format ":%s" (car doc-view--current-converter-processes))))
901 (funcall (process-get proc 'callback))))))
903 (defun doc-view-start-process (name program args callback)
904 ;; Make sure the process is started in an existing directory, (rather than
905 ;; some file-name-handler-managed dir, for example).
906 (let* ((default-directory (or (unhandled-file-name-directory
907 default-directory)
908 (expand-file-name "~/")))
909 (proc (apply 'start-process name doc-view-conversion-buffer
910 program args)))
911 (push proc doc-view--current-converter-processes)
912 (setq mode-line-process (list (format ":%s" proc)))
913 (set-process-sentinel proc 'doc-view-sentinel)
914 (process-put proc 'buffer (current-buffer))
915 (process-put proc 'callback callback)))
917 (defun doc-view-dvi->pdf (dvi pdf callback)
918 "Convert DVI to PDF asynchronously and call CALLBACK when finished."
919 ;; Prefer dvipdf over dvipdfm, because the latter has problems if the DVI
920 ;; references and includes other PS files.
921 (if (and doc-view-dvipdf-program
922 (executable-find doc-view-dvipdf-program))
923 (doc-view-start-process "dvi->pdf" doc-view-dvipdf-program
924 (list dvi pdf)
925 callback)
926 (doc-view-start-process "dvi->pdf" doc-view-dvipdfm-program
927 (list "-o" pdf dvi)
928 callback)))
930 (defun doc-view-pdf->png-converter-ghostscript (pdf png page callback)
931 (doc-view-start-process
932 "pdf/ps->png" doc-view-ghostscript-program
933 `(,@doc-view-ghostscript-options
934 ,(format "-r%d" (round doc-view-resolution))
935 ,@(if page `(,(format "-dFirstPage=%d" page)))
936 ,@(if page `(,(format "-dLastPage=%d" page)))
937 ,(concat "-sOutputFile=" png)
938 ,pdf)
939 callback))
941 (defalias 'doc-view-ps->png-converter-ghostscript
942 'doc-view-pdf->png-converter-ghostscript)
944 (defun doc-view-djvu->tiff-converter-ddjvu (djvu tiff page callback)
945 "Convert PAGE of a DJVU file to bitmap(s) asynchronously.
946 Call CALLBACK with no arguments when done.
947 If PAGE is nil, convert the whole document."
948 (doc-view-start-process
949 "djvu->tiff" "ddjvu"
950 `("-format=tiff"
951 ;; ddjvu only accepts the range 1-999.
952 ,(format "-scale=%d" (round doc-view-resolution))
953 ;; -eachpage was only added after djvulibre-3.5.25.3!
954 ,@(unless page '("-eachpage"))
955 ,@(if page `(,(format "-page=%d" page)))
956 ,djvu
957 ,tiff)
958 callback))
960 (defun doc-view-pdf->png-converter-mupdf (pdf png page callback)
961 (doc-view-start-process
962 "pdf->png" doc-view-pdfdraw-program
963 `(,(concat "-o" png)
964 ,(format "-r%d" (round doc-view-resolution))
965 ,pdf
966 ,@(if page `(,(format "%d" page))))
967 callback))
969 (defun doc-view-odf->pdf-converter-unoconv (odf callback)
970 "Convert ODF to PDF asynchronously and call CALLBACK when finished.
971 The converted PDF is put into the current cache directory, and it
972 is named like ODF with the extension turned to pdf."
973 (doc-view-start-process "odf->pdf" doc-view-odf->pdf-converter-program
974 (list "-f" "pdf" "-o" (doc-view--current-cache-dir) odf)
975 callback))
977 (defun doc-view-odf->pdf-converter-soffice (odf callback)
978 "Convert ODF to PDF asynchronously and call CALLBACK when finished.
979 The converted PDF is put into the current cache directory, and it
980 is named like ODF with the extension turned to pdf."
981 ;; FIXME: soffice doesn't work when there's another running
982 ;; LibreOffice instance, in which case it returns success without
983 ;; actually doing anything. See LibreOffice bug
984 ;; https://bugs.freedesktop.org/show_bug.cgi?id=37531. A workaround
985 ;; is to start soffice with a separate UserInstallation directory.
986 (let ((tmp-user-install-dir (make-temp-file "libreoffice-docview" t)))
987 (doc-view-start-process "odf->pdf" doc-view-odf->pdf-converter-program
988 (list
989 (concat "-env:UserInstallation=file://"
990 ;; The URL must be
991 ;; file:///C:/tmp/dir on Windows.
992 ;; https://wiki.documentfoundation.org/UserProfile.
993 (when (eq system-type 'windows-nt)
994 "/")
995 tmp-user-install-dir)
996 "--headless" "--convert-to" "pdf"
997 "--outdir" (doc-view--current-cache-dir) odf)
998 (lambda ()
999 (delete-directory tmp-user-install-dir t)
1000 (funcall callback)))))
1002 (defun doc-view-pdf/ps->png (pdf-ps png)
1003 ;; FIXME: Fix name and docstring to account for djvu&tiff.
1004 "Convert PDF-PS to PNG asynchronously."
1005 (funcall
1006 (pcase doc-view-doc-type
1007 (`pdf doc-view-pdf->png-converter-function)
1008 (`djvu #'doc-view-djvu->tiff-converter-ddjvu)
1009 (_ #'doc-view-ps->png-converter-ghostscript))
1010 pdf-ps png nil
1011 (let ((resolution doc-view-resolution))
1012 (lambda ()
1013 ;; Only create the resolution file when it's all done, so it also
1014 ;; serves as a witness that the conversion is complete.
1015 (write-region (prin1-to-string resolution) nil
1016 (expand-file-name "resolution.el"
1017 (doc-view--current-cache-dir))
1018 nil 'silently)
1019 (when doc-view--current-timer
1020 (cancel-timer doc-view--current-timer)
1021 (setq doc-view--current-timer nil))
1022 (doc-view-display (current-buffer) 'force))))
1024 ;; Update the displayed pages as soon as they're done generating.
1025 (when doc-view-conversion-refresh-interval
1026 (setq doc-view--current-timer
1027 (run-at-time "1 secs" doc-view-conversion-refresh-interval
1028 'doc-view-display
1029 (current-buffer)))))
1031 (declare-function clear-image-cache "image.c" (&optional filter))
1033 (defun doc-view-document->bitmap (pdf png pages)
1034 "Convert a document file to bitmap images asynchronously.
1035 Start by converting PAGES, and then the rest."
1036 (if (null pages)
1037 (doc-view-pdf/ps->png pdf png)
1038 ;; We could render several `pages' with a single process if they're
1039 ;; (almost) consecutive, but since in 99% of the cases, there'll be only
1040 ;; a single page anyway, and of the remaining 1%, few cases will have
1041 ;; consecutive pages, it's not worth the trouble.
1042 (let ((rest (cdr pages)))
1043 (funcall doc-view-single-page-converter-function
1044 pdf (format png (car pages)) (car pages)
1045 (lambda ()
1046 (if rest
1047 (doc-view-document->bitmap pdf png rest)
1048 ;; Yippie, the important pages are done, update the display.
1049 (clear-image-cache)
1050 ;; For the windows that have a message (like "Welcome to
1051 ;; DocView") display property, clearing the image cache is
1052 ;; not sufficient.
1053 (dolist (win (get-buffer-window-list (current-buffer) nil 'visible))
1054 (with-selected-window win
1055 (when (stringp (overlay-get (doc-view-current-overlay) 'display))
1056 (doc-view-goto-page (doc-view-current-page)))))
1057 ;; Convert the rest of the pages.
1058 (doc-view-pdf/ps->png pdf png)))))))
1060 (defun doc-view-pdf->txt (pdf txt callback)
1061 "Convert PDF to TXT asynchronously and call CALLBACK when finished."
1062 (or (executable-find doc-view-pdftotext-program)
1063 (error "You need the `pdftotext' program to convert a PDF to text"))
1064 (doc-view-start-process "pdf->txt" doc-view-pdftotext-program
1065 (list "-raw" pdf txt)
1066 callback))
1068 (defun doc-view-current-cache-doc-pdf ()
1069 "Return the name of the doc.pdf in the current cache dir.
1070 This file exists only if the current document isn't a PDF or PS file already."
1071 (expand-file-name "doc.pdf" (doc-view--current-cache-dir)))
1073 (defun doc-view-doc->txt (txt callback)
1074 "Convert the current document to text and call CALLBACK when done."
1075 (make-directory (doc-view--current-cache-dir) t)
1076 (pcase doc-view-doc-type
1077 (`pdf
1078 ;; Doc is a PDF, so convert it to TXT
1079 (doc-view-pdf->txt doc-view--buffer-file-name txt callback))
1080 (`ps
1081 ;; Doc is a PS, so convert it to PDF (which will be converted to
1082 ;; TXT thereafter).
1083 (let ((pdf (doc-view-current-cache-doc-pdf)))
1084 (doc-view-ps->pdf doc-view--buffer-file-name pdf
1085 (lambda () (doc-view-pdf->txt pdf txt callback)))))
1086 (`dvi
1087 ;; Doc is a DVI. This means that a doc.pdf already exists in its
1088 ;; cache subdirectory.
1089 (doc-view-pdf->txt (doc-view-current-cache-doc-pdf) txt callback))
1090 (`odf
1091 ;; Doc is some ODF (or MS Office) doc. This means that a doc.pdf
1092 ;; already exists in its cache subdirectory.
1093 (doc-view-pdf->txt (doc-view-current-cache-doc-pdf) txt callback))
1094 (_ (error "DocView doesn't know what to do"))))
1096 (defun doc-view-ps->pdf (ps pdf callback)
1097 "Convert PS to PDF asynchronously and call CALLBACK when finished."
1098 (or (executable-find doc-view-ps2pdf-program)
1099 (error "You need the `ps2pdf' program to convert PS to PDF"))
1100 (doc-view-start-process "ps->pdf" doc-view-ps2pdf-program
1101 (list
1102 ;; Avoid security problems when rendering files from
1103 ;; untrusted sources.
1104 "-dSAFER"
1105 ;; in-file and out-file
1106 ps pdf)
1107 callback))
1109 (defun doc-view-active-pages ()
1110 (let ((pages ()))
1111 (dolist (win (get-buffer-window-list (current-buffer) nil 'visible))
1112 (let ((page (image-mode-window-get 'page win)))
1113 (unless (memq page pages) (push page pages))))
1114 pages))
1116 (defun doc-view-convert-current-doc ()
1117 "Convert `doc-view--buffer-file-name' to a set of png files, one file per page.
1118 Those files are saved in the directory given by the function
1119 `doc-view--current-cache-dir'."
1120 ;; Let stale files still display while we recompute the new ones, so only
1121 ;; flush the cache when the conversion is over. One of the reasons why it
1122 ;; is important to keep displaying the stale page is so that revert-buffer
1123 ;; preserves the horizontal/vertical scroll settings (which are otherwise
1124 ;; reset during the redisplay).
1125 (setq doc-view--pending-cache-flush t)
1126 (let ((png-file (expand-file-name
1127 (format doc-view--image-file-pattern "%d")
1128 (doc-view--current-cache-dir))))
1129 (make-directory (doc-view--current-cache-dir) t)
1130 (pcase doc-view-doc-type
1131 (`dvi
1132 ;; DVI files have to be converted to PDF before Ghostscript can process
1133 ;; it.
1134 (let ((pdf (doc-view-current-cache-doc-pdf)))
1135 (doc-view-dvi->pdf doc-view--buffer-file-name pdf
1136 (lambda () (doc-view-pdf/ps->png pdf png-file)))))
1137 (`odf
1138 ;; ODF files have to be converted to PDF before Ghostscript can
1139 ;; process it.
1140 (let ((pdf (doc-view-current-cache-doc-pdf))
1141 (opdf (expand-file-name
1142 (concat (file-name-base doc-view--buffer-file-name)
1143 ".pdf")
1144 doc-view--current-cache-dir))
1145 (png-file png-file))
1146 ;; The unoconv tool only supports an output directory, but no
1147 ;; file name. It's named like the input file with the
1148 ;; extension replaced by pdf.
1149 (funcall doc-view-odf->pdf-converter-function doc-view--buffer-file-name
1150 (lambda ()
1151 ;; Rename to doc.pdf
1152 (rename-file opdf pdf)
1153 (doc-view-pdf/ps->png pdf png-file)))))
1154 ((or `pdf `djvu)
1155 (let ((pages (doc-view-active-pages)))
1156 ;; Convert doc to bitmap images starting with the active pages.
1157 (doc-view-document->bitmap doc-view--buffer-file-name png-file pages)))
1159 ;; Convert to PNG images.
1160 (doc-view-pdf/ps->png doc-view--buffer-file-name png-file)))))
1162 ;;;; Slicing
1164 (declare-function image-size "image.c" (spec &optional pixels frame))
1166 (defun doc-view-set-slice (x y width height)
1167 "Set the slice of the images that should be displayed.
1168 You can use this function to tell doc-view not to display the
1169 margins of the document. It prompts for the top-left corner (X
1170 and Y) of the slice to display and its WIDTH and HEIGHT.
1172 See `doc-view-set-slice-using-mouse' and
1173 `doc-view-set-slice-from-bounding-box' for more convenient ways
1174 to do that. To reset the slice use `doc-view-reset-slice'."
1175 (interactive
1176 (let* ((size (image-size (doc-view-current-image) t))
1177 (a (read-number (format "Top-left X (0..%d): " (car size))))
1178 (b (read-number (format "Top-left Y (0..%d): " (cdr size))))
1179 (c (read-number (format "Width (0..%d): " (- (car size) a))))
1180 (d (read-number (format "Height (0..%d): " (- (cdr size) b)))))
1181 (list a b c d)))
1182 (setf (doc-view-current-slice) (list x y width height))
1183 ;; Redisplay
1184 (doc-view-goto-page (doc-view-current-page)))
1186 (defun doc-view-set-slice-using-mouse ()
1187 "Set the slice of the images that should be displayed.
1188 You set the slice by pressing mouse-1 at its top-left corner and
1189 dragging it to its bottom-right corner. See also
1190 `doc-view-set-slice' and `doc-view-reset-slice'."
1191 (interactive)
1192 (let (x y w h done)
1193 (while (not done)
1194 (let ((e (read-event
1195 (concat "Press mouse-1 at the top-left corner and "
1196 "drag it to the bottom-right corner!"))))
1197 (when (eq (car e) 'drag-mouse-1)
1198 (setq x (car (posn-object-x-y (event-start e))))
1199 (setq y (cdr (posn-object-x-y (event-start e))))
1200 (setq w (- (car (posn-object-x-y (event-end e))) x))
1201 (setq h (- (cdr (posn-object-x-y (event-end e))) y))
1202 (setq done t))))
1203 (doc-view-set-slice x y w h)))
1205 (defun doc-view-get-bounding-box ()
1206 "Get the BoundingBox information of the current page."
1207 (let* ((page (doc-view-current-page))
1208 (doc (let ((cache-doc (doc-view-current-cache-doc-pdf)))
1209 (if (file-exists-p cache-doc)
1210 cache-doc
1211 doc-view--buffer-file-name)))
1212 (o (shell-command-to-string
1213 (concat doc-view-ghostscript-program
1214 " -dSAFER -dBATCH -dNOPAUSE -q -sDEVICE=bbox "
1215 (format "-dFirstPage=%s -dLastPage=%s %s"
1216 page page doc)))))
1217 (save-match-data
1218 (when (string-match (concat "%%BoundingBox: "
1219 "\\([[:digit:]]+\\) \\([[:digit:]]+\\) "
1220 "\\([[:digit:]]+\\) \\([[:digit:]]+\\)") o)
1221 (mapcar #'string-to-number
1222 (list (match-string 1 o)
1223 (match-string 2 o)
1224 (match-string 3 o)
1225 (match-string 4 o)))))))
1227 (defvar doc-view-paper-sizes
1228 '((a4 595 842)
1229 (a4-landscape 842 595)
1230 (letter 612 792)
1231 (letter-landscape 792 612)
1232 (legal 612 1008)
1233 (legal-landscape 1008 612)
1234 (a3 842 1191)
1235 (a3-landscape 1191 842)
1236 (tabloid 792 1224)
1237 (ledger 1224 792))
1238 "An alist from paper size names to dimensions.")
1240 (defun doc-view-guess-paper-size (iw ih)
1241 "Guess the paper size according to the aspect ratio."
1242 (cl-labels ((div (x y)
1243 (round (/ (* 100.0 x) y))))
1244 (let ((ar (div iw ih))
1245 (al (mapcar (lambda (l)
1246 (list (div (nth 1 l) (nth 2 l)) (car l)))
1247 doc-view-paper-sizes)))
1248 (cadr (assoc ar al)))))
1250 (defun doc-view-scale-bounding-box (ps iw ih bb)
1251 (list (/ (* (nth 0 bb) iw) (nth 1 (assoc ps doc-view-paper-sizes)))
1252 (/ (* (nth 1 bb) ih) (nth 2 (assoc ps doc-view-paper-sizes)))
1253 (/ (* (nth 2 bb) iw) (nth 1 (assoc ps doc-view-paper-sizes)))
1254 (/ (* (nth 3 bb) ih) (nth 2 (assoc ps doc-view-paper-sizes)))))
1256 (defun doc-view-set-slice-from-bounding-box (&optional force-paper-size)
1257 "Set the slice from the document's BoundingBox information.
1258 The result is that the margins are almost completely cropped,
1259 much more accurate than could be done manually using
1260 `doc-view-set-slice-using-mouse'."
1261 (interactive "P")
1262 (let ((bb (doc-view-get-bounding-box)))
1263 (if (not bb)
1264 (message "BoundingBox couldn't be determined")
1265 (let* ((is (image-size (doc-view-current-image) t))
1266 (iw (car is))
1267 (ih (cdr is))
1268 (ps (or (and (null force-paper-size)
1269 (doc-view-guess-paper-size iw ih))
1270 (intern (completing-read "Paper size: "
1271 doc-view-paper-sizes
1272 nil t))))
1273 (bb (doc-view-scale-bounding-box ps iw ih bb))
1274 (x1 (nth 0 bb))
1275 (y1 (nth 1 bb))
1276 (x2 (nth 2 bb))
1277 (y2 (nth 3 bb)))
1278 ;; We keep a 2 pixel margin.
1279 (doc-view-set-slice (- x1 2) (- ih y2 2)
1280 (+ (- x2 x1) 4) (+ (- y2 y1) 4))))))
1282 (defun doc-view-reset-slice ()
1283 "Reset the current slice.
1284 After calling this function whole pages will be visible again."
1285 (interactive)
1286 (setf (doc-view-current-slice) nil)
1287 ;; Redisplay
1288 (doc-view-goto-page (doc-view-current-page)))
1290 ;;;; Display
1292 (defun doc-view-insert-image (file &rest args)
1293 "Insert the given png FILE.
1294 ARGS is a list of image descriptors."
1295 (when doc-view--pending-cache-flush
1296 (clear-image-cache)
1297 (setq doc-view--pending-cache-flush nil))
1298 (let ((ol (doc-view-current-overlay)))
1299 ;; Only insert the image if the buffer is visible.
1300 (when (window-live-p (overlay-get ol 'window))
1301 (let* ((image (if (and file (file-readable-p file))
1302 (if (not (and doc-view-scale-internally
1303 (fboundp 'imagemagick-types)))
1304 (apply 'create-image file doc-view--image-type nil args)
1305 (unless (member :width args)
1306 (setq args `(,@args :width ,doc-view-image-width)))
1307 (apply 'create-image file 'imagemagick nil args))))
1308 (slice (doc-view-current-slice))
1309 (img-width (and image (car (image-size image))))
1310 (displayed-img-width (if (and image slice)
1311 (* (/ (float (nth 2 slice))
1312 (car (image-size image 'pixels)))
1313 img-width)
1314 img-width))
1315 (window-width (window-width)))
1316 (setf (doc-view-current-image) image)
1317 (move-overlay ol (point-min) (point-max))
1318 ;; In case the window is wider than the image, center the image
1319 ;; horizontally.
1320 (overlay-put ol 'before-string
1321 (when (and image (> window-width displayed-img-width))
1322 (propertize " " 'display
1323 `(space :align-to (+ center (-0.5 . ,displayed-img-width))))))
1324 (overlay-put ol 'display
1325 (cond
1326 (image
1327 (if slice
1328 (list (cons 'slice slice) image)
1329 image))
1330 ;; We're trying to display a page that doesn't exist.
1331 (doc-view--current-converter-processes
1332 ;; Maybe the page doesn't exist *yet*.
1333 "Cannot display this page (yet)!")
1335 ;; Typically happens if the conversion process somehow
1336 ;; failed. Better not signal an error here because it
1337 ;; could prevent a subsequent reconversion from fixing
1338 ;; the problem.
1339 (concat "Cannot display this page!\n"
1340 "Maybe because of a conversion failure!"))))
1341 (let ((win (overlay-get ol 'window)))
1342 (if (stringp (overlay-get ol 'display))
1343 (progn ;Make sure the text is not scrolled out of view.
1344 (set-window-hscroll win 0)
1345 (set-window-vscroll win 0))
1346 (let ((hscroll (image-mode-window-get 'hscroll win))
1347 (vscroll (image-mode-window-get 'vscroll win)))
1348 ;; Reset scroll settings, in case they were changed.
1349 (if hscroll (set-window-hscroll win hscroll))
1350 (if vscroll (set-window-vscroll win vscroll)))))))))
1352 (defun doc-view-sort (a b)
1353 "Return non-nil if A should be sorted before B.
1354 Predicate for sorting `doc-view--current-files'."
1355 (or (< (length a) (length b))
1356 (and (= (length a) (length b))
1357 (string< a b))))
1359 (defun doc-view-display (buffer &optional force)
1360 "Start viewing the document in BUFFER.
1361 If FORCE is non-nil, start viewing even if the document does not
1362 have the page we want to view."
1363 (with-current-buffer buffer
1364 (let ((prev-pages doc-view--current-files))
1365 (setq doc-view--current-files
1366 (sort (directory-files (doc-view--current-cache-dir) t
1367 (format doc-view--image-file-pattern
1368 "[0-9]+")
1370 'doc-view-sort))
1371 (unless (eq (length prev-pages) (length doc-view--current-files))
1372 (force-mode-line-update))
1373 (dolist (win (or (get-buffer-window-list buffer nil t)
1374 (list t)))
1375 (let* ((page (doc-view-current-page win))
1376 (pagefile (expand-file-name
1377 (format doc-view--image-file-pattern page)
1378 (doc-view--current-cache-dir))))
1379 (when (or force
1380 (and (not (member pagefile prev-pages))
1381 (member pagefile doc-view--current-files)))
1382 (if (windowp win)
1383 (with-selected-window win
1384 (cl-assert (eq (current-buffer) buffer) t)
1385 (doc-view-goto-page page))
1386 (doc-view-goto-page page))))))))
1388 (defun doc-view-buffer-message ()
1389 ;; Only show this message initially, not when refreshing the buffer (in which
1390 ;; case it's better to keep displaying the "stale" page while computing
1391 ;; the fresh new ones).
1392 (unless (overlay-get (doc-view-current-overlay) 'display)
1393 (overlay-put (doc-view-current-overlay) 'display
1394 (concat (propertize "Welcome to DocView!" 'face 'bold)
1395 "\n"
1397 If you see this buffer it means that the document you want to view is being
1398 converted to PNG and the conversion of the first page hasn't finished yet or
1399 `doc-view-conversion-refresh-interval' is set to nil.
1401 For now these keys are useful:
1403 `q' : Bury this buffer. Conversion will go on in background.
1404 `k' : Kill the conversion process and this buffer.
1405 `K' : Kill the conversion process.\n"))))
1407 (declare-function tooltip-show "tooltip" (text &optional use-echo-area))
1409 (defun doc-view-show-tooltip ()
1410 (interactive)
1411 (tooltip-show (doc-view-current-info)))
1413 (defun doc-view-open-text ()
1414 "Display the current doc's contents as text."
1415 (interactive)
1416 (if doc-view--current-converter-processes
1417 (message "DocView: please wait till conversion finished.")
1418 (let ((txt (expand-file-name "doc.txt" (doc-view--current-cache-dir))))
1419 (if (file-readable-p txt)
1420 (let ((inhibit-read-only t)
1421 (buffer-undo-list t)
1422 (dv-bfn doc-view--buffer-file-name))
1423 (erase-buffer)
1424 (set-buffer-multibyte t)
1425 (insert-file-contents txt)
1426 (text-mode)
1427 (setq-local doc-view--buffer-file-name dv-bfn)
1428 (set-buffer-modified-p nil)
1429 (doc-view-minor-mode)
1430 (add-hook 'write-file-functions
1431 (lambda ()
1432 (when (eq major-mode 'text-mode)
1433 (error "Cannot save text contents of document %s"
1434 buffer-file-name)))
1435 nil t))
1436 (doc-view-doc->txt txt 'doc-view-open-text)))))
1438 ;;;;; Toggle between editing and viewing
1440 (defvar-local doc-view-saved-settings nil
1441 "Doc-view settings saved while in some other mode.")
1442 (put 'doc-view-saved-settings 'permanent-local t)
1444 (defun doc-view-toggle-display ()
1445 "Toggle between editing a document as text or viewing it."
1446 (interactive)
1447 (cond
1448 ((eq major-mode 'doc-view-mode)
1449 ;; Switch to editing mode
1450 (doc-view-kill-proc)
1451 (setq buffer-read-only nil)
1452 ;; Switch to the previously used major mode or fall back to
1453 ;; normal mode.
1454 (doc-view-fallback-mode)
1455 (doc-view-minor-mode 1))
1456 ((eq major-mode 'text-mode)
1457 (let ((buffer-undo-list t))
1458 ;; We're currently viewing the document's text contents, so switch
1459 ;; back to .
1460 (setq buffer-read-only nil)
1461 (insert-file-contents doc-view--buffer-file-name nil nil nil t)
1462 (doc-view-fallback-mode)
1463 (doc-view-minor-mode 1)
1464 (set-buffer-modified-p nil)))
1466 ;; Switch to doc-view-mode
1467 (when (and (buffer-modified-p)
1468 (y-or-n-p "The buffer has been modified. Save the changes? "))
1469 (save-buffer))
1470 (doc-view-mode))))
1472 ;;;; Searching
1475 (defun doc-view-search-internal (regexp file)
1476 "Return a list of FILE's pages that contain text matching REGEXP.
1477 The value is an alist of the form (PAGE CONTEXTS) where PAGE is
1478 the pagenumber and CONTEXTS are all lines of text containing a match."
1479 (with-temp-buffer
1480 (insert-file-contents file)
1481 (let ((page 1)
1482 (lastpage 1)
1483 matches)
1484 (while (re-search-forward (concat "\\(?:\\([\f]\\)\\|\\("
1485 regexp "\\)\\)") nil t)
1486 (when (match-string 1) (setq page (1+ page)))
1487 (when (match-string 2)
1488 (if (/= page lastpage)
1489 (push (cons page
1490 (list (buffer-substring
1491 (line-beginning-position)
1492 (line-end-position))))
1493 matches)
1494 (setq matches (cons
1495 (append
1497 ;; This page already is a match.
1498 (car matches)
1499 ;; This is the first match on page.
1500 (list page))
1501 (list (buffer-substring
1502 (line-beginning-position)
1503 (line-end-position))))
1504 (cdr matches))))
1505 (setq lastpage page)))
1506 (nreverse matches))))
1508 (defun doc-view-search-no-of-matches (list)
1509 "Extract the number of matches from the search result LIST."
1510 (let ((no 0))
1511 (dolist (p list)
1512 (setq no (+ no (1- (length p)))))
1513 no))
1515 (defun doc-view-search-backward (new-query)
1516 "Call `doc-view-search' for backward search.
1517 If prefix NEW-QUERY is given, ask for a new regexp."
1518 (interactive "P")
1519 (doc-view-search new-query t))
1521 (defun doc-view-search (new-query &optional backward)
1522 "Jump to the next match or initiate a new search if NEW-QUERY is given.
1523 If the current document hasn't been transformed to plain text
1524 till now do that first.
1525 If BACKWARD is non-nil, jump to the previous match."
1526 (interactive "P")
1527 (if (and (not new-query)
1528 doc-view--current-search-matches)
1529 (if backward
1530 (doc-view-search-previous-match 1)
1531 (doc-view-search-next-match 1))
1532 ;; New search, so forget the old results.
1533 (setq doc-view--current-search-matches nil)
1534 (let ((txt (expand-file-name "doc.txt"
1535 (doc-view--current-cache-dir))))
1536 (if (file-readable-p txt)
1537 (progn
1538 (setq doc-view--current-search-matches
1539 (doc-view-search-internal
1540 (read-from-minibuffer "Regexp: ")
1541 txt))
1542 (message "DocView: search yielded %d matches."
1543 (doc-view-search-no-of-matches
1544 doc-view--current-search-matches)))
1545 ;; We must convert to TXT first!
1546 (if doc-view--current-converter-processes
1547 (message "DocView: please wait till conversion finished.")
1548 (doc-view-doc->txt txt (lambda () (doc-view-search nil))))))))
1550 (defun doc-view-search-next-match (arg)
1551 "Go to the ARGth next matching page."
1552 (interactive "p")
1553 (let* ((next-pages (cl-remove-if
1554 (lambda (i) (<= (car i) (doc-view-current-page)))
1555 doc-view--current-search-matches))
1556 (page (car (nth (1- arg) next-pages))))
1557 (if page
1558 (doc-view-goto-page page)
1559 (when (and
1560 doc-view--current-search-matches
1561 (y-or-n-p "No more matches after current page. Wrap to first match? "))
1562 (doc-view-goto-page (caar doc-view--current-search-matches))))))
1564 (defun doc-view-search-previous-match (arg)
1565 "Go to the ARGth previous matching page."
1566 (interactive "p")
1567 (let* ((prev-pages (cl-remove-if
1568 (lambda (i) (>= (car i) (doc-view-current-page)))
1569 doc-view--current-search-matches))
1570 (page (car (nth (1- arg) (nreverse prev-pages)))))
1571 (if page
1572 (doc-view-goto-page page)
1573 (when (and
1574 doc-view--current-search-matches
1575 (y-or-n-p "No more matches before current page. Wrap to last match? "))
1576 (doc-view-goto-page (caar (last doc-view--current-search-matches)))))))
1578 ;;;; User interface commands and the mode
1580 (put 'doc-view-mode 'mode-class 'special)
1582 (defun doc-view-already-converted-p ()
1583 "Return non-nil if the current doc was already converted."
1584 (and (file-exists-p (doc-view--current-cache-dir))
1585 ;; Check that the resolution info is there, otherwise it means
1586 ;; the conversion is incomplete.
1587 (file-readable-p (expand-file-name "resolution.el"
1588 (doc-view--current-cache-dir)))
1589 (> (length (directory-files
1590 (doc-view--current-cache-dir)
1591 nil (format doc-view--image-file-pattern "[0-9]+")))
1592 0)))
1594 (defun doc-view-initiate-display ()
1595 ;; Switch to image display if possible.
1596 (if (doc-view-mode-p doc-view-doc-type)
1597 (progn
1598 (doc-view-buffer-message)
1599 (setf (doc-view-current-page) (or (doc-view-current-page) 1))
1600 (if (doc-view-already-converted-p)
1601 (progn
1602 (message "DocView: using cached files!")
1603 ;; Load the saved resolution.
1604 (let* ((res-file
1605 (expand-file-name "resolution.el"
1606 (doc-view--current-cache-dir)))
1607 (res
1608 (with-temp-buffer
1609 (when (file-readable-p res-file)
1610 (insert-file-contents res-file)
1611 (read (current-buffer))))))
1612 (when (numberp res)
1613 (setq-local doc-view-resolution res)))
1614 (doc-view-display (current-buffer) 'force))
1615 (doc-view-convert-current-doc))
1616 (message
1617 "%s"
1618 (substitute-command-keys
1619 (concat "Type \\[doc-view-toggle-display] to toggle between "
1620 "editing or viewing the document."))))
1621 (message
1622 "%s"
1623 (concat "No PNG support is available, or some conversion utility for "
1624 (file-name-extension doc-view--buffer-file-name)
1625 " files is missing."))
1626 (if (and (executable-find doc-view-pdftotext-program)
1627 (y-or-n-p
1628 "Unable to render file. View extracted text instead? "))
1629 (doc-view-open-text)
1630 (doc-view-toggle-display))))
1632 (defvar bookmark-make-record-function)
1634 (defun doc-view-clone-buffer-hook ()
1635 ;; FIXME: There are several potential problems linked with reconversion
1636 ;; and auto-revert when we have indirect buffers because they share their
1637 ;; /tmp cache directory. This sharing is good (you'd rather not reconvert
1638 ;; for each clone), but that means that clones need to collaborate a bit.
1639 ;; I guess it mostly means: detect when a reconversion process is already
1640 ;; running, and run the sentinel in all clones.
1642 ;; Maybe the clones should really have a separate /tmp directory
1643 ;; so they could have a different resolution and you could use clones
1644 ;; for zooming.
1645 (remove-overlays (point-min) (point-max) 'doc-view t)
1646 (if (consp image-mode-winprops-alist) (setq image-mode-winprops-alist nil)))
1648 (defun doc-view-intersection (l1 l2)
1649 (let ((l ()))
1650 (dolist (x l1) (if (memq x l2) (push x l)))
1653 (defun doc-view-set-doc-type ()
1654 "Figure out the current document type (`doc-view-doc-type')."
1655 (let ((name-types
1656 (when buffer-file-name
1657 (cdr (assoc-string
1658 (file-name-extension buffer-file-name)
1660 ;; DVI
1661 ("dvi" dvi)
1662 ;; PDF
1663 ("pdf" pdf) ("epdf" pdf)
1664 ;; PostScript
1665 ("ps" ps) ("eps" ps)
1666 ;; DjVu
1667 ("djvu" djvu)
1668 ;; OpenDocument formats.
1669 ("odt" odf) ("ods" odf) ("odp" odf) ("odg" odf)
1670 ("odc" odf) ("odi" odf) ("odm" odf) ("ott" odf)
1671 ("ots" odf) ("otp" odf) ("otg" odf)
1672 ;; Microsoft Office formats (also handled by the odf
1673 ;; conversion chain).
1674 ("doc" odf) ("docx" odf) ("xls" odf) ("xlsx" odf)
1675 ("ppt" odf) ("pps" odf) ("pptx" odf) ("rtf" odf))
1676 t))))
1677 (content-types
1678 (save-excursion
1679 (goto-char (point-min))
1680 (cond
1681 ((looking-at "%!") '(ps))
1682 ((looking-at "%PDF") '(pdf))
1683 ((looking-at "\367\002") '(dvi))
1684 ((looking-at "AT&TFORM") '(djvu))))))
1685 (setq-local
1686 doc-view-doc-type
1687 (car (or (doc-view-intersection name-types content-types)
1688 (when (and name-types content-types)
1689 (error "Conflicting types: name says %s but content says %s"
1690 name-types content-types))
1691 name-types content-types
1692 (error "Cannot determine the document type"))))))
1694 (defun doc-view-set-up-single-converter ()
1695 "Find the right single-page converter for the current document type"
1696 (pcase-let ((`(,conv-function ,type ,extension)
1697 (pcase doc-view-doc-type
1698 (`djvu (list #'doc-view-djvu->tiff-converter-ddjvu 'tiff "tif"))
1699 (_ (list doc-view-pdf->png-converter-function 'png "png")))))
1700 (setq-local doc-view-single-page-converter-function conv-function)
1701 (setq-local doc-view--image-type type)
1702 (setq-local doc-view--image-file-pattern (concat "page-%s." extension))))
1704 ;; desktop.el integration
1706 (defun doc-view-desktop-save-buffer (_desktop-dirname)
1707 ;; FIXME: This is wrong, since this info is per-window but we only do it once
1708 ;; here for the buffer. IOW it should be saved via something like
1709 ;; `window-persistent-parameters'.
1710 `((page . ,(doc-view-current-page))
1711 (slice . ,(doc-view-current-slice))))
1713 (declare-function desktop-restore-file-buffer "desktop"
1714 (buffer-filename buffer-name buffer-misc))
1716 (defun doc-view-restore-desktop-buffer (file name misc)
1717 (let ((page (cdr (assq 'page misc)))
1718 (slice (cdr (assq 'slice misc))))
1719 (desktop-restore-file-buffer file name misc)
1720 ;; FIXME: We need to run this code after displaying the buffer.
1721 (with-selected-window (or (get-buffer-window (current-buffer) 0)
1722 (selected-window))
1723 ;; FIXME: This should be done for all windows restored that show
1724 ;; this buffer. Basically, the page/slice should be saved as
1725 ;; window-parameters in the window-state(s) and then restoring this
1726 ;; window-state should call us back (to interpret/use those parameters).
1727 (doc-view-goto-page page)
1728 (when slice (apply 'doc-view-set-slice slice))
1729 (current-buffer))))
1731 (add-to-list 'desktop-buffer-mode-handlers
1732 '(doc-view-mode . doc-view-restore-desktop-buffer))
1734 ;;;###autoload
1735 (defun doc-view-mode ()
1736 "Major mode in DocView buffers.
1738 DocView Mode is an Emacs document viewer. It displays PDF, PS
1739 and DVI files (as PNG images) in Emacs buffers.
1741 You can use \\<doc-view-mode-map>\\[doc-view-toggle-display] to
1742 toggle between displaying the document or editing it as text.
1743 \\{doc-view-mode-map}"
1744 (interactive)
1746 (if (= (point-min) (point-max))
1747 ;; The doc is empty or doesn't exist at all, so fallback to
1748 ;; another mode. We used to also check file-exists-p, but this
1749 ;; returns nil for tar members.
1750 (doc-view-fallback-mode)
1752 (let* ((prev-major-mode (if (derived-mode-p 'doc-view-mode)
1753 doc-view--previous-major-mode
1754 (unless (eq major-mode 'fundamental-mode)
1755 major-mode))))
1756 (kill-all-local-variables)
1757 (setq-local doc-view--previous-major-mode prev-major-mode))
1759 (dolist (var doc-view-saved-settings)
1760 (set (make-local-variable (car var)) (cdr var)))
1762 ;; Figure out the document type.
1763 (unless doc-view-doc-type
1764 (doc-view-set-doc-type))
1765 (doc-view-set-up-single-converter)
1767 (doc-view-make-safe-dir doc-view-cache-directory)
1768 ;; Handle compressed files, remote files, files inside archives
1769 (setq-local doc-view--buffer-file-name
1770 (cond
1771 (jka-compr-really-do-compress
1772 ;; FIXME: there's a risk of name conflicts here.
1773 (expand-file-name
1774 (file-name-nondirectory
1775 (file-name-sans-extension buffer-file-name))
1776 doc-view-cache-directory))
1777 ;; Is the file readable by local processes?
1778 ;; We used to use `file-remote-p' but it's unclear what it's
1779 ;; supposed to return nil for things like local files accessed
1780 ;; via `su' or via file://...
1781 ((let ((file-name-handler-alist nil))
1782 (not (and buffer-file-name
1783 (file-readable-p buffer-file-name))))
1784 ;; FIXME: there's a risk of name conflicts here.
1785 (expand-file-name
1786 (if buffer-file-name
1787 (file-name-nondirectory buffer-file-name)
1788 (buffer-name))
1789 doc-view-cache-directory))
1790 (t buffer-file-name)))
1791 (when (not (string= doc-view--buffer-file-name buffer-file-name))
1792 (write-region nil nil doc-view--buffer-file-name))
1794 (setq-local revert-buffer-function #'doc-view-revert-buffer)
1796 (add-hook 'change-major-mode-hook
1797 (lambda ()
1798 (doc-view-kill-proc)
1799 (remove-overlays (point-min) (point-max) 'doc-view t))
1800 nil t)
1801 (add-hook 'clone-indirect-buffer-hook 'doc-view-clone-buffer-hook nil t)
1802 (add-hook 'kill-buffer-hook 'doc-view-kill-proc nil t)
1803 (setq-local desktop-save-buffer 'doc-view-desktop-save-buffer)
1805 (remove-overlays (point-min) (point-max) 'doc-view t) ;Just in case.
1806 ;; Keep track of display info ([vh]scroll, page number, overlay,
1807 ;; ...) for each window in which this document is shown.
1808 (add-hook 'image-mode-new-window-functions
1809 'doc-view-new-window-function nil t)
1810 (image-mode-setup-winprops)
1812 (setq-local mode-line-position
1813 '(" P" (:eval (number-to-string (doc-view-current-page)))
1814 "/" (:eval (number-to-string (doc-view-last-page-number)))))
1815 ;; Don't scroll unless the user specifically asked for it.
1816 (setq-local auto-hscroll-mode nil)
1817 (if (boundp 'mwheel-scroll-up-function) ; not --without-x build
1818 (setq-local mwheel-scroll-up-function
1819 #'doc-view-scroll-up-or-next-page))
1820 (if (boundp 'mwheel-scroll-down-function)
1821 (setq-local mwheel-scroll-down-function
1822 #'doc-view-scroll-down-or-previous-page))
1823 (setq-local cursor-type nil)
1824 (use-local-map doc-view-mode-map)
1825 (add-hook 'after-revert-hook 'doc-view-reconvert-doc nil t)
1826 (setq-local bookmark-make-record-function
1827 #'doc-view-bookmark-make-record)
1828 (setq mode-name "DocView"
1829 buffer-read-only t
1830 major-mode 'doc-view-mode)
1831 (doc-view-initiate-display)
1832 ;; Switch off view-mode explicitly, because doc-view-mode is the
1833 ;; canonical view mode for PDF/PS/DVI files. This could be
1834 ;; switched on automatically depending on the value of
1835 ;; `view-read-only'.
1836 (setq-local view-read-only nil)
1837 (run-mode-hooks 'doc-view-mode-hook)))
1839 (defun doc-view-fallback-mode ()
1840 "Fallback to the previous or next best major mode."
1841 (let ((vars (if (derived-mode-p 'doc-view-mode)
1842 (mapcar (lambda (var) (cons var (symbol-value var)))
1843 '(doc-view-resolution
1844 image-mode-winprops-alist)))))
1845 (remove-overlays (point-min) (point-max) 'doc-view t)
1846 (if doc-view--previous-major-mode
1847 (funcall doc-view--previous-major-mode)
1848 (let ((auto-mode-alist
1849 (rassq-delete-all
1850 'doc-view-mode-maybe
1851 (rassq-delete-all 'doc-view-mode
1852 (copy-alist auto-mode-alist)))))
1853 (normal-mode)))
1854 (when vars
1855 (setq-local doc-view-saved-settings vars))))
1857 ;;;###autoload
1858 (defun doc-view-mode-maybe ()
1859 "Switch to `doc-view-mode' if possible.
1860 If the required external tools are not available, then fallback
1861 to the next best mode."
1862 (condition-case nil
1863 (doc-view-set-doc-type)
1864 (error (doc-view-fallback-mode)))
1865 (if (doc-view-mode-p doc-view-doc-type)
1866 (doc-view-mode)
1867 (doc-view-fallback-mode)))
1869 ;;;###autoload
1870 (define-minor-mode doc-view-minor-mode
1871 "Toggle displaying buffer via Doc View (Doc View minor mode).
1872 With a prefix argument ARG, enable Doc View minor mode if ARG is
1873 positive, and disable it otherwise. If called from Lisp, enable
1874 the mode if ARG is omitted or nil.
1876 See the command `doc-view-mode' for more information on this mode."
1877 nil " DocView" doc-view-minor-mode-map
1878 :group 'doc-view
1879 (when doc-view-minor-mode
1880 (add-hook 'change-major-mode-hook (lambda () (doc-view-minor-mode -1)) nil t)
1881 (message
1882 "%s"
1883 (substitute-command-keys
1884 "Type \\[doc-view-toggle-display] to toggle between editing or viewing the document."))))
1886 (defun doc-view-clear-cache ()
1887 "Delete the whole cache (`doc-view-cache-directory')."
1888 (interactive)
1889 (dired-delete-file doc-view-cache-directory 'always))
1891 (defun doc-view-dired-cache ()
1892 "Open `dired' in `doc-view-cache-directory'."
1893 (interactive)
1894 (dired doc-view-cache-directory))
1897 ;;;; Bookmark integration
1899 (declare-function bookmark-make-record-default
1900 "bookmark" (&optional no-file no-context posn))
1901 (declare-function bookmark-prop-get "bookmark" (bookmark prop))
1902 (declare-function bookmark-default-handler "bookmark" (bmk))
1904 (defun doc-view-bookmark-make-record ()
1905 (nconc (bookmark-make-record-default)
1906 `((page . ,(doc-view-current-page))
1907 (handler . doc-view-bookmark-jump))))
1909 ;;;###autoload
1910 (defun doc-view-bookmark-jump (bmk)
1911 ;; This implements the `handler' function interface for record type
1912 ;; returned by `doc-view-bookmark-make-record', which see.
1913 (let ((page (bookmark-prop-get bmk 'page))
1914 (show-fn-sym (make-symbol "doc-view-bookmark-after-jump-hook")))
1915 (fset show-fn-sym
1916 (lambda ()
1917 (remove-hook 'bookmark-after-jump-hook show-fn-sym)
1918 (when (not (eq major-mode 'doc-view-mode))
1919 (doc-view-toggle-display))
1920 (with-selected-window
1921 (or (get-buffer-window (current-buffer) 0)
1922 (selected-window))
1923 (doc-view-goto-page page))))
1924 (add-hook 'bookmark-after-jump-hook show-fn-sym)
1925 (bookmark-default-handler bmk)))
1927 (provide 'doc-view)
1929 ;; Local Variables:
1930 ;; eval: (outline-minor-mode 1)
1931 ;; End:
1933 ;;; doc-view.el ends here