* lisp/emacs-lisp/bytecomp.el (byte-compile-file): Use let.
[emacs.git] / lisp / doc-view.el
blob89d2edd3dbb429edaa9e00d71720c59e165f94a2
1 ;;; doc-view.el --- View PDF/PostScript/DVI files in Emacs -*- lexical-binding: t -*-
4 ;; Copyright (C) 2007-2013 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Tassilo Horn <tsdh@gnu.org>
7 ;; Maintainer: Tassilo Horn <tsdh@gnu.org>
8 ;; Keywords: files, pdf, ps, dvi
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;; Requirements:
27 ;; doc-view.el requires GNU Emacs 22.1 or newer. You also need Ghostscript,
28 ;; `dvipdf' (comes with Ghostscript) or `dvipdfm' (comes with teTeX or TeXLive)
29 ;; and `pdftotext', which comes with xpdf (http://www.foolabs.com/xpdf/) or
30 ;; poppler (http://poppler.freedesktop.org/).
32 ;;; Commentary:
34 ;; DocView is a document viewer for Emacs. It converts PDF, PS and DVI files
35 ;; to a set of PNG files, one PNG for each page, and displays the PNG images
36 ;; inside an Emacs buffer. This buffer uses `doc-view-mode' which provides
37 ;; convenient key bindings for browsing the document.
39 ;; To use it simply open a document file with
41 ;; C-x C-f ~/path/to/document RET
43 ;; and the document will be converted and displayed, if your emacs supports png
44 ;; images. With `C-c C-c' you can toggle between the rendered images
45 ;; representation and the source text representation of the document.
47 ;; Since conversion may take some time all the PNG images are cached in a
48 ;; subdirectory of `doc-view-cache-directory' and reused when you want to view
49 ;; that file again. To reconvert a document hit `g' (`doc-view-reconvert-doc')
50 ;; when displaying the document. To delete all cached files use
51 ;; `doc-view-clear-cache'. To open the cache with dired, so that you can tidy
52 ;; it out use `doc-view-dired-cache'.
54 ;; When conversion in underway the first page will be displayed as soon as it
55 ;; is available and the available pages are refreshed every
56 ;; `doc-view-conversion-refresh-interval' seconds. If that variable is nil the
57 ;; pages won't be displayed before conversion of the document finished
58 ;; completely.
60 ;; DocView lets you select a slice of the displayed pages. This slice
61 ;; will be remembered and applied to all pages of the current
62 ;; document. This enables you to cut away the margins of a document
63 ;; to save some space. To select a slice you can use
64 ;; `doc-view-set-slice' (bound to `s s') which will query you for the
65 ;; coordinates of the slice's top-left corner and its width and
66 ;; height. A much more convenient way to do the same is offered by
67 ;; the command `doc-view-set-slice-using-mouse' (bound to `s m').
68 ;; After invocation you only have to press mouse-1 at the top-left
69 ;; corner and drag it to the bottom-right corner of the desired slice.
70 ;; Even more accurate and convenient is to use
71 ;; `doc-view-set-slice-from-bounding-box' (bound to `s b') which uses
72 ;; the BoundingBox information of the current page to set an optimal
73 ;; slice. To reset the slice use `doc-view-reset-slice' (bound to `s
74 ;; r').
76 ;; You can also search within the document. The command `doc-view-search'
77 ;; (bound to `C-s') queries for a search regexp and initializes a list of all
78 ;; matching pages and messages how many match-pages were found. After that you
79 ;; can jump to the next page containing a match with an additional `C-s'. With
80 ;; `C-r' you can do the same, but backwards. To search for a new regexp give a
81 ;; prefix arg to one of the search functions, e.g. by typing `C-u C-s'. The
82 ;; searching works by using a plain text representation of the document. If
83 ;; that doesn't already exist the first invocation of `doc-view-search' (or
84 ;; `doc-view-search-backward') starts the conversion. When that finishes and
85 ;; you're still viewing the document (i.e. you didn't switch to another buffer)
86 ;; you're queried for the regexp then.
88 ;; Dired users can simply hit `v' on a document file. If it's a PS, PDF or DVI
89 ;; it will be opened using `doc-view-mode'.
92 ;;; Configuration:
94 ;; If the images are too small or too big you should set the "-rXXX" option in
95 ;; `doc-view-ghostscript-options' to another value. (The bigger your screen,
96 ;; the higher the value.)
98 ;; This and all other options can be set with the customization interface.
99 ;; Simply do
101 ;; M-x customize-group RET doc-view RET
103 ;; and modify them to your needs.
105 ;;; Todo:
107 ;; - add print command.
108 ;; - share more code with image-mode.
109 ;; - better menu.
110 ;; - Bind slicing to a drag event.
111 ;; - zoom the region around the cursor (like xdvi).
112 ;; - get rid of the silly arrow in the fringe.
113 ;; - improve anti-aliasing (pdf-utils gets it better).
115 ;;;; About isearch support
117 ;; I tried implementing isearch by setting
118 ;; `isearch-search-fun-function' buffer-locally, but that didn't
119 ;; work too good. The function doing the real search was called
120 ;; endlessly somehow. But even if we'd get that working no real
121 ;; isearch feeling comes up due to the missing match highlighting.
122 ;; Currently I display all lines containing a match in a tooltip and
123 ;; each C-s or C-r jumps directly to the next/previous page with a
124 ;; match. With isearch we could only display the current match. So
125 ;; we had to decide if another C-s jumps to the next page with a
126 ;; match (thus only the first match in a page will be displayed in a
127 ;; tooltip) or to the next match, which would do nothing visible
128 ;; (except the tooltip) if the next match is on the same page.
130 ;; And it's much slower than the current search facility, because
131 ;; isearch really searches for each step forward or backward whereas
132 ;; the current approach searches once and then it knows to which
133 ;; pages to jump.
135 ;; Anyway, if someone with better isearch knowledge wants to give it a try,
136 ;; feel free to do it. --Tassilo
138 ;;; Code:
140 (eval-when-compile (require 'cl-lib))
141 (require 'dired)
142 (require 'image-mode)
143 (require 'jka-compr)
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 :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 (defun doc-view-new-window-function (winprops)
310 ;; (message "New window %s for buf %s" (car winprops) (current-buffer))
311 (cl-assert (or (eq t (car winprops))
312 (eq (window-buffer (car winprops)) (current-buffer))))
313 (let ((ol (image-mode-window-get 'overlay winprops)))
314 (if ol
315 (progn
316 (setq ol (copy-overlay ol))
317 ;; `ol' might actually be dead.
318 (move-overlay ol (point-min) (point-max)))
319 (setq ol (make-overlay (point-min) (point-max) nil t))
320 (overlay-put ol 'doc-view t))
321 (overlay-put ol 'window (car winprops))
322 (unless (windowp (car winprops))
323 ;; It's a pseudo entry. Let's make sure it's not displayed (the
324 ;; `window' property is only effective if its value is a window).
325 (cl-assert (eq t (car winprops)))
326 (delete-overlay ol))
327 (image-mode-window-put 'overlay ol winprops)))
329 (defvar doc-view-current-files nil
330 "Only used internally.")
331 (make-variable-buffer-local 'doc-view-current-files)
333 (defvar doc-view-current-converter-processes nil
334 "Only used internally.")
335 (make-variable-buffer-local 'doc-view-current-converter-processes)
337 (defvar doc-view-current-timer nil
338 "Only used internally.")
339 (make-variable-buffer-local 'doc-view-current-timer)
341 (defvar doc-view-current-cache-dir nil
342 "Only used internally.")
343 (make-variable-buffer-local 'doc-view-current-cache-dir)
345 (defvar doc-view-current-search-matches nil
346 "Only used internally.")
347 (make-variable-buffer-local 'doc-view-current-search-matches)
349 (defvar doc-view-pending-cache-flush nil
350 "Only used internally.")
352 (defvar doc-view-previous-major-mode nil
353 "Only used internally.")
355 (defvar doc-view-buffer-file-name nil
356 "Only used internally.
357 The file name used for conversion. Normally it's the same as
358 `buffer-file-name', but for remote files, compressed files and
359 files inside an archive it is a temporary copy of
360 the (uncompressed, extracted) file residing in
361 `doc-view-cache-directory'.")
363 (defvar doc-view-doc-type nil
364 "The type of document in the current buffer.
365 Can be `dvi', `pdf', or `ps'.")
367 (defvar doc-view-single-page-converter-function nil
368 "Function to call to convert a single page of the document to a bitmap file.
369 May operate on the source document or on some intermediate (typically PDF)
370 conversion of it.")
372 (defvar-local doc-view--image-type nil
373 "The type of image in the current buffer.
374 Can be `png' or `tiff'.")
376 (defvar-local doc-view--image-file-pattern nil
377 "The `format' pattern of image file names.
378 Typically \"page-%s.png\".")
380 ;;;; DocView Keymaps
382 (defvar doc-view-mode-map
383 (let ((map (make-sparse-keymap)))
384 (set-keymap-parent map image-mode-map)
385 ;; Navigation in the document
386 (define-key map (kbd "n") 'doc-view-next-page)
387 (define-key map (kbd "p") 'doc-view-previous-page)
388 (define-key map (kbd "<next>") 'forward-page)
389 (define-key map (kbd "<prior>") 'backward-page)
390 (define-key map [remap forward-page] 'doc-view-next-page)
391 (define-key map [remap backward-page] 'doc-view-previous-page)
392 (define-key map (kbd "SPC") 'doc-view-scroll-up-or-next-page)
393 (define-key map (kbd "S-SPC") 'doc-view-scroll-down-or-previous-page)
394 (define-key map (kbd "DEL") 'doc-view-scroll-down-or-previous-page)
395 (define-key map (kbd "C-n") 'doc-view-next-line-or-next-page)
396 (define-key map (kbd "<down>") 'doc-view-next-line-or-next-page)
397 (define-key map (kbd "C-p") 'doc-view-previous-line-or-previous-page)
398 (define-key map (kbd "<up>") 'doc-view-previous-line-or-previous-page)
399 (define-key map (kbd "M-<") 'doc-view-first-page)
400 (define-key map (kbd "M->") 'doc-view-last-page)
401 (define-key map [remap goto-line] 'doc-view-goto-page)
402 (define-key map (kbd "RET") 'image-next-line)
403 ;; Zoom in/out.
404 (define-key map "+" 'doc-view-enlarge)
405 (define-key map "-" 'doc-view-shrink)
406 ;; Fit the image to the window
407 (define-key map "W" 'doc-view-fit-width-to-window)
408 (define-key map "H" 'doc-view-fit-height-to-window)
409 (define-key map "P" 'doc-view-fit-page-to-window)
410 ;; Killing the buffer (and the process)
411 (define-key map (kbd "k") 'doc-view-kill-proc-and-buffer)
412 (define-key map (kbd "K") 'doc-view-kill-proc)
413 ;; Slicing the image
414 (define-key map (kbd "s s") 'doc-view-set-slice)
415 (define-key map (kbd "s m") 'doc-view-set-slice-using-mouse)
416 (define-key map (kbd "s b") 'doc-view-set-slice-from-bounding-box)
417 (define-key map (kbd "s r") 'doc-view-reset-slice)
418 ;; Searching
419 (define-key map (kbd "C-s") 'doc-view-search)
420 (define-key map (kbd "<find>") 'doc-view-search)
421 (define-key map (kbd "C-r") 'doc-view-search-backward)
422 ;; Show the tooltip
423 (define-key map (kbd "C-t") 'doc-view-show-tooltip)
424 ;; Toggle between text and image display or editing
425 (define-key map (kbd "C-c C-c") 'doc-view-toggle-display)
426 ;; Open a new buffer with doc's text contents
427 (define-key map (kbd "C-c C-t") 'doc-view-open-text)
428 ;; Reconvert the current document. Don't just use revert-buffer
429 ;; because that resets the scale factor, the page number, ...
430 (define-key map (kbd "g") 'doc-view-revert-buffer)
431 (define-key map (kbd "r") 'doc-view-revert-buffer)
432 map)
433 "Keymap used by `doc-view-mode' when displaying a doc as a set of images.")
435 (defun doc-view-revert-buffer (&optional ignore-auto noconfirm)
436 "Like `revert-buffer', but preserves the buffer's current modes."
437 ;; FIXME: this should probably be moved to files.el and used for
438 ;; most/all "g" bindings to revert-buffer.
439 (interactive (list (not current-prefix-arg)))
440 (revert-buffer ignore-auto noconfirm 'preserve-modes))
443 (easy-menu-define doc-view-menu doc-view-mode-map
444 "Menu for Doc View mode."
445 '("DocView"
446 ["Toggle display" doc-view-toggle-display]
447 ("Continuous"
448 ["Off" (setq doc-view-continuous nil)
449 :style radio :selected (eq doc-view-continuous nil)]
450 ["On" (setq doc-view-continuous t)
451 :style radio :selected (eq doc-view-continuous t)]
452 "---"
453 ["Save as Default"
454 (customize-save-variable 'doc-view-continuous doc-view-continuous) t]
456 "---"
457 ["Set Slice" doc-view-set-slice-using-mouse]
458 ["Set Slice (BoundingBox)" doc-view-set-slice-from-bounding-box]
459 ["Set Slice (manual)" doc-view-set-slice]
460 ["Reset Slice" doc-view-reset-slice]
461 "---"
462 ["Search" doc-view-search]
463 ["Search Backwards" doc-view-search-backward]
466 (defvar doc-view-minor-mode-map
467 (let ((map (make-sparse-keymap)))
468 ;; Toggle between text and image display or editing
469 (define-key map (kbd "C-c C-c") 'doc-view-toggle-display)
470 map)
471 "Keymap used by `doc-minor-view-mode'.")
473 ;;;; Navigation Commands
475 (defmacro doc-view-current-page (&optional win)
476 `(image-mode-window-get 'page ,win))
477 (defmacro doc-view-current-info () `(image-mode-window-get 'info))
478 (defmacro doc-view-current-overlay () `(image-mode-window-get 'overlay))
479 (defmacro doc-view-current-image () `(image-mode-window-get 'image))
480 (defmacro doc-view-current-slice () `(image-mode-window-get 'slice))
482 (defun doc-view-last-page-number ()
483 (length doc-view-current-files))
485 (defun doc-view-goto-page (page)
486 "View the page given by PAGE."
487 (interactive "nPage: ")
488 (let ((len (doc-view-last-page-number))
489 (hscroll (window-hscroll)))
490 (if (< page 1)
491 (setq page 1)
492 (when (and (> page len)
493 ;; As long as the converter is running, we don't know
494 ;; how many pages will be available.
495 (null doc-view-current-converter-processes))
496 (setq page len)))
497 (setf (doc-view-current-page) page
498 (doc-view-current-info)
499 (concat
500 (propertize
501 (format "Page %d of %d." page len) 'face 'bold)
502 ;; Tell user if converting isn't finished yet
503 (if doc-view-current-converter-processes
504 " (still converting...)\n"
505 "\n")
506 ;; Display context infos if this page matches the last search
507 (when (and doc-view-current-search-matches
508 (assq page doc-view-current-search-matches))
509 (concat (propertize "Search matches:\n" 'face 'bold)
510 (let ((contexts ""))
511 (dolist (m (cdr (assq page
512 doc-view-current-search-matches)))
513 (setq contexts (concat contexts " - \"" m "\"\n")))
514 contexts)))))
515 ;; Update the buffer
516 ;; We used to find the file name from doc-view-current-files but
517 ;; that's not right if the pages are not generated sequentially
518 ;; or if the page isn't in doc-view-current-files yet.
519 (let ((file (expand-file-name
520 (format doc-view--image-file-pattern page)
521 (doc-view-current-cache-dir))))
522 (doc-view-insert-image file :pointer 'arrow)
523 (set-window-hscroll (selected-window) hscroll)
524 (when (and (not (file-exists-p file))
525 doc-view-current-converter-processes)
526 ;; The PNG file hasn't been generated yet.
527 (funcall doc-view-single-page-converter-function
528 doc-view-buffer-file-name file page
529 (let ((win (selected-window)))
530 (lambda ()
531 (and (eq (current-buffer) (window-buffer win))
532 ;; If we changed page in the mean
533 ;; time, don't mess things up.
534 (eq (doc-view-current-page win) page)
535 ;; Make sure we don't infloop.
536 (file-readable-p file)
537 (with-selected-window win
538 (doc-view-goto-page page))))))))
539 (overlay-put (doc-view-current-overlay)
540 'help-echo (doc-view-current-info))))
542 (defun doc-view-next-page (&optional arg)
543 "Browse ARG pages forward."
544 (interactive "p")
545 (doc-view-goto-page (+ (doc-view-current-page) (or arg 1))))
547 (defun doc-view-previous-page (&optional arg)
548 "Browse ARG pages backward."
549 (interactive "p")
550 (doc-view-goto-page (- (doc-view-current-page) (or arg 1))))
552 (defun doc-view-first-page ()
553 "View the first page."
554 (interactive)
555 (doc-view-goto-page 1))
557 (defun doc-view-last-page ()
558 "View the last page."
559 (interactive)
560 (doc-view-goto-page (doc-view-last-page-number)))
562 (defun doc-view-scroll-up-or-next-page (&optional arg)
563 "Scroll page up ARG lines if possible, else goto next page.
564 When `doc-view-continuous' is non-nil, scrolling upward
565 at the bottom edge of the page moves to the next page.
566 Otherwise, goto next page only on typing SPC (ARG is nil)."
567 (interactive "P")
568 (if (or doc-view-continuous (null arg))
569 (let ((hscroll (window-hscroll))
570 (cur-page (doc-view-current-page)))
571 (when (= (window-vscroll) (image-scroll-up arg))
572 (doc-view-next-page)
573 (when (/= cur-page (doc-view-current-page))
574 (image-bob)
575 (image-bol 1))
576 (set-window-hscroll (selected-window) hscroll)))
577 (image-scroll-up arg)))
579 (defun doc-view-scroll-down-or-previous-page (&optional arg)
580 "Scroll page down ARG lines if possible, else goto previous page.
581 When `doc-view-continuous' is non-nil, scrolling downward
582 at the top edge of the page moves to the previous page.
583 Otherwise, goto previous page only on typing DEL (ARG is nil)."
584 (interactive "P")
585 (if (or doc-view-continuous (null arg))
586 (let ((hscroll (window-hscroll))
587 (cur-page (doc-view-current-page)))
588 (when (= (window-vscroll) (image-scroll-down arg))
589 (doc-view-previous-page)
590 (when (/= cur-page (doc-view-current-page))
591 (image-eob)
592 (image-bol 1))
593 (set-window-hscroll (selected-window) hscroll)))
594 (image-scroll-down arg)))
596 (defun doc-view-next-line-or-next-page (&optional arg)
597 "Scroll upward by ARG lines if possible, else goto next page.
598 When `doc-view-continuous' is non-nil, scrolling a line upward
599 at the bottom edge of the page moves to the next page."
600 (interactive "p")
601 (if doc-view-continuous
602 (let ((hscroll (window-hscroll))
603 (cur-page (doc-view-current-page)))
604 (when (= (window-vscroll) (image-next-line arg))
605 (doc-view-next-page)
606 (when (/= cur-page (doc-view-current-page))
607 (image-bob)
608 (image-bol 1))
609 (set-window-hscroll (selected-window) hscroll)))
610 (image-next-line 1)))
612 (defun doc-view-previous-line-or-previous-page (&optional arg)
613 "Scroll downward by ARG lines if possible, else goto previous page.
614 When `doc-view-continuous' is non-nil, scrolling a line downward
615 at the top edge of the page moves to the previous page."
616 (interactive "p")
617 (if doc-view-continuous
618 (let ((hscroll (window-hscroll))
619 (cur-page (doc-view-current-page)))
620 (when (= (window-vscroll) (image-previous-line arg))
621 (doc-view-previous-page)
622 (when (/= cur-page (doc-view-current-page))
623 (image-eob)
624 (image-bol 1))
625 (set-window-hscroll (selected-window) hscroll)))
626 (image-previous-line arg)))
628 ;;;; Utility Functions
630 (defun doc-view-kill-proc ()
631 "Kill the current converter process(es)."
632 (interactive)
633 (while (consp doc-view-current-converter-processes)
634 (ignore-errors ;; Some entries might not be processes, and maybe
635 ;; some are dead already?
636 (kill-process (pop doc-view-current-converter-processes))))
637 (when doc-view-current-timer
638 (cancel-timer doc-view-current-timer)
639 (setq doc-view-current-timer nil))
640 (setq mode-line-process nil))
642 (defun doc-view-kill-proc-and-buffer ()
643 "Kill the current converter process and buffer."
644 (interactive)
645 (doc-view-kill-proc)
646 (when (eq major-mode 'doc-view-mode)
647 (kill-buffer (current-buffer))))
649 (defun doc-view-make-safe-dir (dir)
650 (condition-case nil
651 (let ((umask (default-file-modes)))
652 (unwind-protect
653 (progn
654 ;; Create temp files with strict access rights. It's easy to
655 ;; loosen them later, whereas it's impossible to close the
656 ;; time-window of loose permissions otherwise.
657 (set-default-file-modes #o0700)
658 (make-directory dir))
659 ;; Reset the umask.
660 (set-default-file-modes umask)))
661 (file-already-exists
662 (when (file-symlink-p dir)
663 (error "Danger: %s points to a symbolic link" dir))
664 ;; In case it was created earlier with looser rights.
665 ;; We could check the mode info returned by file-attributes, but it's
666 ;; a pain to parse and it may not tell you what we want under
667 ;; non-standard file-systems. So let's just say what we want and let
668 ;; the underlying C code and file-system figure it out.
669 ;; This also ends up checking a bunch of useful conditions: it makes
670 ;; sure we have write-access to the directory and that we own it, thus
671 ;; closing a bunch of security holes.
672 (condition-case error
673 (set-file-modes dir #o0700)
674 (file-error
675 (error
676 (format "Unable to use temporary directory %s: %s"
677 dir (mapconcat 'identity (cdr error) " "))))))))
679 (defun doc-view-current-cache-dir ()
680 "Return the directory where the png files of the current doc should be saved.
681 It's a subdirectory of `doc-view-cache-directory'."
682 (if doc-view-current-cache-dir
683 doc-view-current-cache-dir
684 ;; Try and make sure doc-view-cache-directory exists and is safe.
685 (doc-view-make-safe-dir doc-view-cache-directory)
686 ;; Now compute the subdirectory to use.
687 (setq doc-view-current-cache-dir
688 (file-name-as-directory
689 (expand-file-name
690 (concat (subst-char-in-string ?% ?_ ;; bug#13679
691 (file-name-nondirectory doc-view-buffer-file-name))
693 (let ((file doc-view-buffer-file-name))
694 (with-temp-buffer
695 (set-buffer-multibyte nil)
696 (insert-file-contents-literally file)
697 (md5 (current-buffer)))))
698 doc-view-cache-directory)))))
700 (defun doc-view-remove-if (predicate list)
701 "Return LIST with all items removed that satisfy PREDICATE."
702 (let (new-list)
703 (dolist (item list)
704 (when (not (funcall predicate item))
705 (setq new-list (cons item new-list))))
706 (nreverse new-list)))
708 ;;;###autoload
709 (defun doc-view-mode-p (type)
710 "Return non-nil if document type TYPE is available for `doc-view'.
711 Document types are symbols like `dvi', `ps', `pdf', or `odf' (any
712 OpenDocument format)."
713 (and (display-graphic-p)
714 (or (image-type-available-p 'imagemagick)
715 (image-type-available-p 'png))
716 (cond
717 ((eq type 'dvi)
718 (and (doc-view-mode-p 'pdf)
719 (or (and doc-view-dvipdf-program
720 (executable-find doc-view-dvipdf-program))
721 (and doc-view-dvipdfm-program
722 (executable-find doc-view-dvipdfm-program)))))
723 ((memq type '(postscript ps eps pdf))
724 ;; FIXME: allow mupdf here
725 (and doc-view-ghostscript-program
726 (executable-find doc-view-ghostscript-program)))
727 ((eq type 'odf)
728 (and doc-view-odf->pdf-converter-program
729 (executable-find doc-view-odf->pdf-converter-program)
730 (doc-view-mode-p 'pdf)))
731 ((eq type 'djvu)
732 (executable-find "ddjvu"))
733 (t ;; unknown image type
734 nil))))
736 ;;;; Conversion Functions
738 (defvar doc-view-shrink-factor 1.125)
740 (defun doc-view-enlarge (factor)
741 "Enlarge the document by FACTOR."
742 (interactive (list doc-view-shrink-factor))
743 (if (and doc-view-scale-internally
744 (eq (plist-get (cdr (doc-view-current-image)) :type)
745 'imagemagick))
746 ;; ImageMagick supports on-the-fly-rescaling.
747 (let ((new (ceiling (* factor doc-view-image-width))))
748 (unless (equal new doc-view-image-width)
749 (setq-local doc-view-image-width new)
750 (doc-view-insert-image
751 (plist-get (cdr (doc-view-current-image)) :file)
752 :width doc-view-image-width)))
753 (let ((new (ceiling (* factor doc-view-resolution))))
754 (unless (equal new doc-view-resolution)
755 (setq-local doc-view-resolution new)
756 (doc-view-reconvert-doc)))))
758 (defun doc-view-shrink (factor)
759 "Shrink the document."
760 (interactive (list doc-view-shrink-factor))
761 (doc-view-enlarge (/ 1.0 factor)))
763 (defun doc-view-fit-width-to-window ()
764 "Fit the image width to the window width."
765 (interactive)
766 (let ((win-width (- (nth 2 (window-inside-pixel-edges))
767 (nth 0 (window-inside-pixel-edges))))
768 (slice (doc-view-current-slice)))
769 (if (not slice)
770 (let ((img-width (car (image-display-size
771 (image-get-display-property) t))))
772 (doc-view-enlarge (/ (float win-width) (float img-width))))
774 ;; If slice is set
775 (let* ((slice-width (nth 2 slice))
776 (scale-factor (/ (float win-width) (float slice-width)))
777 (new-slice (mapcar (lambda (x) (ceiling (* scale-factor x))) slice)))
779 (doc-view-enlarge scale-factor)
780 (setf (doc-view-current-slice) new-slice)
781 (doc-view-goto-page (doc-view-current-page))))))
783 (defun doc-view-fit-height-to-window ()
784 "Fit the image height to the window height."
785 (interactive)
786 (let ((win-height (- (nth 3 (window-inside-pixel-edges))
787 (nth 1 (window-inside-pixel-edges))))
788 (slice (doc-view-current-slice)))
789 (if (not slice)
790 (let ((img-height (cdr (image-display-size
791 (image-get-display-property) t))))
792 ;; When users call 'doc-view-fit-height-to-window',
793 ;; they might want to go to next page by typing SPC
794 ;; ONLY once. So I used '(- win-height 1)' instead of
795 ;; 'win-height'
796 (doc-view-enlarge (/ (float (- win-height 1)) (float img-height))))
798 ;; If slice is set
799 (let* ((slice-height (nth 3 slice))
800 (scale-factor (/ (float (- win-height 1)) (float slice-height)))
801 (new-slice (mapcar (lambda (x) (ceiling (* scale-factor x))) slice)))
803 (doc-view-enlarge scale-factor)
804 (setf (doc-view-current-slice) new-slice)
805 (doc-view-goto-page (doc-view-current-page))))))
807 (defun doc-view-fit-page-to-window ()
808 "Fit the image to the window.
809 More specifically, this function enlarges image by:
811 min {(window-width / image-width), (window-height / image-height)} times."
812 (interactive)
813 (let ((win-width (- (nth 2 (window-inside-pixel-edges))
814 (nth 0 (window-inside-pixel-edges))))
815 (win-height (- (nth 3 (window-inside-pixel-edges))
816 (nth 1 (window-inside-pixel-edges))))
817 (slice (doc-view-current-slice)))
818 (if (not slice)
819 (let ((img-width (car (image-display-size
820 (image-get-display-property) t)))
821 (img-height (cdr (image-display-size
822 (image-get-display-property) t))))
823 (doc-view-enlarge (min (/ (float win-width) (float img-width))
824 (/ (float (- win-height 1))
825 (float img-height)))))
826 ;; If slice is set
827 (let* ((slice-width (nth 2 slice))
828 (slice-height (nth 3 slice))
829 (scale-factor (min (/ (float win-width) (float slice-width))
830 (/ (float (- win-height 1))
831 (float slice-height))))
832 (new-slice (mapcar (lambda (x) (ceiling (* scale-factor x))) slice)))
833 (doc-view-enlarge scale-factor)
834 (setf (doc-view-current-slice) new-slice)
835 (doc-view-goto-page (doc-view-current-page))))))
837 (defun doc-view-reconvert-doc ()
838 "Reconvert the current document.
839 Should be invoked when the cached images aren't up-to-date."
840 (interactive)
841 (doc-view-kill-proc)
842 ;; Clear the old cached files
843 (when (file-exists-p (doc-view-current-cache-dir))
844 (delete-directory (doc-view-current-cache-dir) 'recursive))
845 (kill-local-variable 'doc-view-last-page-number)
846 (doc-view-initiate-display))
848 (defun doc-view-sentinel (proc event)
849 "Generic sentinel for doc-view conversion processes."
850 (if (not (string-match "finished" event))
851 (message "DocView: process %s changed status to %s."
852 (process-name proc)
853 (if (string-match "\\(.+\\)\n?\\'" event)
854 (match-string 1 event)
855 event))
856 (when (buffer-live-p (process-get proc 'buffer))
857 (with-current-buffer (process-get proc 'buffer)
858 (setq doc-view-current-converter-processes
859 (delq proc doc-view-current-converter-processes))
860 (setq mode-line-process
861 (if doc-view-current-converter-processes
862 (format ":%s" (car doc-view-current-converter-processes))))
863 (funcall (process-get proc 'callback))))))
865 (defun doc-view-start-process (name program args callback)
866 ;; Make sure the process is started in an existing directory, (rather than
867 ;; some file-name-handler-managed dir, for example).
868 (let* ((default-directory (if (file-readable-p default-directory)
869 default-directory
870 (expand-file-name "~/")))
871 (proc (apply 'start-process name doc-view-conversion-buffer
872 program args)))
873 (push proc doc-view-current-converter-processes)
874 (setq mode-line-process (list (format ":%s" proc)))
875 (set-process-sentinel proc 'doc-view-sentinel)
876 (process-put proc 'buffer (current-buffer))
877 (process-put proc 'callback callback)))
879 (defun doc-view-dvi->pdf (dvi pdf callback)
880 "Convert DVI to PDF asynchronously and call CALLBACK when finished."
881 ;; Prefer dvipdf over dvipdfm, because the latter has problems if the DVI
882 ;; references and includes other PS files.
883 (if (and doc-view-dvipdf-program
884 (executable-find doc-view-dvipdf-program))
885 (doc-view-start-process "dvi->pdf" doc-view-dvipdf-program
886 (list dvi pdf)
887 callback)
888 (doc-view-start-process "dvi->pdf" doc-view-dvipdfm-program
889 (list "-o" pdf dvi)
890 callback)))
892 (defun doc-view-pdf->png-converter-ghostscript (pdf png page callback)
893 (doc-view-start-process
894 "pdf/ps->png" doc-view-ghostscript-program
895 `(,@doc-view-ghostscript-options
896 ,(format "-r%d" (round doc-view-resolution))
897 ,@(if page `(,(format "-dFirstPage=%d" page)))
898 ,@(if page `(,(format "-dLastPage=%d" page)))
899 ,(concat "-sOutputFile=" png)
900 ,pdf)
901 callback))
903 (defalias 'doc-view-ps->png-converter-ghostscript
904 'doc-view-pdf->png-converter-ghostscript)
906 (defun doc-view-djvu->tiff-converter-ddjvu (djvu tiff page callback)
907 "Convert PAGE of a DJVU file to bitmap(s) asynchronously.
908 Call CALLBACK with no arguments when done.
909 If PAGE is nil, convert the whole document."
910 (doc-view-start-process
911 "djvu->tiff" "ddjvu"
912 `("-format=tiff"
913 ;; ddjvu only accepts the range 1-999.
914 ,(format "-scale=%d" (round doc-view-resolution))
915 ;; -eachpage was only added after djvulibre-3.5.25.3!
916 ,@(unless page '("-eachpage"))
917 ,@(if page `(,(format "-page=%d" page)))
918 ,djvu
919 ,tiff)
920 callback))
922 (defun doc-view-pdf->png-converter-mupdf (pdf png page callback)
923 (doc-view-start-process
924 "pdf->png" doc-view-pdfdraw-program
925 `(,(concat "-o" png)
926 ,(format "-r%d" (round doc-view-resolution))
927 ,pdf
928 ,@(if page `(,(format "%d" page))))
929 callback))
931 (defun doc-view-odf->pdf-converter-unoconv (odf callback)
932 "Convert ODF to PDF asynchronously and call CALLBACK when finished.
933 The converted PDF is put into the current cache directory, and it
934 is named like ODF with the extension turned to pdf."
935 (doc-view-start-process "odf->pdf" doc-view-odf->pdf-converter-program
936 (list "-f" "pdf" "-o" (doc-view-current-cache-dir) odf)
937 callback))
939 (defun doc-view-odf->pdf-converter-soffice (odf callback)
940 "Convert ODF to PDF asynchronously and call CALLBACK when finished.
941 The converted PDF is put into the current cache directory, and it
942 is named like ODF with the extension turned to pdf."
943 ;; FIXME: soffice doesn't work when there's another running
944 ;; LibreOffice instance, in which case it returns success without
945 ;; actually doing anything. See LibreOffice bug
946 ;; https://bugs.freedesktop.org/show_bug.cgi?id=37531. A workaround
947 ;; is to start soffice with a separate UserInstallation directory.
948 (let ((tmp-user-install-dir (make-temp-file "libreoffice-docview" t)))
949 (doc-view-start-process "odf->pdf" doc-view-odf->pdf-converter-program
950 (list
951 (concat "-env:UserInstallation=file://"
952 tmp-user-install-dir)
953 "--headless" "--convert-to" "pdf"
954 "--outdir" (doc-view-current-cache-dir) odf)
955 (lambda ()
956 (delete-directory tmp-user-install-dir t)
957 (funcall callback)))))
959 (defun doc-view-pdf/ps->png (pdf-ps png)
960 ;; FIXME: Fix name and docstring to account for djvu&tiff.
961 "Convert PDF-PS to PNG asynchronously."
962 (funcall
963 (pcase doc-view-doc-type
964 (`pdf doc-view-pdf->png-converter-function)
965 (`djvu #'doc-view-djvu->tiff-converter-ddjvu)
966 (_ #'doc-view-ps->png-converter-ghostscript))
967 pdf-ps png nil
968 (let ((resolution doc-view-resolution))
969 (lambda ()
970 ;; Only create the resolution file when it's all done, so it also
971 ;; serves as a witness that the conversion is complete.
972 (write-region (prin1-to-string resolution) nil
973 (expand-file-name "resolution.el"
974 (doc-view-current-cache-dir))
975 nil 'silently)
976 (when doc-view-current-timer
977 (cancel-timer doc-view-current-timer)
978 (setq doc-view-current-timer nil))
979 (doc-view-display (current-buffer) 'force))))
981 ;; Update the displayed pages as soon as they're done generating.
982 (when doc-view-conversion-refresh-interval
983 (setq doc-view-current-timer
984 (run-at-time "1 secs" doc-view-conversion-refresh-interval
985 'doc-view-display
986 (current-buffer)))))
988 (declare-function clear-image-cache "image.c" (&optional filter))
990 (defun doc-view-document->bitmap (pdf png pages)
991 "Convert a document file to bitmap images asynchronously.
992 Start by converting PAGES, and then the rest."
993 (if (null pages)
994 (doc-view-pdf/ps->png pdf png)
995 ;; We could render several `pages' with a single process if they're
996 ;; (almost) consecutive, but since in 99% of the cases, there'll be only
997 ;; a single page anyway, and of the remaining 1%, few cases will have
998 ;; consecutive pages, it's not worth the trouble.
999 (let ((rest (cdr pages)))
1000 (funcall doc-view-single-page-converter-function
1001 pdf (format png (car pages)) (car pages)
1002 (lambda ()
1003 (if rest
1004 (doc-view-document->bitmap pdf png rest)
1005 ;; Yippie, the important pages are done, update the display.
1006 (clear-image-cache)
1007 ;; For the windows that have a message (like "Welcome to
1008 ;; DocView") display property, clearing the image cache is
1009 ;; not sufficient.
1010 (dolist (win (get-buffer-window-list (current-buffer) nil 'visible))
1011 (with-selected-window win
1012 (when (stringp (get-char-property (point-min) 'display))
1013 (doc-view-goto-page (doc-view-current-page)))))
1014 ;; Convert the rest of the pages.
1015 (doc-view-pdf/ps->png pdf png)))))))
1017 (defun doc-view-pdf->txt (pdf txt callback)
1018 "Convert PDF to TXT asynchronously and call CALLBACK when finished."
1019 (or (executable-find doc-view-pdftotext-program)
1020 (error "You need the `pdftotext' program to convert a PDF to text"))
1021 (doc-view-start-process "pdf->txt" doc-view-pdftotext-program
1022 (list "-raw" pdf txt)
1023 callback))
1025 (defun doc-view-current-cache-doc-pdf ()
1026 "Return the name of the doc.pdf in the current cache dir.
1027 This file exists only if the current document isn't a PDF or PS file already."
1028 (expand-file-name "doc.pdf" (doc-view-current-cache-dir)))
1030 (defun doc-view-doc->txt (txt callback)
1031 "Convert the current document to text and call CALLBACK when done."
1032 (make-directory (doc-view-current-cache-dir) t)
1033 (pcase doc-view-doc-type
1034 (`pdf
1035 ;; Doc is a PDF, so convert it to TXT
1036 (doc-view-pdf->txt doc-view-buffer-file-name txt callback))
1037 (`ps
1038 ;; Doc is a PS, so convert it to PDF (which will be converted to
1039 ;; TXT thereafter).
1040 (let ((pdf (doc-view-current-cache-doc-pdf)))
1041 (doc-view-ps->pdf doc-view-buffer-file-name pdf
1042 (lambda () (doc-view-pdf->txt pdf txt callback)))))
1043 (`dvi
1044 ;; Doc is a DVI. This means that a doc.pdf already exists in its
1045 ;; cache subdirectory.
1046 (doc-view-pdf->txt (doc-view-current-cache-doc-pdf) txt callback))
1047 (`odf
1048 ;; Doc is some ODF (or MS Office) doc. This means that a doc.pdf
1049 ;; already exists in its cache subdirectory.
1050 (doc-view-pdf->txt (doc-view-current-cache-doc-pdf) txt callback))
1051 (_ (error "DocView doesn't know what to do"))))
1053 (defun doc-view-ps->pdf (ps pdf callback)
1054 "Convert PS to PDF asynchronously and call CALLBACK when finished."
1055 (or (executable-find doc-view-ps2pdf-program)
1056 (error "You need the `ps2pdf' program to convert PS to PDF"))
1057 (doc-view-start-process "ps->pdf" doc-view-ps2pdf-program
1058 (list
1059 ;; Avoid security problems when rendering files from
1060 ;; untrusted sources.
1061 "-dSAFER"
1062 ;; in-file and out-file
1063 ps pdf)
1064 callback))
1066 (defun doc-view-active-pages ()
1067 (let ((pages ()))
1068 (dolist (win (get-buffer-window-list (current-buffer) nil 'visible))
1069 (let ((page (image-mode-window-get 'page win)))
1070 (unless (memq page pages) (push page pages))))
1071 pages))
1073 (defun doc-view-convert-current-doc ()
1074 "Convert `doc-view-buffer-file-name' to a set of png files, one file per page.
1075 Those files are saved in the directory given by the function
1076 `doc-view-current-cache-dir'."
1077 ;; Let stale files still display while we recompute the new ones, so only
1078 ;; flush the cache when the conversion is over. One of the reasons why it
1079 ;; is important to keep displaying the stale page is so that revert-buffer
1080 ;; preserves the horizontal/vertical scroll settings (which are otherwise
1081 ;; resets during the redisplay).
1082 (setq doc-view-pending-cache-flush t)
1083 (let ((png-file (expand-file-name
1084 (format doc-view--image-file-pattern "%d")
1085 (doc-view-current-cache-dir))))
1086 (make-directory (doc-view-current-cache-dir) t)
1087 (pcase doc-view-doc-type
1088 (`dvi
1089 ;; DVI files have to be converted to PDF before Ghostscript can process
1090 ;; it.
1091 (let ((pdf (doc-view-current-cache-doc-pdf)))
1092 (doc-view-dvi->pdf doc-view-buffer-file-name pdf
1093 (lambda () (doc-view-pdf/ps->png pdf png-file)))))
1094 (`odf
1095 ;; ODF files have to be converted to PDF before Ghostscript can
1096 ;; process it.
1097 (let ((pdf (doc-view-current-cache-doc-pdf))
1098 (opdf (expand-file-name
1099 (concat (file-name-base doc-view-buffer-file-name)
1100 ".pdf")
1101 doc-view-current-cache-dir))
1102 (png-file png-file))
1103 ;; The unoconv tool only supports an output directory, but no
1104 ;; file name. It's named like the input file with the
1105 ;; extension replaced by pdf.
1106 (funcall doc-view-odf->pdf-converter-function doc-view-buffer-file-name
1107 (lambda ()
1108 ;; Rename to doc.pdf
1109 (rename-file opdf pdf)
1110 (doc-view-pdf/ps->png pdf png-file)))))
1111 ((or `pdf `djvu)
1112 (let ((pages (doc-view-active-pages)))
1113 ;; Convert doc to bitmap images starting with the active pages.
1114 (doc-view-document->bitmap doc-view-buffer-file-name png-file pages)))
1116 ;; Convert to PNG images.
1117 (doc-view-pdf/ps->png doc-view-buffer-file-name png-file)))))
1119 ;;;; Slicing
1121 (declare-function image-size "image.c" (spec &optional pixels frame))
1123 (defun doc-view-set-slice (x y width height)
1124 "Set the slice of the images that should be displayed.
1125 You can use this function to tell doc-view not to display the
1126 margins of the document. It prompts for the top-left corner (X
1127 and Y) of the slice to display and its WIDTH and HEIGHT.
1129 See `doc-view-set-slice-using-mouse' and
1130 `doc-view-set-slice-from-bounding-box' for more convenient ways
1131 to do that. To reset the slice use `doc-view-reset-slice'."
1132 (interactive
1133 (let* ((size (image-size (doc-view-current-image) t))
1134 (a (read-number (format "Top-left X (0..%d): " (car size))))
1135 (b (read-number (format "Top-left Y (0..%d): " (cdr size))))
1136 (c (read-number (format "Width (0..%d): " (- (car size) a))))
1137 (d (read-number (format "Height (0..%d): " (- (cdr size) b)))))
1138 (list a b c d)))
1139 (setf (doc-view-current-slice) (list x y width height))
1140 ;; Redisplay
1141 (doc-view-goto-page (doc-view-current-page)))
1143 (defun doc-view-set-slice-using-mouse ()
1144 "Set the slice of the images that should be displayed.
1145 You set the slice by pressing mouse-1 at its top-left corner and
1146 dragging it to its bottom-right corner. See also
1147 `doc-view-set-slice' and `doc-view-reset-slice'."
1148 (interactive)
1149 (let (x y w h done)
1150 (while (not done)
1151 (let ((e (read-event
1152 (concat "Press mouse-1 at the top-left corner and "
1153 "drag it to the bottom-right corner!"))))
1154 (when (eq (car e) 'drag-mouse-1)
1155 (setq x (car (posn-object-x-y (event-start e))))
1156 (setq y (cdr (posn-object-x-y (event-start e))))
1157 (setq w (- (car (posn-object-x-y (event-end e))) x))
1158 (setq h (- (cdr (posn-object-x-y (event-end e))) y))
1159 (setq done t))))
1160 (doc-view-set-slice x y w h)))
1162 (defun doc-view-get-bounding-box ()
1163 "Get the BoundingBox information of the current page."
1164 (let* ((page (doc-view-current-page))
1165 (doc (let ((cache-doc (doc-view-current-cache-doc-pdf)))
1166 (if (file-exists-p cache-doc)
1167 cache-doc
1168 doc-view-buffer-file-name)))
1169 (o (shell-command-to-string
1170 (concat doc-view-ghostscript-program
1171 " -dSAFER -dBATCH -dNOPAUSE -q -sDEVICE=bbox "
1172 (format "-dFirstPage=%s -dLastPage=%s %s"
1173 page page doc)))))
1174 (save-match-data
1175 (when (string-match (concat "%%BoundingBox: "
1176 "\\([[:digit:]]+\\) \\([[:digit:]]+\\) "
1177 "\\([[:digit:]]+\\) \\([[:digit:]]+\\)") o)
1178 (mapcar #'string-to-number
1179 (list (match-string 1 o)
1180 (match-string 2 o)
1181 (match-string 3 o)
1182 (match-string 4 o)))))))
1184 (defvar doc-view-paper-sizes
1185 '((a4 595 842)
1186 (a4-landscape 842 595)
1187 (letter 612 792)
1188 (letter-landscape 792 612)
1189 (legal 612 1008)
1190 (legal-landscape 1008 612)
1191 (a3 842 1191)
1192 (a3-landscape 1191 842)
1193 (tabloid 792 1224)
1194 (ledger 1224 792))
1195 "An alist from paper size names to dimensions.")
1197 (defun doc-view-guess-paper-size (iw ih)
1198 "Guess the paper size according to the aspect ratio."
1199 (cl-labels ((div (x y)
1200 (round (/ (* 100.0 x) y))))
1201 (let ((ar (div iw ih))
1202 (al (mapcar (lambda (l)
1203 (list (div (nth 1 l) (nth 2 l)) (car l)))
1204 doc-view-paper-sizes)))
1205 (cadr (assoc ar al)))))
1207 (defun doc-view-scale-bounding-box (ps iw ih bb)
1208 (list (/ (* (nth 0 bb) iw) (nth 1 (assoc ps doc-view-paper-sizes)))
1209 (/ (* (nth 1 bb) ih) (nth 2 (assoc ps doc-view-paper-sizes)))
1210 (/ (* (nth 2 bb) iw) (nth 1 (assoc ps doc-view-paper-sizes)))
1211 (/ (* (nth 3 bb) ih) (nth 2 (assoc ps doc-view-paper-sizes)))))
1213 (defun doc-view-set-slice-from-bounding-box (&optional force-paper-size)
1214 "Set the slice from the document's BoundingBox information.
1215 The result is that the margins are almost completely cropped,
1216 much more accurate than could be done manually using
1217 `doc-view-set-slice-using-mouse'."
1218 (interactive "P")
1219 (let ((bb (doc-view-get-bounding-box)))
1220 (if (not bb)
1221 (message "BoundingBox couldn't be determined")
1222 (let* ((is (image-size (doc-view-current-image) t))
1223 (iw (car is))
1224 (ih (cdr is))
1225 (ps (or (and (null force-paper-size)
1226 (doc-view-guess-paper-size iw ih))
1227 (intern (completing-read "Paper size: "
1228 doc-view-paper-sizes
1229 nil t))))
1230 (bb (doc-view-scale-bounding-box ps iw ih bb))
1231 (x1 (nth 0 bb))
1232 (y1 (nth 1 bb))
1233 (x2 (nth 2 bb))
1234 (y2 (nth 3 bb)))
1235 ;; We keep a 2 pixel margin.
1236 (doc-view-set-slice (- x1 2) (- ih y2 2)
1237 (+ (- x2 x1) 4) (+ (- y2 y1) 4))))))
1239 (defun doc-view-reset-slice ()
1240 "Reset the current slice.
1241 After calling this function whole pages will be visible again."
1242 (interactive)
1243 (setf (doc-view-current-slice) nil)
1244 ;; Redisplay
1245 (doc-view-goto-page (doc-view-current-page)))
1247 ;;;; Display
1249 (defun doc-view-insert-image (file &rest args)
1250 "Insert the given png FILE.
1251 ARGS is a list of image descriptors."
1252 (when doc-view-pending-cache-flush
1253 (clear-image-cache)
1254 (setq doc-view-pending-cache-flush nil))
1255 (let ((ol (doc-view-current-overlay))
1256 (image (if (and file (file-readable-p file))
1257 (if (not (and doc-view-scale-internally
1258 (fboundp 'imagemagick-types)))
1259 (apply 'create-image file doc-view--image-type nil args)
1260 (unless (member :width args)
1261 (setq args `(,@args :width ,doc-view-image-width)))
1262 (apply 'create-image file 'imagemagick nil args))))
1263 (slice (doc-view-current-slice)))
1264 (setf (doc-view-current-image) image)
1265 (move-overlay ol (point-min) (point-max))
1266 (overlay-put ol 'display
1267 (cond
1268 (image
1269 (if slice
1270 (list (cons 'slice slice) image)
1271 image))
1272 ;; We're trying to display a page that doesn't exist.
1273 (doc-view-current-converter-processes
1274 ;; Maybe the page doesn't exist *yet*.
1275 "Cannot display this page (yet)!")
1277 ;; Typically happens if the conversion process somehow
1278 ;; failed. Better not signal an error here because it
1279 ;; could prevent a subsequent reconversion from fixing
1280 ;; the problem.
1281 (concat "Cannot display this page!\n"
1282 "Maybe because of a conversion failure!"))))
1283 (let ((win (overlay-get ol 'window)))
1284 (if (stringp (overlay-get ol 'display))
1285 (progn ;Make sure the text is not scrolled out of view.
1286 (set-window-hscroll win 0)
1287 (set-window-vscroll win 0))
1288 (let ((hscroll (image-mode-window-get 'hscroll win))
1289 (vscroll (image-mode-window-get 'vscroll win)))
1290 ;; Reset scroll settings, in case they were changed.
1291 (if hscroll (set-window-hscroll win hscroll))
1292 (if vscroll (set-window-vscroll win vscroll)))))))
1294 (defun doc-view-sort (a b)
1295 "Return non-nil if A should be sorted before B.
1296 Predicate for sorting `doc-view-current-files'."
1297 (or (< (length a) (length b))
1298 (and (= (length a) (length b))
1299 (string< a b))))
1301 (defun doc-view-display (buffer &optional force)
1302 "Start viewing the document in BUFFER.
1303 If FORCE is non-nil, start viewing even if the document does not
1304 have the page we want to view."
1305 (with-current-buffer buffer
1306 (let ((prev-pages doc-view-current-files))
1307 (setq doc-view-current-files
1308 (sort (directory-files (doc-view-current-cache-dir) t
1309 (format doc-view--image-file-pattern
1310 "[0-9]+")
1312 'doc-view-sort))
1313 (unless (eq (length prev-pages) (length doc-view-current-files))
1314 (force-mode-line-update))
1315 (dolist (win (or (get-buffer-window-list buffer nil t)
1316 (list t)))
1317 (let* ((page (doc-view-current-page win))
1318 (pagefile (expand-file-name
1319 (format doc-view--image-file-pattern page)
1320 (doc-view-current-cache-dir))))
1321 (when (or force
1322 (and (not (member pagefile prev-pages))
1323 (member pagefile doc-view-current-files)))
1324 (if (windowp win)
1325 (with-selected-window win
1326 (cl-assert (eq (current-buffer) buffer) t)
1327 (doc-view-goto-page page))
1328 (doc-view-goto-page page))))))))
1330 (defun doc-view-buffer-message ()
1331 ;; Only show this message initially, not when refreshing the buffer (in which
1332 ;; case it's better to keep displaying the "stale" page while computing
1333 ;; the fresh new ones).
1334 (unless (overlay-get (doc-view-current-overlay) 'display)
1335 (overlay-put (doc-view-current-overlay) 'display
1336 (concat (propertize "Welcome to DocView!" 'face 'bold)
1337 "\n"
1339 If you see this buffer it means that the document you want to view is being
1340 converted to PNG and the conversion of the first page hasn't finished yet or
1341 `doc-view-conversion-refresh-interval' is set to nil.
1343 For now these keys are useful:
1345 `q' : Bury this buffer. Conversion will go on in background.
1346 `k' : Kill the conversion process and this buffer.
1347 `K' : Kill the conversion process.\n"))))
1349 (declare-function tooltip-show "tooltip" (text &optional use-echo-area))
1351 (defun doc-view-show-tooltip ()
1352 (interactive)
1353 (tooltip-show (doc-view-current-info)))
1355 (defun doc-view-open-text ()
1356 "Open a buffer with the current doc's contents as text."
1357 (interactive)
1358 (if doc-view-current-converter-processes
1359 (message "DocView: please wait till conversion finished.")
1360 (let ((txt (expand-file-name "doc.txt" (doc-view-current-cache-dir))))
1361 (if (file-readable-p txt)
1362 (let ((name (concat "Text contents of "
1363 (file-name-nondirectory buffer-file-name)))
1364 (dir (file-name-directory buffer-file-name)))
1365 (with-current-buffer (find-file txt)
1366 (rename-buffer name)
1367 (setq default-directory dir)))
1368 (doc-view-doc->txt txt 'doc-view-open-text)))))
1370 ;;;;; Toggle between editing and viewing
1372 (defvar-local doc-view-saved-settings nil
1373 "Doc-view settings saved while in some other mode.")
1374 (put 'doc-view-saved-settings 'permanent-local t)
1376 (defun doc-view-toggle-display ()
1377 "Toggle between editing a document as text or viewing it."
1378 (interactive)
1379 (if (eq major-mode 'doc-view-mode)
1380 ;; Switch to editing mode
1381 (progn
1382 (doc-view-kill-proc)
1383 (setq buffer-read-only nil)
1384 (remove-overlays (point-min) (point-max) 'doc-view t)
1385 (setq-local image-mode-winprops-alist t)
1386 ;; Switch to the previously used major mode or fall back to
1387 ;; normal mode.
1388 (doc-view-fallback-mode)
1389 (doc-view-minor-mode 1))
1390 ;; Switch to doc-view-mode
1391 (when (and (buffer-modified-p)
1392 (y-or-n-p "The buffer has been modified. Save the changes? "))
1393 (save-buffer))
1394 (doc-view-mode)))
1396 ;;;; Searching
1399 (defun doc-view-search-internal (regexp file)
1400 "Return a list of FILE's pages that contain text matching REGEXP.
1401 The value is an alist of the form (PAGE CONTEXTS) where PAGE is
1402 the pagenumber and CONTEXTS are all lines of text containing a match."
1403 (with-temp-buffer
1404 (insert-file-contents file)
1405 (let ((page 1)
1406 (lastpage 1)
1407 matches)
1408 (while (re-search-forward (concat "\\(?:\\([\f]\\)\\|\\("
1409 regexp "\\)\\)") nil t)
1410 (when (match-string 1) (setq page (1+ page)))
1411 (when (match-string 2)
1412 (if (/= page lastpage)
1413 (push (cons page
1414 (list (buffer-substring
1415 (line-beginning-position)
1416 (line-end-position))))
1417 matches)
1418 (setq matches (cons
1419 (append
1421 ;; This page already is a match.
1422 (car matches)
1423 ;; This is the first match on page.
1424 (list page))
1425 (list (buffer-substring
1426 (line-beginning-position)
1427 (line-end-position))))
1428 (cdr matches))))
1429 (setq lastpage page)))
1430 (nreverse matches))))
1432 (defun doc-view-search-no-of-matches (list)
1433 "Extract the number of matches from the search result LIST."
1434 (let ((no 0))
1435 (dolist (p list)
1436 (setq no (+ no (1- (length p)))))
1437 no))
1439 (defun doc-view-search-backward (new-query)
1440 "Call `doc-view-search' for backward search.
1441 If prefix NEW-QUERY is given, ask for a new regexp."
1442 (interactive "P")
1443 (doc-view-search new-query t))
1445 (defun doc-view-search (new-query &optional backward)
1446 "Jump to the next match or initiate a new search if NEW-QUERY is given.
1447 If the current document hasn't been transformed to plain text
1448 till now do that first.
1449 If BACKWARD is non-nil, jump to the previous match."
1450 (interactive "P")
1451 (if (and (not new-query)
1452 doc-view-current-search-matches)
1453 (if backward
1454 (doc-view-search-previous-match 1)
1455 (doc-view-search-next-match 1))
1456 ;; New search, so forget the old results.
1457 (setq doc-view-current-search-matches nil)
1458 (let ((txt (expand-file-name "doc.txt"
1459 (doc-view-current-cache-dir))))
1460 (if (file-readable-p txt)
1461 (progn
1462 (setq doc-view-current-search-matches
1463 (doc-view-search-internal
1464 (read-from-minibuffer "Regexp: ")
1465 txt))
1466 (message "DocView: search yielded %d matches."
1467 (doc-view-search-no-of-matches
1468 doc-view-current-search-matches)))
1469 ;; We must convert to TXT first!
1470 (if doc-view-current-converter-processes
1471 (message "DocView: please wait till conversion finished.")
1472 (doc-view-doc->txt txt (lambda () (doc-view-search nil))))))))
1474 (defun doc-view-search-next-match (arg)
1475 "Go to the ARGth next matching page."
1476 (interactive "p")
1477 (let* ((next-pages (doc-view-remove-if
1478 (lambda (i) (<= (car i) (doc-view-current-page)))
1479 doc-view-current-search-matches))
1480 (page (car (nth (1- arg) next-pages))))
1481 (if page
1482 (doc-view-goto-page page)
1483 (when (and
1484 doc-view-current-search-matches
1485 (y-or-n-p "No more matches after current page. Wrap to first match? "))
1486 (doc-view-goto-page (caar doc-view-current-search-matches))))))
1488 (defun doc-view-search-previous-match (arg)
1489 "Go to the ARGth previous matching page."
1490 (interactive "p")
1491 (let* ((prev-pages (doc-view-remove-if
1492 (lambda (i) (>= (car i) (doc-view-current-page)))
1493 doc-view-current-search-matches))
1494 (page (car (nth (1- arg) (nreverse prev-pages)))))
1495 (if page
1496 (doc-view-goto-page page)
1497 (when (and
1498 doc-view-current-search-matches
1499 (y-or-n-p "No more matches before current page. Wrap to last match? "))
1500 (doc-view-goto-page (caar (last doc-view-current-search-matches)))))))
1502 ;;;; User interface commands and the mode
1504 (put 'doc-view-mode 'mode-class 'special)
1506 (defun doc-view-already-converted-p ()
1507 "Return non-nil if the current doc was already converted."
1508 (and (file-exists-p (doc-view-current-cache-dir))
1509 ;; Check that the resolution info is there, otherwise it means
1510 ;; the conversion is incomplete.
1511 (file-readable-p (expand-file-name "resolution.el"
1512 (doc-view-current-cache-dir)))
1513 (> (length (directory-files
1514 (doc-view-current-cache-dir)
1515 nil (format doc-view--image-file-pattern "[0-9]+")))
1516 0)))
1518 (defun doc-view-initiate-display ()
1519 ;; Switch to image display if possible.
1520 (if (doc-view-mode-p doc-view-doc-type)
1521 (progn
1522 (doc-view-buffer-message)
1523 (setf (doc-view-current-page) (or (doc-view-current-page) 1))
1524 (if (doc-view-already-converted-p)
1525 (progn
1526 (message "DocView: using cached files!")
1527 ;; Load the saved resolution.
1528 (let* ((res-file (expand-file-name "resolution.el"
1529 (doc-view-current-cache-dir)))
1530 (res
1531 (with-temp-buffer
1532 (when (file-readable-p res-file)
1533 (insert-file-contents res-file)
1534 (read (current-buffer))))))
1535 (when (numberp res)
1536 (setq-local doc-view-resolution res)))
1537 (doc-view-display (current-buffer) 'force))
1538 (doc-view-convert-current-doc))
1539 (message
1540 "%s"
1541 (substitute-command-keys
1542 (concat "Type \\[doc-view-toggle-display] to toggle between "
1543 "editing or viewing the document."))))
1544 (message
1545 "%s"
1546 (concat "No PNG support is available, or some conversion utility for "
1547 (file-name-extension doc-view-buffer-file-name)
1548 " files is missing."))
1549 (when (and (executable-find doc-view-pdftotext-program)
1550 (y-or-n-p
1551 "Unable to render file. View extracted text instead? "))
1552 (doc-view-open-text))
1553 (doc-view-toggle-display)))
1555 (defvar bookmark-make-record-function)
1557 (defun doc-view-clone-buffer-hook ()
1558 ;; FIXME: There are several potential problems linked with reconversion
1559 ;; and auto-revert when we have indirect buffers because they share their
1560 ;; /tmp cache directory. This sharing is good (you'd rather not reconvert
1561 ;; for each clone), but that means that clones need to collaborate a bit.
1562 ;; I guess it mostly means: detect when a reconversion process is already
1563 ;; running, and run the sentinel in all clones.
1565 ;; Maybe the clones should really have a separate /tmp directory
1566 ;; so they could have a different resolution and you could use clones
1567 ;; for zooming.
1568 (remove-overlays (point-min) (point-max) 'doc-view t)
1569 (if (consp image-mode-winprops-alist) (setq image-mode-winprops-alist nil)))
1571 (defun doc-view-intersection (l1 l2)
1572 (let ((l ()))
1573 (dolist (x l1) (if (memq x l2) (push x l)))
1576 (defun doc-view-set-doc-type ()
1577 "Figure out the current document type (`doc-view-doc-type')."
1578 (let ((name-types
1579 (when buffer-file-name
1580 (cdr (assoc (file-name-extension buffer-file-name)
1582 ;; DVI
1583 ("dvi" dvi)
1584 ;; PDF
1585 ("pdf" pdf) ("epdf" pdf)
1586 ;; PostScript
1587 ("ps" ps) ("eps" ps)
1588 ;; DjVu
1589 ("djvu" djvu)
1590 ;; OpenDocument formats
1591 ("odt" odf) ("ods" odf) ("odp" odf) ("odg" odf)
1592 ("odc" odf) ("odi" odf) ("odm" odf) ("ott" odf)
1593 ("ots" odf) ("otp" odf) ("otg" odf)
1594 ;; Microsoft Office formats (also handled
1595 ;; by the odf conversion chain)
1596 ("doc" odf) ("docx" odf) ("xls" odf) ("xlsx" odf)
1597 ("ppt" odf) ("pptx" odf))))))
1598 (content-types
1599 (save-excursion
1600 (goto-char (point-min))
1601 (cond
1602 ((looking-at "%!") '(ps))
1603 ((looking-at "%PDF") '(pdf))
1604 ((looking-at "\367\002") '(dvi))
1605 ((looking-at "AT&TFORM") '(djvu))))))
1606 (setq-local doc-view-doc-type
1607 (car (or (doc-view-intersection name-types content-types)
1608 (when (and name-types content-types)
1609 (error "Conflicting types: name says %s but content says %s"
1610 name-types content-types))
1611 name-types content-types
1612 (error "Cannot determine the document type"))))))
1614 (defun doc-view-set-up-single-converter ()
1615 "Find the right single-page converter for the current document type"
1616 (pcase-let ((`(,conv-function ,type ,extension)
1617 (pcase doc-view-doc-type
1618 (`djvu (list #'doc-view-djvu->tiff-converter-ddjvu 'tiff "tif"))
1619 (_ (list doc-view-pdf->png-converter-function 'png "png")))))
1620 (setq-local doc-view-single-page-converter-function conv-function)
1621 (setq-local doc-view--image-type type)
1622 (setq-local doc-view--image-file-pattern (concat "page-%s." extension))))
1624 ;;;###autoload
1625 (defun doc-view-mode ()
1626 "Major mode in DocView buffers.
1628 DocView Mode is an Emacs document viewer. It displays PDF, PS
1629 and DVI files (as PNG images) in Emacs buffers.
1631 You can use \\<doc-view-mode-map>\\[doc-view-toggle-display] to
1632 toggle between displaying the document or editing it as text.
1633 \\{doc-view-mode-map}"
1634 (interactive)
1636 (if (= (point-min) (point-max))
1637 ;; The doc is empty or doesn't exist at all, so fallback to
1638 ;; another mode. We used to also check file-exists-p, but this
1639 ;; returns nil for tar members.
1640 (doc-view-fallback-mode)
1642 (let* ((prev-major-mode (if (derived-mode-p 'doc-view-mode)
1643 doc-view-previous-major-mode
1644 (unless (eq major-mode 'fundamental-mode)
1645 major-mode))))
1646 (kill-all-local-variables)
1647 (setq-local doc-view-previous-major-mode prev-major-mode))
1649 (dolist (var doc-view-saved-settings)
1650 (set (make-local-variable (car var)) (cdr var)))
1652 ;; Figure out the document type.
1653 (unless doc-view-doc-type
1654 (doc-view-set-doc-type))
1655 (doc-view-set-up-single-converter)
1657 (doc-view-make-safe-dir doc-view-cache-directory)
1658 ;; Handle compressed files, remote files, files inside archives
1659 (setq-local doc-view-buffer-file-name
1660 (cond
1661 (jka-compr-really-do-compress
1662 ;; FIXME: there's a risk of name conflicts here.
1663 (expand-file-name
1664 (file-name-nondirectory
1665 (file-name-sans-extension buffer-file-name))
1666 doc-view-cache-directory))
1667 ;; Is the file readable by local processes?
1668 ;; We used to use `file-remote-p' but it's unclear what it's
1669 ;; supposed to return nil for things like local files accessed via
1670 ;; `su' or via file://...
1671 ((let ((file-name-handler-alist nil))
1672 (not (and buffer-file-name (file-readable-p buffer-file-name))))
1673 ;; FIXME: there's a risk of name conflicts here.
1674 (expand-file-name
1675 (if buffer-file-name
1676 (file-name-nondirectory buffer-file-name)
1677 (buffer-name))
1678 doc-view-cache-directory))
1679 (t buffer-file-name)))
1680 (when (not (string= doc-view-buffer-file-name buffer-file-name))
1681 (write-region nil nil doc-view-buffer-file-name))
1683 (add-hook 'change-major-mode-hook
1684 (lambda ()
1685 (doc-view-kill-proc)
1686 (remove-overlays (point-min) (point-max) 'doc-view t))
1687 nil t)
1688 (add-hook 'clone-indirect-buffer-hook 'doc-view-clone-buffer-hook nil t)
1689 (add-hook 'kill-buffer-hook 'doc-view-kill-proc nil t)
1691 (remove-overlays (point-min) (point-max) 'doc-view t) ;Just in case.
1692 ;; Keep track of display info ([vh]scroll, page number, overlay,
1693 ;; ...) for each window in which this document is shown.
1694 (add-hook 'image-mode-new-window-functions
1695 'doc-view-new-window-function nil t)
1696 (image-mode-setup-winprops)
1698 (setq-local mode-line-position
1699 '(" P" (:eval (number-to-string (doc-view-current-page)))
1700 "/" (:eval (number-to-string (doc-view-last-page-number)))))
1701 ;; Don't scroll unless the user specifically asked for it.
1702 (setq-local auto-hscroll-mode nil)
1703 (setq-local mwheel-scroll-up-function #'doc-view-scroll-up-or-next-page)
1704 (setq-local mwheel-scroll-down-function
1705 #'doc-view-scroll-down-or-previous-page)
1706 (setq-local cursor-type nil)
1707 (use-local-map doc-view-mode-map)
1708 (add-hook 'after-revert-hook 'doc-view-reconvert-doc nil t)
1709 (setq-local bookmark-make-record-function
1710 #'doc-view-bookmark-make-record)
1711 (setq mode-name "DocView"
1712 buffer-read-only t
1713 major-mode 'doc-view-mode)
1714 (doc-view-initiate-display)
1715 ;; Switch off view-mode explicitly, because doc-view-mode is the
1716 ;; canonical view mode for PDF/PS/DVI files. This could be
1717 ;; switched on automatically depending on the value of
1718 ;; `view-read-only'.
1719 (setq-local view-read-only nil)
1720 (run-mode-hooks 'doc-view-mode-hook)))
1722 (defun doc-view-fallback-mode ()
1723 "Fallback to the previous or next best major mode."
1724 (let ((vars (if (derived-mode-p 'doc-view-mode)
1725 (mapcar (lambda (var) (cons var (symbol-value var)))
1726 '(doc-view-resolution
1727 image-mode-winprops-alist)))))
1728 (if doc-view-previous-major-mode
1729 (funcall doc-view-previous-major-mode)
1730 (let ((auto-mode-alist
1731 (rassq-delete-all
1732 'doc-view-mode-maybe
1733 (rassq-delete-all 'doc-view-mode
1734 (copy-alist auto-mode-alist)))))
1735 (normal-mode)))
1736 (when vars
1737 (setq-local doc-view-saved-settings vars))))
1739 ;;;###autoload
1740 (defun doc-view-mode-maybe ()
1741 "Switch to `doc-view-mode' if possible.
1742 If the required external tools are not available, then fallback
1743 to the next best mode."
1744 (condition-case nil
1745 (doc-view-set-doc-type)
1746 (error (doc-view-fallback-mode)))
1747 (if (doc-view-mode-p doc-view-doc-type)
1748 (doc-view-mode)
1749 (doc-view-fallback-mode)))
1751 ;;;###autoload
1752 (define-minor-mode doc-view-minor-mode
1753 "Toggle displaying buffer via Doc View (Doc View minor mode).
1754 With a prefix argument ARG, enable Doc View minor mode if ARG is
1755 positive, and disable it otherwise. If called from Lisp, enable
1756 the mode if ARG is omitted or nil.
1758 See the command `doc-view-mode' for more information on this mode."
1759 nil " DocView" doc-view-minor-mode-map
1760 :group 'doc-view
1761 (when doc-view-minor-mode
1762 (add-hook 'change-major-mode-hook (lambda () (doc-view-minor-mode -1)) nil t)
1763 (message
1764 "%s"
1765 (substitute-command-keys
1766 "Type \\[doc-view-toggle-display] to toggle between editing or viewing the document."))))
1768 (defun doc-view-clear-cache ()
1769 "Delete the whole cache (`doc-view-cache-directory')."
1770 (interactive)
1771 (dired-delete-file doc-view-cache-directory 'always))
1773 (defun doc-view-dired-cache ()
1774 "Open `dired' in `doc-view-cache-directory'."
1775 (interactive)
1776 (dired doc-view-cache-directory))
1779 ;;;; Bookmark integration
1781 (declare-function bookmark-make-record-default
1782 "bookmark" (&optional no-file no-context posn))
1783 (declare-function bookmark-prop-get "bookmark" (bookmark prop))
1784 (declare-function bookmark-default-handler "bookmark" (bmk))
1786 (defun doc-view-bookmark-make-record ()
1787 (nconc (bookmark-make-record-default)
1788 `((page . ,(doc-view-current-page))
1789 (handler . doc-view-bookmark-jump))))
1792 ;;;###autoload
1793 (defun doc-view-bookmark-jump (bmk)
1794 ;; This implements the `handler' function interface for record type
1795 ;; returned by `doc-view-bookmark-make-record', which see.
1796 (prog1 (bookmark-default-handler bmk)
1797 (let ((page (bookmark-prop-get bmk 'page)))
1798 (when (not (eq major-mode 'doc-view-mode))
1799 (doc-view-toggle-display))
1800 (with-selected-window
1801 (or (get-buffer-window (current-buffer) 0)
1802 (selected-window))
1803 (doc-view-goto-page page)))))
1806 (provide 'doc-view)
1808 ;; Local Variables:
1809 ;; eval: (outline-minor-mode 1)
1810 ;; End:
1812 ;;; doc-view.el ends here