Merge branch 'master' into comment-cache
[emacs.git] / lisp / doc-view.el
blob172ea163c1824a7047ade911d951b2e9b1a4e562
1 ;;; doc-view.el --- View PDF/PostScript/DVI files in Emacs -*- lexical-binding: t -*-
3 ;; Copyright (C) 2007-2017 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 (if (< undo-outer-limit (* 2 (buffer-size)))
446 ;; It's normal for this operation to result in a very large undo entry.
447 (setq-local undo-outer-limit (* 2 (buffer-size))))
448 (cl-labels ((revert ()
449 (let (revert-buffer-function)
450 (revert-buffer ignore-auto noconfirm 'preserve-modes))))
451 (if (and (eq 'pdf doc-view-doc-type)
452 (executable-find "pdfinfo"))
453 ;; We don't want to revert if the PDF file is corrupted which
454 ;; might happen when it it currently recompiled from a tex
455 ;; file. (TODO: We'd like to have something like that also
456 ;; for other types, at least PS, but I don't know a good way
457 ;; to test if a PS file is complete.)
458 (if (= 0 (call-process (executable-find "pdfinfo") nil nil nil
459 doc-view--buffer-file-name))
460 (revert)
461 (when (called-interactively-p 'interactive)
462 (message "Can't revert right now because the file is corrupted.")))
463 (revert))))
466 (easy-menu-define doc-view-menu doc-view-mode-map
467 "Menu for Doc View mode."
468 '("DocView"
469 ["Toggle display" doc-view-toggle-display]
470 ("Continuous"
471 ["Off" (setq doc-view-continuous nil)
472 :style radio :selected (eq doc-view-continuous nil)]
473 ["On" (setq doc-view-continuous t)
474 :style radio :selected (eq doc-view-continuous t)]
475 "---"
476 ["Save as Default"
477 (customize-save-variable 'doc-view-continuous doc-view-continuous) t]
479 "---"
480 ["Set Slice" doc-view-set-slice-using-mouse]
481 ["Set Slice (BoundingBox)" doc-view-set-slice-from-bounding-box]
482 ["Set Slice (manual)" doc-view-set-slice]
483 ["Reset Slice" doc-view-reset-slice]
484 "---"
485 ["Search" doc-view-search]
486 ["Search Backwards" doc-view-search-backward]
489 (defvar doc-view-minor-mode-map
490 (let ((map (make-sparse-keymap)))
491 ;; Toggle between text and image display or editing
492 (define-key map (kbd "C-c C-c") 'doc-view-toggle-display)
493 map)
494 "Keymap used by `doc-minor-view-mode'.")
496 ;;;; Navigation Commands
498 (defmacro doc-view-current-page (&optional win)
499 `(image-mode-window-get 'page ,win))
500 (defmacro doc-view-current-info () `(image-mode-window-get 'info))
501 (defmacro doc-view-current-overlay () `(image-mode-window-get 'overlay))
502 (defmacro doc-view-current-image () `(image-mode-window-get 'image))
503 (defmacro doc-view-current-slice () `(image-mode-window-get 'slice))
505 (defun doc-view-last-page-number ()
506 (length doc-view--current-files))
508 (defun doc-view-goto-page (page)
509 "View the page given by PAGE."
510 (interactive "nPage: ")
511 (let ((len (doc-view-last-page-number)))
512 (if (< page 1)
513 (setq page 1)
514 (when (and (> page len)
515 ;; As long as the converter is running, we don't know
516 ;; how many pages will be available.
517 (null doc-view--current-converter-processes))
518 (setq page len)))
519 (force-mode-line-update) ;To update `current-page'.
520 (setf (doc-view-current-page) page
521 (doc-view-current-info)
522 (concat
523 (propertize
524 (format "Page %d of %d." page len) 'face 'bold)
525 ;; Tell user if converting isn't finished yet
526 (if doc-view--current-converter-processes
527 " (still converting...)\n"
528 "\n")
529 ;; Display context infos if this page matches the last search
530 (when (and doc-view--current-search-matches
531 (assq page doc-view--current-search-matches))
532 (concat (propertize "Search matches:\n" 'face 'bold)
533 (let ((contexts ""))
534 (dolist (m (cdr (assq page
535 doc-view--current-search-matches)))
536 (setq contexts (concat contexts " - \"" m "\"\n")))
537 contexts)))))
538 ;; Update the buffer
539 ;; We used to find the file name from doc-view--current-files but
540 ;; that's not right if the pages are not generated sequentially
541 ;; or if the page isn't in doc-view--current-files yet.
542 (let ((file (expand-file-name
543 (format doc-view--image-file-pattern page)
544 (doc-view--current-cache-dir))))
545 (doc-view-insert-image file :pointer 'arrow)
546 (when (and (not (file-exists-p file))
547 doc-view--current-converter-processes)
548 ;; The PNG file hasn't been generated yet.
549 (funcall doc-view-single-page-converter-function
550 doc-view--buffer-file-name file page
551 (let ((win (selected-window)))
552 (lambda ()
553 (and (eq (current-buffer) (window-buffer win))
554 ;; If we changed page in the mean
555 ;; time, don't mess things up.
556 (eq (doc-view-current-page win) page)
557 ;; Make sure we don't infloop.
558 (file-readable-p file)
559 (with-selected-window win
560 (doc-view-goto-page page))))))))
561 (overlay-put (doc-view-current-overlay)
562 'help-echo (doc-view-current-info))))
564 (defun doc-view-next-page (&optional arg)
565 "Browse ARG pages forward."
566 (interactive "p")
567 (doc-view-goto-page (+ (doc-view-current-page) (or arg 1))))
569 (defun doc-view-previous-page (&optional arg)
570 "Browse ARG pages backward."
571 (interactive "p")
572 (doc-view-goto-page (- (doc-view-current-page) (or arg 1))))
574 (defun doc-view-first-page ()
575 "View the first page."
576 (interactive)
577 (doc-view-goto-page 1))
579 (defun doc-view-last-page ()
580 "View the last page."
581 (interactive)
582 (doc-view-goto-page (doc-view-last-page-number)))
584 (defun doc-view-scroll-up-or-next-page (&optional arg)
585 "Scroll page up ARG lines if possible, else goto next page.
586 When `doc-view-continuous' is non-nil, scrolling upward
587 at the bottom edge of the page moves to the next page.
588 Otherwise, goto next page only on typing SPC (ARG is nil)."
589 (interactive "P")
590 (if (or doc-view-continuous (null arg))
591 (let ((hscroll (window-hscroll))
592 (cur-page (doc-view-current-page)))
593 (when (= (window-vscroll) (image-scroll-up arg))
594 (doc-view-next-page)
595 (when (/= cur-page (doc-view-current-page))
596 (image-bob)
597 (image-bol 1))
598 (set-window-hscroll (selected-window) hscroll)))
599 (image-scroll-up arg)))
601 (defun doc-view-scroll-down-or-previous-page (&optional arg)
602 "Scroll page down ARG lines if possible, else goto previous page.
603 When `doc-view-continuous' is non-nil, scrolling downward
604 at the top edge of the page moves to the previous page.
605 Otherwise, goto previous page only on typing DEL (ARG is nil)."
606 (interactive "P")
607 (if (or doc-view-continuous (null arg))
608 (let ((hscroll (window-hscroll))
609 (cur-page (doc-view-current-page)))
610 (when (= (window-vscroll) (image-scroll-down arg))
611 (doc-view-previous-page)
612 (when (/= cur-page (doc-view-current-page))
613 (image-eob)
614 (image-bol 1))
615 (set-window-hscroll (selected-window) hscroll)))
616 (image-scroll-down arg)))
618 (defun doc-view-next-line-or-next-page (&optional arg)
619 "Scroll upward by ARG lines if possible, else goto next page.
620 When `doc-view-continuous' is non-nil, scrolling a line upward
621 at the bottom edge of the page moves to the next page."
622 (interactive "p")
623 (if doc-view-continuous
624 (let ((hscroll (window-hscroll))
625 (cur-page (doc-view-current-page)))
626 (when (= (window-vscroll) (image-next-line arg))
627 (doc-view-next-page)
628 (when (/= cur-page (doc-view-current-page))
629 (image-bob)
630 (image-bol 1))
631 (set-window-hscroll (selected-window) hscroll)))
632 (image-next-line arg)))
634 (defun doc-view-previous-line-or-previous-page (&optional arg)
635 "Scroll downward by ARG lines if possible, else goto previous page.
636 When `doc-view-continuous' is non-nil, scrolling a line downward
637 at the top edge of the page moves to the previous page."
638 (interactive "p")
639 (if doc-view-continuous
640 (let ((hscroll (window-hscroll))
641 (cur-page (doc-view-current-page)))
642 (when (= (window-vscroll) (image-previous-line arg))
643 (doc-view-previous-page)
644 (when (/= cur-page (doc-view-current-page))
645 (image-eob)
646 (image-bol 1))
647 (set-window-hscroll (selected-window) hscroll)))
648 (image-previous-line arg)))
650 ;;;; Utility Functions
652 (defun doc-view-kill-proc ()
653 "Kill the current converter process(es)."
654 (interactive)
655 (while (consp doc-view--current-converter-processes)
656 (ignore-errors ;; Some entries might not be processes, and maybe
657 ;; some are dead already?
658 (kill-process (pop doc-view--current-converter-processes))))
659 (when doc-view--current-timer
660 (cancel-timer doc-view--current-timer)
661 (setq doc-view--current-timer nil))
662 (setq mode-line-process nil))
664 (define-obsolete-function-alias 'doc-view-kill-proc-and-buffer
665 #'image-kill-buffer "25.1")
667 (defun doc-view-make-safe-dir (dir)
668 (condition-case nil
669 ;; Create temp files with strict access rights. It's easy to
670 ;; loosen them later, whereas it's impossible to close the
671 ;; time-window of loose permissions otherwise.
672 (with-file-modes #o0700 (make-directory dir))
673 (file-already-exists
674 (when (file-symlink-p dir)
675 (error "Danger: %s points to a symbolic link" dir))
676 ;; In case it was created earlier with looser rights.
677 ;; We could check the mode info returned by file-attributes, but it's
678 ;; a pain to parse and it may not tell you what we want under
679 ;; non-standard file-systems. So let's just say what we want and let
680 ;; the underlying C code and file-system figure it out.
681 ;; This also ends up checking a bunch of useful conditions: it makes
682 ;; sure we have write-access to the directory and that we own it, thus
683 ;; closing a bunch of security holes.
684 (condition-case error
685 (set-file-modes dir #o0700)
686 (file-error
687 (error
688 (format "Unable to use temporary directory %s: %s"
689 dir (mapconcat 'identity (cdr error) " "))))))))
691 (defun doc-view--current-cache-dir ()
692 "Return the directory where the png files of the current doc should be saved.
693 It's a subdirectory of `doc-view-cache-directory'."
694 (if doc-view--current-cache-dir
695 doc-view--current-cache-dir
696 ;; Try and make sure doc-view-cache-directory exists and is safe.
697 (doc-view-make-safe-dir doc-view-cache-directory)
698 ;; Now compute the subdirectory to use.
699 (setq doc-view--current-cache-dir
700 (file-name-as-directory
701 (expand-file-name
702 (concat (thread-last
703 (file-name-nondirectory doc-view--buffer-file-name)
704 ;; bug#13679
705 (subst-char-in-string ?% ?_)
706 ;; arc-mode concatenates archive name and file name
707 ;; with colon, which isn't allowed on MS-Windows.
708 (subst-char-in-string ?: ?_))
710 (let ((file doc-view--buffer-file-name))
711 (with-temp-buffer
712 (set-buffer-multibyte nil)
713 (insert-file-contents-literally file)
714 (md5 (current-buffer)))))
715 doc-view-cache-directory)))))
717 ;;;###autoload
718 (defun doc-view-mode-p (type)
719 "Return non-nil if document type TYPE is available for `doc-view'.
720 Document types are symbols like `dvi', `ps', `pdf', or `odf' (any
721 OpenDocument format)."
722 (and (display-graphic-p)
723 (or (image-type-available-p 'imagemagick)
724 (image-type-available-p 'png))
725 (cond
726 ((eq type 'dvi)
727 (and (doc-view-mode-p 'pdf)
728 (or (and doc-view-dvipdf-program
729 (executable-find doc-view-dvipdf-program))
730 (and doc-view-dvipdfm-program
731 (executable-find doc-view-dvipdfm-program)))))
732 ((memq type '(postscript ps eps pdf))
733 ;; FIXME: allow mupdf here
734 (and doc-view-ghostscript-program
735 (executable-find doc-view-ghostscript-program)))
736 ((eq type 'odf)
737 (and doc-view-odf->pdf-converter-program
738 (executable-find doc-view-odf->pdf-converter-program)
739 (doc-view-mode-p 'pdf)))
740 ((eq type 'djvu)
741 (executable-find "ddjvu"))
742 (t ;; unknown image type
743 nil))))
745 ;;;; Conversion Functions
747 (defvar doc-view-shrink-factor 1.125)
749 (defun doc-view-enlarge (factor)
750 "Enlarge the document by FACTOR."
751 (interactive (list doc-view-shrink-factor))
752 (if (and doc-view-scale-internally
753 (eq (plist-get (cdr (doc-view-current-image)) :type)
754 'imagemagick))
755 ;; ImageMagick supports on-the-fly-rescaling.
756 (let ((new (ceiling (* factor doc-view-image-width))))
757 (unless (equal new doc-view-image-width)
758 (setq-local doc-view-image-width new)
759 (doc-view-insert-image
760 (plist-get (cdr (doc-view-current-image)) :file)
761 :width doc-view-image-width)))
762 (let ((new (ceiling (* factor doc-view-resolution))))
763 (unless (equal new doc-view-resolution)
764 (setq-local doc-view-resolution new)
765 (doc-view-reconvert-doc)))))
767 (defun doc-view-shrink (factor)
768 "Shrink the document."
769 (interactive (list doc-view-shrink-factor))
770 (doc-view-enlarge (/ 1.0 factor)))
772 (defun doc-view-scale-reset ()
773 "Reset the document size/zoom level to the initial one."
774 (interactive)
775 (if (and doc-view-scale-internally
776 (eq (plist-get (cdr (doc-view-current-image)) :type)
777 'imagemagick))
778 (progn
779 (kill-local-variable 'doc-view-image-width)
780 (doc-view-insert-image
781 (plist-get (cdr (doc-view-current-image)) :file)
782 :width doc-view-image-width))
783 (kill-local-variable 'doc-view-resolution)
784 (doc-view-reconvert-doc)))
786 (defun doc-view-scale-adjust (factor)
787 "Adjust the scale of the DocView page images by FACTOR.
788 FACTOR defaults to `doc-view-shrink-factor'.
790 The actual adjustment made depends on the final component of the
791 key-binding used to invoke the command, with all modifiers removed:
793 +, = Increase the image scale by FACTOR
794 - Decrease the image scale by FACTOR
795 0 Reset the image scale to the initial scale"
796 (interactive (list doc-view-shrink-factor))
797 (let ((ev last-command-event)
798 (echo-keystrokes nil))
799 (pcase (event-basic-type ev)
800 ((or ?+ ?=) (doc-view-enlarge factor))
801 (?- (doc-view-shrink factor))
802 (?0 (doc-view-scale-reset)))))
804 (defun doc-view-fit-width-to-window ()
805 "Fit the image width to the window width."
806 (interactive)
807 (let ((win-width (- (nth 2 (window-inside-pixel-edges))
808 (nth 0 (window-inside-pixel-edges))))
809 (slice (doc-view-current-slice)))
810 (if (not slice)
811 (let ((img-width (car (image-display-size
812 (image-get-display-property) t))))
813 (doc-view-enlarge (/ (float win-width) (float img-width))))
815 ;; If slice is set
816 (let* ((slice-width (nth 2 slice))
817 (scale-factor (/ (float win-width) (float slice-width)))
818 (new-slice (mapcar (lambda (x) (ceiling (* scale-factor x))) slice)))
820 (doc-view-enlarge scale-factor)
821 (setf (doc-view-current-slice) new-slice)
822 (doc-view-goto-page (doc-view-current-page))))))
824 (defun doc-view-fit-height-to-window ()
825 "Fit the image height to the window height."
826 (interactive)
827 (let ((win-height (- (nth 3 (window-inside-pixel-edges))
828 (nth 1 (window-inside-pixel-edges))))
829 (slice (doc-view-current-slice)))
830 (if (not slice)
831 (let ((img-height (cdr (image-display-size
832 (image-get-display-property) t))))
833 ;; When users call 'doc-view-fit-height-to-window',
834 ;; they might want to go to next page by typing SPC
835 ;; ONLY once. So I used '(- win-height 1)' instead of
836 ;; 'win-height'
837 (doc-view-enlarge (/ (float (- win-height 1)) (float img-height))))
839 ;; If slice is set
840 (let* ((slice-height (nth 3 slice))
841 (scale-factor (/ (float (- win-height 1)) (float slice-height)))
842 (new-slice (mapcar (lambda (x) (ceiling (* scale-factor x))) slice)))
844 (doc-view-enlarge scale-factor)
845 (setf (doc-view-current-slice) new-slice)
846 (doc-view-goto-page (doc-view-current-page))))))
848 (defun doc-view-fit-page-to-window ()
849 "Fit the image to the window.
850 More specifically, this function enlarges image by:
852 min {(window-width / image-width), (window-height / image-height)} times."
853 (interactive)
854 (let ((win-width (- (nth 2 (window-inside-pixel-edges))
855 (nth 0 (window-inside-pixel-edges))))
856 (win-height (- (nth 3 (window-inside-pixel-edges))
857 (nth 1 (window-inside-pixel-edges))))
858 (slice (doc-view-current-slice)))
859 (if (not slice)
860 (let ((img-width (car (image-display-size
861 (image-get-display-property) t)))
862 (img-height (cdr (image-display-size
863 (image-get-display-property) t))))
864 (doc-view-enlarge (min (/ (float win-width) (float img-width))
865 (/ (float (- win-height 1))
866 (float img-height)))))
867 ;; If slice is set
868 (let* ((slice-width (nth 2 slice))
869 (slice-height (nth 3 slice))
870 (scale-factor (min (/ (float win-width) (float slice-width))
871 (/ (float (- win-height 1))
872 (float slice-height))))
873 (new-slice (mapcar (lambda (x) (ceiling (* scale-factor x))) slice)))
874 (doc-view-enlarge scale-factor)
875 (setf (doc-view-current-slice) new-slice)
876 (doc-view-goto-page (doc-view-current-page))))))
878 (defun doc-view-reconvert-doc ()
879 "Reconvert the current document.
880 Should be invoked when the cached images aren't up-to-date."
881 (interactive)
882 (doc-view-kill-proc)
883 ;; Clear the old cached files
884 (when (file-exists-p (doc-view--current-cache-dir))
885 (delete-directory (doc-view--current-cache-dir) 'recursive))
886 (kill-local-variable 'doc-view-last-page-number)
887 (doc-view-initiate-display))
889 (defun doc-view-sentinel (proc event)
890 "Generic sentinel for doc-view conversion processes."
891 (if (not (string-match "finished" event))
892 (message "DocView: process %s changed status to %s."
893 (process-name proc)
894 (if (string-match "\\(.+\\)\n?\\'" event)
895 (match-string 1 event)
896 event))
897 (when (buffer-live-p (process-get proc 'buffer))
898 (with-current-buffer (process-get proc 'buffer)
899 (setq doc-view--current-converter-processes
900 (delq proc doc-view--current-converter-processes))
901 (setq mode-line-process
902 (if doc-view--current-converter-processes
903 (format ":%s" (car doc-view--current-converter-processes))))
904 (funcall (process-get proc 'callback))))))
906 (defun doc-view-start-process (name program args callback)
907 ;; Make sure the process is started in an existing directory, (rather than
908 ;; some file-name-handler-managed dir, for example).
909 (let* ((default-directory (or (unhandled-file-name-directory
910 default-directory)
911 (expand-file-name "~/")))
912 (proc (apply 'start-process name doc-view-conversion-buffer
913 program args)))
914 (push proc doc-view--current-converter-processes)
915 (setq mode-line-process (list (format ":%s" proc)))
916 (set-process-sentinel proc 'doc-view-sentinel)
917 (process-put proc 'buffer (current-buffer))
918 (process-put proc 'callback callback)))
920 (defun doc-view-dvi->pdf (dvi pdf callback)
921 "Convert DVI to PDF asynchronously and call CALLBACK when finished."
922 ;; Prefer dvipdf over dvipdfm, because the latter has problems if the DVI
923 ;; references and includes other PS files.
924 (if (and doc-view-dvipdf-program
925 (executable-find doc-view-dvipdf-program))
926 (doc-view-start-process "dvi->pdf" doc-view-dvipdf-program
927 (list dvi pdf)
928 callback)
929 (doc-view-start-process "dvi->pdf" doc-view-dvipdfm-program
930 (list "-o" pdf dvi)
931 callback)))
933 (defun doc-view-pdf->png-converter-ghostscript (pdf png page callback)
934 (doc-view-start-process
935 "pdf/ps->png" doc-view-ghostscript-program
936 `(,@doc-view-ghostscript-options
937 ,(format "-r%d" (round doc-view-resolution))
938 ,@(if page `(,(format "-dFirstPage=%d" page)))
939 ,@(if page `(,(format "-dLastPage=%d" page)))
940 ,(concat "-sOutputFile=" png)
941 ,pdf)
942 callback))
944 (defalias 'doc-view-ps->png-converter-ghostscript
945 'doc-view-pdf->png-converter-ghostscript)
947 (defun doc-view-djvu->tiff-converter-ddjvu (djvu tiff page callback)
948 "Convert PAGE of a DJVU file to bitmap(s) asynchronously.
949 Call CALLBACK with no arguments when done.
950 If PAGE is nil, convert the whole document."
951 (doc-view-start-process
952 "djvu->tiff" "ddjvu"
953 `("-format=tiff"
954 ;; ddjvu only accepts the range 1-999.
955 ,(format "-scale=%d" (round doc-view-resolution))
956 ;; -eachpage was only added after djvulibre-3.5.25.3!
957 ,@(unless page '("-eachpage"))
958 ,@(if page `(,(format "-page=%d" page)))
959 ,djvu
960 ,tiff)
961 callback))
963 (defun doc-view-pdf->png-converter-mupdf (pdf png page callback)
964 (doc-view-start-process
965 "pdf->png" doc-view-pdfdraw-program
966 `(,(concat "-o" png)
967 ,(format "-r%d" (round doc-view-resolution))
968 ,pdf
969 ,@(if page `(,(format "%d" page))))
970 callback))
972 (defun doc-view-odf->pdf-converter-unoconv (odf callback)
973 "Convert ODF to PDF asynchronously and call CALLBACK when finished.
974 The converted PDF is put into the current cache directory, and it
975 is named like ODF with the extension turned to pdf."
976 (doc-view-start-process "odf->pdf" doc-view-odf->pdf-converter-program
977 (list "-f" "pdf" "-o" (doc-view--current-cache-dir) odf)
978 callback))
980 (defun doc-view-odf->pdf-converter-soffice (odf callback)
981 "Convert ODF to PDF asynchronously and call CALLBACK when finished.
982 The converted PDF is put into the current cache directory, and it
983 is named like ODF with the extension turned to pdf."
984 ;; FIXME: soffice doesn't work when there's another running
985 ;; LibreOffice instance, in which case it returns success without
986 ;; actually doing anything. See LibreOffice bug
987 ;; https://bugs.freedesktop.org/show_bug.cgi?id=37531. A workaround
988 ;; is to start soffice with a separate UserInstallation directory.
989 (let ((tmp-user-install-dir (make-temp-file "libreoffice-docview" t)))
990 (doc-view-start-process "odf->pdf" doc-view-odf->pdf-converter-program
991 (list
992 (concat "-env:UserInstallation=file://"
993 ;; The URL must be
994 ;; file:///C:/tmp/dir on Windows.
995 ;; https://wiki.documentfoundation.org/UserProfile.
996 (when (eq system-type 'windows-nt)
997 "/")
998 tmp-user-install-dir)
999 "--headless" "--convert-to" "pdf"
1000 "--outdir" (doc-view--current-cache-dir) odf)
1001 (lambda ()
1002 (delete-directory tmp-user-install-dir t)
1003 (funcall callback)))))
1005 (defun doc-view-pdf/ps->png (pdf-ps png)
1006 ;; FIXME: Fix name and docstring to account for djvu&tiff.
1007 "Convert PDF-PS to PNG asynchronously."
1008 (funcall
1009 (pcase doc-view-doc-type
1010 (`pdf doc-view-pdf->png-converter-function)
1011 (`djvu #'doc-view-djvu->tiff-converter-ddjvu)
1012 (_ #'doc-view-ps->png-converter-ghostscript))
1013 pdf-ps png nil
1014 (let ((resolution doc-view-resolution))
1015 (lambda ()
1016 ;; Only create the resolution file when it's all done, so it also
1017 ;; serves as a witness that the conversion is complete.
1018 (write-region (prin1-to-string resolution) nil
1019 (expand-file-name "resolution.el"
1020 (doc-view--current-cache-dir))
1021 nil 'silently)
1022 (when doc-view--current-timer
1023 (cancel-timer doc-view--current-timer)
1024 (setq doc-view--current-timer nil))
1025 (doc-view-display (current-buffer) 'force))))
1027 ;; Update the displayed pages as soon as they're done generating.
1028 (when doc-view-conversion-refresh-interval
1029 (setq doc-view--current-timer
1030 (run-at-time "1 secs" doc-view-conversion-refresh-interval
1031 'doc-view-display
1032 (current-buffer)))))
1034 (declare-function clear-image-cache "image.c" (&optional filter))
1036 (defun doc-view-document->bitmap (pdf png pages)
1037 "Convert a document file to bitmap images asynchronously.
1038 Start by converting PAGES, and then the rest."
1039 (if (null pages)
1040 (doc-view-pdf/ps->png pdf png)
1041 ;; We could render several `pages' with a single process if they're
1042 ;; (almost) consecutive, but since in 99% of the cases, there'll be only
1043 ;; a single page anyway, and of the remaining 1%, few cases will have
1044 ;; consecutive pages, it's not worth the trouble.
1045 (let ((rest (cdr pages)))
1046 (funcall doc-view-single-page-converter-function
1047 pdf (format png (car pages)) (car pages)
1048 (lambda ()
1049 (if rest
1050 (doc-view-document->bitmap pdf png rest)
1051 ;; Yippie, the important pages are done, update the display.
1052 (clear-image-cache)
1053 ;; For the windows that have a message (like "Welcome to
1054 ;; DocView") display property, clearing the image cache is
1055 ;; not sufficient.
1056 (dolist (win (get-buffer-window-list (current-buffer) nil 'visible))
1057 (with-selected-window win
1058 (when (stringp (overlay-get (doc-view-current-overlay) 'display))
1059 (doc-view-goto-page (doc-view-current-page)))))
1060 ;; Convert the rest of the pages.
1061 (doc-view-pdf/ps->png pdf png)))))))
1063 (defun doc-view-pdf->txt (pdf txt callback)
1064 "Convert PDF to TXT asynchronously and call CALLBACK when finished."
1065 (or (executable-find doc-view-pdftotext-program)
1066 (error "You need the `pdftotext' program to convert a PDF to text"))
1067 (doc-view-start-process "pdf->txt" doc-view-pdftotext-program
1068 (list "-raw" pdf txt)
1069 callback))
1071 (defun doc-view-current-cache-doc-pdf ()
1072 "Return the name of the doc.pdf in the current cache dir.
1073 This file exists only if the current document isn't a PDF or PS file already."
1074 (expand-file-name "doc.pdf" (doc-view--current-cache-dir)))
1076 (defun doc-view-doc->txt (txt callback)
1077 "Convert the current document to text and call CALLBACK when done."
1078 (make-directory (doc-view--current-cache-dir) t)
1079 (pcase doc-view-doc-type
1080 (`pdf
1081 ;; Doc is a PDF, so convert it to TXT
1082 (doc-view-pdf->txt doc-view--buffer-file-name txt callback))
1083 (`ps
1084 ;; Doc is a PS, so convert it to PDF (which will be converted to
1085 ;; TXT thereafter).
1086 (let ((pdf (doc-view-current-cache-doc-pdf)))
1087 (doc-view-ps->pdf doc-view--buffer-file-name pdf
1088 (lambda () (doc-view-pdf->txt pdf txt callback)))))
1089 (`dvi
1090 ;; Doc is a DVI. This means that a doc.pdf already exists in its
1091 ;; cache subdirectory.
1092 (doc-view-pdf->txt (doc-view-current-cache-doc-pdf) txt callback))
1093 (`odf
1094 ;; Doc is some ODF (or MS Office) doc. This means that a doc.pdf
1095 ;; already exists in its cache subdirectory.
1096 (doc-view-pdf->txt (doc-view-current-cache-doc-pdf) txt callback))
1097 (_ (error "DocView doesn't know what to do"))))
1099 (defun doc-view-ps->pdf (ps pdf callback)
1100 "Convert PS to PDF asynchronously and call CALLBACK when finished."
1101 (or (executable-find doc-view-ps2pdf-program)
1102 (error "You need the `ps2pdf' program to convert PS to PDF"))
1103 (doc-view-start-process "ps->pdf" doc-view-ps2pdf-program
1104 (list
1105 ;; Avoid security problems when rendering files from
1106 ;; untrusted sources.
1107 "-dSAFER"
1108 ;; in-file and out-file
1109 ps pdf)
1110 callback))
1112 (defun doc-view-active-pages ()
1113 (let ((pages ()))
1114 (dolist (win (get-buffer-window-list (current-buffer) nil 'visible))
1115 (let ((page (image-mode-window-get 'page win)))
1116 (unless (memq page pages) (push page pages))))
1117 pages))
1119 (defun doc-view-convert-current-doc ()
1120 "Convert `doc-view--buffer-file-name' to a set of png files, one file per page.
1121 Those files are saved in the directory given by the function
1122 `doc-view--current-cache-dir'."
1123 ;; Let stale files still display while we recompute the new ones, so only
1124 ;; flush the cache when the conversion is over. One of the reasons why it
1125 ;; is important to keep displaying the stale page is so that revert-buffer
1126 ;; preserves the horizontal/vertical scroll settings (which are otherwise
1127 ;; reset during the redisplay).
1128 (setq doc-view--pending-cache-flush t)
1129 (let ((png-file (expand-file-name
1130 (format doc-view--image-file-pattern "%d")
1131 (doc-view--current-cache-dir))))
1132 (make-directory (doc-view--current-cache-dir) t)
1133 (pcase doc-view-doc-type
1134 (`dvi
1135 ;; DVI files have to be converted to PDF before Ghostscript can process
1136 ;; it.
1137 (let ((pdf (doc-view-current-cache-doc-pdf)))
1138 (doc-view-dvi->pdf doc-view--buffer-file-name pdf
1139 (lambda () (doc-view-pdf/ps->png pdf png-file)))))
1140 (`odf
1141 ;; ODF files have to be converted to PDF before Ghostscript can
1142 ;; process it.
1143 (let ((pdf (doc-view-current-cache-doc-pdf))
1144 (opdf (expand-file-name
1145 (concat (file-name-base doc-view--buffer-file-name)
1146 ".pdf")
1147 doc-view--current-cache-dir))
1148 (png-file png-file))
1149 ;; The unoconv tool only supports an output directory, but no
1150 ;; file name. It's named like the input file with the
1151 ;; extension replaced by pdf.
1152 (funcall doc-view-odf->pdf-converter-function doc-view--buffer-file-name
1153 (lambda ()
1154 ;; Rename to doc.pdf
1155 (rename-file opdf pdf)
1156 (doc-view-pdf/ps->png pdf png-file)))))
1157 ((or `pdf `djvu)
1158 (let ((pages (doc-view-active-pages)))
1159 ;; Convert doc to bitmap images starting with the active pages.
1160 (doc-view-document->bitmap doc-view--buffer-file-name png-file pages)))
1162 ;; Convert to PNG images.
1163 (doc-view-pdf/ps->png doc-view--buffer-file-name png-file)))))
1165 ;;;; Slicing
1167 (declare-function image-size "image.c" (spec &optional pixels frame))
1169 (defun doc-view-set-slice (x y width height)
1170 "Set the slice of the images that should be displayed.
1171 You can use this function to tell doc-view not to display the
1172 margins of the document. It prompts for the top-left corner (X
1173 and Y) of the slice to display and its WIDTH and HEIGHT.
1175 See `doc-view-set-slice-using-mouse' and
1176 `doc-view-set-slice-from-bounding-box' for more convenient ways
1177 to do that. To reset the slice use `doc-view-reset-slice'."
1178 (interactive
1179 (let* ((size (image-size (doc-view-current-image) t))
1180 (a (read-number (format "Top-left X (0..%d): " (car size))))
1181 (b (read-number (format "Top-left Y (0..%d): " (cdr size))))
1182 (c (read-number (format "Width (0..%d): " (- (car size) a))))
1183 (d (read-number (format "Height (0..%d): " (- (cdr size) b)))))
1184 (list a b c d)))
1185 (setf (doc-view-current-slice) (list x y width height))
1186 ;; Redisplay
1187 (doc-view-goto-page (doc-view-current-page)))
1189 (defun doc-view-set-slice-using-mouse ()
1190 "Set the slice of the images that should be displayed.
1191 You set the slice by pressing mouse-1 at its top-left corner and
1192 dragging it to its bottom-right corner. See also
1193 `doc-view-set-slice' and `doc-view-reset-slice'."
1194 (interactive)
1195 (let (x y w h done)
1196 (while (not done)
1197 (let ((e (read-event
1198 (concat "Press mouse-1 at the top-left corner and "
1199 "drag it to the bottom-right corner!"))))
1200 (when (eq (car e) 'drag-mouse-1)
1201 (setq x (car (posn-object-x-y (event-start e))))
1202 (setq y (cdr (posn-object-x-y (event-start e))))
1203 (setq w (- (car (posn-object-x-y (event-end e))) x))
1204 (setq h (- (cdr (posn-object-x-y (event-end e))) y))
1205 (setq done t))))
1206 (doc-view-set-slice x y w h)))
1208 (defun doc-view-get-bounding-box ()
1209 "Get the BoundingBox information of the current page."
1210 (let* ((page (doc-view-current-page))
1211 (doc (let ((cache-doc (doc-view-current-cache-doc-pdf)))
1212 (if (file-exists-p cache-doc)
1213 cache-doc
1214 doc-view--buffer-file-name)))
1215 (o (shell-command-to-string
1216 (concat doc-view-ghostscript-program
1217 " -dSAFER -dBATCH -dNOPAUSE -q -sDEVICE=bbox "
1218 (format "-dFirstPage=%s -dLastPage=%s %s"
1219 page page doc)))))
1220 (save-match-data
1221 (when (string-match (concat "%%BoundingBox: "
1222 "\\([[:digit:]]+\\) \\([[:digit:]]+\\) "
1223 "\\([[:digit:]]+\\) \\([[:digit:]]+\\)") o)
1224 (mapcar #'string-to-number
1225 (list (match-string 1 o)
1226 (match-string 2 o)
1227 (match-string 3 o)
1228 (match-string 4 o)))))))
1230 (defvar doc-view-paper-sizes
1231 '((a4 595 842)
1232 (a4-landscape 842 595)
1233 (letter 612 792)
1234 (letter-landscape 792 612)
1235 (legal 612 1008)
1236 (legal-landscape 1008 612)
1237 (a3 842 1191)
1238 (a3-landscape 1191 842)
1239 (tabloid 792 1224)
1240 (ledger 1224 792))
1241 "An alist from paper size names to dimensions.")
1243 (defun doc-view-guess-paper-size (iw ih)
1244 "Guess the paper size according to the aspect ratio."
1245 (cl-labels ((div (x y)
1246 (round (/ (* 100.0 x) y))))
1247 (let ((ar (div iw ih))
1248 (al (mapcar (lambda (l)
1249 (list (div (nth 1 l) (nth 2 l)) (car l)))
1250 doc-view-paper-sizes)))
1251 (cadr (assoc ar al)))))
1253 (defun doc-view-scale-bounding-box (ps iw ih bb)
1254 (list (/ (* (nth 0 bb) iw) (nth 1 (assoc ps doc-view-paper-sizes)))
1255 (/ (* (nth 1 bb) ih) (nth 2 (assoc ps doc-view-paper-sizes)))
1256 (/ (* (nth 2 bb) iw) (nth 1 (assoc ps doc-view-paper-sizes)))
1257 (/ (* (nth 3 bb) ih) (nth 2 (assoc ps doc-view-paper-sizes)))))
1259 (defun doc-view-set-slice-from-bounding-box (&optional force-paper-size)
1260 "Set the slice from the document's BoundingBox information.
1261 The result is that the margins are almost completely cropped,
1262 much more accurate than could be done manually using
1263 `doc-view-set-slice-using-mouse'."
1264 (interactive "P")
1265 (let ((bb (doc-view-get-bounding-box)))
1266 (if (not bb)
1267 (message "BoundingBox couldn't be determined")
1268 (let* ((is (image-size (doc-view-current-image) t))
1269 (iw (car is))
1270 (ih (cdr is))
1271 (ps (or (and (null force-paper-size)
1272 (doc-view-guess-paper-size iw ih))
1273 (intern (completing-read "Paper size: "
1274 doc-view-paper-sizes
1275 nil t))))
1276 (bb (doc-view-scale-bounding-box ps iw ih bb))
1277 (x1 (nth 0 bb))
1278 (y1 (nth 1 bb))
1279 (x2 (nth 2 bb))
1280 (y2 (nth 3 bb)))
1281 ;; We keep a 2 pixel margin.
1282 (doc-view-set-slice (- x1 2) (- ih y2 2)
1283 (+ (- x2 x1) 4) (+ (- y2 y1) 4))))))
1285 (defun doc-view-reset-slice ()
1286 "Reset the current slice.
1287 After calling this function whole pages will be visible again."
1288 (interactive)
1289 (setf (doc-view-current-slice) nil)
1290 ;; Redisplay
1291 (doc-view-goto-page (doc-view-current-page)))
1293 ;;;; Display
1295 (defun doc-view-insert-image (file &rest args)
1296 "Insert the given png FILE.
1297 ARGS is a list of image descriptors."
1298 (when doc-view--pending-cache-flush
1299 (clear-image-cache)
1300 (setq doc-view--pending-cache-flush nil))
1301 (let ((ol (doc-view-current-overlay)))
1302 ;; Only insert the image if the buffer is visible.
1303 (when (window-live-p (overlay-get ol 'window))
1304 (let* ((image (if (and file (file-readable-p file))
1305 (if (not (and doc-view-scale-internally
1306 (fboundp 'imagemagick-types)))
1307 (apply 'create-image file doc-view--image-type nil args)
1308 (unless (member :width args)
1309 (setq args `(,@args :width ,doc-view-image-width)))
1310 (apply 'create-image file 'imagemagick nil args))))
1311 (slice (doc-view-current-slice))
1312 (img-width (and image (car (image-size image))))
1313 (displayed-img-width (if (and image slice)
1314 (* (/ (float (nth 2 slice))
1315 (car (image-size image 'pixels)))
1316 img-width)
1317 img-width))
1318 (window-width (window-width)))
1319 (setf (doc-view-current-image) image)
1320 (move-overlay ol (point-min) (point-max))
1321 ;; In case the window is wider than the image, center the image
1322 ;; horizontally.
1323 (overlay-put ol 'before-string
1324 (when (and image (> window-width displayed-img-width))
1325 (propertize " " 'display
1326 `(space :align-to (+ center (-0.5 . ,displayed-img-width))))))
1327 (overlay-put ol 'display
1328 (cond
1329 (image
1330 (if slice
1331 (list (cons 'slice slice) image)
1332 image))
1333 ;; We're trying to display a page that doesn't exist.
1334 (doc-view--current-converter-processes
1335 ;; Maybe the page doesn't exist *yet*.
1336 "Cannot display this page (yet)!")
1338 ;; Typically happens if the conversion process somehow
1339 ;; failed. Better not signal an error here because it
1340 ;; could prevent a subsequent reconversion from fixing
1341 ;; the problem.
1342 (concat "Cannot display this page!\n"
1343 "Maybe because of a conversion failure!"))))
1344 (let ((win (overlay-get ol 'window)))
1345 (if (stringp (overlay-get ol 'display))
1346 (progn ;Make sure the text is not scrolled out of view.
1347 (set-window-hscroll win 0)
1348 (set-window-vscroll win 0))
1349 (let ((hscroll (image-mode-window-get 'hscroll win))
1350 (vscroll (image-mode-window-get 'vscroll win)))
1351 ;; Reset scroll settings, in case they were changed.
1352 (if hscroll (set-window-hscroll win hscroll))
1353 (if vscroll (set-window-vscroll win vscroll)))))))))
1355 (defun doc-view-sort (a b)
1356 "Return non-nil if A should be sorted before B.
1357 Predicate for sorting `doc-view--current-files'."
1358 (or (< (length a) (length b))
1359 (and (= (length a) (length b))
1360 (string< a b))))
1362 (defun doc-view-display (buffer &optional force)
1363 "Start viewing the document in BUFFER.
1364 If FORCE is non-nil, start viewing even if the document does not
1365 have the page we want to view."
1366 (with-current-buffer buffer
1367 (let ((prev-pages doc-view--current-files))
1368 (setq doc-view--current-files
1369 (sort (directory-files (doc-view--current-cache-dir) t
1370 (format doc-view--image-file-pattern
1371 "[0-9]+")
1373 'doc-view-sort))
1374 (unless (eq (length prev-pages) (length doc-view--current-files))
1375 (force-mode-line-update))
1376 (dolist (win (or (get-buffer-window-list buffer nil t)
1377 (list t)))
1378 (let* ((page (doc-view-current-page win))
1379 (pagefile (expand-file-name
1380 (format doc-view--image-file-pattern page)
1381 (doc-view--current-cache-dir))))
1382 (when (or force
1383 (and (not (member pagefile prev-pages))
1384 (member pagefile doc-view--current-files)))
1385 (if (windowp win)
1386 (with-selected-window win
1387 (cl-assert (eq (current-buffer) buffer) t)
1388 (doc-view-goto-page page))
1389 (doc-view-goto-page page))))))))
1391 (defun doc-view-buffer-message ()
1392 ;; Only show this message initially, not when refreshing the buffer (in which
1393 ;; case it's better to keep displaying the "stale" page while computing
1394 ;; the fresh new ones).
1395 (unless (overlay-get (doc-view-current-overlay) 'display)
1396 (overlay-put (doc-view-current-overlay) 'display
1397 (concat (propertize "Welcome to DocView!" 'face 'bold)
1398 "\n"
1400 If you see this buffer it means that the document you want to view is being
1401 converted to PNG and the conversion of the first page hasn't finished yet or
1402 `doc-view-conversion-refresh-interval' is set to nil.
1404 For now these keys are useful:
1406 `q' : Bury this buffer. Conversion will go on in background.
1407 `k' : Kill the conversion process and this buffer.
1408 `K' : Kill the conversion process.\n"))))
1410 (declare-function tooltip-show "tooltip" (text &optional use-echo-area))
1412 (defun doc-view-show-tooltip ()
1413 (interactive)
1414 (tooltip-show (doc-view-current-info)))
1416 (defun doc-view-open-text ()
1417 "Display the current doc's contents as text."
1418 (interactive)
1419 (if doc-view--current-converter-processes
1420 (message "DocView: please wait till conversion finished.")
1421 (let ((txt (expand-file-name "doc.txt" (doc-view--current-cache-dir))))
1422 (if (file-readable-p txt)
1423 (let ((inhibit-read-only t)
1424 (buffer-undo-list t)
1425 (dv-bfn doc-view--buffer-file-name))
1426 (erase-buffer)
1427 (set-buffer-multibyte t)
1428 (insert-file-contents txt)
1429 (text-mode)
1430 (setq-local doc-view--buffer-file-name dv-bfn)
1431 (set-buffer-modified-p nil)
1432 (doc-view-minor-mode)
1433 (add-hook 'write-file-functions
1434 (lambda ()
1435 (when (eq major-mode 'text-mode)
1436 (error "Cannot save text contents of document %s"
1437 buffer-file-name)))
1438 nil t))
1439 (doc-view-doc->txt txt 'doc-view-open-text)))))
1441 ;;;;; Toggle between editing and viewing
1443 (defvar-local doc-view-saved-settings nil
1444 "Doc-view settings saved while in some other mode.")
1445 (put 'doc-view-saved-settings 'permanent-local t)
1447 (defun doc-view-toggle-display ()
1448 "Toggle between editing a document as text or viewing it."
1449 (interactive)
1450 (cond
1451 ((eq major-mode 'doc-view-mode)
1452 ;; Switch to editing mode
1453 (doc-view-kill-proc)
1454 (setq buffer-read-only nil)
1455 ;; Switch to the previously used major mode or fall back to
1456 ;; normal mode.
1457 (doc-view-fallback-mode)
1458 (doc-view-minor-mode 1))
1459 ((eq major-mode 'text-mode)
1460 (let ((buffer-undo-list t))
1461 ;; We're currently viewing the document's text contents, so switch
1462 ;; back to .
1463 (setq buffer-read-only nil)
1464 (insert-file-contents doc-view--buffer-file-name nil nil nil t)
1465 (doc-view-fallback-mode)
1466 (doc-view-minor-mode 1)
1467 (set-buffer-modified-p nil)))
1469 ;; Switch to doc-view-mode
1470 (when (and (buffer-modified-p)
1471 (y-or-n-p "The buffer has been modified. Save the changes? "))
1472 (save-buffer))
1473 (doc-view-mode))))
1475 ;;;; Searching
1478 (defun doc-view-search-internal (regexp file)
1479 "Return a list of FILE's pages that contain text matching REGEXP.
1480 The value is an alist of the form (PAGE CONTEXTS) where PAGE is
1481 the pagenumber and CONTEXTS are all lines of text containing a match."
1482 (with-temp-buffer
1483 (insert-file-contents file)
1484 (let ((page 1)
1485 (lastpage 1)
1486 matches)
1487 (while (re-search-forward (concat "\\(?:\\([\f]\\)\\|\\("
1488 regexp "\\)\\)") nil t)
1489 (when (match-string 1) (setq page (1+ page)))
1490 (when (match-string 2)
1491 (if (/= page lastpage)
1492 (push (cons page
1493 (list (buffer-substring
1494 (line-beginning-position)
1495 (line-end-position))))
1496 matches)
1497 (setq matches (cons
1498 (append
1500 ;; This page already is a match.
1501 (car matches)
1502 ;; This is the first match on page.
1503 (list page))
1504 (list (buffer-substring
1505 (line-beginning-position)
1506 (line-end-position))))
1507 (cdr matches))))
1508 (setq lastpage page)))
1509 (nreverse matches))))
1511 (defun doc-view-search-no-of-matches (list)
1512 "Extract the number of matches from the search result LIST."
1513 (let ((no 0))
1514 (dolist (p list)
1515 (setq no (+ no (1- (length p)))))
1516 no))
1518 (defun doc-view-search-backward (new-query)
1519 "Call `doc-view-search' for backward search.
1520 If prefix NEW-QUERY is given, ask for a new regexp."
1521 (interactive "P")
1522 (doc-view-search new-query t))
1524 (defun doc-view-search (new-query &optional backward)
1525 "Jump to the next match or initiate a new search if NEW-QUERY is given.
1526 If the current document hasn't been transformed to plain text
1527 till now do that first.
1528 If BACKWARD is non-nil, jump to the previous match."
1529 (interactive "P")
1530 (if (and (not new-query)
1531 doc-view--current-search-matches)
1532 (if backward
1533 (doc-view-search-previous-match 1)
1534 (doc-view-search-next-match 1))
1535 ;; New search, so forget the old results.
1536 (setq doc-view--current-search-matches nil)
1537 (let ((txt (expand-file-name "doc.txt"
1538 (doc-view--current-cache-dir))))
1539 (if (file-readable-p txt)
1540 (progn
1541 (setq doc-view--current-search-matches
1542 (doc-view-search-internal
1543 (read-from-minibuffer "Regexp: ")
1544 txt))
1545 (message "DocView: search yielded %d matches."
1546 (doc-view-search-no-of-matches
1547 doc-view--current-search-matches)))
1548 ;; We must convert to TXT first!
1549 (if doc-view--current-converter-processes
1550 (message "DocView: please wait till conversion finished.")
1551 (doc-view-doc->txt txt (lambda () (doc-view-search nil))))))))
1553 (defun doc-view-search-next-match (arg)
1554 "Go to the ARGth next matching page."
1555 (interactive "p")
1556 (let* ((next-pages (cl-remove-if
1557 (lambda (i) (<= (car i) (doc-view-current-page)))
1558 doc-view--current-search-matches))
1559 (page (car (nth (1- arg) next-pages))))
1560 (if page
1561 (doc-view-goto-page page)
1562 (when (and
1563 doc-view--current-search-matches
1564 (y-or-n-p "No more matches after current page. Wrap to first match? "))
1565 (doc-view-goto-page (caar doc-view--current-search-matches))))))
1567 (defun doc-view-search-previous-match (arg)
1568 "Go to the ARGth previous matching page."
1569 (interactive "p")
1570 (let* ((prev-pages (cl-remove-if
1571 (lambda (i) (>= (car i) (doc-view-current-page)))
1572 doc-view--current-search-matches))
1573 (page (car (nth (1- arg) (nreverse prev-pages)))))
1574 (if page
1575 (doc-view-goto-page page)
1576 (when (and
1577 doc-view--current-search-matches
1578 (y-or-n-p "No more matches before current page. Wrap to last match? "))
1579 (doc-view-goto-page (caar (last doc-view--current-search-matches)))))))
1581 ;;;; User interface commands and the mode
1583 (put 'doc-view-mode 'mode-class 'special)
1585 (defun doc-view-already-converted-p ()
1586 "Return non-nil if the current doc was already converted."
1587 (and (file-exists-p (doc-view--current-cache-dir))
1588 ;; Check that the resolution info is there, otherwise it means
1589 ;; the conversion is incomplete.
1590 (file-readable-p (expand-file-name "resolution.el"
1591 (doc-view--current-cache-dir)))
1592 (> (length (directory-files
1593 (doc-view--current-cache-dir)
1594 nil (format doc-view--image-file-pattern "[0-9]+")))
1595 0)))
1597 (defun doc-view-initiate-display ()
1598 ;; Switch to image display if possible.
1599 (if (doc-view-mode-p doc-view-doc-type)
1600 (progn
1601 (doc-view-buffer-message)
1602 (setf (doc-view-current-page) (or (doc-view-current-page) 1))
1603 (if (doc-view-already-converted-p)
1604 (progn
1605 (message "DocView: using cached files!")
1606 ;; Load the saved resolution.
1607 (let* ((res-file
1608 (expand-file-name "resolution.el"
1609 (doc-view--current-cache-dir)))
1610 (res
1611 (with-temp-buffer
1612 (when (file-readable-p res-file)
1613 (insert-file-contents res-file)
1614 (read (current-buffer))))))
1615 (when (numberp res)
1616 (setq-local doc-view-resolution res)))
1617 (doc-view-display (current-buffer) 'force))
1618 (doc-view-convert-current-doc))
1619 (message
1620 "%s"
1621 (substitute-command-keys
1622 (concat "Type \\[doc-view-toggle-display] to toggle between "
1623 "editing or viewing the document."))))
1624 (message
1625 "%s"
1626 (concat "No PNG support is available, or some conversion utility for "
1627 (file-name-extension doc-view--buffer-file-name)
1628 " files is missing."))
1629 (if (and (executable-find doc-view-pdftotext-program)
1630 (y-or-n-p
1631 "Unable to render file. View extracted text instead? "))
1632 (doc-view-open-text)
1633 (doc-view-toggle-display))))
1635 (defvar bookmark-make-record-function)
1637 (defun doc-view-clone-buffer-hook ()
1638 ;; FIXME: There are several potential problems linked with reconversion
1639 ;; and auto-revert when we have indirect buffers because they share their
1640 ;; /tmp cache directory. This sharing is good (you'd rather not reconvert
1641 ;; for each clone), but that means that clones need to collaborate a bit.
1642 ;; I guess it mostly means: detect when a reconversion process is already
1643 ;; running, and run the sentinel in all clones.
1645 ;; Maybe the clones should really have a separate /tmp directory
1646 ;; so they could have a different resolution and you could use clones
1647 ;; for zooming.
1648 (remove-overlays (point-min) (point-max) 'doc-view t)
1649 (if (consp image-mode-winprops-alist) (setq image-mode-winprops-alist nil)))
1651 (defun doc-view-intersection (l1 l2)
1652 (let ((l ()))
1653 (dolist (x l1) (if (memq x l2) (push x l)))
1656 (defun doc-view-set-doc-type ()
1657 "Figure out the current document type (`doc-view-doc-type')."
1658 (let ((name-types
1659 (when buffer-file-name
1660 (cdr (assoc-string
1661 (file-name-extension buffer-file-name)
1663 ;; DVI
1664 ("dvi" dvi)
1665 ;; PDF
1666 ("pdf" pdf) ("epdf" pdf)
1667 ;; PostScript
1668 ("ps" ps) ("eps" ps)
1669 ;; DjVu
1670 ("djvu" djvu)
1671 ;; OpenDocument formats.
1672 ("odt" odf) ("ods" odf) ("odp" odf) ("odg" odf)
1673 ("odc" odf) ("odi" odf) ("odm" odf) ("ott" odf)
1674 ("ots" odf) ("otp" odf) ("otg" odf)
1675 ;; Microsoft Office formats (also handled by the odf
1676 ;; conversion chain).
1677 ("doc" odf) ("docx" odf) ("xls" odf) ("xlsx" odf)
1678 ("ppt" odf) ("pps" odf) ("pptx" odf) ("rtf" odf))
1679 t))))
1680 (content-types
1681 (save-excursion
1682 (goto-char (point-min))
1683 (cond
1684 ((looking-at "%!") '(ps))
1685 ((looking-at "%PDF") '(pdf))
1686 ((looking-at "\367\002") '(dvi))
1687 ((looking-at "AT&TFORM") '(djvu))))))
1688 (setq-local
1689 doc-view-doc-type
1690 (car (or (doc-view-intersection name-types content-types)
1691 (when (and name-types content-types)
1692 (error "Conflicting types: name says %s but content says %s"
1693 name-types content-types))
1694 name-types content-types
1695 (error "Cannot determine the document type"))))))
1697 (defun doc-view-set-up-single-converter ()
1698 "Find the right single-page converter for the current document type"
1699 (pcase-let ((`(,conv-function ,type ,extension)
1700 (pcase doc-view-doc-type
1701 (`djvu (list #'doc-view-djvu->tiff-converter-ddjvu 'tiff "tif"))
1702 (_ (list doc-view-pdf->png-converter-function 'png "png")))))
1703 (setq-local doc-view-single-page-converter-function conv-function)
1704 (setq-local doc-view--image-type type)
1705 (setq-local doc-view--image-file-pattern (concat "page-%s." extension))))
1707 ;; desktop.el integration
1709 (defun doc-view-desktop-save-buffer (_desktop-dirname)
1710 ;; FIXME: This is wrong, since this info is per-window but we only do it once
1711 ;; here for the buffer. IOW it should be saved via something like
1712 ;; `window-persistent-parameters'.
1713 `((page . ,(doc-view-current-page))
1714 (slice . ,(doc-view-current-slice))))
1716 (declare-function desktop-restore-file-buffer "desktop"
1717 (buffer-filename buffer-name buffer-misc))
1719 (defun doc-view-restore-desktop-buffer (file name misc)
1720 (let ((page (cdr (assq 'page misc)))
1721 (slice (cdr (assq 'slice misc))))
1722 (desktop-restore-file-buffer file name misc)
1723 ;; FIXME: We need to run this code after displaying the buffer.
1724 (with-selected-window (or (get-buffer-window (current-buffer) 0)
1725 (selected-window))
1726 ;; FIXME: This should be done for all windows restored that show
1727 ;; this buffer. Basically, the page/slice should be saved as
1728 ;; window-parameters in the window-state(s) and then restoring this
1729 ;; window-state should call us back (to interpret/use those parameters).
1730 (doc-view-goto-page page)
1731 (when slice (apply 'doc-view-set-slice slice))
1732 (current-buffer))))
1734 (add-to-list 'desktop-buffer-mode-handlers
1735 '(doc-view-mode . doc-view-restore-desktop-buffer))
1737 ;;;###autoload
1738 (defun doc-view-mode ()
1739 "Major mode in DocView buffers.
1741 DocView Mode is an Emacs document viewer. It displays PDF, PS
1742 and DVI files (as PNG images) in Emacs buffers.
1744 You can use \\<doc-view-mode-map>\\[doc-view-toggle-display] to
1745 toggle between displaying the document or editing it as text.
1746 \\{doc-view-mode-map}"
1747 (interactive)
1749 (if (= (point-min) (point-max))
1750 ;; The doc is empty or doesn't exist at all, so fallback to
1751 ;; another mode. We used to also check file-exists-p, but this
1752 ;; returns nil for tar members.
1753 (doc-view-fallback-mode)
1755 (let* ((prev-major-mode (if (derived-mode-p 'doc-view-mode)
1756 doc-view--previous-major-mode
1757 (unless (eq major-mode 'fundamental-mode)
1758 major-mode))))
1759 (kill-all-local-variables)
1760 (setq-local doc-view--previous-major-mode prev-major-mode))
1762 (dolist (var doc-view-saved-settings)
1763 (set (make-local-variable (car var)) (cdr var)))
1765 ;; Figure out the document type.
1766 (unless doc-view-doc-type
1767 (doc-view-set-doc-type))
1768 (doc-view-set-up-single-converter)
1769 (unless (memq doc-view-doc-type '(ps))
1770 (setq-local require-final-newline nil))
1772 (doc-view-make-safe-dir doc-view-cache-directory)
1773 ;; Handle compressed files, remote files, files inside archives
1774 (setq-local doc-view--buffer-file-name
1775 (cond
1776 (jka-compr-really-do-compress
1777 ;; FIXME: there's a risk of name conflicts here.
1778 (expand-file-name
1779 (file-name-nondirectory
1780 (file-name-sans-extension buffer-file-name))
1781 doc-view-cache-directory))
1782 ;; Is the file readable by local processes?
1783 ;; We used to use `file-remote-p' but it's unclear what it's
1784 ;; supposed to return nil for things like local files accessed
1785 ;; via `su' or via file://...
1786 ((let ((file-name-handler-alist nil))
1787 (not (and buffer-file-name
1788 (file-readable-p buffer-file-name))))
1789 ;; FIXME: there's a risk of name conflicts here.
1790 (expand-file-name
1791 (if buffer-file-name
1792 (file-name-nondirectory buffer-file-name)
1793 (buffer-name))
1794 doc-view-cache-directory))
1795 (t buffer-file-name)))
1796 (when (not (string= doc-view--buffer-file-name buffer-file-name))
1797 (write-region nil nil doc-view--buffer-file-name))
1799 (setq-local revert-buffer-function #'doc-view-revert-buffer)
1801 (add-hook 'change-major-mode-hook
1802 (lambda ()
1803 (doc-view-kill-proc)
1804 (remove-overlays (point-min) (point-max) 'doc-view t))
1805 nil t)
1806 (add-hook 'clone-indirect-buffer-hook 'doc-view-clone-buffer-hook nil t)
1807 (add-hook 'kill-buffer-hook 'doc-view-kill-proc nil t)
1808 (setq-local desktop-save-buffer 'doc-view-desktop-save-buffer)
1810 (remove-overlays (point-min) (point-max) 'doc-view t) ;Just in case.
1811 ;; Keep track of display info ([vh]scroll, page number, overlay,
1812 ;; ...) for each window in which this document is shown.
1813 (add-hook 'image-mode-new-window-functions
1814 'doc-view-new-window-function nil t)
1815 (image-mode-setup-winprops)
1817 (setq-local mode-line-position
1818 '(" P" (:eval (number-to-string (doc-view-current-page)))
1819 "/" (:eval (number-to-string (doc-view-last-page-number)))))
1820 ;; Don't scroll unless the user specifically asked for it.
1821 (setq-local auto-hscroll-mode nil)
1822 (if (boundp 'mwheel-scroll-up-function) ; not --without-x build
1823 (setq-local mwheel-scroll-up-function
1824 #'doc-view-scroll-up-or-next-page))
1825 (if (boundp 'mwheel-scroll-down-function)
1826 (setq-local mwheel-scroll-down-function
1827 #'doc-view-scroll-down-or-previous-page))
1828 (setq-local cursor-type nil)
1829 (use-local-map doc-view-mode-map)
1830 (add-hook 'after-revert-hook 'doc-view-reconvert-doc nil t)
1831 (setq-local bookmark-make-record-function
1832 #'doc-view-bookmark-make-record)
1833 (setq mode-name "DocView"
1834 buffer-read-only t
1835 major-mode 'doc-view-mode)
1836 (doc-view-initiate-display)
1837 ;; Switch off view-mode explicitly, because doc-view-mode is the
1838 ;; canonical view mode for PDF/PS/DVI files. This could be
1839 ;; switched on automatically depending on the value of
1840 ;; `view-read-only'.
1841 (setq-local view-read-only nil)
1842 (run-mode-hooks 'doc-view-mode-hook)))
1844 (defun doc-view-fallback-mode ()
1845 "Fallback to the previous or next best major mode."
1846 (let ((vars (if (derived-mode-p 'doc-view-mode)
1847 (mapcar (lambda (var) (cons var (symbol-value var)))
1848 '(doc-view-resolution
1849 image-mode-winprops-alist)))))
1850 (remove-overlays (point-min) (point-max) 'doc-view t)
1851 (if doc-view--previous-major-mode
1852 (funcall doc-view--previous-major-mode)
1853 (let ((auto-mode-alist
1854 (rassq-delete-all
1855 'doc-view-mode-maybe
1856 (rassq-delete-all 'doc-view-mode
1857 (copy-alist auto-mode-alist)))))
1858 (normal-mode)))
1859 (when vars
1860 (setq-local doc-view-saved-settings vars))))
1862 ;;;###autoload
1863 (defun doc-view-mode-maybe ()
1864 "Switch to `doc-view-mode' if possible.
1865 If the required external tools are not available, then fallback
1866 to the next best mode."
1867 (condition-case nil
1868 (doc-view-set-doc-type)
1869 (error (doc-view-fallback-mode)))
1870 (if (doc-view-mode-p doc-view-doc-type)
1871 (doc-view-mode)
1872 (doc-view-fallback-mode)))
1874 ;;;###autoload
1875 (define-minor-mode doc-view-minor-mode
1876 "Toggle displaying buffer via Doc View (Doc View minor mode).
1877 With a prefix argument ARG, enable Doc View minor mode if ARG is
1878 positive, and disable it otherwise. If called from Lisp, enable
1879 the mode if ARG is omitted or nil.
1881 See the command `doc-view-mode' for more information on this mode."
1882 nil " DocView" doc-view-minor-mode-map
1883 :group 'doc-view
1884 (when doc-view-minor-mode
1885 (add-hook 'change-major-mode-hook (lambda () (doc-view-minor-mode -1)) nil t)
1886 (message
1887 "%s"
1888 (substitute-command-keys
1889 "Type \\[doc-view-toggle-display] to toggle between editing or viewing the document."))))
1891 (defun doc-view-clear-cache ()
1892 "Delete the whole cache (`doc-view-cache-directory')."
1893 (interactive)
1894 (dired-delete-file doc-view-cache-directory 'always))
1896 (defun doc-view-dired-cache ()
1897 "Open `dired' in `doc-view-cache-directory'."
1898 (interactive)
1899 (dired doc-view-cache-directory))
1902 ;;;; Bookmark integration
1904 (declare-function bookmark-make-record-default
1905 "bookmark" (&optional no-file no-context posn))
1906 (declare-function bookmark-prop-get "bookmark" (bookmark prop))
1907 (declare-function bookmark-default-handler "bookmark" (bmk))
1909 (defun doc-view-bookmark-make-record ()
1910 (nconc (bookmark-make-record-default)
1911 `((page . ,(doc-view-current-page))
1912 (handler . doc-view-bookmark-jump))))
1914 ;;;###autoload
1915 (defun doc-view-bookmark-jump (bmk)
1916 ;; This implements the `handler' function interface for record type
1917 ;; returned by `doc-view-bookmark-make-record', which see.
1918 (let ((page (bookmark-prop-get bmk 'page))
1919 (show-fn-sym (make-symbol "doc-view-bookmark-after-jump-hook")))
1920 (fset show-fn-sym
1921 (lambda ()
1922 (remove-hook 'bookmark-after-jump-hook show-fn-sym)
1923 (when (not (eq major-mode 'doc-view-mode))
1924 (doc-view-toggle-display))
1925 (with-selected-window
1926 (or (get-buffer-window (current-buffer) 0)
1927 (selected-window))
1928 (doc-view-goto-page page))))
1929 (add-hook 'bookmark-after-jump-hook show-fn-sym)
1930 (bookmark-default-handler bmk)))
1932 (provide 'doc-view)
1934 ;; Local Variables:
1935 ;; eval: (outline-minor-mode 1)
1936 ;; End:
1938 ;;; doc-view.el ends here