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