In window_resize_apply adjust margin width, if necessary (Bug#16649).
[emacs.git] / lisp / doc-view.el
blob6706865e5984154c2e9b91311784ab7c92429ffc
1 ;;; doc-view.el --- View PDF/PostScript/DVI files in Emacs -*- lexical-binding: t -*-
3 ;; Copyright (C) 2007-2014 Free Software Foundation, Inc.
4 ;;
5 ;; Author: Tassilo Horn <tsdh@gnu.org>
6 ;; Maintainer: Tassilo Horn <tsdh@gnu.org>
7 ;; Keywords: files, pdf, ps, dvi
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24 ;;; Requirements:
26 ;; doc-view.el requires GNU Emacs 22.1 or newer. You also need Ghostscript,
27 ;; `dvipdf' (comes with Ghostscript) or `dvipdfm' (comes with teTeX or TeXLive)
28 ;; and `pdftotext', which comes with xpdf (http://www.foolabs.com/xpdf/) or
29 ;; poppler (http://poppler.freedesktop.org/).
31 ;;; Commentary:
33 ;; DocView is a document viewer for Emacs. It converts PDF, PS and DVI files
34 ;; to a set of PNG files, one PNG for each page, and displays the PNG images
35 ;; inside an Emacs buffer. This buffer uses `doc-view-mode' which provides
36 ;; convenient key bindings for browsing the document.
38 ;; To use it simply open a document file with
40 ;; C-x C-f ~/path/to/document RET
42 ;; and the document will be converted and displayed, if your emacs supports png
43 ;; images. With `C-c C-c' you can toggle between the rendered images
44 ;; representation and the source text representation of the document.
46 ;; Since conversion may take some time all the PNG images are cached in a
47 ;; subdirectory of `doc-view-cache-directory' and reused when you want to view
48 ;; that file again. To reconvert a document hit `g' (`doc-view-reconvert-doc')
49 ;; when displaying the document. To delete all cached files use
50 ;; `doc-view-clear-cache'. To open the cache with dired, so that you can tidy
51 ;; it out use `doc-view-dired-cache'.
53 ;; When conversion in underway the first page will be displayed as soon as it
54 ;; is available and the available pages are refreshed every
55 ;; `doc-view-conversion-refresh-interval' seconds. If that variable is nil the
56 ;; pages won't be displayed before conversion of the document finished
57 ;; completely.
59 ;; DocView lets you select a slice of the displayed pages. This slice
60 ;; will be remembered and applied to all pages of the current
61 ;; document. This enables you to cut away the margins of a document
62 ;; to save some space. To select a slice you can use
63 ;; `doc-view-set-slice' (bound to `s s') which will query you for the
64 ;; coordinates of the slice's top-left corner and its width and
65 ;; height. A much more convenient way to do the same is offered by
66 ;; the command `doc-view-set-slice-using-mouse' (bound to `s m').
67 ;; After invocation you only have to press mouse-1 at the top-left
68 ;; corner and drag it to the bottom-right corner of the desired slice.
69 ;; Even more accurate and convenient is to use
70 ;; `doc-view-set-slice-from-bounding-box' (bound to `s b') which uses
71 ;; the BoundingBox information of the current page to set an optimal
72 ;; slice. To reset the slice use `doc-view-reset-slice' (bound to `s
73 ;; r').
75 ;; You can also search within the document. The command `doc-view-search'
76 ;; (bound to `C-s') queries for a search regexp and initializes a list of all
77 ;; matching pages and messages how many match-pages were found. After that you
78 ;; can jump to the next page containing a match with an additional `C-s'. With
79 ;; `C-r' you can do the same, but backwards. To search for a new regexp give a
80 ;; prefix arg to one of the search functions, e.g. by typing `C-u C-s'. The
81 ;; searching works by using a plain text representation of the document. If
82 ;; that doesn't already exist the first invocation of `doc-view-search' (or
83 ;; `doc-view-search-backward') starts the conversion. When that finishes and
84 ;; you're still viewing the document (i.e. you didn't switch to another buffer)
85 ;; you're queried for the regexp then.
87 ;; Dired users can simply hit `v' on a document file. If it's a PS, PDF or DVI
88 ;; it will be opened using `doc-view-mode'.
91 ;;; Configuration:
93 ;; If the images are too small or too big you should set the "-rXXX" option in
94 ;; `doc-view-ghostscript-options' to another value. (The bigger your screen,
95 ;; the higher the value.)
97 ;; This and all other options can be set with the customization interface.
98 ;; Simply do
100 ;; M-x customize-group RET doc-view RET
102 ;; and modify them to your needs.
104 ;;; Todo:
106 ;; - add print command.
107 ;; - share more code with image-mode.
108 ;; - better menu.
109 ;; - Bind slicing to a drag event.
110 ;; - zoom the region around the cursor (like xdvi).
111 ;; - get rid of the silly arrow in the fringe.
112 ;; - improve anti-aliasing (pdf-utils gets it better).
114 ;;;; About isearch support
116 ;; I tried implementing isearch by setting
117 ;; `isearch-search-fun-function' buffer-locally, but that didn't
118 ;; work too good. The function doing the real search was called
119 ;; endlessly somehow. But even if we'd get that working no real
120 ;; isearch feeling comes up due to the missing match highlighting.
121 ;; Currently I display all lines containing a match in a tooltip and
122 ;; each C-s or C-r jumps directly to the next/previous page with a
123 ;; match. With isearch we could only display the current match. So
124 ;; we had to decide if another C-s jumps to the next page with a
125 ;; match (thus only the first match in a page will be displayed in a
126 ;; tooltip) or to the next match, which would do nothing visible
127 ;; (except the tooltip) if the next match is on the same page.
129 ;; And it's much slower than the current search facility, because
130 ;; isearch really searches for each step forward or backward whereas
131 ;; the current approach searches once and then it knows to which
132 ;; pages to jump.
134 ;; Anyway, if someone with better isearch knowledge wants to give it a try,
135 ;; feel free to do it. --Tassilo
137 ;;; Code:
139 (require 'cl-lib)
140 (require 'dired)
141 (require 'image-mode)
142 (require 'jka-compr)
144 ;;;; Customization Options
146 (defgroup doc-view nil
147 "In-buffer viewer for PDF, PostScript, DVI, and DJVU files."
148 :link '(function-link doc-view)
149 :version "22.2"
150 :group 'applications
151 :group 'data
152 :group 'multimedia
153 :prefix "doc-view-")
155 (defcustom doc-view-ghostscript-program "gs"
156 "Program to convert PS and PDF files to PNG."
157 :type 'file
158 :group 'doc-view)
160 (defcustom doc-view-pdfdraw-program
161 (cond
162 ((executable-find "pdfdraw") "pdfdraw")
163 (t "mudraw"))
164 "Name of MuPDF's program to convert PDF files to PNG."
165 :type 'file
166 :version "24.4")
168 (defcustom doc-view-pdf->png-converter-function
169 (if (executable-find doc-view-pdfdraw-program)
170 #'doc-view-pdf->png-converter-mupdf
171 #'doc-view-pdf->png-converter-ghostscript)
172 "Function to call to convert a PDF file into a PNG file."
173 :type '(radio
174 (function-item doc-view-pdf->png-converter-ghostscript
175 :doc "Use ghostscript")
176 (function-item doc-view-pdf->png-converter-mupdf
177 :doc "Use mupdf")
178 function)
179 :version "24.4")
181 (defcustom doc-view-ghostscript-options
182 '("-dSAFER" ;; Avoid security problems when rendering files from untrusted
183 ;; sources.
184 "-dNOPAUSE" "-sDEVICE=png16m" "-dTextAlphaBits=4"
185 "-dBATCH" "-dGraphicsAlphaBits=4" "-dQUIET")
186 "A list of options to give to ghostscript."
187 :type '(repeat string)
188 :group 'doc-view)
190 (defcustom doc-view-resolution 100
191 "Dots per inch resolution used to render the documents.
192 Higher values result in larger images."
193 :type 'number
194 :group 'doc-view)
196 (defcustom doc-view-scale-internally t
197 "Whether we should try to rescale images ourselves.
198 If nil, the document is re-rendered every time the scaling factor is modified.
199 This only has an effect if the image libraries linked with Emacs support
200 scaling."
201 :version "24.4"
202 :type 'boolean)
204 (defcustom doc-view-image-width 850
205 "Default image width.
206 Has only an effect if `doc-view-scale-internally' is non-nil and support for
207 scaling is compiled into emacs."
208 :version "24.1"
209 :type 'number
210 :group 'doc-view)
212 (defcustom doc-view-dvipdfm-program "dvipdfm"
213 "Program to convert DVI files to PDF.
215 DVI file will be converted to PDF before the resulting PDF is
216 converted to PNG.
218 If this and `doc-view-dvipdf-program' are set,
219 `doc-view-dvipdf-program' will be preferred."
220 :type 'file
221 :group 'doc-view)
223 (defcustom doc-view-dvipdf-program "dvipdf"
224 "Program to convert DVI files to PDF.
226 DVI file will be converted to PDF before the resulting PDF is
227 converted to PNG.
229 If this and `doc-view-dvipdfm-program' are set,
230 `doc-view-dvipdf-program' will be preferred."
231 :type 'file
232 :group 'doc-view)
234 (define-obsolete-variable-alias 'doc-view-unoconv-program
235 'doc-view-odf->pdf-converter-program
236 "24.4")
238 (defcustom doc-view-odf->pdf-converter-program
239 (cond
240 ((executable-find "soffice") "soffice")
241 ((executable-find "unoconv") "unoconv")
242 (t "soffice"))
243 "Program to convert any file type readable by OpenOffice.org to PDF.
245 Needed for viewing OpenOffice.org (and MS Office) files."
246 :version "24.4"
247 :type 'file
248 :group 'doc-view)
250 (defcustom doc-view-odf->pdf-converter-function
251 (cond
252 ((string-match "unoconv\\'" doc-view-odf->pdf-converter-program)
253 #'doc-view-odf->pdf-converter-unoconv)
254 ((string-match "soffice\\'" doc-view-odf->pdf-converter-program)
255 #'doc-view-odf->pdf-converter-soffice))
256 "Function to call to convert a ODF file into a PDF file."
257 :type '(radio
258 (function-item doc-view-odf->pdf-converter-unoconv
259 :doc "Use unoconv")
260 (function-item doc-view-odf->pdf-converter-soffice
261 :doc "Use LibreOffice")
262 function)
263 :version "24.4")
265 (defcustom doc-view-ps2pdf-program "ps2pdf"
266 "Program to convert PS files to PDF.
268 PS files will be converted to PDF before searching is possible."
269 :type 'file
270 :group 'doc-view)
272 (defcustom doc-view-pdftotext-program "pdftotext"
273 "Program to convert PDF files to plain text.
275 Needed for searching."
276 :type 'file
277 :group 'doc-view)
279 (defcustom doc-view-cache-directory
280 (expand-file-name (format "docview%d" (user-uid))
281 temporary-file-directory)
282 "The base directory, where the PNG images will be saved."
283 :type 'directory
284 :group 'doc-view)
286 (defvar doc-view-conversion-buffer " *doc-view conversion output*"
287 "The buffer where messages from the converter programs go to.")
289 (defcustom doc-view-conversion-refresh-interval 1
290 "Interval in seconds between refreshes of the DocView buffer while converting.
291 After such a refresh newly converted pages will be available for
292 viewing. If set to nil there won't be any refreshes and the
293 pages won't be displayed before conversion of the whole document
294 has finished."
295 :type 'integer
296 :group 'doc-view)
298 (defcustom doc-view-continuous nil
299 "In Continuous mode reaching the page edge advances to next/previous page.
300 When non-nil, scrolling a line upward at the bottom edge of the page
301 moves to the next page, and scrolling a line downward at the top edge
302 of the page moves to the previous page."
303 :type 'boolean
304 :group 'doc-view
305 :version "23.2")
307 ;;;; Internal Variables
309 (defvar-local doc-view--current-converter-processes nil
310 "Only used internally.")
312 (defun doc-view-new-window-function (winprops)
313 ;; (message "New window %s for buf %s" (car winprops) (current-buffer))
314 (cl-assert (or (eq t (car winprops))
315 (eq (window-buffer (car winprops)) (current-buffer))))
316 (let ((ol (image-mode-window-get 'overlay winprops)))
317 (if ol
318 (progn
319 (setq ol (copy-overlay ol))
320 ;; `ol' might actually be dead.
321 (move-overlay ol (point-min) (point-max)))
322 (setq ol (make-overlay (point-min) (point-max) nil t))
323 (overlay-put ol 'doc-view t))
324 (overlay-put ol 'window (car winprops))
325 (unless (windowp (car winprops))
326 ;; It's a pseudo entry. Let's make sure it's not displayed (the
327 ;; `window' property is only effective if its value is a window).
328 (cl-assert (eq t (car winprops)))
329 (delete-overlay ol))
330 (image-mode-window-put 'overlay ol winprops)
331 (when (and (windowp (car winprops))
332 (stringp (overlay-get ol 'display))
333 (null doc-view--current-converter-processes))
334 ;; We're not displaying an image yet, so let's do so. This happens when
335 ;; the buffer is displayed for the first time.
336 ;; Don't do it if there's a conversion is running, since in that case, it
337 ;; will be done later.
338 (with-selected-window (car winprops)
339 (doc-view-goto-page 1)))))
341 (defvar-local doc-view--current-files nil
342 "Only used internally.")
344 (defvar-local doc-view--current-timer nil
345 "Only used internally.")
347 (defvar-local doc-view--current-cache-dir nil
348 "Only used internally.")
350 (defvar-local doc-view--current-search-matches nil
351 "Only used internally.")
353 (defvar doc-view--pending-cache-flush nil
354 "Only used internally.")
356 (defvar doc-view--previous-major-mode nil
357 "Only used internally.")
359 (defvar doc-view--buffer-file-name nil
360 "Only used internally.
361 The file name used for conversion. Normally it's the same as
362 `buffer-file-name', but for remote files, compressed files and
363 files inside an archive it is a temporary copy of
364 the (uncompressed, extracted) file residing in
365 `doc-view-cache-directory'.")
367 (defvar doc-view-doc-type nil
368 "The type of document in the current buffer.
369 Can be `dvi', `pdf', or `ps'.")
371 (defvar doc-view-single-page-converter-function nil
372 "Function to call to convert a single page of the document to a bitmap file.
373 May operate on the source document or on some intermediate (typically PDF)
374 conversion of it.")
376 (defvar-local doc-view--image-type nil
377 "The type of image in the current buffer.
378 Can be `png' or `tiff'.")
380 (defvar-local doc-view--image-file-pattern nil
381 "The `format' pattern of image file names.
382 Typically \"page-%s.png\".")
384 ;;;; DocView Keymaps
386 (defvar doc-view-mode-map
387 (let ((map (make-sparse-keymap)))
388 (set-keymap-parent map image-mode-map)
389 ;; Navigation in the document
390 (define-key map (kbd "n") 'doc-view-next-page)
391 (define-key map (kbd "p") 'doc-view-previous-page)
392 (define-key map (kbd "<next>") 'forward-page)
393 (define-key map (kbd "<prior>") 'backward-page)
394 (define-key map [remap forward-page] 'doc-view-next-page)
395 (define-key map [remap backward-page] 'doc-view-previous-page)
396 (define-key map (kbd "SPC") 'doc-view-scroll-up-or-next-page)
397 (define-key map (kbd "S-SPC") 'doc-view-scroll-down-or-previous-page)
398 (define-key map (kbd "DEL") 'doc-view-scroll-down-or-previous-page)
399 (define-key map (kbd "C-n") 'doc-view-next-line-or-next-page)
400 (define-key map (kbd "<down>") 'doc-view-next-line-or-next-page)
401 (define-key map (kbd "C-p") 'doc-view-previous-line-or-previous-page)
402 (define-key map (kbd "<up>") 'doc-view-previous-line-or-previous-page)
403 (define-key map (kbd "M-<") 'doc-view-first-page)
404 (define-key map (kbd "M->") 'doc-view-last-page)
405 (define-key map [remap goto-line] 'doc-view-goto-page)
406 (define-key map (kbd "RET") 'image-next-line)
407 ;; Zoom in/out.
408 (define-key map "+" 'doc-view-enlarge)
409 (define-key map "=" 'doc-view-enlarge)
410 (define-key map "-" 'doc-view-shrink)
411 (define-key map "0" 'doc-view-scale-reset)
412 (define-key map [remap text-scale-adjust] 'doc-view-scale-adjust)
413 ;; Fit the image to the window
414 (define-key map "W" 'doc-view-fit-width-to-window)
415 (define-key map "H" 'doc-view-fit-height-to-window)
416 (define-key map "P" 'doc-view-fit-page-to-window)
417 ;; Killing the buffer (and the process)
418 (define-key map (kbd "k") 'doc-view-kill-proc-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 (force-mode-line-update) ;To update `current-page'.
504 (setf (doc-view-current-page) page
505 (doc-view-current-info)
506 (concat
507 (propertize
508 (format "Page %d of %d." page len) 'face 'bold)
509 ;; Tell user if converting isn't finished yet
510 (if doc-view--current-converter-processes
511 " (still converting...)\n"
512 "\n")
513 ;; Display context infos if this page matches the last search
514 (when (and doc-view--current-search-matches
515 (assq page doc-view--current-search-matches))
516 (concat (propertize "Search matches:\n" 'face 'bold)
517 (let ((contexts ""))
518 (dolist (m (cdr (assq page
519 doc-view--current-search-matches)))
520 (setq contexts (concat contexts " - \"" m "\"\n")))
521 contexts)))))
522 ;; Update the buffer
523 ;; We used to find the file name from doc-view--current-files but
524 ;; that's not right if the pages are not generated sequentially
525 ;; or if the page isn't in doc-view--current-files yet.
526 (let ((file (expand-file-name
527 (format doc-view--image-file-pattern page)
528 (doc-view--current-cache-dir))))
529 (doc-view-insert-image file :pointer 'arrow)
530 (when (and (not (file-exists-p file))
531 doc-view--current-converter-processes)
532 ;; The PNG file hasn't been generated yet.
533 (funcall doc-view-single-page-converter-function
534 doc-view--buffer-file-name file page
535 (let ((win (selected-window)))
536 (lambda ()
537 (and (eq (current-buffer) (window-buffer win))
538 ;; If we changed page in the mean
539 ;; time, don't mess things up.
540 (eq (doc-view-current-page win) page)
541 ;; Make sure we don't infloop.
542 (file-readable-p file)
543 (with-selected-window win
544 (doc-view-goto-page page))))))))
545 (overlay-put (doc-view-current-overlay)
546 'help-echo (doc-view-current-info))))
548 (defun doc-view-next-page (&optional arg)
549 "Browse ARG pages forward."
550 (interactive "p")
551 (doc-view-goto-page (+ (doc-view-current-page) (or arg 1))))
553 (defun doc-view-previous-page (&optional arg)
554 "Browse ARG pages backward."
555 (interactive "p")
556 (doc-view-goto-page (- (doc-view-current-page) (or arg 1))))
558 (defun doc-view-first-page ()
559 "View the first page."
560 (interactive)
561 (doc-view-goto-page 1))
563 (defun doc-view-last-page ()
564 "View the last page."
565 (interactive)
566 (doc-view-goto-page (doc-view-last-page-number)))
568 (defun doc-view-scroll-up-or-next-page (&optional arg)
569 "Scroll page up ARG lines if possible, else goto next page.
570 When `doc-view-continuous' is non-nil, scrolling upward
571 at the bottom edge of the page moves to the next page.
572 Otherwise, goto next page only on typing SPC (ARG is nil)."
573 (interactive "P")
574 (if (or doc-view-continuous (null arg))
575 (let ((hscroll (window-hscroll))
576 (cur-page (doc-view-current-page)))
577 (when (= (window-vscroll) (image-scroll-up arg))
578 (doc-view-next-page)
579 (when (/= cur-page (doc-view-current-page))
580 (image-bob)
581 (image-bol 1))
582 (set-window-hscroll (selected-window) hscroll)))
583 (image-scroll-up arg)))
585 (defun doc-view-scroll-down-or-previous-page (&optional arg)
586 "Scroll page down ARG lines if possible, else goto previous page.
587 When `doc-view-continuous' is non-nil, scrolling downward
588 at the top edge of the page moves to the previous page.
589 Otherwise, goto previous page only on typing DEL (ARG is nil)."
590 (interactive "P")
591 (if (or doc-view-continuous (null arg))
592 (let ((hscroll (window-hscroll))
593 (cur-page (doc-view-current-page)))
594 (when (= (window-vscroll) (image-scroll-down arg))
595 (doc-view-previous-page)
596 (when (/= cur-page (doc-view-current-page))
597 (image-eob)
598 (image-bol 1))
599 (set-window-hscroll (selected-window) hscroll)))
600 (image-scroll-down arg)))
602 (defun doc-view-next-line-or-next-page (&optional arg)
603 "Scroll upward by ARG lines if possible, else goto next page.
604 When `doc-view-continuous' is non-nil, scrolling a line upward
605 at the bottom edge of the page moves to the next page."
606 (interactive "p")
607 (if doc-view-continuous
608 (let ((hscroll (window-hscroll))
609 (cur-page (doc-view-current-page)))
610 (when (= (window-vscroll) (image-next-line arg))
611 (doc-view-next-page)
612 (when (/= cur-page (doc-view-current-page))
613 (image-bob)
614 (image-bol 1))
615 (set-window-hscroll (selected-window) hscroll)))
616 (image-next-line 1)))
618 (defun doc-view-previous-line-or-previous-page (&optional arg)
619 "Scroll downward by ARG lines if possible, else goto previous page.
620 When `doc-view-continuous' is non-nil, scrolling a line downward
621 at the top edge of the page moves to the previous page."
622 (interactive "p")
623 (if doc-view-continuous
624 (let ((hscroll (window-hscroll))
625 (cur-page (doc-view-current-page)))
626 (when (= (window-vscroll) (image-previous-line arg))
627 (doc-view-previous-page)
628 (when (/= cur-page (doc-view-current-page))
629 (image-eob)
630 (image-bol 1))
631 (set-window-hscroll (selected-window) hscroll)))
632 (image-previous-line arg)))
634 ;;;; Utility Functions
636 (defun doc-view-kill-proc ()
637 "Kill the current converter process(es)."
638 (interactive)
639 (while (consp doc-view--current-converter-processes)
640 (ignore-errors ;; Some entries might not be processes, and maybe
641 ;; some are dead already?
642 (kill-process (pop doc-view--current-converter-processes))))
643 (when doc-view--current-timer
644 (cancel-timer doc-view--current-timer)
645 (setq doc-view--current-timer nil))
646 (setq mode-line-process nil))
648 (defun doc-view-kill-proc-and-buffer ()
649 "Kill the current converter process and buffer."
650 (interactive)
651 (doc-view-kill-proc)
652 (when (eq major-mode 'doc-view-mode)
653 (kill-buffer (current-buffer))))
655 (defun doc-view-make-safe-dir (dir)
656 (condition-case nil
657 (let ((umask (default-file-modes)))
658 (unwind-protect
659 (progn
660 ;; Create temp files with strict access rights. It's easy to
661 ;; loosen them later, whereas it's impossible to close the
662 ;; time-window of loose permissions otherwise.
663 (set-default-file-modes #o0700)
664 (make-directory dir))
665 ;; Reset the umask.
666 (set-default-file-modes umask)))
667 (file-already-exists
668 (when (file-symlink-p dir)
669 (error "Danger: %s points to a symbolic link" dir))
670 ;; In case it was created earlier with looser rights.
671 ;; We could check the mode info returned by file-attributes, but it's
672 ;; a pain to parse and it may not tell you what we want under
673 ;; non-standard file-systems. So let's just say what we want and let
674 ;; the underlying C code and file-system figure it out.
675 ;; This also ends up checking a bunch of useful conditions: it makes
676 ;; sure we have write-access to the directory and that we own it, thus
677 ;; closing a bunch of security holes.
678 (condition-case error
679 (set-file-modes dir #o0700)
680 (file-error
681 (error
682 (format "Unable to use temporary directory %s: %s"
683 dir (mapconcat 'identity (cdr error) " "))))))))
685 (defun doc-view--current-cache-dir ()
686 "Return the directory where the png files of the current doc should be saved.
687 It's a subdirectory of `doc-view-cache-directory'."
688 (if doc-view--current-cache-dir
689 doc-view--current-cache-dir
690 ;; Try and make sure doc-view-cache-directory exists and is safe.
691 (doc-view-make-safe-dir doc-view-cache-directory)
692 ;; Now compute the subdirectory to use.
693 (setq doc-view--current-cache-dir
694 (file-name-as-directory
695 (expand-file-name
696 (concat (subst-char-in-string ?% ?_ ;; bug#13679
697 (file-name-nondirectory doc-view--buffer-file-name))
699 (let ((file doc-view--buffer-file-name))
700 (with-temp-buffer
701 (set-buffer-multibyte nil)
702 (insert-file-contents-literally file)
703 (md5 (current-buffer)))))
704 doc-view-cache-directory)))))
706 ;;;###autoload
707 (defun doc-view-mode-p (type)
708 "Return non-nil if document type TYPE is available for `doc-view'.
709 Document types are symbols like `dvi', `ps', `pdf', or `odf' (any
710 OpenDocument format)."
711 (and (display-graphic-p)
712 (or (image-type-available-p 'imagemagick)
713 (image-type-available-p 'png))
714 (cond
715 ((eq type 'dvi)
716 (and (doc-view-mode-p 'pdf)
717 (or (and doc-view-dvipdf-program
718 (executable-find doc-view-dvipdf-program))
719 (and doc-view-dvipdfm-program
720 (executable-find doc-view-dvipdfm-program)))))
721 ((memq type '(postscript ps eps pdf))
722 ;; FIXME: allow mupdf here
723 (and doc-view-ghostscript-program
724 (executable-find doc-view-ghostscript-program)))
725 ((eq type 'odf)
726 (and doc-view-odf->pdf-converter-program
727 (executable-find doc-view-odf->pdf-converter-program)
728 (doc-view-mode-p 'pdf)))
729 ((eq type 'djvu)
730 (executable-find "ddjvu"))
731 (t ;; unknown image type
732 nil))))
734 ;;;; Conversion Functions
736 (defvar doc-view-shrink-factor 1.125)
738 (defun doc-view-enlarge (factor)
739 "Enlarge the document by FACTOR."
740 (interactive (list doc-view-shrink-factor))
741 (if (and doc-view-scale-internally
742 (eq (plist-get (cdr (doc-view-current-image)) :type)
743 'imagemagick))
744 ;; ImageMagick supports on-the-fly-rescaling.
745 (let ((new (ceiling (* factor doc-view-image-width))))
746 (unless (equal new doc-view-image-width)
747 (setq-local doc-view-image-width new)
748 (doc-view-insert-image
749 (plist-get (cdr (doc-view-current-image)) :file)
750 :width doc-view-image-width)))
751 (let ((new (ceiling (* factor doc-view-resolution))))
752 (unless (equal new doc-view-resolution)
753 (setq-local doc-view-resolution new)
754 (doc-view-reconvert-doc)))))
756 (defun doc-view-shrink (factor)
757 "Shrink the document."
758 (interactive (list doc-view-shrink-factor))
759 (doc-view-enlarge (/ 1.0 factor)))
761 (defun doc-view-scale-reset ()
762 "Reset the document size/zoom level to the initial one."
763 (interactive)
764 (if (and doc-view-scale-internally
765 (eq (plist-get (cdr (doc-view-current-image)) :type)
766 'imagemagick))
767 (progn
768 (kill-local-variable 'doc-view-image-width)
769 (doc-view-insert-image
770 (plist-get (cdr (doc-view-current-image)) :file)
771 :width doc-view-image-width))
772 (kill-local-variable 'doc-view-resolution)
773 (doc-view-reconvert-doc)))
775 (defun doc-view-scale-adjust (factor)
776 "Adjust the scale of the DocView page images by FACTOR.
777 FACTOR defaults to `doc-view-shrink-factor'.
779 The actual adjustment made depends on the final component of the
780 key-binding used to invoke the command, with all modifiers removed:
782 +, = Increase the image scale by FACTOR
783 - Decrease the image scale by FACTOR
784 0 Reset the image scale to the initial scale"
785 (interactive (list doc-view-shrink-factor))
786 (let ((ev last-command-event)
787 (echo-keystrokes nil))
788 (pcase (event-basic-type ev)
789 ((or ?+ ?=) (doc-view-enlarge factor))
790 (?- (doc-view-shrink factor))
791 (?0 (doc-view-scale-reset)))))
793 (defun doc-view-fit-width-to-window ()
794 "Fit the image width to the window width."
795 (interactive)
796 (let ((win-width (- (nth 2 (window-inside-pixel-edges))
797 (nth 0 (window-inside-pixel-edges))))
798 (slice (doc-view-current-slice)))
799 (if (not slice)
800 (let ((img-width (car (image-display-size
801 (image-get-display-property) t))))
802 (doc-view-enlarge (/ (float win-width) (float img-width))))
804 ;; If slice is set
805 (let* ((slice-width (nth 2 slice))
806 (scale-factor (/ (float win-width) (float slice-width)))
807 (new-slice (mapcar (lambda (x) (ceiling (* scale-factor x))) slice)))
809 (doc-view-enlarge scale-factor)
810 (setf (doc-view-current-slice) new-slice)
811 (doc-view-goto-page (doc-view-current-page))))))
813 (defun doc-view-fit-height-to-window ()
814 "Fit the image height to the window height."
815 (interactive)
816 (let ((win-height (- (nth 3 (window-inside-pixel-edges))
817 (nth 1 (window-inside-pixel-edges))))
818 (slice (doc-view-current-slice)))
819 (if (not slice)
820 (let ((img-height (cdr (image-display-size
821 (image-get-display-property) t))))
822 ;; When users call 'doc-view-fit-height-to-window',
823 ;; they might want to go to next page by typing SPC
824 ;; ONLY once. So I used '(- win-height 1)' instead of
825 ;; 'win-height'
826 (doc-view-enlarge (/ (float (- win-height 1)) (float img-height))))
828 ;; If slice is set
829 (let* ((slice-height (nth 3 slice))
830 (scale-factor (/ (float (- win-height 1)) (float slice-height)))
831 (new-slice (mapcar (lambda (x) (ceiling (* scale-factor x))) slice)))
833 (doc-view-enlarge scale-factor)
834 (setf (doc-view-current-slice) new-slice)
835 (doc-view-goto-page (doc-view-current-page))))))
837 (defun doc-view-fit-page-to-window ()
838 "Fit the image to the window.
839 More specifically, this function enlarges image by:
841 min {(window-width / image-width), (window-height / image-height)} times."
842 (interactive)
843 (let ((win-width (- (nth 2 (window-inside-pixel-edges))
844 (nth 0 (window-inside-pixel-edges))))
845 (win-height (- (nth 3 (window-inside-pixel-edges))
846 (nth 1 (window-inside-pixel-edges))))
847 (slice (doc-view-current-slice)))
848 (if (not slice)
849 (let ((img-width (car (image-display-size
850 (image-get-display-property) t)))
851 (img-height (cdr (image-display-size
852 (image-get-display-property) t))))
853 (doc-view-enlarge (min (/ (float win-width) (float img-width))
854 (/ (float (- win-height 1))
855 (float img-height)))))
856 ;; If slice is set
857 (let* ((slice-width (nth 2 slice))
858 (slice-height (nth 3 slice))
859 (scale-factor (min (/ (float win-width) (float slice-width))
860 (/ (float (- win-height 1))
861 (float slice-height))))
862 (new-slice (mapcar (lambda (x) (ceiling (* scale-factor x))) slice)))
863 (doc-view-enlarge scale-factor)
864 (setf (doc-view-current-slice) new-slice)
865 (doc-view-goto-page (doc-view-current-page))))))
867 (defun doc-view-reconvert-doc ()
868 "Reconvert the current document.
869 Should be invoked when the cached images aren't up-to-date."
870 (interactive)
871 (doc-view-kill-proc)
872 ;; Clear the old cached files
873 (when (file-exists-p (doc-view--current-cache-dir))
874 (delete-directory (doc-view--current-cache-dir) 'recursive))
875 (kill-local-variable 'doc-view-last-page-number)
876 (doc-view-initiate-display))
878 (defun doc-view-sentinel (proc event)
879 "Generic sentinel for doc-view conversion processes."
880 (if (not (string-match "finished" event))
881 (message "DocView: process %s changed status to %s."
882 (process-name proc)
883 (if (string-match "\\(.+\\)\n?\\'" event)
884 (match-string 1 event)
885 event))
886 (when (buffer-live-p (process-get proc 'buffer))
887 (with-current-buffer (process-get proc 'buffer)
888 (setq doc-view--current-converter-processes
889 (delq proc doc-view--current-converter-processes))
890 (setq mode-line-process
891 (if doc-view--current-converter-processes
892 (format ":%s" (car doc-view--current-converter-processes))))
893 (funcall (process-get proc 'callback))))))
895 (defun doc-view-start-process (name program args callback)
896 ;; Make sure the process is started in an existing directory, (rather than
897 ;; some file-name-handler-managed dir, for example).
898 (let* ((default-directory (or (unhandled-file-name-directory
899 default-directory)
900 (expand-file-name "~/")))
901 (proc (apply 'start-process name doc-view-conversion-buffer
902 program args)))
903 (push proc doc-view--current-converter-processes)
904 (setq mode-line-process (list (format ":%s" proc)))
905 (set-process-sentinel proc 'doc-view-sentinel)
906 (process-put proc 'buffer (current-buffer))
907 (process-put proc 'callback callback)))
909 (defun doc-view-dvi->pdf (dvi pdf callback)
910 "Convert DVI to PDF asynchronously and call CALLBACK when finished."
911 ;; Prefer dvipdf over dvipdfm, because the latter has problems if the DVI
912 ;; references and includes other PS files.
913 (if (and doc-view-dvipdf-program
914 (executable-find doc-view-dvipdf-program))
915 (doc-view-start-process "dvi->pdf" doc-view-dvipdf-program
916 (list dvi pdf)
917 callback)
918 (doc-view-start-process "dvi->pdf" doc-view-dvipdfm-program
919 (list "-o" pdf dvi)
920 callback)))
922 (defun doc-view-pdf->png-converter-ghostscript (pdf png page callback)
923 (doc-view-start-process
924 "pdf/ps->png" doc-view-ghostscript-program
925 `(,@doc-view-ghostscript-options
926 ,(format "-r%d" (round doc-view-resolution))
927 ,@(if page `(,(format "-dFirstPage=%d" page)))
928 ,@(if page `(,(format "-dLastPage=%d" page)))
929 ,(concat "-sOutputFile=" png)
930 ,pdf)
931 callback))
933 (defalias 'doc-view-ps->png-converter-ghostscript
934 'doc-view-pdf->png-converter-ghostscript)
936 (defun doc-view-djvu->tiff-converter-ddjvu (djvu tiff page callback)
937 "Convert PAGE of a DJVU file to bitmap(s) asynchronously.
938 Call CALLBACK with no arguments when done.
939 If PAGE is nil, convert the whole document."
940 (doc-view-start-process
941 "djvu->tiff" "ddjvu"
942 `("-format=tiff"
943 ;; ddjvu only accepts the range 1-999.
944 ,(format "-scale=%d" (round doc-view-resolution))
945 ;; -eachpage was only added after djvulibre-3.5.25.3!
946 ,@(unless page '("-eachpage"))
947 ,@(if page `(,(format "-page=%d" page)))
948 ,djvu
949 ,tiff)
950 callback))
952 (defun doc-view-pdf->png-converter-mupdf (pdf png page callback)
953 (doc-view-start-process
954 "pdf->png" doc-view-pdfdraw-program
955 `(,(concat "-o" png)
956 ,(format "-r%d" (round doc-view-resolution))
957 ,pdf
958 ,@(if page `(,(format "%d" page))))
959 callback))
961 (defun doc-view-odf->pdf-converter-unoconv (odf callback)
962 "Convert ODF to PDF asynchronously and call CALLBACK when finished.
963 The converted PDF is put into the current cache directory, and it
964 is named like ODF with the extension turned to pdf."
965 (doc-view-start-process "odf->pdf" doc-view-odf->pdf-converter-program
966 (list "-f" "pdf" "-o" (doc-view--current-cache-dir) odf)
967 callback))
969 (defun doc-view-odf->pdf-converter-soffice (odf callback)
970 "Convert ODF to PDF asynchronously and call CALLBACK when finished.
971 The converted PDF is put into the current cache directory, and it
972 is named like ODF with the extension turned to pdf."
973 ;; FIXME: soffice doesn't work when there's another running
974 ;; LibreOffice instance, in which case it returns success without
975 ;; actually doing anything. See LibreOffice bug
976 ;; https://bugs.freedesktop.org/show_bug.cgi?id=37531. A workaround
977 ;; is to start soffice with a separate UserInstallation directory.
978 (let ((tmp-user-install-dir (make-temp-file "libreoffice-docview" t)))
979 (doc-view-start-process "odf->pdf" doc-view-odf->pdf-converter-program
980 (list
981 (concat "-env:UserInstallation=file://"
982 tmp-user-install-dir)
983 "--headless" "--convert-to" "pdf"
984 "--outdir" (doc-view--current-cache-dir) odf)
985 (lambda ()
986 (delete-directory tmp-user-install-dir t)
987 (funcall callback)))))
989 (defun doc-view-pdf/ps->png (pdf-ps png)
990 ;; FIXME: Fix name and docstring to account for djvu&tiff.
991 "Convert PDF-PS to PNG asynchronously."
992 (funcall
993 (pcase doc-view-doc-type
994 (`pdf doc-view-pdf->png-converter-function)
995 (`djvu #'doc-view-djvu->tiff-converter-ddjvu)
996 (_ #'doc-view-ps->png-converter-ghostscript))
997 pdf-ps png nil
998 (let ((resolution doc-view-resolution))
999 (lambda ()
1000 ;; Only create the resolution file when it's all done, so it also
1001 ;; serves as a witness that the conversion is complete.
1002 (write-region (prin1-to-string resolution) nil
1003 (expand-file-name "resolution.el"
1004 (doc-view--current-cache-dir))
1005 nil 'silently)
1006 (when doc-view--current-timer
1007 (cancel-timer doc-view--current-timer)
1008 (setq doc-view--current-timer nil))
1009 (doc-view-display (current-buffer) 'force))))
1011 ;; Update the displayed pages as soon as they're done generating.
1012 (when doc-view-conversion-refresh-interval
1013 (setq doc-view--current-timer
1014 (run-at-time "1 secs" doc-view-conversion-refresh-interval
1015 'doc-view-display
1016 (current-buffer)))))
1018 (declare-function clear-image-cache "image.c" (&optional filter))
1020 (defun doc-view-document->bitmap (pdf png pages)
1021 "Convert a document file to bitmap images asynchronously.
1022 Start by converting PAGES, and then the rest."
1023 (if (null pages)
1024 (doc-view-pdf/ps->png pdf png)
1025 ;; We could render several `pages' with a single process if they're
1026 ;; (almost) consecutive, but since in 99% of the cases, there'll be only
1027 ;; a single page anyway, and of the remaining 1%, few cases will have
1028 ;; consecutive pages, it's not worth the trouble.
1029 (let ((rest (cdr pages)))
1030 (funcall doc-view-single-page-converter-function
1031 pdf (format png (car pages)) (car pages)
1032 (lambda ()
1033 (if rest
1034 (doc-view-document->bitmap pdf png rest)
1035 ;; Yippie, the important pages are done, update the display.
1036 (clear-image-cache)
1037 ;; For the windows that have a message (like "Welcome to
1038 ;; DocView") display property, clearing the image cache is
1039 ;; not sufficient.
1040 (dolist (win (get-buffer-window-list (current-buffer) nil 'visible))
1041 (with-selected-window win
1042 (when (stringp (overlay-get (doc-view-current-overlay) 'display))
1043 (doc-view-goto-page (doc-view-current-page)))))
1044 ;; Convert the rest of the pages.
1045 (doc-view-pdf/ps->png pdf png)))))))
1047 (defun doc-view-pdf->txt (pdf txt callback)
1048 "Convert PDF to TXT asynchronously and call CALLBACK when finished."
1049 (or (executable-find doc-view-pdftotext-program)
1050 (error "You need the `pdftotext' program to convert a PDF to text"))
1051 (doc-view-start-process "pdf->txt" doc-view-pdftotext-program
1052 (list "-raw" pdf txt)
1053 callback))
1055 (defun doc-view-current-cache-doc-pdf ()
1056 "Return the name of the doc.pdf in the current cache dir.
1057 This file exists only if the current document isn't a PDF or PS file already."
1058 (expand-file-name "doc.pdf" (doc-view--current-cache-dir)))
1060 (defun doc-view-doc->txt (txt callback)
1061 "Convert the current document to text and call CALLBACK when done."
1062 (make-directory (doc-view--current-cache-dir) t)
1063 (pcase doc-view-doc-type
1064 (`pdf
1065 ;; Doc is a PDF, so convert it to TXT
1066 (doc-view-pdf->txt doc-view--buffer-file-name txt callback))
1067 (`ps
1068 ;; Doc is a PS, so convert it to PDF (which will be converted to
1069 ;; TXT thereafter).
1070 (let ((pdf (doc-view-current-cache-doc-pdf)))
1071 (doc-view-ps->pdf doc-view--buffer-file-name pdf
1072 (lambda () (doc-view-pdf->txt pdf txt callback)))))
1073 (`dvi
1074 ;; Doc is a DVI. This means that a doc.pdf already exists in its
1075 ;; cache subdirectory.
1076 (doc-view-pdf->txt (doc-view-current-cache-doc-pdf) txt callback))
1077 (`odf
1078 ;; Doc is some ODF (or MS Office) doc. This means that a doc.pdf
1079 ;; already exists in its cache subdirectory.
1080 (doc-view-pdf->txt (doc-view-current-cache-doc-pdf) txt callback))
1081 (_ (error "DocView doesn't know what to do"))))
1083 (defun doc-view-ps->pdf (ps pdf callback)
1084 "Convert PS to PDF asynchronously and call CALLBACK when finished."
1085 (or (executable-find doc-view-ps2pdf-program)
1086 (error "You need the `ps2pdf' program to convert PS to PDF"))
1087 (doc-view-start-process "ps->pdf" doc-view-ps2pdf-program
1088 (list
1089 ;; Avoid security problems when rendering files from
1090 ;; untrusted sources.
1091 "-dSAFER"
1092 ;; in-file and out-file
1093 ps pdf)
1094 callback))
1096 (defun doc-view-active-pages ()
1097 (let ((pages ()))
1098 (dolist (win (get-buffer-window-list (current-buffer) nil 'visible))
1099 (let ((page (image-mode-window-get 'page win)))
1100 (unless (memq page pages) (push page pages))))
1101 pages))
1103 (defun doc-view-convert-current-doc ()
1104 "Convert `doc-view--buffer-file-name' to a set of png files, one file per page.
1105 Those files are saved in the directory given by the function
1106 `doc-view--current-cache-dir'."
1107 ;; Let stale files still display while we recompute the new ones, so only
1108 ;; flush the cache when the conversion is over. One of the reasons why it
1109 ;; is important to keep displaying the stale page is so that revert-buffer
1110 ;; preserves the horizontal/vertical scroll settings (which are otherwise
1111 ;; reset during the redisplay).
1112 (setq doc-view--pending-cache-flush t)
1113 (let ((png-file (expand-file-name
1114 (format doc-view--image-file-pattern "%d")
1115 (doc-view--current-cache-dir))))
1116 (make-directory (doc-view--current-cache-dir) t)
1117 (pcase doc-view-doc-type
1118 (`dvi
1119 ;; DVI files have to be converted to PDF before Ghostscript can process
1120 ;; it.
1121 (let ((pdf (doc-view-current-cache-doc-pdf)))
1122 (doc-view-dvi->pdf doc-view--buffer-file-name pdf
1123 (lambda () (doc-view-pdf/ps->png pdf png-file)))))
1124 (`odf
1125 ;; ODF files have to be converted to PDF before Ghostscript can
1126 ;; process it.
1127 (let ((pdf (doc-view-current-cache-doc-pdf))
1128 (opdf (expand-file-name
1129 (concat (file-name-base doc-view--buffer-file-name)
1130 ".pdf")
1131 doc-view--current-cache-dir))
1132 (png-file png-file))
1133 ;; The unoconv tool only supports an output directory, but no
1134 ;; file name. It's named like the input file with the
1135 ;; extension replaced by pdf.
1136 (funcall doc-view-odf->pdf-converter-function doc-view--buffer-file-name
1137 (lambda ()
1138 ;; Rename to doc.pdf
1139 (rename-file opdf pdf)
1140 (doc-view-pdf/ps->png pdf png-file)))))
1141 ((or `pdf `djvu)
1142 (let ((pages (doc-view-active-pages)))
1143 ;; Convert doc to bitmap images starting with the active pages.
1144 (doc-view-document->bitmap doc-view--buffer-file-name png-file pages)))
1146 ;; Convert to PNG images.
1147 (doc-view-pdf/ps->png doc-view--buffer-file-name png-file)))))
1149 ;;;; Slicing
1151 (declare-function image-size "image.c" (spec &optional pixels frame))
1153 (defun doc-view-set-slice (x y width height)
1154 "Set the slice of the images that should be displayed.
1155 You can use this function to tell doc-view not to display the
1156 margins of the document. It prompts for the top-left corner (X
1157 and Y) of the slice to display and its WIDTH and HEIGHT.
1159 See `doc-view-set-slice-using-mouse' and
1160 `doc-view-set-slice-from-bounding-box' for more convenient ways
1161 to do that. To reset the slice use `doc-view-reset-slice'."
1162 (interactive
1163 (let* ((size (image-size (doc-view-current-image) t))
1164 (a (read-number (format "Top-left X (0..%d): " (car size))))
1165 (b (read-number (format "Top-left Y (0..%d): " (cdr size))))
1166 (c (read-number (format "Width (0..%d): " (- (car size) a))))
1167 (d (read-number (format "Height (0..%d): " (- (cdr size) b)))))
1168 (list a b c d)))
1169 (setf (doc-view-current-slice) (list x y width height))
1170 ;; Redisplay
1171 (doc-view-goto-page (doc-view-current-page)))
1173 (defun doc-view-set-slice-using-mouse ()
1174 "Set the slice of the images that should be displayed.
1175 You set the slice by pressing mouse-1 at its top-left corner and
1176 dragging it to its bottom-right corner. See also
1177 `doc-view-set-slice' and `doc-view-reset-slice'."
1178 (interactive)
1179 (let (x y w h done)
1180 (while (not done)
1181 (let ((e (read-event
1182 (concat "Press mouse-1 at the top-left corner and "
1183 "drag it to the bottom-right corner!"))))
1184 (when (eq (car e) 'drag-mouse-1)
1185 (setq x (car (posn-object-x-y (event-start e))))
1186 (setq y (cdr (posn-object-x-y (event-start e))))
1187 (setq w (- (car (posn-object-x-y (event-end e))) x))
1188 (setq h (- (cdr (posn-object-x-y (event-end e))) y))
1189 (setq done t))))
1190 (doc-view-set-slice x y w h)))
1192 (defun doc-view-get-bounding-box ()
1193 "Get the BoundingBox information of the current page."
1194 (let* ((page (doc-view-current-page))
1195 (doc (let ((cache-doc (doc-view-current-cache-doc-pdf)))
1196 (if (file-exists-p cache-doc)
1197 cache-doc
1198 doc-view--buffer-file-name)))
1199 (o (shell-command-to-string
1200 (concat doc-view-ghostscript-program
1201 " -dSAFER -dBATCH -dNOPAUSE -q -sDEVICE=bbox "
1202 (format "-dFirstPage=%s -dLastPage=%s %s"
1203 page page doc)))))
1204 (save-match-data
1205 (when (string-match (concat "%%BoundingBox: "
1206 "\\([[:digit:]]+\\) \\([[:digit:]]+\\) "
1207 "\\([[:digit:]]+\\) \\([[:digit:]]+\\)") o)
1208 (mapcar #'string-to-number
1209 (list (match-string 1 o)
1210 (match-string 2 o)
1211 (match-string 3 o)
1212 (match-string 4 o)))))))
1214 (defvar doc-view-paper-sizes
1215 '((a4 595 842)
1216 (a4-landscape 842 595)
1217 (letter 612 792)
1218 (letter-landscape 792 612)
1219 (legal 612 1008)
1220 (legal-landscape 1008 612)
1221 (a3 842 1191)
1222 (a3-landscape 1191 842)
1223 (tabloid 792 1224)
1224 (ledger 1224 792))
1225 "An alist from paper size names to dimensions.")
1227 (defun doc-view-guess-paper-size (iw ih)
1228 "Guess the paper size according to the aspect ratio."
1229 (cl-labels ((div (x y)
1230 (round (/ (* 100.0 x) y))))
1231 (let ((ar (div iw ih))
1232 (al (mapcar (lambda (l)
1233 (list (div (nth 1 l) (nth 2 l)) (car l)))
1234 doc-view-paper-sizes)))
1235 (cadr (assoc ar al)))))
1237 (defun doc-view-scale-bounding-box (ps iw ih bb)
1238 (list (/ (* (nth 0 bb) iw) (nth 1 (assoc ps doc-view-paper-sizes)))
1239 (/ (* (nth 1 bb) ih) (nth 2 (assoc ps doc-view-paper-sizes)))
1240 (/ (* (nth 2 bb) iw) (nth 1 (assoc ps doc-view-paper-sizes)))
1241 (/ (* (nth 3 bb) ih) (nth 2 (assoc ps doc-view-paper-sizes)))))
1243 (defun doc-view-set-slice-from-bounding-box (&optional force-paper-size)
1244 "Set the slice from the document's BoundingBox information.
1245 The result is that the margins are almost completely cropped,
1246 much more accurate than could be done manually using
1247 `doc-view-set-slice-using-mouse'."
1248 (interactive "P")
1249 (let ((bb (doc-view-get-bounding-box)))
1250 (if (not bb)
1251 (message "BoundingBox couldn't be determined")
1252 (let* ((is (image-size (doc-view-current-image) t))
1253 (iw (car is))
1254 (ih (cdr is))
1255 (ps (or (and (null force-paper-size)
1256 (doc-view-guess-paper-size iw ih))
1257 (intern (completing-read "Paper size: "
1258 doc-view-paper-sizes
1259 nil t))))
1260 (bb (doc-view-scale-bounding-box ps iw ih bb))
1261 (x1 (nth 0 bb))
1262 (y1 (nth 1 bb))
1263 (x2 (nth 2 bb))
1264 (y2 (nth 3 bb)))
1265 ;; We keep a 2 pixel margin.
1266 (doc-view-set-slice (- x1 2) (- ih y2 2)
1267 (+ (- x2 x1) 4) (+ (- y2 y1) 4))))))
1269 (defun doc-view-reset-slice ()
1270 "Reset the current slice.
1271 After calling this function whole pages will be visible again."
1272 (interactive)
1273 (setf (doc-view-current-slice) nil)
1274 ;; Redisplay
1275 (doc-view-goto-page (doc-view-current-page)))
1277 ;;;; Display
1279 (defun doc-view-insert-image (file &rest args)
1280 "Insert the given png FILE.
1281 ARGS is a list of image descriptors."
1282 (when doc-view--pending-cache-flush
1283 (clear-image-cache)
1284 (setq doc-view--pending-cache-flush nil))
1285 (let ((ol (doc-view-current-overlay)))
1286 ;; Only insert the image if the buffer is visible.
1287 (when (window-live-p (overlay-get ol 'window))
1288 (let* ((image (if (and file (file-readable-p file))
1289 (if (not (and doc-view-scale-internally
1290 (fboundp 'imagemagick-types)))
1291 (apply 'create-image file doc-view--image-type nil args)
1292 (unless (member :width args)
1293 (setq args `(,@args :width ,doc-view-image-width)))
1294 (apply 'create-image file 'imagemagick nil args))))
1295 (slice (doc-view-current-slice))
1296 (img-width (and image (car (image-size image))))
1297 (displayed-img-width (if (and image slice)
1298 (* (/ (float (nth 2 slice))
1299 (car (image-size image 'pixels)))
1300 img-width)
1301 img-width))
1302 (window-width (window-width)))
1303 (setf (doc-view-current-image) image)
1304 (move-overlay ol (point-min) (point-max))
1305 ;; In case the window is wider than the image, center the image
1306 ;; horizontally.
1307 (overlay-put ol 'before-string
1308 (when (and image (> window-width displayed-img-width))
1309 (propertize " " 'display
1310 `(space :align-to (+ center (-0.5 . ,displayed-img-width))))))
1311 (overlay-put ol 'display
1312 (cond
1313 (image
1314 (if slice
1315 (list (cons 'slice slice) image)
1316 image))
1317 ;; We're trying to display a page that doesn't exist.
1318 (doc-view--current-converter-processes
1319 ;; Maybe the page doesn't exist *yet*.
1320 "Cannot display this page (yet)!")
1322 ;; Typically happens if the conversion process somehow
1323 ;; failed. Better not signal an error here because it
1324 ;; could prevent a subsequent reconversion from fixing
1325 ;; the problem.
1326 (concat "Cannot display this page!\n"
1327 "Maybe because of a conversion failure!"))))
1328 (let ((win (overlay-get ol 'window)))
1329 (if (stringp (overlay-get ol 'display))
1330 (progn ;Make sure the text is not scrolled out of view.
1331 (set-window-hscroll win 0)
1332 (set-window-vscroll win 0))
1333 (let ((hscroll (image-mode-window-get 'hscroll win))
1334 (vscroll (image-mode-window-get 'vscroll win)))
1335 ;; Reset scroll settings, in case they were changed.
1336 (if hscroll (set-window-hscroll win hscroll))
1337 (if vscroll (set-window-vscroll win vscroll)))))))))
1339 (defun doc-view-sort (a b)
1340 "Return non-nil if A should be sorted before B.
1341 Predicate for sorting `doc-view--current-files'."
1342 (or (< (length a) (length b))
1343 (and (= (length a) (length b))
1344 (string< a b))))
1346 (defun doc-view-display (buffer &optional force)
1347 "Start viewing the document in BUFFER.
1348 If FORCE is non-nil, start viewing even if the document does not
1349 have the page we want to view."
1350 (with-current-buffer buffer
1351 (let ((prev-pages doc-view--current-files))
1352 (setq doc-view--current-files
1353 (sort (directory-files (doc-view--current-cache-dir) t
1354 (format doc-view--image-file-pattern
1355 "[0-9]+")
1357 'doc-view-sort))
1358 (unless (eq (length prev-pages) (length doc-view--current-files))
1359 (force-mode-line-update))
1360 (dolist (win (or (get-buffer-window-list buffer nil t)
1361 (list t)))
1362 (let* ((page (doc-view-current-page win))
1363 (pagefile (expand-file-name
1364 (format doc-view--image-file-pattern page)
1365 (doc-view--current-cache-dir))))
1366 (when (or force
1367 (and (not (member pagefile prev-pages))
1368 (member pagefile doc-view--current-files)))
1369 (if (windowp win)
1370 (with-selected-window win
1371 (cl-assert (eq (current-buffer) buffer) t)
1372 (doc-view-goto-page page))
1373 (doc-view-goto-page page))))))))
1375 (defun doc-view-buffer-message ()
1376 ;; Only show this message initially, not when refreshing the buffer (in which
1377 ;; case it's better to keep displaying the "stale" page while computing
1378 ;; the fresh new ones).
1379 (unless (overlay-get (doc-view-current-overlay) 'display)
1380 (overlay-put (doc-view-current-overlay) 'display
1381 (concat (propertize "Welcome to DocView!" 'face 'bold)
1382 "\n"
1384 If you see this buffer it means that the document you want to view is being
1385 converted to PNG and the conversion of the first page hasn't finished yet or
1386 `doc-view-conversion-refresh-interval' is set to nil.
1388 For now these keys are useful:
1390 `q' : Bury this buffer. Conversion will go on in background.
1391 `k' : Kill the conversion process and this buffer.
1392 `K' : Kill the conversion process.\n"))))
1394 (declare-function tooltip-show "tooltip" (text &optional use-echo-area))
1396 (defun doc-view-show-tooltip ()
1397 (interactive)
1398 (tooltip-show (doc-view-current-info)))
1400 (defun doc-view-open-text ()
1401 "Open a buffer with the current doc's contents as text."
1402 (interactive)
1403 (if doc-view--current-converter-processes
1404 (message "DocView: please wait till conversion finished.")
1405 (let ((txt (expand-file-name "doc.txt" (doc-view--current-cache-dir))))
1406 (if (file-readable-p txt)
1407 (let ((name (concat "Text contents of "
1408 (file-name-nondirectory buffer-file-name)))
1409 (dir (file-name-directory buffer-file-name)))
1410 (with-current-buffer (find-file txt)
1411 (rename-buffer name)
1412 (setq default-directory dir)))
1413 (doc-view-doc->txt txt 'doc-view-open-text)))))
1415 ;;;;; Toggle between editing and viewing
1417 (defvar-local doc-view-saved-settings nil
1418 "Doc-view settings saved while in some other mode.")
1419 (put 'doc-view-saved-settings 'permanent-local t)
1421 (defun doc-view-toggle-display ()
1422 "Toggle between editing a document as text or viewing it."
1423 (interactive)
1424 (if (eq major-mode 'doc-view-mode)
1425 ;; Switch to editing mode
1426 (progn
1427 (doc-view-kill-proc)
1428 (setq buffer-read-only nil)
1429 ;; Switch to the previously used major mode or fall back to
1430 ;; normal mode.
1431 (doc-view-fallback-mode)
1432 (doc-view-minor-mode 1))
1433 ;; Switch to doc-view-mode
1434 (when (and (buffer-modified-p)
1435 (y-or-n-p "The buffer has been modified. Save the changes? "))
1436 (save-buffer))
1437 (doc-view-mode)))
1439 ;;;; Searching
1442 (defun doc-view-search-internal (regexp file)
1443 "Return a list of FILE's pages that contain text matching REGEXP.
1444 The value is an alist of the form (PAGE CONTEXTS) where PAGE is
1445 the pagenumber and CONTEXTS are all lines of text containing a match."
1446 (with-temp-buffer
1447 (insert-file-contents file)
1448 (let ((page 1)
1449 (lastpage 1)
1450 matches)
1451 (while (re-search-forward (concat "\\(?:\\([\f]\\)\\|\\("
1452 regexp "\\)\\)") nil t)
1453 (when (match-string 1) (setq page (1+ page)))
1454 (when (match-string 2)
1455 (if (/= page lastpage)
1456 (push (cons page
1457 (list (buffer-substring
1458 (line-beginning-position)
1459 (line-end-position))))
1460 matches)
1461 (setq matches (cons
1462 (append
1464 ;; This page already is a match.
1465 (car matches)
1466 ;; This is the first match on page.
1467 (list page))
1468 (list (buffer-substring
1469 (line-beginning-position)
1470 (line-end-position))))
1471 (cdr matches))))
1472 (setq lastpage page)))
1473 (nreverse matches))))
1475 (defun doc-view-search-no-of-matches (list)
1476 "Extract the number of matches from the search result LIST."
1477 (let ((no 0))
1478 (dolist (p list)
1479 (setq no (+ no (1- (length p)))))
1480 no))
1482 (defun doc-view-search-backward (new-query)
1483 "Call `doc-view-search' for backward search.
1484 If prefix NEW-QUERY is given, ask for a new regexp."
1485 (interactive "P")
1486 (doc-view-search new-query t))
1488 (defun doc-view-search (new-query &optional backward)
1489 "Jump to the next match or initiate a new search if NEW-QUERY is given.
1490 If the current document hasn't been transformed to plain text
1491 till now do that first.
1492 If BACKWARD is non-nil, jump to the previous match."
1493 (interactive "P")
1494 (if (and (not new-query)
1495 doc-view--current-search-matches)
1496 (if backward
1497 (doc-view-search-previous-match 1)
1498 (doc-view-search-next-match 1))
1499 ;; New search, so forget the old results.
1500 (setq doc-view--current-search-matches nil)
1501 (let ((txt (expand-file-name "doc.txt"
1502 (doc-view--current-cache-dir))))
1503 (if (file-readable-p txt)
1504 (progn
1505 (setq doc-view--current-search-matches
1506 (doc-view-search-internal
1507 (read-from-minibuffer "Regexp: ")
1508 txt))
1509 (message "DocView: search yielded %d matches."
1510 (doc-view-search-no-of-matches
1511 doc-view--current-search-matches)))
1512 ;; We must convert to TXT first!
1513 (if doc-view--current-converter-processes
1514 (message "DocView: please wait till conversion finished.")
1515 (doc-view-doc->txt txt (lambda () (doc-view-search nil))))))))
1517 (defun doc-view-search-next-match (arg)
1518 "Go to the ARGth next matching page."
1519 (interactive "p")
1520 (let* ((next-pages (cl-remove-if
1521 (lambda (i) (<= (car i) (doc-view-current-page)))
1522 doc-view--current-search-matches))
1523 (page (car (nth (1- arg) next-pages))))
1524 (if page
1525 (doc-view-goto-page page)
1526 (when (and
1527 doc-view--current-search-matches
1528 (y-or-n-p "No more matches after current page. Wrap to first match? "))
1529 (doc-view-goto-page (caar doc-view--current-search-matches))))))
1531 (defun doc-view-search-previous-match (arg)
1532 "Go to the ARGth previous matching page."
1533 (interactive "p")
1534 (let* ((prev-pages (cl-remove-if
1535 (lambda (i) (>= (car i) (doc-view-current-page)))
1536 doc-view--current-search-matches))
1537 (page (car (nth (1- arg) (nreverse prev-pages)))))
1538 (if page
1539 (doc-view-goto-page page)
1540 (when (and
1541 doc-view--current-search-matches
1542 (y-or-n-p "No more matches before current page. Wrap to last match? "))
1543 (doc-view-goto-page (caar (last doc-view--current-search-matches)))))))
1545 ;;;; User interface commands and the mode
1547 (put 'doc-view-mode 'mode-class 'special)
1549 (defun doc-view-already-converted-p ()
1550 "Return non-nil if the current doc was already converted."
1551 (and (file-exists-p (doc-view--current-cache-dir))
1552 ;; Check that the resolution info is there, otherwise it means
1553 ;; the conversion is incomplete.
1554 (file-readable-p (expand-file-name "resolution.el"
1555 (doc-view--current-cache-dir)))
1556 (> (length (directory-files
1557 (doc-view--current-cache-dir)
1558 nil (format doc-view--image-file-pattern "[0-9]+")))
1559 0)))
1561 (defun doc-view-initiate-display ()
1562 ;; Switch to image display if possible.
1563 (if (doc-view-mode-p doc-view-doc-type)
1564 (progn
1565 (doc-view-buffer-message)
1566 (setf (doc-view-current-page) (or (doc-view-current-page) 1))
1567 (if (doc-view-already-converted-p)
1568 (progn
1569 (message "DocView: using cached files!")
1570 ;; Load the saved resolution.
1571 (let* ((res-file
1572 (expand-file-name "resolution.el"
1573 (doc-view--current-cache-dir)))
1574 (res
1575 (with-temp-buffer
1576 (when (file-readable-p res-file)
1577 (insert-file-contents res-file)
1578 (read (current-buffer))))))
1579 (when (numberp res)
1580 (setq-local doc-view-resolution res)))
1581 (doc-view-display (current-buffer) 'force))
1582 (doc-view-convert-current-doc))
1583 (message
1584 "%s"
1585 (substitute-command-keys
1586 (concat "Type \\[doc-view-toggle-display] to toggle between "
1587 "editing or viewing the document."))))
1588 (message
1589 "%s"
1590 (concat "No PNG support is available, or some conversion utility for "
1591 (file-name-extension doc-view--buffer-file-name)
1592 " files is missing."))
1593 (when (and (executable-find doc-view-pdftotext-program)
1594 (y-or-n-p
1595 "Unable to render file. View extracted text instead? "))
1596 (doc-view-open-text))
1597 (doc-view-toggle-display)))
1599 (defvar bookmark-make-record-function)
1601 (defun doc-view-clone-buffer-hook ()
1602 ;; FIXME: There are several potential problems linked with reconversion
1603 ;; and auto-revert when we have indirect buffers because they share their
1604 ;; /tmp cache directory. This sharing is good (you'd rather not reconvert
1605 ;; for each clone), but that means that clones need to collaborate a bit.
1606 ;; I guess it mostly means: detect when a reconversion process is already
1607 ;; running, and run the sentinel in all clones.
1609 ;; Maybe the clones should really have a separate /tmp directory
1610 ;; so they could have a different resolution and you could use clones
1611 ;; for zooming.
1612 (remove-overlays (point-min) (point-max) 'doc-view t)
1613 (if (consp image-mode-winprops-alist) (setq image-mode-winprops-alist nil)))
1615 (defun doc-view-intersection (l1 l2)
1616 (let ((l ()))
1617 (dolist (x l1) (if (memq x l2) (push x l)))
1620 (defun doc-view-set-doc-type ()
1621 "Figure out the current document type (`doc-view-doc-type')."
1622 (let ((name-types
1623 (when buffer-file-name
1624 (cdr (assoc (file-name-extension buffer-file-name)
1626 ;; DVI
1627 ("dvi" dvi)
1628 ;; PDF
1629 ("pdf" pdf) ("epdf" pdf)
1630 ;; PostScript
1631 ("ps" ps) ("eps" ps)
1632 ;; DjVu
1633 ("djvu" djvu)
1634 ;; OpenDocument formats
1635 ("odt" odf) ("ods" odf) ("odp" odf) ("odg" odf)
1636 ("odc" odf) ("odi" odf) ("odm" odf) ("ott" odf)
1637 ("ots" odf) ("otp" odf) ("otg" odf)
1638 ;; Microsoft Office formats (also handled
1639 ;; by the odf conversion chain)
1640 ("doc" odf) ("docx" odf) ("xls" odf) ("xlsx" odf)
1641 ("ppt" odf) ("pptx" odf))))))
1642 (content-types
1643 (save-excursion
1644 (goto-char (point-min))
1645 (cond
1646 ((looking-at "%!") '(ps))
1647 ((looking-at "%PDF") '(pdf))
1648 ((looking-at "\367\002") '(dvi))
1649 ((looking-at "AT&TFORM") '(djvu))))))
1650 (setq-local
1651 doc-view-doc-type
1652 (car (or (doc-view-intersection name-types content-types)
1653 (when (and name-types content-types)
1654 (error "Conflicting types: name says %s but content says %s"
1655 name-types content-types))
1656 name-types content-types
1657 (error "Cannot determine the document type"))))))
1659 (defun doc-view-set-up-single-converter ()
1660 "Find the right single-page converter for the current document type"
1661 (pcase-let ((`(,conv-function ,type ,extension)
1662 (pcase doc-view-doc-type
1663 (`djvu (list #'doc-view-djvu->tiff-converter-ddjvu 'tiff "tif"))
1664 (_ (list doc-view-pdf->png-converter-function 'png "png")))))
1665 (setq-local doc-view-single-page-converter-function conv-function)
1666 (setq-local doc-view--image-type type)
1667 (setq-local doc-view--image-file-pattern (concat "page-%s." extension))))
1669 ;; desktop.el integration
1671 (defun doc-view-desktop-save-buffer (_desktop-dirname)
1672 `((page . ,(doc-view-current-page))
1673 (slice . ,(doc-view-current-slice))))
1675 (declare-function desktop-restore-file-buffer "desktop"
1676 (buffer-filename buffer-name buffer-misc))
1678 (defun doc-view-restore-desktop-buffer (file name misc)
1679 (let ((page (cdr (assq 'page misc)))
1680 (slice (cdr (assq 'slice misc))))
1681 (desktop-restore-file-buffer file name misc)
1682 (with-selected-window (or (get-buffer-window (current-buffer) 0)
1683 (selected-window))
1684 (doc-view-goto-page page)
1685 (when slice (apply 'doc-view-set-slice slice)))))
1687 (add-to-list 'desktop-buffer-mode-handlers
1688 '(doc-view-mode . doc-view-restore-desktop-buffer))
1690 ;;;###autoload
1691 (defun doc-view-mode ()
1692 "Major mode in DocView buffers.
1694 DocView Mode is an Emacs document viewer. It displays PDF, PS
1695 and DVI files (as PNG images) in Emacs buffers.
1697 You can use \\<doc-view-mode-map>\\[doc-view-toggle-display] to
1698 toggle between displaying the document or editing it as text.
1699 \\{doc-view-mode-map}"
1700 (interactive)
1702 (if (= (point-min) (point-max))
1703 ;; The doc is empty or doesn't exist at all, so fallback to
1704 ;; another mode. We used to also check file-exists-p, but this
1705 ;; returns nil for tar members.
1706 (doc-view-fallback-mode)
1708 (let* ((prev-major-mode (if (derived-mode-p 'doc-view-mode)
1709 doc-view--previous-major-mode
1710 (unless (eq major-mode 'fundamental-mode)
1711 major-mode))))
1712 (kill-all-local-variables)
1713 (setq-local doc-view--previous-major-mode prev-major-mode))
1715 (dolist (var doc-view-saved-settings)
1716 (set (make-local-variable (car var)) (cdr var)))
1718 ;; Figure out the document type.
1719 (unless doc-view-doc-type
1720 (doc-view-set-doc-type))
1721 (doc-view-set-up-single-converter)
1723 (doc-view-make-safe-dir doc-view-cache-directory)
1724 ;; Handle compressed files, remote files, files inside archives
1725 (setq-local doc-view--buffer-file-name
1726 (cond
1727 (jka-compr-really-do-compress
1728 ;; FIXME: there's a risk of name conflicts here.
1729 (expand-file-name
1730 (file-name-nondirectory
1731 (file-name-sans-extension buffer-file-name))
1732 doc-view-cache-directory))
1733 ;; Is the file readable by local processes?
1734 ;; We used to use `file-remote-p' but it's unclear what it's
1735 ;; supposed to return nil for things like local files accessed
1736 ;; via `su' or via file://...
1737 ((let ((file-name-handler-alist nil))
1738 (not (and buffer-file-name
1739 (file-readable-p buffer-file-name))))
1740 ;; FIXME: there's a risk of name conflicts here.
1741 (expand-file-name
1742 (if buffer-file-name
1743 (file-name-nondirectory buffer-file-name)
1744 (buffer-name))
1745 doc-view-cache-directory))
1746 (t buffer-file-name)))
1747 (when (not (string= doc-view--buffer-file-name buffer-file-name))
1748 (write-region nil nil doc-view--buffer-file-name))
1750 (add-hook 'change-major-mode-hook
1751 (lambda ()
1752 (doc-view-kill-proc)
1753 (remove-overlays (point-min) (point-max) 'doc-view t))
1754 nil t)
1755 (add-hook 'clone-indirect-buffer-hook 'doc-view-clone-buffer-hook nil t)
1756 (add-hook 'kill-buffer-hook 'doc-view-kill-proc nil t)
1757 (when (and (boundp 'desktop-save-mode)
1758 desktop-save-mode)
1759 (setq-local desktop-save-buffer 'doc-view-desktop-save-buffer))
1761 (remove-overlays (point-min) (point-max) 'doc-view t) ;Just in case.
1762 ;; Keep track of display info ([vh]scroll, page number, overlay,
1763 ;; ...) for each window in which this document is shown.
1764 (add-hook 'image-mode-new-window-functions
1765 'doc-view-new-window-function nil t)
1766 (image-mode-setup-winprops)
1768 (setq-local mode-line-position
1769 '(" P" (:eval (number-to-string (doc-view-current-page)))
1770 "/" (:eval (number-to-string (doc-view-last-page-number)))))
1771 ;; Don't scroll unless the user specifically asked for it.
1772 (setq-local auto-hscroll-mode nil)
1773 (if (boundp 'mwheel-scroll-up-function) ; not --without-x build
1774 (setq-local mwheel-scroll-up-function
1775 #'doc-view-scroll-up-or-next-page))
1776 (if (boundp 'mwheel-scroll-down-function)
1777 (setq-local mwheel-scroll-down-function
1778 #'doc-view-scroll-down-or-previous-page))
1779 (setq-local cursor-type nil)
1780 (use-local-map doc-view-mode-map)
1781 (add-hook 'after-revert-hook 'doc-view-reconvert-doc nil t)
1782 (setq-local bookmark-make-record-function
1783 #'doc-view-bookmark-make-record)
1784 (setq mode-name "DocView"
1785 buffer-read-only t
1786 major-mode 'doc-view-mode)
1787 (doc-view-initiate-display)
1788 ;; Switch off view-mode explicitly, because doc-view-mode is the
1789 ;; canonical view mode for PDF/PS/DVI files. This could be
1790 ;; switched on automatically depending on the value of
1791 ;; `view-read-only'.
1792 (setq-local view-read-only nil)
1793 (run-mode-hooks 'doc-view-mode-hook)))
1795 (defun doc-view-fallback-mode ()
1796 "Fallback to the previous or next best major mode."
1797 (let ((vars (if (derived-mode-p 'doc-view-mode)
1798 (mapcar (lambda (var) (cons var (symbol-value var)))
1799 '(doc-view-resolution
1800 image-mode-winprops-alist)))))
1801 (remove-overlays (point-min) (point-max) 'doc-view t)
1802 (if doc-view--previous-major-mode
1803 (funcall doc-view--previous-major-mode)
1804 (let ((auto-mode-alist
1805 (rassq-delete-all
1806 'doc-view-mode-maybe
1807 (rassq-delete-all 'doc-view-mode
1808 (copy-alist auto-mode-alist)))))
1809 (normal-mode)))
1810 (when vars
1811 (setq-local doc-view-saved-settings vars))))
1813 ;;;###autoload
1814 (defun doc-view-mode-maybe ()
1815 "Switch to `doc-view-mode' if possible.
1816 If the required external tools are not available, then fallback
1817 to the next best mode."
1818 (condition-case nil
1819 (doc-view-set-doc-type)
1820 (error (doc-view-fallback-mode)))
1821 (if (doc-view-mode-p doc-view-doc-type)
1822 (doc-view-mode)
1823 (doc-view-fallback-mode)))
1825 ;;;###autoload
1826 (define-minor-mode doc-view-minor-mode
1827 "Toggle displaying buffer via Doc View (Doc View minor mode).
1828 With a prefix argument ARG, enable Doc View minor mode if ARG is
1829 positive, and disable it otherwise. If called from Lisp, enable
1830 the mode if ARG is omitted or nil.
1832 See the command `doc-view-mode' for more information on this mode."
1833 nil " DocView" doc-view-minor-mode-map
1834 :group 'doc-view
1835 (when doc-view-minor-mode
1836 (add-hook 'change-major-mode-hook (lambda () (doc-view-minor-mode -1)) nil t)
1837 (message
1838 "%s"
1839 (substitute-command-keys
1840 "Type \\[doc-view-toggle-display] to toggle between editing or viewing the document."))))
1842 (defun doc-view-clear-cache ()
1843 "Delete the whole cache (`doc-view-cache-directory')."
1844 (interactive)
1845 (dired-delete-file doc-view-cache-directory 'always))
1847 (defun doc-view-dired-cache ()
1848 "Open `dired' in `doc-view-cache-directory'."
1849 (interactive)
1850 (dired doc-view-cache-directory))
1853 ;;;; Bookmark integration
1855 (declare-function bookmark-make-record-default
1856 "bookmark" (&optional no-file no-context posn))
1857 (declare-function bookmark-prop-get "bookmark" (bookmark prop))
1858 (declare-function bookmark-default-handler "bookmark" (bmk))
1860 (defun doc-view-bookmark-make-record ()
1861 (nconc (bookmark-make-record-default)
1862 `((page . ,(doc-view-current-page))
1863 (handler . doc-view-bookmark-jump))))
1866 ;;;###autoload
1867 (defun doc-view-bookmark-jump (bmk)
1868 ;; This implements the `handler' function interface for record type
1869 ;; returned by `doc-view-bookmark-make-record', which see.
1870 (prog1 (bookmark-default-handler bmk)
1871 (let ((page (bookmark-prop-get bmk 'page)))
1872 (when (not (eq major-mode 'doc-view-mode))
1873 (doc-view-toggle-display))
1874 (with-selected-window
1875 (or (get-buffer-window (current-buffer) 0)
1876 (selected-window))
1877 (doc-view-goto-page page)))))
1880 (provide 'doc-view)
1882 ;; Local Variables:
1883 ;; eval: (outline-minor-mode 1)
1884 ;; End:
1886 ;;; doc-view.el ends here