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 ;; (message "New window %s for buf %s" (car winprops) (current-buffer))
259 (cl-assert (or (eq t
(car winprops
))
260 (eq (window-buffer (car winprops
)) (current-buffer))))
261 (let ((ol (image-mode-window-get 'overlay winprops
)))
264 (setq ol
(copy-overlay ol
))
265 ;; `ol' might actually be dead.
266 (move-overlay ol
(point-min) (point-max)))
267 (setq ol
(make-overlay (point-min) (point-max) nil t
))
268 (overlay-put ol
'doc-view t
))
269 (overlay-put ol
'window
(car winprops
))
270 (unless (windowp (car winprops
))
271 ;; It's a pseudo entry. Let's make sure it's not displayed (the
272 ;; `window' property is only effective if its value is a window).
273 (cl-assert (eq t
(car winprops
)))
275 (image-mode-window-put 'overlay ol winprops
)))
277 (defvar doc-view-current-files nil
278 "Only used internally.")
279 (make-variable-buffer-local 'doc-view-current-files
)
281 (defvar doc-view-current-converter-processes nil
282 "Only used internally.")
283 (make-variable-buffer-local 'doc-view-current-converter-processes
)
285 (defvar doc-view-current-timer nil
286 "Only used internally.")
287 (make-variable-buffer-local 'doc-view-current-timer
)
289 (defvar doc-view-current-cache-dir nil
290 "Only used internally.")
291 (make-variable-buffer-local 'doc-view-current-cache-dir
)
293 (defvar doc-view-current-search-matches nil
294 "Only used internally.")
295 (make-variable-buffer-local 'doc-view-current-search-matches
)
297 (defvar doc-view-pending-cache-flush nil
298 "Only used internally.")
300 (defvar doc-view-previous-major-mode nil
301 "Only used internally.")
303 (defvar doc-view-buffer-file-name nil
304 "Only used internally.
305 The file name used for conversion. Normally it's the same as
306 `buffer-file-name', but for remote files, compressed files and
307 files inside an archive it is a temporary copy of
308 the (uncompressed, extracted) file residing in
309 `doc-view-cache-directory'.")
311 (defvar doc-view-doc-type nil
312 "The type of document in the current buffer.
313 Can be `dvi', `pdf', or `ps'.")
317 (defvar doc-view-mode-map
318 (let ((map (make-sparse-keymap)))
319 (set-keymap-parent map image-mode-map
)
320 ;; Navigation in the document
321 (define-key map
(kbd "n") 'doc-view-next-page
)
322 (define-key map
(kbd "p") 'doc-view-previous-page
)
323 (define-key map
(kbd "<next>") 'forward-page
)
324 (define-key map
(kbd "<prior>") 'backward-page
)
325 (define-key map
[remap forward-page
] 'doc-view-next-page
)
326 (define-key map
[remap backward-page
] 'doc-view-previous-page
)
327 (define-key map
(kbd "SPC") 'doc-view-scroll-up-or-next-page
)
328 (define-key map
(kbd "DEL") 'doc-view-scroll-down-or-previous-page
)
329 (define-key map
(kbd "C-n") 'doc-view-next-line-or-next-page
)
330 (define-key map
(kbd "<down>") 'doc-view-next-line-or-next-page
)
331 (define-key map
(kbd "C-p") 'doc-view-previous-line-or-previous-page
)
332 (define-key map
(kbd "<up>") 'doc-view-previous-line-or-previous-page
)
333 (define-key map
(kbd "M-<") 'doc-view-first-page
)
334 (define-key map
(kbd "M->") 'doc-view-last-page
)
335 (define-key map
[remap goto-line
] 'doc-view-goto-page
)
336 (define-key map
(kbd "RET") 'image-next-line
)
338 (define-key map
"+" 'doc-view-enlarge
)
339 (define-key map
"-" 'doc-view-shrink
)
340 ;; Fit the image to the window
341 (define-key map
"W" 'doc-view-fit-width-to-window
)
342 (define-key map
"H" 'doc-view-fit-height-to-window
)
343 (define-key map
"P" 'doc-view-fit-page-to-window
)
344 ;; Killing the buffer (and the process)
345 (define-key map
(kbd "k") 'doc-view-kill-proc-and-buffer
)
346 (define-key map
(kbd "K") 'doc-view-kill-proc
)
348 (define-key map
(kbd "s s") 'doc-view-set-slice
)
349 (define-key map
(kbd "s m") 'doc-view-set-slice-using-mouse
)
350 (define-key map
(kbd "s b") 'doc-view-set-slice-from-bounding-box
)
351 (define-key map
(kbd "s r") 'doc-view-reset-slice
)
353 (define-key map
(kbd "C-s") 'doc-view-search
)
354 (define-key map
(kbd "<find>") 'doc-view-search
)
355 (define-key map
(kbd "C-r") 'doc-view-search-backward
)
357 (define-key map
(kbd "C-t") 'doc-view-show-tooltip
)
358 ;; Toggle between text and image display or editing
359 (define-key map
(kbd "C-c C-c") 'doc-view-toggle-display
)
360 ;; Open a new buffer with doc's text contents
361 (define-key map
(kbd "C-c C-t") 'doc-view-open-text
)
362 ;; Reconvert the current document. Don't just use revert-buffer
363 ;; because that resets the scale factor, the page number, ...
364 (define-key map
(kbd "g") 'doc-view-revert-buffer
)
365 (define-key map
(kbd "r") 'doc-view-revert-buffer
)
367 "Keymap used by `doc-view-mode' when displaying a doc as a set of images.")
369 (defun doc-view-revert-buffer (&optional ignore-auto noconfirm
)
370 "Like `revert-buffer', but preserves the buffer's current modes."
371 ;; FIXME: this should probably be moved to files.el and used for
372 ;; most/all "g" bindings to revert-buffer.
373 (interactive (list (not current-prefix-arg
)))
374 (revert-buffer ignore-auto noconfirm
'preserve-modes
))
377 (easy-menu-define doc-view-menu doc-view-mode-map
378 "Menu for Doc View mode."
380 ["Toggle display" doc-view-toggle-display
]
382 ["Off" (setq doc-view-continuous nil
)
383 :style radio
:selected
(eq doc-view-continuous nil
)]
384 ["On" (setq doc-view-continuous t
)
385 :style radio
:selected
(eq doc-view-continuous t
)]
388 (customize-save-variable 'doc-view-continuous doc-view-continuous
) t
]
391 ["Set Slice" doc-view-set-slice-using-mouse
]
392 ["Set Slice (BoundingBox)" doc-view-set-slice-from-bounding-box
]
393 ["Set Slice (manual)" doc-view-set-slice
]
394 ["Reset Slice" doc-view-reset-slice
]
396 ["Search" doc-view-search
]
397 ["Search Backwards" doc-view-search-backward
]
400 (defvar doc-view-minor-mode-map
401 (let ((map (make-sparse-keymap)))
402 ;; Toggle between text and image display or editing
403 (define-key map
(kbd "C-c C-c") 'doc-view-toggle-display
)
405 "Keymap used by `doc-minor-view-mode'.")
407 ;;;; Navigation Commands
409 (defmacro doc-view-current-page
(&optional win
)
410 `(image-mode-window-get 'page
,win
))
411 (defmacro doc-view-current-info
() `(image-mode-window-get 'info
))
412 (defmacro doc-view-current-overlay
() `(image-mode-window-get 'overlay
))
413 (defmacro doc-view-current-image
() `(image-mode-window-get 'image
))
414 (defmacro doc-view-current-slice
() `(image-mode-window-get 'slice
))
416 (defun doc-view-last-page-number ()
417 (length doc-view-current-files
))
419 (defun doc-view-goto-page (page)
420 "View the page given by PAGE."
421 (interactive "nPage: ")
422 (let ((len (doc-view-last-page-number))
423 (hscroll (window-hscroll)))
426 (when (and (> page len
)
427 ;; As long as the converter is running, we don't know
428 ;; how many pages will be available.
429 (null doc-view-current-converter-processes
))
431 (setf (doc-view-current-page) page
432 (doc-view-current-info)
435 (format "Page %d of %d." page len
) 'face
'bold
)
436 ;; Tell user if converting isn't finished yet
437 (if doc-view-current-converter-processes
438 " (still converting...)\n"
440 ;; Display context infos if this page matches the last search
441 (when (and doc-view-current-search-matches
442 (assq page doc-view-current-search-matches
))
443 (concat (propertize "Search matches:\n" 'face
'bold
)
445 (dolist (m (cdr (assq page
446 doc-view-current-search-matches
)))
447 (setq contexts
(concat contexts
" - \"" m
"\"\n")))
450 ;; We used to find the file name from doc-view-current-files but
451 ;; that's not right if the pages are not generated sequentially
452 ;; or if the page isn't in doc-view-current-files yet.
453 (let ((file (expand-file-name (format "page-%d.png" page
)
454 (doc-view-current-cache-dir))))
455 (doc-view-insert-image file
:pointer
'arrow
)
456 (set-window-hscroll (selected-window) hscroll
)
457 (when (and (not (file-exists-p file
))
458 doc-view-current-converter-processes
)
459 ;; The PNG file hasn't been generated yet.
460 (doc-view-pdf->png-1 doc-view-buffer-file-name file page
461 (let ((win (selected-window)))
463 (and (eq (current-buffer) (window-buffer win
))
464 ;; If we changed page in the mean
465 ;; time, don't mess things up.
466 (eq (doc-view-current-page win
) page
)
467 ;; Make sure we don't infloop.
468 (file-readable-p file
)
469 (with-selected-window win
470 (doc-view-goto-page page
))))))))
471 (overlay-put (doc-view-current-overlay)
472 'help-echo
(doc-view-current-info))))
474 (defun doc-view-next-page (&optional arg
)
475 "Browse ARG pages forward."
477 (doc-view-goto-page (+ (doc-view-current-page) (or arg
1))))
479 (defun doc-view-previous-page (&optional arg
)
480 "Browse ARG pages backward."
482 (doc-view-goto-page (- (doc-view-current-page) (or arg
1))))
484 (defun doc-view-first-page ()
485 "View the first page."
487 (doc-view-goto-page 1))
489 (defun doc-view-last-page ()
490 "View the last page."
492 (doc-view-goto-page (doc-view-last-page-number)))
494 (defun doc-view-scroll-up-or-next-page (&optional arg
)
495 "Scroll page up ARG lines if possible, else goto next page.
496 When `doc-view-continuous' is non-nil, scrolling upward
497 at the bottom edge of the page moves to the next page.
498 Otherwise, goto next page only on typing SPC (ARG is nil)."
500 (if (or doc-view-continuous
(null arg
))
501 (let ((hscroll (window-hscroll))
502 (cur-page (doc-view-current-page)))
503 (when (= (window-vscroll) (image-scroll-up arg
))
505 (when (/= cur-page
(doc-view-current-page))
508 (set-window-hscroll (selected-window) hscroll
)))
509 (image-scroll-up arg
)))
511 (defun doc-view-scroll-down-or-previous-page (&optional arg
)
512 "Scroll page down ARG lines if possible, else goto previous page.
513 When `doc-view-continuous' is non-nil, scrolling downward
514 at the top edge of the page moves to the previous page.
515 Otherwise, goto previous page only on typing DEL (ARG is nil)."
517 (if (or doc-view-continuous
(null arg
))
518 (let ((hscroll (window-hscroll))
519 (cur-page (doc-view-current-page)))
520 (when (= (window-vscroll) (image-scroll-down arg
))
521 (doc-view-previous-page)
522 (when (/= cur-page
(doc-view-current-page))
525 (set-window-hscroll (selected-window) hscroll
)))
526 (image-scroll-down arg
)))
528 (defun doc-view-next-line-or-next-page (&optional arg
)
529 "Scroll upward by ARG lines if possible, else goto next page.
530 When `doc-view-continuous' is non-nil, scrolling a line upward
531 at the bottom edge of the page moves to the next page."
533 (if doc-view-continuous
534 (let ((hscroll (window-hscroll))
535 (cur-page (doc-view-current-page)))
536 (when (= (window-vscroll) (image-next-line arg
))
538 (when (/= cur-page
(doc-view-current-page))
541 (set-window-hscroll (selected-window) hscroll
)))
542 (image-next-line 1)))
544 (defun doc-view-previous-line-or-previous-page (&optional arg
)
545 "Scroll downward by ARG lines if possible, else goto previous page.
546 When `doc-view-continuous' is non-nil, scrolling a line downward
547 at the top edge of the page moves to the previous page."
549 (if doc-view-continuous
550 (let ((hscroll (window-hscroll))
551 (cur-page (doc-view-current-page)))
552 (when (= (window-vscroll) (image-previous-line arg
))
553 (doc-view-previous-page)
554 (when (/= cur-page
(doc-view-current-page))
557 (set-window-hscroll (selected-window) hscroll
)))
558 (image-previous-line arg
)))
560 ;;;; Utility Functions
562 (defun doc-view-kill-proc ()
563 "Kill the current converter process(es)."
565 (while (consp doc-view-current-converter-processes
)
566 (ignore-errors ;; Some entries might not be processes, and maybe
567 ;; some are dead already?
568 (kill-process (pop doc-view-current-converter-processes
))))
569 (when doc-view-current-timer
570 (cancel-timer doc-view-current-timer
)
571 (setq doc-view-current-timer nil
))
572 (setq mode-line-process nil
))
574 (defun doc-view-kill-proc-and-buffer ()
575 "Kill the current converter process and buffer."
578 (when (eq major-mode
'doc-view-mode
)
579 (kill-buffer (current-buffer))))
581 (defun doc-view-make-safe-dir (dir)
583 (let ((umask (default-file-modes)))
586 ;; Create temp files with strict access rights. It's easy to
587 ;; loosen them later, whereas it's impossible to close the
588 ;; time-window of loose permissions otherwise.
589 (set-default-file-modes #o0700
)
590 (make-directory dir
))
592 (set-default-file-modes umask
)))
594 (when (file-symlink-p dir
)
595 (error "Danger: %s points to a symbolic link" dir
))
596 ;; In case it was created earlier with looser rights.
597 ;; We could check the mode info returned by file-attributes, but it's
598 ;; a pain to parse and it may not tell you what we want under
599 ;; non-standard file-systems. So let's just say what we want and let
600 ;; the underlying C code and file-system figure it out.
601 ;; This also ends up checking a bunch of useful conditions: it makes
602 ;; sure we have write-access to the directory and that we own it, thus
603 ;; closing a bunch of security holes.
604 (condition-case error
605 (set-file-modes dir
#o0700
)
608 (format "Unable to use temporary directory %s: %s"
609 dir
(mapconcat 'identity
(cdr error
) " "))))))))
611 (defun doc-view-current-cache-dir ()
612 "Return the directory where the png files of the current doc should be saved.
613 It's a subdirectory of `doc-view-cache-directory'."
614 (if doc-view-current-cache-dir
615 doc-view-current-cache-dir
616 ;; Try and make sure doc-view-cache-directory exists and is safe.
617 (doc-view-make-safe-dir doc-view-cache-directory
)
618 ;; Now compute the subdirectory to use.
619 (setq doc-view-current-cache-dir
620 (file-name-as-directory
622 (concat (file-name-nondirectory doc-view-buffer-file-name
)
624 (let ((file doc-view-buffer-file-name
))
626 (set-buffer-multibyte nil
)
627 (insert-file-contents-literally file
)
628 (md5 (current-buffer)))))
629 doc-view-cache-directory
)))))
631 (defun doc-view-remove-if (predicate list
)
632 "Return LIST with all items removed that satisfy PREDICATE."
635 (when (not (funcall predicate item
))
636 (setq new-list
(cons item new-list
))))
637 (nreverse new-list
)))
640 (defun doc-view-mode-p (type)
641 "Return non-nil if document type TYPE is available for `doc-view'.
642 Document types are symbols like `dvi', `ps', `pdf', or `odf' (any
643 OpenDocument format)."
644 (and (display-graphic-p)
645 (or (image-type-available-p 'imagemagick
)
646 (image-type-available-p 'png
))
649 (and (doc-view-mode-p 'pdf
)
650 (or (and doc-view-dvipdf-program
651 (executable-find doc-view-dvipdf-program
))
652 (and doc-view-dvipdfm-program
653 (executable-find doc-view-dvipdfm-program
)))))
654 ((or (eq type
'postscript
) (eq type
'ps
) (eq type
'eps
)
656 (and doc-view-ghostscript-program
657 (executable-find doc-view-ghostscript-program
)))
659 (and doc-view-unoconv-program
660 (executable-find doc-view-unoconv-program
)
661 (doc-view-mode-p 'pdf
)))
662 (t ;; unknown image type
665 ;;;; Conversion Functions
667 (defvar doc-view-shrink-factor
1.125)
669 (defun doc-view-enlarge (factor)
670 "Enlarge the document by FACTOR."
671 (interactive (list doc-view-shrink-factor
))
672 (if (eq (plist-get (cdr (doc-view-current-image)) :type
)
674 ;; ImageMagick supports on-the-fly-rescaling.
675 (let ((new (ceiling (* factor doc-view-image-width
))))
676 (unless (equal new doc-view-image-width
)
677 (set (make-local-variable 'doc-view-image-width
) new
)
678 (doc-view-insert-image
679 (plist-get (cdr (doc-view-current-image)) :file
)
680 :width doc-view-image-width
)))
681 (let ((new (ceiling (* factor doc-view-resolution
))))
682 (unless (equal new doc-view-resolution
)
683 (set (make-local-variable 'doc-view-resolution
) new
)
684 (doc-view-reconvert-doc)))))
686 (defun doc-view-shrink (factor)
687 "Shrink the document."
688 (interactive (list doc-view-shrink-factor
))
689 (doc-view-enlarge (/ 1.0 factor
)))
691 (defun doc-view-fit-width-to-window ()
692 "Fit the image width to the window width."
694 (let ((win-width (- (nth 2 (window-inside-pixel-edges))
695 (nth 0 (window-inside-pixel-edges))))
696 (slice (doc-view-current-slice)))
698 (let ((img-width (car (image-display-size
699 (image-get-display-property) t
))))
700 (doc-view-enlarge (/ (float win-width
) (float img-width
))))
703 (let* ((slice-width (nth 2 slice
))
704 (scale-factor (/ (float win-width
) (float slice-width
)))
705 (new-slice (mapcar (lambda (x) (ceiling (* scale-factor x
))) slice
)))
707 (doc-view-enlarge scale-factor
)
708 (setf (doc-view-current-slice) new-slice
)
709 (doc-view-goto-page (doc-view-current-page))))))
711 (defun doc-view-fit-height-to-window ()
712 "Fit the image height to the window height."
714 (let ((win-height (- (nth 3 (window-inside-pixel-edges))
715 (nth 1 (window-inside-pixel-edges))))
716 (slice (doc-view-current-slice)))
718 (let ((img-height (cdr (image-display-size
719 (image-get-display-property) t
))))
720 ;; When users call 'doc-view-fit-height-to-window',
721 ;; they might want to go to next page by typing SPC
722 ;; ONLY once. So I used '(- win-height 1)' instead of
724 (doc-view-enlarge (/ (float (- win-height
1)) (float img-height
))))
727 (let* ((slice-height (nth 3 slice
))
728 (scale-factor (/ (float (- win-height
1)) (float slice-height
)))
729 (new-slice (mapcar (lambda (x) (ceiling (* scale-factor x
))) slice
)))
731 (doc-view-enlarge scale-factor
)
732 (setf (doc-view-current-slice) new-slice
)
733 (doc-view-goto-page (doc-view-current-page))))))
735 (defun doc-view-fit-page-to-window ()
736 "Fit the image to the window.
737 More specifically, this function enlarges image by:
739 min {(window-width / image-width), (window-height / image-height)} times."
741 (let ((win-width (- (nth 2 (window-inside-pixel-edges))
742 (nth 0 (window-inside-pixel-edges))))
743 (win-height (- (nth 3 (window-inside-pixel-edges))
744 (nth 1 (window-inside-pixel-edges))))
745 (slice (doc-view-current-slice)))
747 (let ((img-width (car (image-display-size
748 (image-get-display-property) t
)))
749 (img-height (cdr (image-display-size
750 (image-get-display-property) t
))))
751 (doc-view-enlarge (min (/ (float win-width
) (float img-width
))
752 (/ (float (- win-height
1))
753 (float img-height
)))))
755 (let* ((slice-width (nth 2 slice
))
756 (slice-height (nth 3 slice
))
757 (scale-factor (min (/ (float win-width
) (float slice-width
))
758 (/ (float (- win-height
1))
759 (float slice-height
))))
760 (new-slice (mapcar (lambda (x) (ceiling (* scale-factor x
))) slice
)))
761 (doc-view-enlarge scale-factor
)
762 (setf (doc-view-current-slice) new-slice
)
763 (doc-view-goto-page (doc-view-current-page))))))
765 (defun doc-view-reconvert-doc ()
766 "Reconvert the current document.
767 Should be invoked when the cached images aren't up-to-date."
770 ;; Clear the old cached files
771 (when (file-exists-p (doc-view-current-cache-dir))
772 (delete-directory (doc-view-current-cache-dir) 'recursive
))
773 (kill-local-variable 'doc-view-last-page-number
)
774 (doc-view-initiate-display))
776 (defun doc-view-sentinel (proc event
)
777 "Generic sentinel for doc-view conversion processes."
778 (if (not (string-match "finished" event
))
779 (message "DocView: process %s changed status to %s."
781 (if (string-match "\\(.+\\)\n?\\'" event
)
782 (match-string 1 event
)
784 (when (buffer-live-p (process-get proc
'buffer
))
785 (with-current-buffer (process-get proc
'buffer
)
786 (setq doc-view-current-converter-processes
787 (delq proc doc-view-current-converter-processes
))
788 (setq mode-line-process
789 (if doc-view-current-converter-processes
790 (format ":%s" (car doc-view-current-converter-processes
))))
791 (funcall (process-get proc
'callback
))))))
793 (defun doc-view-start-process (name program args callback
)
794 ;; Make sure the process is started in an existing directory, (rather than
795 ;; some file-name-handler-managed dir, for example).
796 (let* ((default-directory (if (file-readable-p default-directory
)
798 (expand-file-name "~/")))
799 (proc (apply 'start-process name doc-view-conversion-buffer
801 (push proc doc-view-current-converter-processes
)
802 (setq mode-line-process
(list (format ":%s" proc
)))
803 (set-process-sentinel proc
'doc-view-sentinel
)
804 (process-put proc
'buffer
(current-buffer))
805 (process-put proc
'callback callback
)))
807 (defun doc-view-dvi->pdf
(dvi pdf callback
)
808 "Convert DVI to PDF asynchronously and call CALLBACK when finished."
809 ;; Prefer dvipdf over dvipdfm, because the latter has problems if the DVI
810 ;; references and includes other PS files.
811 (if (and doc-view-dvipdf-program
812 (executable-find doc-view-dvipdf-program
))
813 (doc-view-start-process "dvi->pdf" doc-view-dvipdf-program
816 (doc-view-start-process "dvi->pdf" doc-view-dvipdfm-program
820 (defun doc-view-odf->pdf
(odf callback
)
821 "Convert ODF to PDF asynchronously and call CALLBACK when finished.
822 The converted PDF is put into the current cache directory, and it
823 is named like ODF with the extension turned to pdf."
824 (doc-view-start-process "odf->pdf" doc-view-unoconv-program
825 (list "-f" "pdf" "-o" (doc-view-current-cache-dir) odf
)
828 (defun doc-view-pdf/ps-
>png
(pdf-ps png
)
829 "Convert PDF-PS to PNG asynchronously."
830 (doc-view-start-process
831 "pdf/ps->png" doc-view-ghostscript-program
832 (append doc-view-ghostscript-options
833 (list (format "-r%d" (round doc-view-resolution
))
834 (concat "-sOutputFile=" png
)
836 (let ((resolution doc-view-resolution
))
838 ;; Only create the resolution file when it's all done, so it also
839 ;; serves as a witness that the conversion is complete.
840 (write-region (prin1-to-string resolution
) nil
841 (expand-file-name "resolution.el"
842 (doc-view-current-cache-dir))
844 (when doc-view-current-timer
845 (cancel-timer doc-view-current-timer
)
846 (setq doc-view-current-timer nil
))
847 (doc-view-display (current-buffer) 'force
))))
848 ;; Update the displayed pages as soon as they're done generating.
849 (when doc-view-conversion-refresh-interval
850 (setq doc-view-current-timer
851 (run-at-time "1 secs" doc-view-conversion-refresh-interval
855 (defun doc-view-pdf->png-1
(pdf png page callback
)
856 "Convert a PAGE of a PDF file to PNG asynchronously.
857 Call CALLBACK with no arguments when done."
858 (doc-view-start-process
859 "pdf->png-1" doc-view-ghostscript-program
860 (append doc-view-ghostscript-options
861 (list (format "-r%d" (round doc-view-resolution
))
862 ;; Sadly, `gs' only supports the page-range
864 (format "-dFirstPage=%d" page
)
865 (format "-dLastPage=%d" page
)
866 (concat "-sOutputFile=" png
)
870 (declare-function clear-image-cache
"image.c" (&optional filter
))
872 (defun doc-view-pdf->png
(pdf png pages
)
873 "Convert a PDF file to PNG asynchronously.
874 Start by converting PAGES, and then the rest."
876 (doc-view-pdf/ps-
>png pdf png
)
877 ;; We could render several `pages' with a single process if they're
878 ;; (almost) consecutive, but since in 99% of the cases, there'll be only
879 ;; a single page anyway, and of the remaining 1%, few cases will have
880 ;; consecutive pages, it's not worth the trouble.
881 (let ((rest (cdr pages
)))
883 pdf
(format png
(car pages
)) (car pages
)
886 (doc-view-pdf->png pdf png rest
)
887 ;; Yippie, the important pages are done, update the display.
889 ;; For the windows that have a message (like "Welcome to
890 ;; DocView") display property, clearing the image cache is
892 (dolist (win (get-buffer-window-list (current-buffer) nil
'visible
))
893 (with-selected-window win
894 (when (stringp (get-char-property (point-min) 'display
))
895 (doc-view-goto-page (doc-view-current-page)))))
896 ;; Convert the rest of the pages.
897 (doc-view-pdf/ps-
>png pdf png
)))))))
899 (defun doc-view-pdf->txt
(pdf txt callback
)
900 "Convert PDF to TXT asynchronously and call CALLBACK when finished."
901 (or (executable-find doc-view-pdftotext-program
)
902 (error "You need the `pdftotext' program to convert a PDF to text"))
903 (doc-view-start-process "pdf->txt" doc-view-pdftotext-program
904 (list "-raw" pdf txt
)
907 (defun doc-view-current-cache-doc-pdf ()
908 "Return the name of the doc.pdf in the current cache dir.
909 This file exists only if the current document isn't a PDF or PS file already."
910 (expand-file-name "doc.pdf" (doc-view-current-cache-dir)))
912 (defun doc-view-doc->txt
(txt callback
)
913 "Convert the current document to text and call CALLBACK when done."
914 (make-directory (doc-view-current-cache-dir) t
)
915 (pcase doc-view-doc-type
917 ;; Doc is a PDF, so convert it to TXT
918 (doc-view-pdf->txt doc-view-buffer-file-name txt callback
))
920 ;; Doc is a PS, so convert it to PDF (which will be converted to
922 (let ((pdf (doc-view-current-cache-doc-pdf)))
923 (doc-view-ps->pdf doc-view-buffer-file-name pdf
924 (lambda () (doc-view-pdf->txt pdf txt callback
)))))
926 ;; Doc is a DVI. This means that a doc.pdf already exists in its
927 ;; cache subdirectory.
928 (doc-view-pdf->txt
(doc-view-current-cache-doc-pdf) txt callback
))
930 ;; Doc is some ODF (or MS Office) doc. This means that a doc.pdf
931 ;; already exists in its cache subdirectory.
932 (doc-view-pdf->txt
(doc-view-current-cache-doc-pdf) txt callback
))
933 (_ (error "DocView doesn't know what to do"))))
935 (defun doc-view-ps->pdf
(ps pdf callback
)
936 "Convert PS to PDF asynchronously and call CALLBACK when finished."
937 (or (executable-find doc-view-ps2pdf-program
)
938 (error "You need the `ps2pdf' program to convert PS to PDF"))
939 (doc-view-start-process "ps->pdf" doc-view-ps2pdf-program
941 ;; Avoid security problems when rendering files from
942 ;; untrusted sources.
944 ;; in-file and out-file
948 (defun doc-view-active-pages ()
950 (dolist (win (get-buffer-window-list (current-buffer) nil
'visible
))
951 (let ((page (image-mode-window-get 'page win
)))
952 (unless (memq page pages
) (push page pages
))))
955 (defun doc-view-convert-current-doc ()
956 "Convert `doc-view-buffer-file-name' to a set of png files, one file per page.
957 Those files are saved in the directory given by the function
958 `doc-view-current-cache-dir'."
959 ;; Let stale files still display while we recompute the new ones, so only
960 ;; flush the cache when the conversion is over. One of the reasons why it
961 ;; is important to keep displaying the stale page is so that revert-buffer
962 ;; preserves the horizontal/vertical scroll settings (which are otherwise
963 ;; resets during the redisplay).
964 (setq doc-view-pending-cache-flush t
)
965 (let ((png-file (expand-file-name "page-%d.png"
966 (doc-view-current-cache-dir))))
967 (make-directory (doc-view-current-cache-dir) t
)
968 (pcase doc-view-doc-type
970 ;; DVI files have to be converted to PDF before Ghostscript can process
972 (let ((pdf (doc-view-current-cache-doc-pdf)))
973 (doc-view-dvi->pdf doc-view-buffer-file-name pdf
974 (lambda () (doc-view-pdf/ps-
>png pdf png-file
)))))
976 ;; ODF files have to be converted to PDF before Ghostscript can
978 (let ((pdf (doc-view-current-cache-doc-pdf))
979 (opdf (expand-file-name (concat (file-name-base doc-view-buffer-file-name
)
981 doc-view-current-cache-dir
))
983 ;; The unoconv tool only supports a output directory, but no
984 ;; file name. It's named like the input file with the
985 ;; extension replaced by pdf.
986 (doc-view-odf->pdf doc-view-buffer-file-name
989 (rename-file opdf pdf
)
990 (doc-view-pdf/ps-
>png pdf png-file
)))))
992 (let ((pages (doc-view-active-pages)))
993 ;; Convert PDF to PNG images starting with the active pages.
994 (doc-view-pdf->png doc-view-buffer-file-name png-file pages
)))
996 ;; Convert to PNG images.
997 (doc-view-pdf/ps-
>png doc-view-buffer-file-name png-file
)))))
1001 (declare-function image-size
"image.c" (spec &optional pixels frame
))
1003 (defun doc-view-set-slice (x y width height
)
1004 "Set the slice of the images that should be displayed.
1005 You can use this function to tell doc-view not to display the
1006 margins of the document. It prompts for the top-left corner (X
1007 and Y) of the slice to display and its WIDTH and HEIGHT.
1009 See `doc-view-set-slice-using-mouse' and
1010 `doc-view-set-slice-from-bounding-box' for more convenient ways
1011 to do that. To reset the slice use `doc-view-reset-slice'."
1013 (let* ((size (image-size (doc-view-current-image) t
))
1014 (a (read-number (format "Top-left X (0..%d): " (car size
))))
1015 (b (read-number (format "Top-left Y (0..%d): " (cdr size
))))
1016 (c (read-number (format "Width (0..%d): " (- (car size
) a
))))
1017 (d (read-number (format "Height (0..%d): " (- (cdr size
) b
)))))
1019 (setf (doc-view-current-slice) (list x y width height
))
1021 (doc-view-goto-page (doc-view-current-page)))
1023 (defun doc-view-set-slice-using-mouse ()
1024 "Set the slice of the images that should be displayed.
1025 You set the slice by pressing mouse-1 at its top-left corner and
1026 dragging it to its bottom-right corner. See also
1027 `doc-view-set-slice' and `doc-view-reset-slice'."
1031 (let ((e (read-event
1032 (concat "Press mouse-1 at the top-left corner and "
1033 "drag it to the bottom-right corner!"))))
1034 (when (eq (car e
) 'drag-mouse-1
)
1035 (setq x
(car (posn-object-x-y (event-start e
))))
1036 (setq y
(cdr (posn-object-x-y (event-start e
))))
1037 (setq w
(- (car (posn-object-x-y (event-end e
))) x
))
1038 (setq h
(- (cdr (posn-object-x-y (event-end e
))) y
))
1040 (doc-view-set-slice x y w h
)))
1042 (defun doc-view-get-bounding-box ()
1043 "Get the BoundingBox information of the current page."
1044 (let* ((page (doc-view-current-page))
1045 (doc (let ((cache-doc (doc-view-current-cache-doc-pdf)))
1046 (if (file-exists-p cache-doc
)
1048 doc-view-buffer-file-name
)))
1049 (o (shell-command-to-string
1050 (concat doc-view-ghostscript-program
1051 " -dSAFER -dBATCH -dNOPAUSE -q -sDEVICE=bbox "
1052 (format "-dFirstPage=%s -dLastPage=%s %s"
1055 (when (string-match (concat "%%BoundingBox: "
1056 "\\([[:digit:]]+\\) \\([[:digit:]]+\\) "
1057 "\\([[:digit:]]+\\) \\([[:digit:]]+\\)") o
)
1058 (mapcar #'string-to-number
1059 (list (match-string 1 o
)
1062 (match-string 4 o
)))))))
1064 (defvar doc-view-paper-sizes
1066 (a4-landscape 842 595)
1068 (letter-landscape 792 612)
1070 (legal-landscape 1008 612)
1072 (a3-landscape 1191 842)
1075 "An alist from paper size names to dimensions.")
1077 (defun doc-view-guess-paper-size (iw ih
)
1078 "Guess the paper size according to the aspect ratio."
1079 (cl-labels ((div (x y
)
1080 (round (/ (* 100.0 x
) y
))))
1081 (let ((ar (div iw ih
))
1082 (al (mapcar (lambda (l)
1083 (list (div (nth 1 l
) (nth 2 l
)) (car l
)))
1084 doc-view-paper-sizes
)))
1085 (cadr (assoc ar al
)))))
1087 (defun doc-view-scale-bounding-box (ps iw ih bb
)
1088 (list (/ (* (nth 0 bb
) iw
) (nth 1 (assoc ps doc-view-paper-sizes
)))
1089 (/ (* (nth 1 bb
) ih
) (nth 2 (assoc ps doc-view-paper-sizes
)))
1090 (/ (* (nth 2 bb
) iw
) (nth 1 (assoc ps doc-view-paper-sizes
)))
1091 (/ (* (nth 3 bb
) ih
) (nth 2 (assoc ps doc-view-paper-sizes
)))))
1093 (defun doc-view-set-slice-from-bounding-box (&optional force-paper-size
)
1094 "Set the slice from the document's BoundingBox information.
1095 The result is that the margins are almost completely cropped,
1096 much more accurate than could be done manually using
1097 `doc-view-set-slice-using-mouse'."
1099 (let ((bb (doc-view-get-bounding-box)))
1101 (message "BoundingBox couldn't be determined")
1102 (let* ((is (image-size (doc-view-current-image) t
))
1105 (ps (or (and (null force-paper-size
) (doc-view-guess-paper-size iw ih
))
1106 (intern (completing-read "Paper size: "
1107 (mapcar #'car doc-view-paper-sizes
)
1109 (bb (doc-view-scale-bounding-box ps iw ih bb
))
1114 ;; We keep a 2 pixel margin.
1115 (doc-view-set-slice (- x1
2) (- ih y2
2)
1116 (+ (- x2 x1
) 4) (+ (- y2 y1
) 4))))))
1118 (defun doc-view-reset-slice ()
1119 "Reset the current slice.
1120 After calling this function whole pages will be visible again."
1122 (setf (doc-view-current-slice) nil
)
1124 (doc-view-goto-page (doc-view-current-page)))
1128 (defun doc-view-insert-image (file &rest args
)
1129 "Insert the given png FILE.
1130 ARGS is a list of image descriptors."
1131 (when doc-view-pending-cache-flush
1133 (setq doc-view-pending-cache-flush nil
))
1134 (let ((ol (doc-view-current-overlay))
1135 (image (if (and file
(file-readable-p file
))
1136 (if (not (fboundp 'imagemagick-types
))
1137 (apply 'create-image file
'png nil args
)
1138 (unless (member :width args
)
1139 (setq args
(append args
(list :width doc-view-image-width
))))
1140 (apply 'create-image file
'imagemagick nil args
))))
1141 (slice (doc-view-current-slice)))
1142 (setf (doc-view-current-image) image
)
1143 (move-overlay ol
(point-min) (point-max))
1144 (overlay-put ol
'display
1148 (list (cons 'slice slice
) image
)
1150 ;; We're trying to display a page that doesn't exist.
1151 (doc-view-current-converter-processes
1152 ;; Maybe the page doesn't exist *yet*.
1153 "Cannot display this page (yet)!")
1155 ;; Typically happens if the conversion process somehow
1156 ;; failed. Better not signal an error here because it
1157 ;; could prevent a subsequent reconversion from fixing
1159 (concat "Cannot display this page!\n"
1160 "Maybe because of a conversion failure!"))))
1161 (let ((win (overlay-get ol
'window
)))
1162 (if (stringp (overlay-get ol
'display
))
1163 (progn ;Make sure the text is not scrolled out of view.
1164 (set-window-hscroll win
0)
1165 (set-window-vscroll win
0))
1166 (let ((hscroll (image-mode-window-get 'hscroll win
))
1167 (vscroll (image-mode-window-get 'vscroll win
)))
1168 ;; Reset scroll settings, in case they were changed.
1169 (if hscroll
(set-window-hscroll win hscroll
))
1170 (if vscroll
(set-window-vscroll win vscroll
)))))))
1172 (defun doc-view-sort (a b
)
1173 "Return non-nil if A should be sorted before B.
1174 Predicate for sorting `doc-view-current-files'."
1175 (or (< (length a
) (length b
))
1176 (and (= (length a
) (length b
))
1179 (defun doc-view-display (buffer &optional force
)
1180 "Start viewing the document in BUFFER.
1181 If FORCE is non-nil, start viewing even if the document does not
1182 have the page we want to view."
1183 (with-current-buffer buffer
1184 (let ((prev-pages doc-view-current-files
))
1185 (setq doc-view-current-files
1186 (sort (directory-files (doc-view-current-cache-dir) t
1187 "page-[0-9]+\\.png" t
)
1189 (dolist (win (or (get-buffer-window-list buffer nil t
)
1191 (let* ((page (doc-view-current-page win
))
1192 (pagefile (expand-file-name (format "page-%d.png" page
)
1193 (doc-view-current-cache-dir))))
1195 (and (not (member pagefile prev-pages
))
1196 (member pagefile doc-view-current-files
)))
1198 (with-selected-window win
1199 (cl-assert (eq (current-buffer) buffer
) t
)
1200 (doc-view-goto-page page
))
1201 (doc-view-goto-page page
))))))))
1203 (defun doc-view-buffer-message ()
1204 ;; Only show this message initially, not when refreshing the buffer (in which
1205 ;; case it's better to keep displaying the "stale" page while computing
1206 ;; the fresh new ones).
1207 (unless (overlay-get (doc-view-current-overlay) 'display
)
1208 (overlay-put (doc-view-current-overlay) 'display
1209 (concat (propertize "Welcome to DocView!" 'face
'bold
)
1212 If you see this buffer it means that the document you want to view is being
1213 converted to PNG and the conversion of the first page hasn't finished yet or
1214 `doc-view-conversion-refresh-interval' is set to nil.
1216 For now these keys are useful:
1218 `q' : Bury this buffer. Conversion will go on in background.
1219 `k' : Kill the conversion process and this buffer.
1220 `K' : Kill the conversion process.\n"))))
1222 (declare-function tooltip-show
"tooltip" (text &optional use-echo-area
))
1224 (defun doc-view-show-tooltip ()
1226 (tooltip-show (doc-view-current-info)))
1228 (defun doc-view-open-text ()
1229 "Open a buffer with the current doc's contents as text."
1231 (if doc-view-current-converter-processes
1232 (message "DocView: please wait till conversion finished.")
1233 (let ((txt (expand-file-name "doc.txt" (doc-view-current-cache-dir))))
1234 (if (file-readable-p txt
)
1235 (let ((name (concat "Text contents of "
1236 (file-name-nondirectory buffer-file-name
)))
1237 (dir (file-name-directory buffer-file-name
)))
1238 (with-current-buffer (find-file txt
)
1239 (rename-buffer name
)
1240 (setq default-directory dir
)))
1241 (doc-view-doc->txt txt
'doc-view-open-text
)))))
1243 ;;;;; Toggle between editing and viewing
1245 (defvar-local doc-view-saved-settings nil
1246 "Doc-view settings saved while in some other mode.")
1247 (put 'doc-view-saved-settings
'permanent-local t
)
1249 (defun doc-view-toggle-display ()
1250 "Toggle between editing a document as text or viewing it."
1252 (if (eq major-mode
'doc-view-mode
)
1253 ;; Switch to editing mode
1255 (doc-view-kill-proc)
1256 (setq buffer-read-only nil
)
1257 (remove-overlays (point-min) (point-max) 'doc-view t
)
1258 (set (make-local-variable 'image-mode-winprops-alist
) t
)
1259 ;; Switch to the previously used major mode or fall back to
1261 (doc-view-fallback-mode)
1262 (doc-view-minor-mode 1))
1263 ;; Switch to doc-view-mode
1264 (when (and (buffer-modified-p)
1265 (y-or-n-p "The buffer has been modified. Save the changes? "))
1272 (defun doc-view-search-internal (regexp file
)
1273 "Return a list of FILE's pages that contain text matching REGEXP.
1274 The value is an alist of the form (PAGE CONTEXTS) where PAGE is
1275 the pagenumber and CONTEXTS are all lines of text containing a match."
1277 (insert-file-contents file
)
1281 (while (re-search-forward (concat "\\(?:\\([\f]\\)\\|\\("
1282 regexp
"\\)\\)") nil t
)
1283 (when (match-string 1) (setq page
(1+ page
)))
1284 (when (match-string 2)
1285 (if (/= page lastpage
)
1287 (list (buffer-substring
1288 (line-beginning-position)
1289 (line-end-position))))
1294 ;; This page already is a match.
1296 ;; This is the first match on page.
1298 (list (buffer-substring
1299 (line-beginning-position)
1300 (line-end-position))))
1302 (setq lastpage page
)))
1303 (nreverse matches
))))
1305 (defun doc-view-search-no-of-matches (list)
1306 "Extract the number of matches from the search result LIST."
1309 (setq no
(+ no
(1- (length p
)))))
1312 (defun doc-view-search-backward (new-query)
1313 "Call `doc-view-search' for backward search.
1314 If prefix NEW-QUERY is given, ask for a new regexp."
1316 (doc-view-search new-query t
))
1318 (defun doc-view-search (new-query &optional backward
)
1319 "Jump to the next match or initiate a new search if NEW-QUERY is given.
1320 If the current document hasn't been transformed to plain text
1321 till now do that first.
1322 If BACKWARD is non-nil, jump to the previous match."
1324 (if (and (not new-query
)
1325 doc-view-current-search-matches
)
1327 (doc-view-search-previous-match 1)
1328 (doc-view-search-next-match 1))
1329 ;; New search, so forget the old results.
1330 (setq doc-view-current-search-matches nil
)
1331 (let ((txt (expand-file-name "doc.txt"
1332 (doc-view-current-cache-dir))))
1333 (if (file-readable-p txt
)
1335 (setq doc-view-current-search-matches
1336 (doc-view-search-internal
1337 (read-from-minibuffer "Regexp: ")
1339 (message "DocView: search yielded %d matches."
1340 (doc-view-search-no-of-matches
1341 doc-view-current-search-matches
)))
1342 ;; We must convert to TXT first!
1343 (if doc-view-current-converter-processes
1344 (message "DocView: please wait till conversion finished.")
1345 (doc-view-doc->txt txt
(lambda () (doc-view-search nil
))))))))
1347 (defun doc-view-search-next-match (arg)
1348 "Go to the ARGth next matching page."
1350 (let* ((next-pages (doc-view-remove-if
1351 (lambda (i) (<= (car i
) (doc-view-current-page)))
1352 doc-view-current-search-matches
))
1353 (page (car (nth (1- arg
) next-pages
))))
1355 (doc-view-goto-page page
)
1357 doc-view-current-search-matches
1358 (y-or-n-p "No more matches after current page. Wrap to first match? "))
1359 (doc-view-goto-page (caar doc-view-current-search-matches
))))))
1361 (defun doc-view-search-previous-match (arg)
1362 "Go to the ARGth previous matching page."
1364 (let* ((prev-pages (doc-view-remove-if
1365 (lambda (i) (>= (car i
) (doc-view-current-page)))
1366 doc-view-current-search-matches
))
1367 (page (car (nth (1- arg
) (nreverse prev-pages
)))))
1369 (doc-view-goto-page page
)
1371 doc-view-current-search-matches
1372 (y-or-n-p "No more matches before current page. Wrap to last match? "))
1373 (doc-view-goto-page (caar (last doc-view-current-search-matches
)))))))
1375 ;;;; User interface commands and the mode
1377 (put 'doc-view-mode
'mode-class
'special
)
1379 (defun doc-view-already-converted-p ()
1380 "Return non-nil if the current doc was already converted."
1381 (and (file-exists-p (doc-view-current-cache-dir))
1382 ;; Check that the resolution info is there, otherwise it means
1383 ;; the conversion is incomplete.
1384 (file-readable-p (expand-file-name "resolution.el"
1385 (doc-view-current-cache-dir)))
1386 (> (length (directory-files (doc-view-current-cache-dir)
1390 (defun doc-view-initiate-display ()
1391 ;; Switch to image display if possible
1392 (if (doc-view-mode-p doc-view-doc-type
)
1394 (doc-view-buffer-message)
1395 (setf (doc-view-current-page) (or (doc-view-current-page) 1))
1396 (if (doc-view-already-converted-p)
1398 (message "DocView: using cached files!")
1399 ;; Load the saved resolution
1400 (let* ((res-file (expand-file-name "resolution.el"
1401 (doc-view-current-cache-dir)))
1404 (when (file-readable-p res-file
)
1405 (insert-file-contents res-file
)
1406 (read (current-buffer))))))
1408 (set (make-local-variable 'doc-view-resolution
) res
)))
1409 (doc-view-display (current-buffer) 'force
))
1410 (doc-view-convert-current-doc))
1413 (substitute-command-keys
1414 (concat "Type \\[doc-view-toggle-display] to toggle between "
1415 "editing or viewing the document."))))
1418 (concat "No PNG support is available, or some conversion utility for "
1419 (file-name-extension doc-view-buffer-file-name
)
1420 " files is missing."))
1421 (when (and (executable-find doc-view-pdftotext-program
)
1423 "Unable to render file. View extracted text instead? "))
1424 (doc-view-open-text))
1425 (doc-view-toggle-display)))
1427 (defvar bookmark-make-record-function
)
1429 (defun doc-view-clone-buffer-hook ()
1430 ;; FIXME: There are several potential problems linked with reconversion
1431 ;; and auto-revert when we have indirect buffers because they share their
1432 ;; /tmp cache directory. This sharing is good (you'd rather not reconvert
1433 ;; for each clone), but that means that clones need to collaborate a bit.
1434 ;; I guess it mostly means: detect when a reconversion process is already
1435 ;; running, and run the sentinel in all clones.
1437 ;; Maybe the clones should really have a separate /tmp directory
1438 ;; so they could have a different resolution and you could use clones
1440 (remove-overlays (point-min) (point-max) 'doc-view t
)
1441 (if (consp image-mode-winprops-alist
) (setq image-mode-winprops-alist nil
)))
1443 (defun doc-view-intersection (l1 l2
)
1445 (dolist (x l1
) (if (memq x l2
) (push x l
)))
1448 (defun doc-view-set-doc-type ()
1449 "Figure out the current document type (`doc-view-doc-type')."
1451 (when buffer-file-name
1452 (cdr (assoc (file-name-extension buffer-file-name
)
1457 ("pdf" pdf
) ("epdf" pdf
)
1459 ("ps" ps
) ("eps" ps
)
1460 ;; OpenDocument formats
1461 ("odt" odf
) ("ods" odf
) ("odp" odf
) ("odg" odf
)
1462 ("odc" odf
) ("odi" odf
) ("odm" odf
) ("ott" odf
)
1463 ("ots" odf
) ("otp" odf
) ("otg" odf
)
1464 ;; Microsoft Office formats (also handled
1465 ;; by the odf conversion chain)
1466 ("doc" odf
) ("docx" odf
) ("xls" odf
) ("xlsx" odf
)
1467 ("ppt" odf
) ("pptx" odf
))))))
1470 (goto-char (point-min))
1472 ((looking-at "%!") '(ps))
1473 ((looking-at "%PDF") '(pdf))
1474 ((looking-at "\367\002") '(dvi))))))
1475 (set (make-local-variable 'doc-view-doc-type
)
1476 (car (or (doc-view-intersection name-types content-types
)
1477 (when (and name-types content-types
)
1478 (error "Conflicting types: name says %s but content says %s"
1479 name-types content-types
))
1480 name-types content-types
1481 (error "Cannot determine the document type"))))))
1484 (defun doc-view-mode ()
1485 "Major mode in DocView buffers.
1487 DocView Mode is an Emacs document viewer. It displays PDF, PS
1488 and DVI files (as PNG images) in Emacs buffers.
1490 You can use \\<doc-view-mode-map>\\[doc-view-toggle-display] to
1491 toggle between displaying the document or editing it as text.
1492 \\{doc-view-mode-map}"
1495 (if (= (point-min) (point-max))
1496 ;; The doc is empty or doesn't exist at all, so fallback to
1497 ;; another mode. We used to also check file-exists-p, but this
1498 ;; returns nil for tar members.
1499 (doc-view-fallback-mode)
1501 (let* ((prev-major-mode (if (derived-mode-p 'doc-view-mode
)
1502 doc-view-previous-major-mode
1503 (unless (eq major-mode
'fundamental-mode
)
1505 (kill-all-local-variables)
1506 (set (make-local-variable 'doc-view-previous-major-mode
)
1509 (dolist (var doc-view-saved-settings
)
1510 (set (make-local-variable (car var
)) (cdr var
)))
1512 ;; Figure out the document type.
1513 (unless doc-view-doc-type
1514 (doc-view-set-doc-type))
1516 (doc-view-make-safe-dir doc-view-cache-directory
)
1517 ;; Handle compressed files, remote files, files inside archives
1518 (set (make-local-variable 'doc-view-buffer-file-name
)
1520 (jka-compr-really-do-compress
1521 ;; FIXME: there's a risk of name conflicts here.
1523 (file-name-nondirectory
1524 (file-name-sans-extension buffer-file-name
))
1525 doc-view-cache-directory
))
1526 ;; Is the file readable by local processes?
1527 ;; We used to use `file-remote-p' but it's unclear what it's
1528 ;; supposed to return nil for things like local files accessed via
1529 ;; `su' or via file://...
1530 ((let ((file-name-handler-alist nil
))
1531 (not (and buffer-file-name
(file-readable-p buffer-file-name
))))
1532 ;; FIXME: there's a risk of name conflicts here.
1534 (if buffer-file-name
1535 (file-name-nondirectory buffer-file-name
)
1537 doc-view-cache-directory
))
1538 (t buffer-file-name
)))
1539 (when (not (string= doc-view-buffer-file-name buffer-file-name
))
1540 (write-region nil nil doc-view-buffer-file-name
))
1542 (add-hook 'change-major-mode-hook
1544 (doc-view-kill-proc)
1545 (remove-overlays (point-min) (point-max) 'doc-view t
))
1547 (add-hook 'clone-indirect-buffer-hook
'doc-view-clone-buffer-hook nil t
)
1548 (add-hook 'kill-buffer-hook
'doc-view-kill-proc nil t
)
1550 (remove-overlays (point-min) (point-max) 'doc-view t
) ;Just in case.
1551 ;; Keep track of display info ([vh]scroll, page number, overlay,
1552 ;; ...) for each window in which this document is shown.
1553 (add-hook 'image-mode-new-window-functions
1554 'doc-view-new-window-function nil t
)
1555 (image-mode-setup-winprops)
1557 (set (make-local-variable 'mode-line-position
)
1558 '(" P" (:eval
(number-to-string (doc-view-current-page)))
1559 "/" (:eval
(number-to-string (doc-view-last-page-number)))))
1560 ;; Don't scroll unless the user specifically asked for it.
1561 (set (make-local-variable 'auto-hscroll-mode
) nil
)
1562 (set (make-local-variable 'mwheel-scroll-up-function
)
1563 'doc-view-scroll-up-or-next-page
)
1564 (set (make-local-variable 'mwheel-scroll-down-function
)
1565 'doc-view-scroll-down-or-previous-page
)
1566 (set (make-local-variable 'cursor-type
) nil
)
1567 (use-local-map doc-view-mode-map
)
1568 (set (make-local-variable 'after-revert-hook
) 'doc-view-reconvert-doc
)
1569 (set (make-local-variable 'bookmark-make-record-function
)
1570 'doc-view-bookmark-make-record
)
1571 (setq mode-name
"DocView"
1573 major-mode
'doc-view-mode
)
1574 (doc-view-initiate-display)
1575 ;; Switch off view-mode explicitly, because doc-view-mode is the
1576 ;; canonical view mode for PDF/PS/DVI files. This could be
1577 ;; switched on automatically depending on the value of
1578 ;; `view-read-only'.
1579 (set (make-local-variable 'view-read-only
) nil
)
1580 (run-mode-hooks 'doc-view-mode-hook
)))
1582 (defun doc-view-fallback-mode ()
1583 "Fallback to the previous or next best major mode."
1584 (let ((vars (if (derived-mode-p 'doc-view-mode
)
1585 (mapcar (lambda (var) (cons var
(symbol-value var
)))
1586 '(doc-view-resolution
1587 image-mode-winprops-alist
)))))
1588 (if doc-view-previous-major-mode
1589 (funcall doc-view-previous-major-mode
)
1590 (let ((auto-mode-alist
1592 'doc-view-mode-maybe
1593 (rassq-delete-all 'doc-view-mode
1594 (copy-alist auto-mode-alist
)))))
1597 (setq-local doc-view-saved-settings vars
))))
1600 (defun doc-view-mode-maybe ()
1601 "Switch to `doc-view-mode' if possible.
1602 If the required external tools are not available, then fallback
1603 to the next best mode."
1605 (doc-view-set-doc-type)
1606 (error (doc-view-fallback-mode)))
1607 (if (doc-view-mode-p doc-view-doc-type
)
1609 (doc-view-fallback-mode)))
1612 (define-minor-mode doc-view-minor-mode
1613 "Toggle displaying buffer via Doc View (Doc View minor mode).
1614 With a prefix argument ARG, enable Doc View minor mode if ARG is
1615 positive, and disable it otherwise. If called from Lisp, enable
1616 the mode if ARG is omitted or nil.
1618 See the command `doc-view-mode' for more information on this mode."
1619 nil
" DocView" doc-view-minor-mode-map
1621 (when doc-view-minor-mode
1622 (add-hook 'change-major-mode-hook
(lambda () (doc-view-minor-mode -
1)) nil t
)
1625 (substitute-command-keys
1626 "Type \\[doc-view-toggle-display] to toggle between editing or viewing the document."))))
1628 (defun doc-view-clear-cache ()
1629 "Delete the whole cache (`doc-view-cache-directory')."
1631 (dired-delete-file doc-view-cache-directory
'always
))
1633 (defun doc-view-dired-cache ()
1634 "Open `dired' in `doc-view-cache-directory'."
1636 (dired doc-view-cache-directory
))
1639 ;;;; Bookmark integration
1641 (declare-function bookmark-make-record-default
1642 "bookmark" (&optional no-file no-context posn
))
1643 (declare-function bookmark-prop-get
"bookmark" (bookmark prop
))
1644 (declare-function bookmark-default-handler
"bookmark" (bmk))
1646 (defun doc-view-bookmark-make-record ()
1647 (nconc (bookmark-make-record-default)
1648 `((page .
,(doc-view-current-page))
1649 (handler . doc-view-bookmark-jump
))))
1653 (defun doc-view-bookmark-jump (bmk)
1654 ;; This implements the `handler' function interface for record type
1655 ;; returned by `doc-view-bookmark-make-record', which see.
1656 (prog1 (bookmark-default-handler bmk
)
1657 (let ((page (bookmark-prop-get bmk
'page
)))
1658 (when (not (eq major-mode
'doc-view-mode
))
1659 (doc-view-toggle-display))
1660 (with-selected-window
1661 (or (get-buffer-window (current-buffer) 0)
1663 (doc-view-goto-page page
)))))
1669 ;; eval: (outline-minor-mode 1)
1672 ;;; doc-view.el ends here