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