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