Re-arrange and edit NEWS.
[emacs.git] / lisp / doc-view.el
blob158d447a1d4a7c6be5736c624a31ce284e1e8612
1 ;;; doc-view.el --- View PDF/PostScript/DVI files in Emacs -*- lexical-binding: t -*-
4 ;; Copyright (C) 2007-2012 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-ghostscript-options
162 '("-dSAFER" ;; Avoid security problems when rendering files from untrusted
163 ;; sources.
164 "-dNOPAUSE" "-sDEVICE=png16m" "-dTextAlphaBits=4"
165 "-dBATCH" "-dGraphicsAlphaBits=4" "-dQUIET")
166 "A list of options to give to ghostscript."
167 :type '(repeat string)
168 :group 'doc-view)
170 (defcustom doc-view-resolution 100
171 "Dots per inch resolution used to render the documents.
172 Higher values result in larger images."
173 :type 'number
174 :group 'doc-view)
176 (defcustom doc-view-image-width 850
177 "Default image width.
178 Has only an effect if imagemagick support is compiled into emacs."
179 :version "24.1"
180 :type 'number
181 :group 'doc-view)
183 (defcustom doc-view-dvipdfm-program "dvipdfm"
184 "Program to convert DVI files to PDF.
186 DVI file will be converted to PDF before the resulting PDF is
187 converted to PNG.
189 If this and `doc-view-dvipdf-program' are set,
190 `doc-view-dvipdf-program' will be preferred."
191 :type 'file
192 :group 'doc-view)
194 (defcustom doc-view-dvipdf-program "dvipdf"
195 "Program to convert DVI files to PDF.
197 DVI file will be converted to PDF before the resulting PDF is
198 converted to PNG.
200 If this and `doc-view-dvipdfm-program' are set,
201 `doc-view-dvipdf-program' will be preferred."
202 :type 'file
203 :group 'doc-view)
205 (defcustom doc-view-unoconv-program "unoconv"
206 "Program to convert any file type readable by OpenOffice.org to PDF.
208 Needed for viewing OpenOffice.org (and MS Office) files."
209 :version "24.1"
210 :type 'file
211 :group 'doc-view)
213 (defcustom doc-view-ps2pdf-program "ps2pdf"
214 "Program to convert PS files to PDF.
216 PS files will be converted to PDF before searching is possible."
217 :type 'file
218 :group 'doc-view)
220 (defcustom doc-view-pdftotext-program "pdftotext"
221 "Program to convert PDF files to plain text.
223 Needed for searching."
224 :type 'file
225 :group 'doc-view)
227 (defcustom doc-view-cache-directory
228 (expand-file-name (format "docview%d" (user-uid))
229 temporary-file-directory)
230 "The base directory, where the PNG images will be saved."
231 :type 'directory
232 :group 'doc-view)
234 (defvar doc-view-conversion-buffer " *doc-view conversion output*"
235 "The buffer where messages from the converter programs go to.")
237 (defcustom doc-view-conversion-refresh-interval 1
238 "Interval in seconds between refreshes of the DocView buffer while converting.
239 After such a refresh newly converted pages will be available for
240 viewing. If set to nil there won't be any refreshes and the
241 pages won't be displayed before conversion of the whole document
242 has finished."
243 :type 'integer
244 :group 'doc-view)
246 (defcustom doc-view-continuous nil
247 "In Continuous mode reaching the page edge advances to next/previous page.
248 When non-nil, scrolling a line upward at the bottom edge of the page
249 moves to the next page, and scrolling a line downward at the top edge
250 of the page moves to the previous page."
251 :type 'boolean
252 :group 'doc-view
253 :version "23.2")
255 ;;;; Internal Variables
257 (defun doc-view-new-window-function (winprops)
258 (let ((ol (image-mode-window-get 'overlay winprops)))
259 (when (and ol (not (overlay-buffer ol)))
260 ;; I've seen `ol' be a dead overlay. I do not yet know how this
261 ;; happened, so maybe the bug is elsewhere, but in the mean time,
262 ;; this seems like a safe approach.
263 (setq ol nil))
264 (if ol
265 (progn
266 (cl-assert (eq (overlay-buffer ol) (current-buffer)))
267 (setq ol (copy-overlay ol)))
268 (cl-assert (not (get-char-property (point-min) 'display)))
269 (setq ol (make-overlay (point-min) (point-max) nil t))
270 (overlay-put ol 'doc-view t))
271 (overlay-put ol 'window (car winprops))
272 (image-mode-window-put 'overlay ol winprops)))
274 (defvar doc-view-current-files nil
275 "Only used internally.")
276 (make-variable-buffer-local 'doc-view-current-files)
278 (defvar doc-view-current-converter-processes nil
279 "Only used internally.")
280 (make-variable-buffer-local 'doc-view-current-converter-processes)
282 (defvar doc-view-current-timer nil
283 "Only used internally.")
284 (make-variable-buffer-local 'doc-view-current-timer)
286 (defvar doc-view-current-cache-dir nil
287 "Only used internally.")
288 (make-variable-buffer-local 'doc-view-current-cache-dir)
290 (defvar doc-view-current-search-matches nil
291 "Only used internally.")
292 (make-variable-buffer-local 'doc-view-current-search-matches)
294 (defvar doc-view-pending-cache-flush nil
295 "Only used internally.")
297 (defvar doc-view-previous-major-mode nil
298 "Only used internally.")
300 (defvar doc-view-buffer-file-name nil
301 "Only used internally.
302 The file name used for conversion. Normally it's the same as
303 `buffer-file-name', but for remote files, compressed files and
304 files inside an archive it is a temporary copy of
305 the (uncompressed, extracted) file residing in
306 `doc-view-cache-directory'.")
308 (defvar doc-view-doc-type nil
309 "The type of document in the current buffer.
310 Can be `dvi', `pdf', or `ps'.")
312 ;;;; DocView Keymaps
314 (defvar doc-view-mode-map
315 (let ((map (make-sparse-keymap)))
316 (set-keymap-parent map image-mode-map)
317 ;; Navigation in the document
318 (define-key map (kbd "n") 'doc-view-next-page)
319 (define-key map (kbd "p") 'doc-view-previous-page)
320 (define-key map (kbd "<next>") 'forward-page)
321 (define-key map (kbd "<prior>") 'backward-page)
322 (define-key map [remap forward-page] 'doc-view-next-page)
323 (define-key map [remap backward-page] 'doc-view-previous-page)
324 (define-key map (kbd "SPC") 'doc-view-scroll-up-or-next-page)
325 (define-key map (kbd "DEL") 'doc-view-scroll-down-or-previous-page)
326 (define-key map (kbd "C-n") 'doc-view-next-line-or-next-page)
327 (define-key map (kbd "<down>") 'doc-view-next-line-or-next-page)
328 (define-key map (kbd "C-p") 'doc-view-previous-line-or-previous-page)
329 (define-key map (kbd "<up>") 'doc-view-previous-line-or-previous-page)
330 (define-key map (kbd "M-<") 'doc-view-first-page)
331 (define-key map (kbd "M->") 'doc-view-last-page)
332 (define-key map [remap goto-line] 'doc-view-goto-page)
333 (define-key map (kbd "RET") 'image-next-line)
334 ;; Zoom in/out.
335 (define-key map "+" 'doc-view-enlarge)
336 (define-key map "-" 'doc-view-shrink)
337 ;; Fit the image to the window
338 (define-key map "W" 'doc-view-fit-width-to-window)
339 (define-key map "H" 'doc-view-fit-height-to-window)
340 (define-key map "P" 'doc-view-fit-page-to-window)
341 ;; Killing the buffer (and the process)
342 (define-key map (kbd "k") 'doc-view-kill-proc-and-buffer)
343 (define-key map (kbd "K") 'doc-view-kill-proc)
344 ;; Slicing the image
345 (define-key map (kbd "s s") 'doc-view-set-slice)
346 (define-key map (kbd "s m") 'doc-view-set-slice-using-mouse)
347 (define-key map (kbd "s b") 'doc-view-set-slice-from-bounding-box)
348 (define-key map (kbd "s r") 'doc-view-reset-slice)
349 ;; Searching
350 (define-key map (kbd "C-s") 'doc-view-search)
351 (define-key map (kbd "<find>") 'doc-view-search)
352 (define-key map (kbd "C-r") 'doc-view-search-backward)
353 ;; Show the tooltip
354 (define-key map (kbd "C-t") 'doc-view-show-tooltip)
355 ;; Toggle between text and image display or editing
356 (define-key map (kbd "C-c C-c") 'doc-view-toggle-display)
357 ;; Open a new buffer with doc's text contents
358 (define-key map (kbd "C-c C-t") 'doc-view-open-text)
359 ;; Reconvert the current document. Don't just use revert-buffer
360 ;; because that resets the scale factor, the page number, ...
361 (define-key map (kbd "g") 'doc-view-revert-buffer)
362 (define-key map (kbd "r") 'doc-view-revert-buffer)
363 map)
364 "Keymap used by `doc-view-mode' when displaying a doc as a set of images.")
366 (defun doc-view-revert-buffer (&optional ignore-auto noconfirm)
367 "Like `revert-buffer', but preserves the buffer's current modes."
368 ;; FIXME: this should probably be moved to files.el and used for
369 ;; most/all "g" bindings to revert-buffer.
370 (interactive (list (not current-prefix-arg)))
371 (revert-buffer ignore-auto noconfirm 'preserve-modes))
374 (easy-menu-define doc-view-menu doc-view-mode-map
375 "Menu for Doc View mode."
376 '("DocView"
377 ["Toggle display" doc-view-toggle-display]
378 ("Continuous"
379 ["Off" (setq doc-view-continuous nil)
380 :style radio :selected (eq doc-view-continuous nil)]
381 ["On" (setq doc-view-continuous t)
382 :style radio :selected (eq doc-view-continuous t)]
383 "---"
384 ["Save as Default"
385 (customize-save-variable 'doc-view-continuous doc-view-continuous) t]
387 "---"
388 ["Set Slice" doc-view-set-slice-using-mouse]
389 ["Set Slice (BoundingBox)" doc-view-set-slice-from-bounding-box]
390 ["Set Slice (manual)" doc-view-set-slice]
391 ["Reset Slice" doc-view-reset-slice]
392 "---"
393 ["Search" doc-view-search]
394 ["Search Backwards" doc-view-search-backward]
397 (defvar doc-view-minor-mode-map
398 (let ((map (make-sparse-keymap)))
399 ;; Toggle between text and image display or editing
400 (define-key map (kbd "C-c C-c") 'doc-view-toggle-display)
401 map)
402 "Keymap used by `doc-minor-view-mode'.")
404 ;;;; Navigation Commands
406 (defmacro doc-view-current-page (&optional win)
407 `(image-mode-window-get 'page ,win))
408 (defmacro doc-view-current-info () `(image-mode-window-get 'info))
409 (defmacro doc-view-current-overlay () `(image-mode-window-get 'overlay))
410 (defmacro doc-view-current-image () `(image-mode-window-get 'image))
411 (defmacro doc-view-current-slice () `(image-mode-window-get 'slice))
413 (defun doc-view-last-page-number ()
414 (length doc-view-current-files))
416 (defun doc-view-goto-page (page)
417 "View the page given by PAGE."
418 (interactive "nPage: ")
419 (let ((len (doc-view-last-page-number))
420 (hscroll (window-hscroll)))
421 (if (< page 1)
422 (setq page 1)
423 (when (and (> page len)
424 ;; As long as the converter is running, we don't know
425 ;; how many pages will be available.
426 (null doc-view-current-converter-processes))
427 (setq page len)))
428 (setf (doc-view-current-page) page
429 (doc-view-current-info)
430 (concat
431 (propertize
432 (format "Page %d of %d." page len) 'face 'bold)
433 ;; Tell user if converting isn't finished yet
434 (if doc-view-current-converter-processes
435 " (still converting...)\n"
436 "\n")
437 ;; Display context infos if this page matches the last search
438 (when (and doc-view-current-search-matches
439 (assq page doc-view-current-search-matches))
440 (concat (propertize "Search matches:\n" 'face 'bold)
441 (let ((contexts ""))
442 (dolist (m (cdr (assq page
443 doc-view-current-search-matches)))
444 (setq contexts (concat contexts " - \"" m "\"\n")))
445 contexts)))))
446 ;; Update the buffer
447 ;; We used to find the file name from doc-view-current-files but
448 ;; that's not right if the pages are not generated sequentially
449 ;; or if the page isn't in doc-view-current-files yet.
450 (let ((file (expand-file-name (format "page-%d.png" page)
451 (doc-view-current-cache-dir))))
452 (doc-view-insert-image file :pointer 'arrow)
453 (set-window-hscroll (selected-window) hscroll)
454 (when (and (not (file-exists-p file))
455 doc-view-current-converter-processes)
456 ;; The PNG file hasn't been generated yet.
457 (doc-view-pdf->png-1 doc-view-buffer-file-name file page
458 (let ((win (selected-window)))
459 (lambda ()
460 (and (eq (current-buffer) (window-buffer win))
461 ;; If we changed page in the mean
462 ;; time, don't mess things up.
463 (eq (doc-view-current-page win) page)
464 ;; Make sure we don't infloop.
465 (file-readable-p file)
466 (with-selected-window win
467 (doc-view-goto-page page))))))))
468 (overlay-put (doc-view-current-overlay)
469 'help-echo (doc-view-current-info))))
471 (defun doc-view-next-page (&optional arg)
472 "Browse ARG pages forward."
473 (interactive "p")
474 (doc-view-goto-page (+ (doc-view-current-page) (or arg 1))))
476 (defun doc-view-previous-page (&optional arg)
477 "Browse ARG pages backward."
478 (interactive "p")
479 (doc-view-goto-page (- (doc-view-current-page) (or arg 1))))
481 (defun doc-view-first-page ()
482 "View the first page."
483 (interactive)
484 (doc-view-goto-page 1))
486 (defun doc-view-last-page ()
487 "View the last page."
488 (interactive)
489 (doc-view-goto-page (doc-view-last-page-number)))
491 (defun doc-view-scroll-up-or-next-page (&optional arg)
492 "Scroll page up ARG lines if possible, else goto next page.
493 When `doc-view-continuous' is non-nil, scrolling upward
494 at the bottom edge of the page moves to the next page.
495 Otherwise, goto next page only on typing SPC (ARG is nil)."
496 (interactive "P")
497 (if (or doc-view-continuous (null arg))
498 (let ((hscroll (window-hscroll))
499 (cur-page (doc-view-current-page)))
500 (when (= (window-vscroll) (image-scroll-up arg))
501 (doc-view-next-page)
502 (when (/= cur-page (doc-view-current-page))
503 (image-bob)
504 (image-bol 1))
505 (set-window-hscroll (selected-window) hscroll)))
506 (image-scroll-up arg)))
508 (defun doc-view-scroll-down-or-previous-page (&optional arg)
509 "Scroll page down ARG lines if possible, else goto previous page.
510 When `doc-view-continuous' is non-nil, scrolling downward
511 at the top edge of the page moves to the previous page.
512 Otherwise, goto previous page only on typing DEL (ARG is nil)."
513 (interactive "P")
514 (if (or doc-view-continuous (null arg))
515 (let ((hscroll (window-hscroll))
516 (cur-page (doc-view-current-page)))
517 (when (= (window-vscroll) (image-scroll-down arg))
518 (doc-view-previous-page)
519 (when (/= cur-page (doc-view-current-page))
520 (image-eob)
521 (image-bol 1))
522 (set-window-hscroll (selected-window) hscroll)))
523 (image-scroll-down arg)))
525 (defun doc-view-next-line-or-next-page (&optional arg)
526 "Scroll upward by ARG lines if possible, else goto next page.
527 When `doc-view-continuous' is non-nil, scrolling a line upward
528 at the bottom edge of the page moves to the next page."
529 (interactive "p")
530 (if doc-view-continuous
531 (let ((hscroll (window-hscroll))
532 (cur-page (doc-view-current-page)))
533 (when (= (window-vscroll) (image-next-line arg))
534 (doc-view-next-page)
535 (when (/= cur-page (doc-view-current-page))
536 (image-bob)
537 (image-bol 1))
538 (set-window-hscroll (selected-window) hscroll)))
539 (image-next-line 1)))
541 (defun doc-view-previous-line-or-previous-page (&optional arg)
542 "Scroll downward by ARG lines if possible, else goto previous page.
543 When `doc-view-continuous' is non-nil, scrolling a line downward
544 at the top edge of the page moves to the previous page."
545 (interactive "p")
546 (if doc-view-continuous
547 (let ((hscroll (window-hscroll))
548 (cur-page (doc-view-current-page)))
549 (when (= (window-vscroll) (image-previous-line arg))
550 (doc-view-previous-page)
551 (when (/= cur-page (doc-view-current-page))
552 (image-eob)
553 (image-bol 1))
554 (set-window-hscroll (selected-window) hscroll)))
555 (image-previous-line arg)))
557 ;;;; Utility Functions
559 (defun doc-view-kill-proc ()
560 "Kill the current converter process(es)."
561 (interactive)
562 (while (consp doc-view-current-converter-processes)
563 (ignore-errors ;; Maybe it's dead already?
564 (kill-process (pop doc-view-current-converter-processes))))
565 (when doc-view-current-timer
566 (cancel-timer doc-view-current-timer)
567 (setq doc-view-current-timer nil))
568 (setq mode-line-process nil))
570 (defun doc-view-kill-proc-and-buffer ()
571 "Kill the current converter process and buffer."
572 (interactive)
573 (doc-view-kill-proc)
574 (when (eq major-mode 'doc-view-mode)
575 (kill-buffer (current-buffer))))
577 (defun doc-view-make-safe-dir (dir)
578 (condition-case nil
579 (let ((umask (default-file-modes)))
580 (unwind-protect
581 (progn
582 ;; Create temp files with strict access rights. It's easy to
583 ;; loosen them later, whereas it's impossible to close the
584 ;; time-window of loose permissions otherwise.
585 (set-default-file-modes #o0700)
586 (make-directory dir))
587 ;; Reset the umask.
588 (set-default-file-modes umask)))
589 (file-already-exists
590 (when (file-symlink-p dir)
591 (error "Danger: %s points to a symbolic link" dir))
592 ;; In case it was created earlier with looser rights.
593 ;; We could check the mode info returned by file-attributes, but it's
594 ;; a pain to parse and it may not tell you what we want under
595 ;; non-standard file-systems. So let's just say what we want and let
596 ;; the underlying C code and file-system figure it out.
597 ;; This also ends up checking a bunch of useful conditions: it makes
598 ;; sure we have write-access to the directory and that we own it, thus
599 ;; closing a bunch of security holes.
600 (condition-case error
601 (set-file-modes dir #o0700)
602 (file-error
603 (error
604 (format "Unable to use temporary directory %s: %s"
605 dir (mapconcat 'identity (cdr error) " "))))))))
607 (defun doc-view-current-cache-dir ()
608 "Return the directory where the png files of the current doc should be saved.
609 It's a subdirectory of `doc-view-cache-directory'."
610 (if doc-view-current-cache-dir
611 doc-view-current-cache-dir
612 ;; Try and make sure doc-view-cache-directory exists and is safe.
613 (doc-view-make-safe-dir doc-view-cache-directory)
614 ;; Now compute the subdirectory to use.
615 (setq doc-view-current-cache-dir
616 (file-name-as-directory
617 (expand-file-name
618 (concat (file-name-nondirectory doc-view-buffer-file-name)
620 (let ((file doc-view-buffer-file-name))
621 (with-temp-buffer
622 (set-buffer-multibyte nil)
623 (insert-file-contents-literally file)
624 (md5 (current-buffer)))))
625 doc-view-cache-directory)))))
627 (defun doc-view-remove-if (predicate list)
628 "Return LIST with all items removed that satisfy PREDICATE."
629 (let (new-list)
630 (dolist (item list)
631 (when (not (funcall predicate item))
632 (setq new-list (cons item new-list))))
633 (nreverse new-list)))
635 ;;;###autoload
636 (defun doc-view-mode-p (type)
637 "Return non-nil if document type TYPE is available for `doc-view'.
638 Document types are symbols like `dvi', `ps', `pdf', or `odf' (any
639 OpenDocument format)."
640 (and (display-graphic-p)
641 (or (image-type-available-p 'imagemagick)
642 (image-type-available-p 'png))
643 (cond
644 ((eq type 'dvi)
645 (and (doc-view-mode-p 'pdf)
646 (or (and doc-view-dvipdf-program
647 (executable-find doc-view-dvipdf-program))
648 (and doc-view-dvipdfm-program
649 (executable-find doc-view-dvipdfm-program)))))
650 ((or (eq type 'postscript) (eq type 'ps) (eq type 'eps)
651 (eq type 'pdf))
652 (and doc-view-ghostscript-program
653 (executable-find doc-view-ghostscript-program)))
654 ((eq type 'odf)
655 (and doc-view-unoconv-program
656 (executable-find doc-view-unoconv-program)
657 (doc-view-mode-p 'pdf)))
658 (t ;; unknown image type
659 nil))))
661 ;;;; Conversion Functions
663 (defvar doc-view-shrink-factor 1.125)
665 (defun doc-view-enlarge (factor)
666 "Enlarge the document."
667 (interactive (list doc-view-shrink-factor))
668 (if (eq (plist-get (cdr (doc-view-current-image)) :type)
669 'imagemagick)
670 ;; ImageMagick supports on-the-fly-rescaling
671 (progn
672 (set (make-local-variable 'doc-view-image-width)
673 (ceiling (* factor doc-view-image-width)))
674 (doc-view-insert-image (plist-get (cdr (doc-view-current-image)) :file)
675 :width doc-view-image-width))
676 (set (make-local-variable 'doc-view-resolution)
677 (ceiling (* factor doc-view-resolution)))
678 (doc-view-reconvert-doc)))
680 (defun doc-view-shrink (factor)
681 "Shrink the document."
682 (interactive (list doc-view-shrink-factor))
683 (doc-view-enlarge (/ 1.0 factor)))
685 (defun doc-view-fit-width-to-window ()
686 "Fit the image width to the window width."
687 (interactive)
688 (let ((win-width (- (nth 2 (window-inside-pixel-edges))
689 (nth 0 (window-inside-pixel-edges))))
690 (slice (doc-view-current-slice)))
691 (if (not slice)
692 (let ((img-width (car (image-display-size
693 (image-get-display-property) t))))
694 (doc-view-enlarge (/ (float win-width) (float img-width))))
696 ;; If slice is set
697 (let* ((slice-width (nth 2 slice))
698 (scale-factor (/ (float win-width) (float slice-width)))
699 (new-slice (mapcar (lambda (x) (ceiling (* scale-factor x))) slice)))
701 (doc-view-enlarge scale-factor)
702 (setf (doc-view-current-slice) new-slice)
703 (doc-view-goto-page (doc-view-current-page))))))
705 (defun doc-view-fit-height-to-window ()
706 "Fit the image height to the window height."
707 (interactive)
708 (let ((win-height (- (nth 3 (window-inside-pixel-edges))
709 (nth 1 (window-inside-pixel-edges))))
710 (slice (doc-view-current-slice)))
711 (if (not slice)
712 (let ((img-height (cdr (image-display-size
713 (image-get-display-property) t))))
714 ;; When users call 'doc-view-fit-height-to-window',
715 ;; they might want to go to next page by typing SPC
716 ;; ONLY once. So I used '(- win-height 1)' instead of
717 ;; 'win-height'
718 (doc-view-enlarge (/ (float (- win-height 1)) (float img-height))))
720 ;; If slice is set
721 (let* ((slice-height (nth 3 slice))
722 (scale-factor (/ (float (- win-height 1)) (float slice-height)))
723 (new-slice (mapcar (lambda (x) (ceiling (* scale-factor x))) slice)))
725 (doc-view-enlarge scale-factor)
726 (setf (doc-view-current-slice) new-slice)
727 (doc-view-goto-page (doc-view-current-page))))))
729 (defun doc-view-fit-page-to-window ()
730 "Fit the image to the window.
731 More specifically, this function enlarges image by:
733 min {(window-width / image-width), (window-height / image-height)} times."
734 (interactive)
735 (let ((win-width (- (nth 2 (window-inside-pixel-edges))
736 (nth 0 (window-inside-pixel-edges))))
737 (win-height (- (nth 3 (window-inside-pixel-edges))
738 (nth 1 (window-inside-pixel-edges))))
739 (slice (doc-view-current-slice)))
740 (if (not slice)
741 (let ((img-width (car (image-display-size
742 (image-get-display-property) t)))
743 (img-height (cdr (image-display-size
744 (image-get-display-property) t))))
745 (doc-view-enlarge (min (/ (float win-width) (float img-width))
746 (/ (float (- win-height 1)) (float img-height)))))
747 ;; If slice is set
748 (let* ((slice-width (nth 2 slice))
749 (slice-height (nth 3 slice))
750 (scale-factor (min (/ (float win-width) (float slice-width))
751 (/ (float (- win-height 1)) (float slice-height))))
752 (new-slice (mapcar (lambda (x) (ceiling (* scale-factor x))) slice)))
753 (doc-view-enlarge scale-factor)
754 (setf (doc-view-current-slice) new-slice)
755 (doc-view-goto-page (doc-view-current-page))))))
757 (defun doc-view-reconvert-doc ()
758 "Reconvert the current document.
759 Should be invoked when the cached images aren't up-to-date."
760 (interactive)
761 (doc-view-kill-proc)
762 ;; Clear the old cached files
763 (when (file-exists-p (doc-view-current-cache-dir))
764 (delete-directory (doc-view-current-cache-dir) 'recursive))
765 (doc-view-initiate-display))
767 (defun doc-view-sentinel (proc event)
768 "Generic sentinel for doc-view conversion processes."
769 (if (not (string-match "finished" event))
770 (message "DocView: process %s changed status to %s."
771 (process-name proc)
772 (if (string-match "\\(.+\\)\n?\\'" event)
773 (match-string 1 event)
774 event))
775 (when (buffer-live-p (process-get proc 'buffer))
776 (with-current-buffer (process-get proc 'buffer)
777 (setq doc-view-current-converter-processes
778 (delq proc doc-view-current-converter-processes))
779 (setq mode-line-process
780 (if doc-view-current-converter-processes
781 (format ":%s" (car doc-view-current-converter-processes))))
782 (funcall (process-get proc 'callback))))))
784 (defun doc-view-start-process (name program args callback)
785 ;; Make sure the process is started in an existing directory, (rather than
786 ;; some file-name-handler-managed dir, for example).
787 (let* ((default-directory (if (file-readable-p default-directory)
788 default-directory
789 (expand-file-name "~/")))
790 (proc (apply 'start-process name doc-view-conversion-buffer
791 program args)))
792 (push proc doc-view-current-converter-processes)
793 (setq mode-line-process (list (format ":%s" proc)))
794 (set-process-sentinel proc 'doc-view-sentinel)
795 (process-put proc 'buffer (current-buffer))
796 (process-put proc 'callback callback)))
798 (defun doc-view-dvi->pdf (dvi pdf callback)
799 "Convert DVI to PDF asynchronously and call CALLBACK when finished."
800 ;; Prefer dvipdf over dvipdfm, because the latter has problems if the DVI
801 ;; references and includes other PS files.
802 (if (and doc-view-dvipdf-program
803 (executable-find doc-view-dvipdf-program))
804 (doc-view-start-process "dvi->pdf" doc-view-dvipdf-program
805 (list dvi pdf)
806 callback)
807 (doc-view-start-process "dvi->pdf" doc-view-dvipdfm-program
808 (list "-o" pdf dvi)
809 callback)))
811 (defun doc-view-odf->pdf (odf callback)
812 "Convert ODF to PDF asynchronously and call CALLBACK when finished.
813 The converted PDF is put into the current cache directory, and it
814 is named like ODF with the extension turned to pdf."
815 (doc-view-start-process "odf->pdf" doc-view-unoconv-program
816 (list "-f" "pdf" "-o" (doc-view-current-cache-dir) odf)
817 callback))
819 (defun doc-view-pdf/ps->png (pdf-ps png)
820 "Convert PDF-PS to PNG asynchronously."
821 (doc-view-start-process
822 "pdf/ps->png" doc-view-ghostscript-program
823 (append doc-view-ghostscript-options
824 (list (format "-r%d" (round doc-view-resolution))
825 (concat "-sOutputFile=" png)
826 pdf-ps))
827 (let ((resolution doc-view-resolution))
828 (lambda ()
829 ;; Only create the resolution file when it's all done, so it also
830 ;; serves as a witness that the conversion is complete.
831 (write-region (prin1-to-string resolution) nil
832 (expand-file-name "resolution.el"
833 (doc-view-current-cache-dir))
834 nil 'silently)
835 (when doc-view-current-timer
836 (cancel-timer doc-view-current-timer)
837 (setq doc-view-current-timer nil))
838 (doc-view-display (current-buffer) 'force))))
839 ;; Update the displayed pages as soon as they're done generating.
840 (when doc-view-conversion-refresh-interval
841 (setq doc-view-current-timer
842 (run-at-time "1 secs" doc-view-conversion-refresh-interval
843 'doc-view-display
844 (current-buffer)))))
846 (defun doc-view-pdf->png-1 (pdf png page callback)
847 "Convert a PAGE of a PDF file to PNG asynchronously.
848 Call CALLBACK with no arguments when done."
849 (doc-view-start-process
850 "pdf->png-1" doc-view-ghostscript-program
851 (append doc-view-ghostscript-options
852 (list (format "-r%d" (round doc-view-resolution))
853 ;; Sadly, `gs' only supports the page-range
854 ;; for PDF files.
855 (format "-dFirstPage=%d" page)
856 (format "-dLastPage=%d" page)
857 (concat "-sOutputFile=" png)
858 pdf))
859 callback))
861 (declare-function clear-image-cache "image.c" (&optional filter))
863 (defun doc-view-pdf->png (pdf png pages)
864 "Convert a PDF file to PNG asynchronously.
865 Start by converting PAGES, and then the rest."
866 (if (null pages)
867 (doc-view-pdf/ps->png pdf png)
868 ;; We could render several `pages' with a single process if they're
869 ;; (almost) consecutive, but since in 99% of the cases, there'll be only
870 ;; a single page anyway, and of the remaining 1%, few cases will have
871 ;; consecutive pages, it's not worth the trouble.
872 (let ((rest (cdr pages)))
873 (doc-view-pdf->png-1
874 pdf (format png (car pages)) (car pages)
875 (lambda ()
876 (if rest
877 (doc-view-pdf->png pdf png rest)
878 ;; Yippie, the important pages are done, update the display.
879 (clear-image-cache)
880 ;; For the windows that have a message (like "Welcome to
881 ;; DocView") display property, clearing the image cache is
882 ;; not sufficient.
883 (dolist (win (get-buffer-window-list (current-buffer) nil 'visible))
884 (with-selected-window win
885 (when (stringp (get-char-property (point-min) 'display))
886 (doc-view-goto-page (doc-view-current-page)))))
887 ;; Convert the rest of the pages.
888 (doc-view-pdf/ps->png pdf png)))))))
890 (defun doc-view-pdf->txt (pdf txt callback)
891 "Convert PDF to TXT asynchronously and call CALLBACK when finished."
892 (or (executable-find doc-view-pdftotext-program)
893 (error "You need the `pdftotext' program to convert a PDF to text"))
894 (doc-view-start-process "pdf->txt" doc-view-pdftotext-program
895 (list "-raw" pdf txt)
896 callback))
898 (defun doc-view-doc->txt (txt callback)
899 "Convert the current document to text and call CALLBACK when done."
900 (make-directory (doc-view-current-cache-dir) t)
901 (pcase doc-view-doc-type
902 (`pdf
903 ;; Doc is a PDF, so convert it to TXT
904 (doc-view-pdf->txt doc-view-buffer-file-name txt callback))
905 (`ps
906 ;; Doc is a PS, so convert it to PDF (which will be converted to
907 ;; TXT thereafter).
908 (let ((pdf (expand-file-name "doc.pdf"
909 (doc-view-current-cache-dir))))
910 (doc-view-ps->pdf doc-view-buffer-file-name pdf
911 (lambda () (doc-view-pdf->txt pdf txt callback)))))
912 (`dvi
913 ;; Doc is a DVI. This means that a doc.pdf already exists in its
914 ;; cache subdirectory.
915 (doc-view-pdf->txt (expand-file-name "doc.pdf"
916 (doc-view-current-cache-dir))
917 txt callback))
918 (`odf
919 ;; Doc is some ODF (or MS Office) doc. This means that a doc.pdf
920 ;; already exists in its cache subdirectory.
921 (doc-view-pdf->txt (expand-file-name "doc.pdf"
922 (doc-view-current-cache-dir))
923 txt callback))
924 (_ (error "DocView doesn't know what to do"))))
926 (defun doc-view-ps->pdf (ps pdf callback)
927 "Convert PS to PDF asynchronously and call CALLBACK when finished."
928 (or (executable-find doc-view-ps2pdf-program)
929 (error "You need the `ps2pdf' program to convert PS to PDF"))
930 (doc-view-start-process "ps->pdf" doc-view-ps2pdf-program
931 (list
932 ;; Avoid security problems when rendering files from
933 ;; untrusted sources.
934 "-dSAFER"
935 ;; in-file and out-file
936 ps pdf)
937 callback))
939 (defun doc-view-active-pages ()
940 (let ((pages ()))
941 (dolist (win (get-buffer-window-list (current-buffer) nil 'visible))
942 (let ((page (image-mode-window-get 'page win)))
943 (unless (memq page pages) (push page pages))))
944 pages))
946 (defun doc-view-convert-current-doc ()
947 "Convert `doc-view-buffer-file-name' to a set of png files, one file per page.
948 Those files are saved in the directory given by the function
949 `doc-view-current-cache-dir'."
950 ;; Let stale files still display while we recompute the new ones, so only
951 ;; flush the cache when the conversion is over. One of the reasons why it
952 ;; is important to keep displaying the stale page is so that revert-buffer
953 ;; preserves the horizontal/vertical scroll settings (which are otherwise
954 ;; resets during the redisplay).
955 (setq doc-view-pending-cache-flush t)
956 (let ((png-file (expand-file-name "page-%d.png"
957 (doc-view-current-cache-dir))))
958 (make-directory (doc-view-current-cache-dir) t)
959 (pcase doc-view-doc-type
960 (`dvi
961 ;; DVI files have to be converted to PDF before Ghostscript can process
962 ;; it.
963 (let ((pdf (expand-file-name "doc.pdf" doc-view-current-cache-dir)))
964 (doc-view-dvi->pdf doc-view-buffer-file-name pdf
965 (lambda () (doc-view-pdf/ps->png pdf png-file)))))
966 (`odf
967 ;; ODF files have to be converted to PDF before Ghostscript can
968 ;; process it.
969 (let ((pdf (expand-file-name "doc.pdf" doc-view-current-cache-dir))
970 (opdf (expand-file-name (concat (file-name-base doc-view-buffer-file-name)
971 ".pdf")
972 doc-view-current-cache-dir))
973 (png-file png-file))
974 ;; The unoconv tool only supports a output directory, but no
975 ;; file name. It's named like the input file with the
976 ;; extension replaced by pdf.
977 (doc-view-odf->pdf doc-view-buffer-file-name
978 (lambda ()
979 ;; Rename to doc.pdf
980 (rename-file opdf pdf)
981 (doc-view-pdf/ps->png pdf png-file)))))
982 (`pdf
983 (let ((pages (doc-view-active-pages)))
984 ;; Convert PDF to PNG images starting with the active pages.
985 (doc-view-pdf->png doc-view-buffer-file-name png-file pages)))
987 ;; Convert to PNG images.
988 (doc-view-pdf/ps->png doc-view-buffer-file-name png-file)))))
990 ;;;; Slicing
992 (declare-function image-size "image.c" (spec &optional pixels frame))
994 (defun doc-view-set-slice (x y width height)
995 "Set the slice of the images that should be displayed.
996 You can use this function to tell doc-view not to display the
997 margins of the document. It prompts for the top-left corner (X
998 and Y) of the slice to display and its WIDTH and HEIGHT.
1000 See `doc-view-set-slice-using-mouse' and
1001 `doc-view-set-slice-from-bounding-box' for more convenient ways
1002 to do that. To reset the slice use `doc-view-reset-slice'."
1003 (interactive
1004 (let* ((size (image-size (doc-view-current-image) t))
1005 (a (read-number (format "Top-left X (0..%d): " (car size))))
1006 (b (read-number (format "Top-left Y (0..%d): " (cdr size))))
1007 (c (read-number (format "Width (0..%d): " (- (car size) a))))
1008 (d (read-number (format "Height (0..%d): " (- (cdr size) b)))))
1009 (list a b c d)))
1010 (setf (doc-view-current-slice) (list x y width height))
1011 ;; Redisplay
1012 (doc-view-goto-page (doc-view-current-page)))
1014 (defun doc-view-set-slice-using-mouse ()
1015 "Set the slice of the images that should be displayed.
1016 You set the slice by pressing mouse-1 at its top-left corner and
1017 dragging it to its bottom-right corner. See also
1018 `doc-view-set-slice' and `doc-view-reset-slice'."
1019 (interactive)
1020 (let (x y w h done)
1021 (while (not done)
1022 (let ((e (read-event
1023 (concat "Press mouse-1 at the top-left corner and "
1024 "drag it to the bottom-right corner!"))))
1025 (when (eq (car e) 'drag-mouse-1)
1026 (setq x (car (posn-object-x-y (event-start e))))
1027 (setq y (cdr (posn-object-x-y (event-start e))))
1028 (setq w (- (car (posn-object-x-y (event-end e))) x))
1029 (setq h (- (cdr (posn-object-x-y (event-end e))) y))
1030 (setq done t))))
1031 (doc-view-set-slice x y w h)))
1033 (defun doc-view-get-bounding-box ()
1034 "Get the BoundingBox information of the current page."
1035 (let* ((page (doc-view-current-page))
1036 (o (shell-command-to-string
1037 (concat doc-view-ghostscript-program
1038 " -dSAFER -dBATCH -dNOPAUSE -q -sDEVICE=bbox "
1039 (format "-dFirstPage=%s -dLastPage=%s %s"
1040 page page
1041 doc-view-buffer-file-name)))))
1042 (save-match-data
1043 (when (string-match (concat "%%BoundingBox: "
1044 "\\([[:digit:]]+\\) \\([[:digit:]]+\\) "
1045 "\\([[:digit:]]+\\) \\([[:digit:]]+\\)") o)
1046 (mapcar #'string-to-number
1047 (list (match-string 1 o)
1048 (match-string 2 o)
1049 (match-string 3 o)
1050 (match-string 4 o)))))))
1052 (defvar doc-view-paper-sizes
1053 '((a4 595 842)
1054 (a4-landscape 842 595)
1055 (letter 612 792)
1056 (letter-landscape 792 612)
1057 (legal 612 1008)
1058 (legal-landscape 1008 612)
1059 (a3 842 1191)
1060 (a3-landscape 1191 842)
1061 (tabloid 792 1224)
1062 (ledger 1224 792))
1063 "An alist from paper size names to dimensions.")
1065 (defun doc-view-guess-paper-size (iw ih)
1066 "Guess the paper size according to the aspect ratio."
1067 (cl-labels ((div (x y)
1068 (round (/ (* 100.0 x) y))))
1069 (let ((ar (div iw ih))
1070 (al (mapcar (lambda (l)
1071 (list (div (nth 1 l) (nth 2 l)) (car l)))
1072 doc-view-paper-sizes)))
1073 (cadr (assoc ar al)))))
1075 (defun doc-view-scale-bounding-box (ps iw ih bb)
1076 (list (/ (* (nth 0 bb) iw) (nth 1 (assoc ps doc-view-paper-sizes)))
1077 (/ (* (nth 1 bb) ih) (nth 2 (assoc ps doc-view-paper-sizes)))
1078 (/ (* (nth 2 bb) iw) (nth 1 (assoc ps doc-view-paper-sizes)))
1079 (/ (* (nth 3 bb) ih) (nth 2 (assoc ps doc-view-paper-sizes)))))
1081 (defun doc-view-set-slice-from-bounding-box (&optional force-paper-size)
1082 "Set the slice from the document's BoundingBox information.
1083 The result is that the margins are almost completely cropped,
1084 much more accurate than could be done manually using
1085 `doc-view-set-slice-using-mouse'."
1086 (interactive "P")
1087 (let ((bb (doc-view-get-bounding-box)))
1088 (if (not bb)
1089 (message "BoundingBox couldn't be determined")
1090 (let* ((is (image-size (doc-view-current-image) t))
1091 (iw (car is))
1092 (ih (cdr is))
1093 (ps (or (and (null force-paper-size) (doc-view-guess-paper-size iw ih))
1094 (intern (completing-read "Paper size: "
1095 (mapcar #'car doc-view-paper-sizes)
1096 nil t))))
1097 (bb (doc-view-scale-bounding-box ps iw ih bb))
1098 (x1 (nth 0 bb))
1099 (y1 (nth 1 bb))
1100 (x2 (nth 2 bb))
1101 (y2 (nth 3 bb)))
1102 ;; We keep a 2 pixel margin.
1103 (doc-view-set-slice (- x1 2) (- ih y2 2)
1104 (+ (- x2 x1) 4) (+ (- y2 y1) 4))))))
1106 (defun doc-view-reset-slice ()
1107 "Reset the current slice.
1108 After calling this function whole pages will be visible again."
1109 (interactive)
1110 (setf (doc-view-current-slice) nil)
1111 ;; Redisplay
1112 (doc-view-goto-page (doc-view-current-page)))
1114 ;;;; Display
1116 (defun doc-view-insert-image (file &rest args)
1117 "Insert the given png FILE.
1118 ARGS is a list of image descriptors."
1119 (when doc-view-pending-cache-flush
1120 (clear-image-cache)
1121 (setq doc-view-pending-cache-flush nil))
1122 (let ((ol (doc-view-current-overlay))
1123 (image (if (and file (file-readable-p file))
1124 (if (not (fboundp 'imagemagick-types))
1125 (apply 'create-image file 'png nil args)
1126 (unless (member :width args)
1127 (setq args (append args (list :width doc-view-image-width))))
1128 (apply 'create-image file 'imagemagick nil args))))
1129 (slice (doc-view-current-slice)))
1130 (setf (doc-view-current-image) image)
1131 (move-overlay ol (point-min) (point-max))
1132 (overlay-put ol 'display
1133 (cond
1134 (image
1135 (if slice
1136 (list (cons 'slice slice) image)
1137 image))
1138 ;; We're trying to display a page that doesn't exist.
1139 (doc-view-current-converter-processes
1140 ;; Maybe the page doesn't exist *yet*.
1141 "Cannot display this page (yet)!")
1143 ;; Typically happens if the conversion process somehow
1144 ;; failed. Better not signal an error here because it
1145 ;; could prevent a subsequent reconversion from fixing
1146 ;; the problem.
1147 (concat "Cannot display this page!\n"
1148 "Maybe because of a conversion failure!"))))
1149 (let ((win (overlay-get ol 'window)))
1150 (if (stringp (overlay-get ol 'display))
1151 (progn ;Make sure the text is not scrolled out of view.
1152 (set-window-hscroll win 0)
1153 (set-window-vscroll win 0))
1154 (let ((hscroll (image-mode-window-get 'hscroll win))
1155 (vscroll (image-mode-window-get 'vscroll win)))
1156 ;; Reset scroll settings, in case they were changed.
1157 (if hscroll (set-window-hscroll win hscroll))
1158 (if vscroll (set-window-vscroll win vscroll)))))))
1160 (defun doc-view-sort (a b)
1161 "Return non-nil if A should be sorted before B.
1162 Predicate for sorting `doc-view-current-files'."
1163 (or (< (length a) (length b))
1164 (and (= (length a) (length b))
1165 (string< a b))))
1167 (defun doc-view-display (buffer &optional force)
1168 "Start viewing the document in BUFFER.
1169 If FORCE is non-nil, start viewing even if the document does not
1170 have the page we want to view."
1171 (with-current-buffer buffer
1172 (let ((prev-pages doc-view-current-files)
1173 (windows (get-buffer-window-list buffer nil t)))
1174 (setq doc-view-current-files
1175 (sort (directory-files (doc-view-current-cache-dir) t
1176 "page-[0-9]+\\.png" t)
1177 'doc-view-sort))
1178 (unless windows
1179 (switch-to-buffer buffer)
1180 (setq windows (get-buffer-window-list buffer nil t)))
1181 (dolist (win windows)
1182 (let* ((page (doc-view-current-page win))
1183 (pagefile (expand-file-name (format "page-%d.png" page)
1184 (doc-view-current-cache-dir))))
1185 (when (or force
1186 (and (not (member pagefile prev-pages))
1187 (member pagefile doc-view-current-files)))
1188 (with-selected-window win
1189 (cl-assert (eq (current-buffer) buffer) t)
1190 (doc-view-goto-page page))))))))
1192 (defun doc-view-buffer-message ()
1193 ;; Only show this message initially, not when refreshing the buffer (in which
1194 ;; case it's better to keep displaying the "stale" page while computing
1195 ;; the fresh new ones).
1196 (unless (overlay-get (doc-view-current-overlay) 'display)
1197 (overlay-put (doc-view-current-overlay) 'display
1198 (concat (propertize "Welcome to DocView!" 'face 'bold)
1199 "\n"
1201 If you see this buffer it means that the document you want to view is being
1202 converted to PNG and the conversion of the first page hasn't finished yet or
1203 `doc-view-conversion-refresh-interval' is set to nil.
1205 For now these keys are useful:
1207 `q' : Bury this buffer. Conversion will go on in background.
1208 `k' : Kill the conversion process and this buffer.
1209 `K' : Kill the conversion process.\n"))))
1211 (declare-function tooltip-show "tooltip" (text &optional use-echo-area))
1213 (defun doc-view-show-tooltip ()
1214 (interactive)
1215 (tooltip-show (doc-view-current-info)))
1217 (defun doc-view-open-text ()
1218 "Open a buffer with the current doc's contents as text."
1219 (interactive)
1220 (if doc-view-current-converter-processes
1221 (message "DocView: please wait till conversion finished.")
1222 (let ((txt (expand-file-name "doc.txt" (doc-view-current-cache-dir))))
1223 (if (file-readable-p txt)
1224 (let ((name (concat "Text contents of "
1225 (file-name-nondirectory buffer-file-name)))
1226 (dir (file-name-directory buffer-file-name)))
1227 (with-current-buffer (find-file txt)
1228 (rename-buffer name)
1229 (setq default-directory dir)))
1230 (doc-view-doc->txt txt 'doc-view-open-text)))))
1232 ;;;;; Toggle between editing and viewing
1234 (defun doc-view-toggle-display ()
1235 "Toggle between editing a document as text or viewing it."
1236 (interactive)
1237 (if (eq major-mode 'doc-view-mode)
1238 ;; Switch to editing mode
1239 (progn
1240 (doc-view-kill-proc)
1241 (setq buffer-read-only nil)
1242 (remove-overlays (point-min) (point-max) 'doc-view t)
1243 (set (make-local-variable 'image-mode-winprops-alist) t)
1244 ;; Switch to the previously used major mode or fall back to
1245 ;; normal mode.
1246 (doc-view-fallback-mode)
1247 (doc-view-minor-mode 1))
1248 ;; Switch to doc-view-mode
1249 (when (and (buffer-modified-p)
1250 (y-or-n-p "The buffer has been modified. Save the changes? "))
1251 (save-buffer))
1252 (doc-view-mode)))
1254 ;;;; Searching
1257 (defun doc-view-search-internal (regexp file)
1258 "Return a list of FILE's pages that contain text matching REGEXP.
1259 The value is an alist of the form (PAGE CONTEXTS) where PAGE is
1260 the pagenumber and CONTEXTS are all lines of text containing a match."
1261 (with-temp-buffer
1262 (insert-file-contents file)
1263 (let ((page 1)
1264 (lastpage 1)
1265 matches)
1266 (while (re-search-forward (concat "\\(?:\\([\f]\\)\\|\\("
1267 regexp "\\)\\)") nil t)
1268 (when (match-string 1) (setq page (1+ page)))
1269 (when (match-string 2)
1270 (if (/= page lastpage)
1271 (push (cons page
1272 (list (buffer-substring
1273 (line-beginning-position)
1274 (line-end-position))))
1275 matches)
1276 (setq matches (cons
1277 (append
1279 ;; This page already is a match.
1280 (car matches)
1281 ;; This is the first match on page.
1282 (list page))
1283 (list (buffer-substring
1284 (line-beginning-position)
1285 (line-end-position))))
1286 (cdr matches))))
1287 (setq lastpage page)))
1288 (nreverse matches))))
1290 (defun doc-view-search-no-of-matches (list)
1291 "Extract the number of matches from the search result LIST."
1292 (let ((no 0))
1293 (dolist (p list)
1294 (setq no (+ no (1- (length p)))))
1295 no))
1297 (defun doc-view-search-backward (new-query)
1298 "Call `doc-view-search' for backward search.
1299 If prefix NEW-QUERY is given, ask for a new regexp."
1300 (interactive "P")
1301 (doc-view-search new-query t))
1303 (defun doc-view-search (new-query &optional backward)
1304 "Jump to the next match or initiate a new search if NEW-QUERY is given.
1305 If the current document hasn't been transformed to plain text
1306 till now do that first.
1307 If BACKWARD is non-nil, jump to the previous match."
1308 (interactive "P")
1309 (if (and (not new-query)
1310 doc-view-current-search-matches)
1311 (if backward
1312 (doc-view-search-previous-match 1)
1313 (doc-view-search-next-match 1))
1314 ;; New search, so forget the old results.
1315 (setq doc-view-current-search-matches nil)
1316 (let ((txt (expand-file-name "doc.txt"
1317 (doc-view-current-cache-dir))))
1318 (if (file-readable-p txt)
1319 (progn
1320 (setq doc-view-current-search-matches
1321 (doc-view-search-internal
1322 (read-from-minibuffer "Regexp: ")
1323 txt))
1324 (message "DocView: search yielded %d matches."
1325 (doc-view-search-no-of-matches
1326 doc-view-current-search-matches)))
1327 ;; We must convert to TXT first!
1328 (if doc-view-current-converter-processes
1329 (message "DocView: please wait till conversion finished.")
1330 (doc-view-doc->txt txt (lambda () (doc-view-search nil))))))))
1332 (defun doc-view-search-next-match (arg)
1333 "Go to the ARGth next matching page."
1334 (interactive "p")
1335 (let* ((next-pages (doc-view-remove-if
1336 (lambda (i) (<= (car i) (doc-view-current-page)))
1337 doc-view-current-search-matches))
1338 (page (car (nth (1- arg) next-pages))))
1339 (if page
1340 (doc-view-goto-page page)
1341 (when (and
1342 doc-view-current-search-matches
1343 (y-or-n-p "No more matches after current page. Wrap to first match? "))
1344 (doc-view-goto-page (caar doc-view-current-search-matches))))))
1346 (defun doc-view-search-previous-match (arg)
1347 "Go to the ARGth previous matching page."
1348 (interactive "p")
1349 (let* ((prev-pages (doc-view-remove-if
1350 (lambda (i) (>= (car i) (doc-view-current-page)))
1351 doc-view-current-search-matches))
1352 (page (car (nth (1- arg) (nreverse prev-pages)))))
1353 (if page
1354 (doc-view-goto-page page)
1355 (when (and
1356 doc-view-current-search-matches
1357 (y-or-n-p "No more matches before current page. Wrap to last match? "))
1358 (doc-view-goto-page (caar (last doc-view-current-search-matches)))))))
1360 ;;;; User interface commands and the mode
1362 (put 'doc-view-mode 'mode-class 'special)
1364 (defun doc-view-already-converted-p ()
1365 "Return non-nil if the current doc was already converted."
1366 (and (file-exists-p (doc-view-current-cache-dir))
1367 ;; Check that the resolution info is there, otherwise it means
1368 ;; the conversion is incomplete.
1369 (file-readable-p (expand-file-name "resolution.el"
1370 (doc-view-current-cache-dir)))
1371 (> (length (directory-files (doc-view-current-cache-dir)
1372 nil "\\.png\\'"))
1373 0)))
1375 (defun doc-view-initiate-display ()
1376 ;; Switch to image display if possible
1377 (if (doc-view-mode-p doc-view-doc-type)
1378 (progn
1379 (doc-view-buffer-message)
1380 (setf (doc-view-current-page) (or (doc-view-current-page) 1))
1381 (if (doc-view-already-converted-p)
1382 (progn
1383 (message "DocView: using cached files!")
1384 ;; Load the saved resolution
1385 (let* ((res-file (expand-file-name "resolution.el"
1386 (doc-view-current-cache-dir)))
1387 (res
1388 (with-temp-buffer
1389 (when (file-readable-p res-file)
1390 (insert-file-contents res-file)
1391 (read (current-buffer))))))
1392 (when (numberp res)
1393 (set (make-local-variable 'doc-view-resolution) res)))
1394 (doc-view-display (current-buffer) 'force))
1395 (doc-view-convert-current-doc))
1396 (message
1397 "%s"
1398 (substitute-command-keys
1399 (concat "Type \\[doc-view-toggle-display] to toggle between "
1400 "editing or viewing the document."))))
1401 (message
1402 "%s"
1403 (concat "No PNG support is available, or some conversion utility for "
1404 (file-name-extension doc-view-buffer-file-name)
1405 " files is missing."))
1406 (when (and (executable-find doc-view-pdftotext-program)
1407 (y-or-n-p
1408 "Unable to render file. View extracted text instead? "))
1409 (doc-view-open-text))
1410 (doc-view-toggle-display)))
1412 (defvar bookmark-make-record-function)
1414 (defun doc-view-clone-buffer-hook ()
1415 ;; FIXME: There are several potential problems linked with reconversion
1416 ;; and auto-revert when we have indirect buffers because they share their
1417 ;; /tmp cache directory. This sharing is good (you'd rather not reconvert
1418 ;; for each clone), but that means that clones need to collaborate a bit.
1419 ;; I guess it mostly means: detect when a reconversion process is already
1420 ;; running, and run the sentinel in all clones.
1422 ;; Maybe the clones should really have a separate /tmp directory
1423 ;; so they could have a different resolution and you could use clones
1424 ;; for zooming.
1425 (remove-overlays (point-min) (point-max) 'doc-view t)
1426 (if (consp image-mode-winprops-alist) (setq image-mode-winprops-alist nil)))
1428 (defun doc-view-intersection (l1 l2)
1429 (let ((l ()))
1430 (dolist (x l1) (if (memq x l2) (push x l)))
1433 (defun doc-view-set-doc-type ()
1434 "Figure out the current document type (`doc-view-doc-type')."
1435 (let ((name-types
1436 (when buffer-file-name
1437 (cdr (assoc (file-name-extension buffer-file-name)
1439 ;; DVI
1440 ("dvi" dvi)
1441 ;; PDF
1442 ("pdf" pdf) ("epdf" pdf)
1443 ;; PostScript
1444 ("ps" ps) ("eps" ps)
1445 ;; OpenDocument formats
1446 ("odt" odf) ("ods" odf) ("odp" odf) ("odg" odf)
1447 ("odc" odf) ("odi" odf) ("odm" odf) ("ott" odf)
1448 ("ots" odf) ("otp" odf) ("otg" odf)
1449 ;; Microsoft Office formats (also handled
1450 ;; by the odf conversion chain)
1451 ("doc" odf) ("docx" odf) ("xls" odf) ("xlsx" odf)
1452 ("ppt" odf) ("pptx" odf))))))
1453 (content-types
1454 (save-excursion
1455 (goto-char (point-min))
1456 (cond
1457 ((looking-at "%!") '(ps))
1458 ((looking-at "%PDF") '(pdf))
1459 ((looking-at "\367\002") '(dvi))))))
1460 (set (make-local-variable 'doc-view-doc-type)
1461 (car (or (doc-view-intersection name-types content-types)
1462 (when (and name-types content-types)
1463 (error "Conflicting types: name says %s but content says %s"
1464 name-types content-types))
1465 name-types content-types
1466 (error "Cannot determine the document type"))))))
1468 ;;;###autoload
1469 (defun doc-view-mode ()
1470 "Major mode in DocView buffers.
1472 DocView Mode is an Emacs document viewer. It displays PDF, PS
1473 and DVI files (as PNG images) in Emacs buffers.
1475 You can use \\<doc-view-mode-map>\\[doc-view-toggle-display] to
1476 toggle between displaying the document or editing it as text.
1477 \\{doc-view-mode-map}"
1478 (interactive)
1480 (if (= (point-min) (point-max))
1481 ;; The doc is empty or doesn't exist at all, so fallback to
1482 ;; another mode. We used to also check file-exists-p, but this
1483 ;; returns nil for tar members.
1484 (doc-view-fallback-mode)
1486 (let* ((prev-major-mode (if (eq major-mode 'doc-view-mode)
1487 doc-view-previous-major-mode
1488 (when (not (memq major-mode
1489 '(doc-view-mode fundamental-mode)))
1490 major-mode))))
1491 (kill-all-local-variables)
1492 (set (make-local-variable 'doc-view-previous-major-mode) prev-major-mode))
1494 ;; Figure out the document type.
1495 (unless doc-view-doc-type
1496 (doc-view-set-doc-type))
1498 (doc-view-make-safe-dir doc-view-cache-directory)
1499 ;; Handle compressed files, remote files, files inside archives
1500 (set (make-local-variable 'doc-view-buffer-file-name)
1501 (cond
1502 (jka-compr-really-do-compress
1503 ;; FIXME: there's a risk of name conflicts here.
1504 (expand-file-name
1505 (file-name-nondirectory
1506 (file-name-sans-extension buffer-file-name))
1507 doc-view-cache-directory))
1508 ;; Is the file readable by local processes?
1509 ;; We used to use `file-remote-p' but it's unclear what it's
1510 ;; supposed to return nil for things like local files accessed via
1511 ;; `su' or via file://...
1512 ((let ((file-name-handler-alist nil))
1513 (not (and buffer-file-name (file-readable-p buffer-file-name))))
1514 ;; FIXME: there's a risk of name conflicts here.
1515 (expand-file-name
1516 (if buffer-file-name
1517 (file-name-nondirectory buffer-file-name)
1518 (buffer-name))
1519 doc-view-cache-directory))
1520 (t buffer-file-name)))
1521 (when (not (string= doc-view-buffer-file-name buffer-file-name))
1522 (write-region nil nil doc-view-buffer-file-name))
1524 (add-hook 'change-major-mode-hook
1525 (lambda ()
1526 (doc-view-kill-proc)
1527 (remove-overlays (point-min) (point-max) 'doc-view t))
1528 nil t)
1529 (add-hook 'clone-indirect-buffer-hook 'doc-view-clone-buffer-hook nil t)
1530 (add-hook 'kill-buffer-hook 'doc-view-kill-proc nil t)
1532 (remove-overlays (point-min) (point-max) 'doc-view t) ;Just in case.
1533 ;; Keep track of display info ([vh]scroll, page number, overlay,
1534 ;; ...) for each window in which this document is shown.
1535 (add-hook 'image-mode-new-window-functions
1536 'doc-view-new-window-function nil t)
1537 (image-mode-setup-winprops)
1539 (set (make-local-variable 'mode-line-position)
1540 '(" P" (:eval (number-to-string (doc-view-current-page)))
1541 "/" (:eval (number-to-string (doc-view-last-page-number)))))
1542 ;; Don't scroll unless the user specifically asked for it.
1543 (set (make-local-variable 'auto-hscroll-mode) nil)
1544 (set (make-local-variable 'mwheel-scroll-up-function)
1545 'doc-view-scroll-up-or-next-page)
1546 (set (make-local-variable 'mwheel-scroll-down-function)
1547 'doc-view-scroll-down-or-previous-page)
1548 (set (make-local-variable 'cursor-type) nil)
1549 (use-local-map doc-view-mode-map)
1550 (set (make-local-variable 'after-revert-hook) 'doc-view-reconvert-doc)
1551 (set (make-local-variable 'bookmark-make-record-function)
1552 'doc-view-bookmark-make-record)
1553 (setq mode-name "DocView"
1554 buffer-read-only t
1555 major-mode 'doc-view-mode)
1556 (doc-view-initiate-display)
1557 ;; Switch off view-mode explicitly, because doc-view-mode is the
1558 ;; canonical view mode for PDF/PS/DVI files. This could be
1559 ;; switched on automatically depending on the value of
1560 ;; `view-read-only'.
1561 (set (make-local-variable 'view-read-only) nil)
1562 (run-mode-hooks 'doc-view-mode-hook)))
1564 (defun doc-view-fallback-mode ()
1565 "Fallback to the previous or next best major mode."
1566 (if doc-view-previous-major-mode
1567 (funcall doc-view-previous-major-mode)
1568 (let ((auto-mode-alist (rassq-delete-all
1569 'doc-view-mode-maybe
1570 (rassq-delete-all 'doc-view-mode
1571 (copy-alist auto-mode-alist)))))
1572 (normal-mode))))
1574 ;;;###autoload
1575 (defun doc-view-mode-maybe ()
1576 "Switch to `doc-view-mode' if possible.
1577 If the required external tools are not available, then fallback
1578 to the next best mode."
1579 (condition-case nil
1580 (doc-view-set-doc-type)
1581 (error (doc-view-fallback-mode)))
1582 (if (doc-view-mode-p doc-view-doc-type)
1583 (doc-view-mode)
1584 (doc-view-fallback-mode)))
1586 ;;;###autoload
1587 (define-minor-mode doc-view-minor-mode
1588 "Toggle displaying buffer via Doc View (Doc View minor mode).
1589 With a prefix argument ARG, enable Doc View minor mode if ARG is
1590 positive, and disable it otherwise. If called from Lisp, enable
1591 the mode if ARG is omitted or nil.
1593 See the command `doc-view-mode' for more information on this mode."
1594 nil " DocView" doc-view-minor-mode-map
1595 :group 'doc-view
1596 (when doc-view-minor-mode
1597 (add-hook 'change-major-mode-hook (lambda () (doc-view-minor-mode -1)) nil t)
1598 (message
1599 "%s"
1600 (substitute-command-keys
1601 "Type \\[doc-view-toggle-display] to toggle between editing or viewing the document."))))
1603 (defun doc-view-clear-cache ()
1604 "Delete the whole cache (`doc-view-cache-directory')."
1605 (interactive)
1606 (dired-delete-file doc-view-cache-directory 'always))
1608 (defun doc-view-dired-cache ()
1609 "Open `dired' in `doc-view-cache-directory'."
1610 (interactive)
1611 (dired doc-view-cache-directory))
1614 ;;;; Bookmark integration
1616 (declare-function bookmark-make-record-default
1617 "bookmark" (&optional no-file no-context posn))
1618 (declare-function bookmark-prop-get "bookmark" (bookmark prop))
1619 (declare-function bookmark-default-handler "bookmark" (bmk))
1621 (defun doc-view-bookmark-make-record ()
1622 (nconc (bookmark-make-record-default)
1623 `((page . ,(doc-view-current-page))
1624 (handler . doc-view-bookmark-jump))))
1627 ;;;###autoload
1628 (defun doc-view-bookmark-jump (bmk)
1629 ;; This implements the `handler' function interface for record type
1630 ;; returned by `doc-view-bookmark-make-record', which see.
1631 (prog1 (bookmark-default-handler bmk)
1632 (let ((page (bookmark-prop-get bmk 'page)))
1633 (when (not (eq major-mode 'doc-view-mode))
1634 (doc-view-toggle-display))
1635 (with-selected-window
1636 (or (get-buffer-window (current-buffer) 0)
1637 (selected-window))
1638 (doc-view-goto-page page)))))
1641 (provide 'doc-view)
1643 ;; Local Variables:
1644 ;; eval: (outline-minor-mode 1)
1645 ;; End:
1647 ;;; doc-view.el ends here