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