1 ;;; doc-view.el --- View PDF/PostScript/DVI files in Emacs -*- lexical-binding: t -*-
4 ;; Copyright (C) 2007-2012 Free Software Foundation, Inc.
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/>.
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/).
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
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
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'.
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.
101 ;; M-x customize-group RET doc-view RET
103 ;; and modify them to your needs.
107 ;; - add print command.
108 ;; - share more code with image-mode.
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
135 ;; Anyway, if someone with better isearch knowledge wants to give it a try,
136 ;; feel free to do it. --Tassilo
140 (eval-when-compile (require 'cl-lib
))
142 (require 'image-mode
)
145 ;;;; Customization Options
147 (defgroup doc-view nil
148 "In-buffer viewer for PDF, PostScript and DVI files."
149 :link
'(function-link doc-view
)
156 (defcustom doc-view-ghostscript-program
"gs"
157 "Program to convert PS and PDF files to PNG."
161 (defcustom doc-view-ghostscript-options
162 '("-dSAFER" ;; Avoid security problems when rendering files from untrusted
164 "-dNOPAUSE" "-sDEVICE=png16m" "-dTextAlphaBits=4"
165 "-dBATCH" "-dGraphicsAlphaBits=4" "-dQUIET")
166 "A list of options to give to ghostscript."
167 :type
'(repeat string
)
170 (defcustom doc-view-resolution
100
171 "Dots per inch resolution used to render the documents.
172 Higher values result in larger images."
176 (defcustom doc-view-image-width
850
177 "Default image width.
178 Has only an effect if imagemagick support is compiled into emacs."
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
189 If this and `doc-view-dvipdf-program' are set,
190 `doc-view-dvipdf-program' will be preferred."
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
200 If this and `doc-view-dvipdfm-program' are set,
201 `doc-view-dvipdf-program' will be preferred."
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."
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."
220 (defcustom doc-view-pdftotext-program
"pdftotext"
221 "Program to convert PDF files to plain text.
223 Needed for searching."
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."
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
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."
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.
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'.")
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
)
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
)
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
)
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
)
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
)
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."
377 ["Toggle display" doc-view-toggle-display
]
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
)]
385 (customize-save-variable 'doc-view-continuous doc-view-continuous
) t
]
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
]
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
)
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)))
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
))
428 (setf (doc-view-current-page) page
429 (doc-view-current-info)
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"
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
)
442 (dolist (m (cdr (assq page
443 doc-view-current-search-matches
)))
444 (setq contexts
(concat contexts
" - \"" m
"\"\n")))
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)))
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."
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."
479 (doc-view-goto-page (- (doc-view-current-page) (or arg
1))))
481 (defun doc-view-first-page ()
482 "View the first page."
484 (doc-view-goto-page 1))
486 (defun doc-view-last-page ()
487 "View the last page."
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)."
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
))
502 (when (/= cur-page
(doc-view-current-page))
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)."
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))
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."
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
))
535 (when (/= cur-page
(doc-view-current-page))
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."
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))
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)."
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."
574 (when (eq major-mode
'doc-view-mode
)
575 (kill-buffer (current-buffer))))
577 (defun doc-view-make-safe-dir (dir)
579 (let ((umask (default-file-modes)))
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
))
588 (set-default-file-modes umask
)))
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
)
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
618 (concat (file-name-nondirectory doc-view-buffer-file-name
)
620 (let ((file doc-view-buffer-file-name
))
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."
631 (when (not (funcall predicate item
))
632 (setq new-list
(cons item new-list
))))
633 (nreverse new-list
)))
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
))
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
)
652 (and doc-view-ghostscript-program
653 (executable-find doc-view-ghostscript-program
)))
655 (and doc-view-unoconv-program
656 (executable-find doc-view-unoconv-program
)
657 (doc-view-mode-p 'pdf
)))
658 (t ;; unknown image type
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
)
670 ;; ImageMagick supports on-the-fly-rescaling
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."
688 (let ((win-width (- (nth 2 (window-inside-pixel-edges))
689 (nth 0 (window-inside-pixel-edges))))
690 (slice (doc-view-current-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
))))
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."
708 (let ((win-height (- (nth 3 (window-inside-pixel-edges))
709 (nth 1 (window-inside-pixel-edges))))
710 (slice (doc-view-current-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
718 (doc-view-enlarge (/ (float (- win-height
1)) (float img-height
))))
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."
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)))
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
)))))
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."
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."
772 (if (string-match "\\(.+\\)\n?\\'" event
)
773 (match-string 1 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
)
789 (expand-file-name "~/")))
790 (proc (apply 'start-process name doc-view-conversion-buffer
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
807 (doc-view-start-process "dvi->pdf" doc-view-dvipdfm-program
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
)
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
)
827 (let ((resolution doc-view-resolution
))
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))
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
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
855 (format "-dFirstPage=%d" page
)
856 (format "-dLastPage=%d" page
)
857 (concat "-sOutputFile=" png
)
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."
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
)))
874 pdf
(format png
(car pages
)) (car pages
)
877 (doc-view-pdf->png pdf png rest
)
878 ;; Yippie, the important pages are done, update the display.
880 ;; For the windows that have a message (like "Welcome to
881 ;; DocView") display property, clearing the image cache is
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
)
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
903 ;; Doc is a PDF, so convert it to TXT
904 (doc-view-pdf->txt doc-view-buffer-file-name txt callback
))
906 ;; Doc is a PS, so convert it to PDF (which will be converted to
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
)))))
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))
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))
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
932 ;; Avoid security problems when rendering files from
933 ;; untrusted sources.
935 ;; in-file and out-file
939 (defun doc-view-active-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
))))
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
961 ;; DVI files have to be converted to PDF before Ghostscript can process
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
)))))
967 ;; ODF files have to be converted to PDF before Ghostscript can
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
)
972 doc-view-current-cache-dir
))
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
980 (rename-file opdf pdf
)
981 (doc-view-pdf/ps-
>png pdf png-file
)))))
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
)))))
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'."
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
)))))
1010 (setf (doc-view-current-slice) (list x y width height
))
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'."
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
))
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"
1041 doc-view-buffer-file-name
)))))
1043 (when (string-match (concat "%%BoundingBox: "
1044 "\\([[:digit:]]+\\) \\([[:digit:]]+\\) "
1045 "\\([[:digit:]]+\\) \\([[:digit:]]+\\)") o
)
1046 (mapcar #'string-to-number
1047 (list (match-string 1 o
)
1050 (match-string 4 o
)))))))
1052 (defvar doc-view-paper-sizes
1054 (a4-landscape 842 595)
1056 (letter-landscape 792 612)
1058 (legal-landscape 1008 612)
1060 (a3-landscape 1191 842)
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'."
1087 (let ((bb (doc-view-get-bounding-box)))
1089 (message "BoundingBox couldn't be determined")
1090 (let* ((is (image-size (doc-view-current-image) t
))
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
)
1097 (bb (doc-view-scale-bounding-box ps iw ih 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."
1110 (setf (doc-view-current-slice) nil
)
1112 (doc-view-goto-page (doc-view-current-page)))
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
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
1136 (list (cons 'slice slice
) 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
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
))
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
)
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))))
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
)
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 ()
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."
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."
1237 (if (eq major-mode
'doc-view-mode
)
1238 ;; Switch to editing mode
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
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? "))
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."
1262 (insert-file-contents file
)
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
)
1272 (list (buffer-substring
1273 (line-beginning-position)
1274 (line-end-position))))
1279 ;; This page already is a match.
1281 ;; This is the first match on page.
1283 (list (buffer-substring
1284 (line-beginning-position)
1285 (line-end-position))))
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."
1294 (setq no
(+ no
(1- (length p
)))))
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."
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."
1309 (if (and (not new-query
)
1310 doc-view-current-search-matches
)
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
)
1320 (setq doc-view-current-search-matches
1321 (doc-view-search-internal
1322 (read-from-minibuffer "Regexp: ")
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."
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
))))
1340 (doc-view-goto-page page
)
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."
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
)))))
1354 (doc-view-goto-page page
)
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)
1375 (defun doc-view-initiate-display ()
1376 ;; Switch to image display if possible
1377 (if (doc-view-mode-p doc-view-doc-type
)
1379 (doc-view-buffer-message)
1380 (setf (doc-view-current-page) (or (doc-view-current-page) 1))
1381 (if (doc-view-already-converted-p)
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)))
1389 (when (file-readable-p res-file
)
1390 (insert-file-contents res-file
)
1391 (read (current-buffer))))))
1393 (set (make-local-variable 'doc-view-resolution
) res
)))
1394 (doc-view-display (current-buffer) 'force
))
1395 (doc-view-convert-current-doc))
1398 (substitute-command-keys
1399 (concat "Type \\[doc-view-toggle-display] to toggle between "
1400 "editing or viewing the document."))))
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
)
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
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
)
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')."
1436 (when buffer-file-name
1437 (cdr (assoc (file-name-extension buffer-file-name
)
1442 ("pdf" pdf
) ("epdf" pdf
)
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
))))))
1455 (goto-char (point-min))
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"))))))
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}"
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
)))
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
)
1502 (jka-compr-really-do-compress
1503 ;; FIXME: there's a risk of name conflicts here.
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.
1516 (if buffer-file-name
1517 (file-name-nondirectory buffer-file-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
1526 (doc-view-kill-proc)
1527 (remove-overlays (point-min) (point-max) 'doc-view 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"
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
)))))
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."
1580 (doc-view-set-doc-type)
1581 (error (doc-view-fallback-mode)))
1582 (if (doc-view-mode-p doc-view-doc-type
)
1584 (doc-view-fallback-mode)))
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
1596 (when doc-view-minor-mode
1597 (add-hook 'change-major-mode-hook
(lambda () (doc-view-minor-mode -
1)) nil t
)
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')."
1606 (dired-delete-file doc-view-cache-directory
'always
))
1608 (defun doc-view-dired-cache ()
1609 "Open `dired' in `doc-view-cache-directory'."
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
))))
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)
1638 (doc-view-goto-page page
)))))
1644 ;; eval: (outline-minor-mode 1)
1647 ;;; doc-view.el ends here