* lisp/vc/vc-svn.el (vc-svn-diff): Use `diff-command' instead of the
[emacs.git] / lisp / doc-view.el
blobc67205fd52b2ee3ac1a22fed33bf8873ec2f5a8e
1 ;;; doc-view.el --- View PDF/PostScript/DVI files in Emacs
3 ;; Copyright (C) 2007-2011 Free Software Foundation, Inc.
4 ;;
5 ;; Author: Tassilo Horn <tassilo@member.fsf.org>
6 ;; Maintainer: Tassilo Horn <tassilo@member.fsf.org>
7 ;; Keywords: files, pdf, ps, dvi
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24 ;;; Requirements:
26 ;; doc-view.el requires GNU Emacs 22.1 or newer. You also need Ghostscript,
27 ;; `dvipdf' (comes with Ghostscript) or `dvipdfm' (comes with teTeX or TeXLive)
28 ;; and `pdftotext', which comes with xpdf (http://www.foolabs.com/xpdf/) or
29 ;; poppler (http://poppler.freedesktop.org/).
31 ;;; Commentary:
33 ;; DocView is a document viewer for Emacs. It converts PDF, PS and DVI files
34 ;; to a set of PNG files, one PNG for each page, and displays the PNG images
35 ;; inside an Emacs buffer. This buffer uses `doc-view-mode' which provides
36 ;; convenient key bindings for browsing the document.
38 ;; To use it simply open a document file with
40 ;; C-x C-f ~/path/to/document RET
42 ;; and the document will be converted and displayed, if your emacs supports png
43 ;; images. With `C-c C-c' you can toggle between the rendered images
44 ;; representation and the source text representation of the document.
46 ;; Since conversion may take some time all the PNG images are cached in a
47 ;; subdirectory of `doc-view-cache-directory' and reused when you want to view
48 ;; that file again. To reconvert a document hit `g' (`doc-view-reconvert-doc')
49 ;; when displaying the document. To delete all cached files use
50 ;; `doc-view-clear-cache'. To open the cache with dired, so that you can tidy
51 ;; it out use `doc-view-dired-cache'.
53 ;; When conversion in underway the first page will be displayed as soon as it
54 ;; is available and the available pages are refreshed every
55 ;; `doc-view-conversion-refresh-interval' seconds. If that variable is nil the
56 ;; pages won't be displayed before conversion of the document finished
57 ;; completely.
59 ;; DocView lets you select a slice of the displayed pages. This slice will be
60 ;; remembered and applied to all pages of the current document. This enables
61 ;; you to cut away the margins of a document to save some space. To select a
62 ;; slice you can use `doc-view-set-slice' (bound to `s s') which will query you
63 ;; for the coordinates of the slice's top-left corner and its width and height.
64 ;; A much more convenient way to do the same is offered by the command
65 ;; `doc-view-set-slice-using-mouse' (bound to `s m'). After invocation you
66 ;; only have to press mouse-1 at the top-left corner and drag it to the
67 ;; bottom-right corner of the desired slice. To reset the slice use
68 ;; `doc-view-reset-slice' (bound to `s r').
70 ;; You can also search within the document. The command `doc-view-search'
71 ;; (bound to `C-s') queries for a search regexp and initializes a list of all
72 ;; matching pages and messages how many match-pages were found. After that you
73 ;; can jump to the next page containing a match with an additional `C-s'. With
74 ;; `C-r' you can do the same, but backwards. To search for a new regexp give a
75 ;; prefix arg to one of the search functions, e.g. by typing `C-u C-s'. The
76 ;; searching works by using a plain text representation of the document. If
77 ;; that doesn't already exist the first invocation of `doc-view-search' (or
78 ;; `doc-view-search-backward') starts the conversion. When that finishes and
79 ;; you're still viewing the document (i.e. you didn't switch to another buffer)
80 ;; you're queried for the regexp then.
82 ;; Dired users can simply hit `v' on a document file. If it's a PS, PDF or DVI
83 ;; it will be opened using `doc-view-mode'.
86 ;;; Configuration:
88 ;; If the images are too small or too big you should set the "-rXXX" option in
89 ;; `doc-view-ghostscript-options' to another value. (The bigger your screen,
90 ;; the higher the value.)
92 ;; This and all other options can be set with the customization interface.
93 ;; Simply do
95 ;; M-x customize-group RET doc-view RET
97 ;; and modify them to your needs.
99 ;;; Todo:
101 ;; - add print command.
102 ;; - share more code with image-mode.
103 ;; - better menu.
104 ;; - Bind slicing to a drag event.
105 ;; - doc-view-fit-doc-to-window and doc-view-fit-window-to-doc?
106 ;; - zoom the region around the cursor (like xdvi).
107 ;; - get rid of the silly arrow in the fringe.
108 ;; - improve anti-aliasing (pdf-utils gets it better).
110 ;;;; About isearch support
112 ;; I tried implementing isearch by setting
113 ;; `isearch-search-fun-function' buffer-locally, but that didn't
114 ;; work too good. The function doing the real search was called
115 ;; endlessly somehow. But even if we'd get that working no real
116 ;; isearch feeling comes up due to the missing match highlighting.
117 ;; Currently I display all lines containing a match in a tooltip and
118 ;; each C-s or C-r jumps directly to the next/previous page with a
119 ;; match. With isearch we could only display the current match. So
120 ;; we had to decide if another C-s jumps to the next page with a
121 ;; match (thus only the first match in a page will be displayed in a
122 ;; tooltip) or to the next match, which would do nothing visible
123 ;; (except the tooltip) if the next match is on the same page.
125 ;; And it's much slower than the current search facility, because
126 ;; isearch really searches for each step forward or backward wheras
127 ;; the current approach searches once and then it knows to which
128 ;; pages to jump.
130 ;; Anyway, if someone with better isearch knowledge wants to give it a try,
131 ;; feel free to do it. --Tassilo
133 ;;; Code:
135 (eval-when-compile (require 'cl))
136 (require 'dired)
137 (require 'image-mode)
138 (require 'jka-compr)
140 ;;;; Customization Options
142 (defgroup doc-view nil
143 "In-buffer viewer for PDF, PostScript and DVI files."
144 :link '(function-link doc-view)
145 :version "22.2"
146 :group 'applications
147 :group 'data
148 :group 'multimedia
149 :prefix "doc-view-")
151 (defcustom doc-view-ghostscript-program (executable-find "gs")
152 "Program to convert PS and PDF files to PNG."
153 :type 'file
154 :group 'doc-view)
156 (defcustom doc-view-ghostscript-options
157 '("-dSAFER" ;; Avoid security problems when rendering files from untrusted
158 ;; sources.
159 "-dNOPAUSE" "-sDEVICE=png16m" "-dTextAlphaBits=4"
160 "-dBATCH" "-dGraphicsAlphaBits=4" "-dQUIET")
161 "A list of options to give to ghostscript."
162 :type '(repeat string)
163 :group 'doc-view)
165 (defcustom doc-view-resolution 100
166 "Dots per inch resolution used to render the documents.
167 Higher values result in larger images."
168 :type 'number
169 :group 'doc-view)
171 (defcustom doc-view-image-width 850
172 "Default image width.
173 Has only an effect if imagemagick support is compiled into emacs."
174 :type 'number
175 :group 'doc-view)
177 (defcustom doc-view-dvipdfm-program (executable-find "dvipdfm")
178 "Program to convert DVI files to PDF.
180 DVI file will be converted to PDF before the resulting PDF is
181 converted to PNG.
183 If this and `doc-view-dvipdf-program' are set,
184 `doc-view-dvipdf-program' will be preferred."
185 :type 'file
186 :group 'doc-view)
188 (defcustom doc-view-dvipdf-program (executable-find "dvipdf")
189 "Program to convert DVI files to PDF.
191 DVI file will be converted to PDF before the resulting PDF is
192 converted to PNG.
194 If this and `doc-view-dvipdfm-program' are set,
195 `doc-view-dvipdf-program' will be preferred."
196 :type 'file
197 :group 'doc-view)
199 (defcustom doc-view-unoconv-program (executable-find "unoconv")
200 "Program to convert any file type readable by OpenOffice.org to PDF.
202 Needed for viewing OpenOffice.org (and MS Office) files."
203 :type 'file
204 :group 'doc-view)
206 (defcustom doc-view-ps2pdf-program (executable-find "ps2pdf")
207 "Program to convert PS files to PDF.
209 PS files will be converted to PDF before searching is possible."
210 :type 'file
211 :group 'doc-view)
213 (defcustom doc-view-pdftotext-program (executable-find "pdftotext")
214 "Program to convert PDF files to plain text.
216 Needed for searching."
217 :type 'file
218 :group 'doc-view)
220 (defcustom doc-view-cache-directory
221 (expand-file-name (format "docview%d" (user-uid))
222 temporary-file-directory)
223 "The base directory, where the PNG images will be saved."
224 :type 'directory
225 :group 'doc-view)
227 (defvar doc-view-conversion-buffer " *doc-view conversion output*"
228 "The buffer where messages from the converter programs go to.")
230 (defcustom doc-view-conversion-refresh-interval 1
231 "Interval in seconds between refreshes of the DocView buffer while converting.
232 After such a refresh newly converted pages will be available for
233 viewing. If set to nil there won't be any refreshes and the
234 pages won't be displayed before conversion of the whole document
235 has finished."
236 :type 'integer
237 :group 'doc-view)
239 (defcustom doc-view-continuous nil
240 "In Continuous mode reaching the page edge advances to next/previous page.
241 When non-nil, scrolling a line upward at the bottom edge of the page
242 moves to the next page, and scrolling a line downward at the top edge
243 of the page moves to the previous page."
244 :type 'boolean
245 :group 'doc-view
246 :version "23.2")
248 ;;;; Internal Variables
250 (defun doc-view-new-window-function (winprops)
251 (let ((ol (image-mode-window-get 'overlay winprops)))
252 (when (and ol (not (overlay-buffer ol)))
253 ;; I've seen `ol' be a dead overlay. I do not yet know how this
254 ;; happened, so maybe the bug is elsewhere, but in the mean time,
255 ;; this seems like a safe approach.
256 (setq ol nil))
257 (if ol
258 (progn
259 (assert (eq (overlay-buffer ol) (current-buffer)))
260 (setq ol (copy-overlay ol)))
261 (assert (not (get-char-property (point-min) 'display)))
262 (setq ol (make-overlay (point-min) (point-max) nil t))
263 (overlay-put ol 'doc-view t))
264 (overlay-put ol 'window (car winprops))
265 (image-mode-window-put 'overlay ol winprops)))
267 (defvar doc-view-current-files nil
268 "Only used internally.")
269 (make-variable-buffer-local 'doc-view-current-files)
271 (defvar doc-view-current-converter-processes nil
272 "Only used internally.")
273 (make-variable-buffer-local 'doc-view-current-converter-processes)
275 (defvar doc-view-current-timer nil
276 "Only used internally.")
277 (make-variable-buffer-local 'doc-view-current-timer)
279 (defvar doc-view-current-cache-dir nil
280 "Only used internally.")
281 (make-variable-buffer-local 'doc-view-current-cache-dir)
283 (defvar doc-view-current-search-matches nil
284 "Only used internally.")
285 (make-variable-buffer-local 'doc-view-current-search-matches)
287 (defvar doc-view-pending-cache-flush nil
288 "Only used internally.")
290 (defvar doc-view-previous-major-mode nil
291 "Only used internally.")
293 (defvar doc-view-buffer-file-name nil
294 "Only used internally.
295 The file name used for conversion. Normally it's the same as
296 `buffer-file-name', but for remote files, compressed files and
297 files inside an archive it is a temporary copy of
298 the (uncompressed, extracted) file residing in
299 `doc-view-cache-directory'.")
301 (defvar doc-view-doc-type nil
302 "The type of document in the current buffer.
303 Can be `dvi', `pdf', or `ps'.")
305 ;;;; DocView Keymaps
307 (defvar doc-view-mode-map
308 (let ((map (make-sparse-keymap)))
309 (set-keymap-parent map image-mode-map)
310 ;; Navigation in the document
311 (define-key map (kbd "n") 'doc-view-next-page)
312 (define-key map (kbd "p") 'doc-view-previous-page)
313 (define-key map (kbd "<next>") 'forward-page)
314 (define-key map (kbd "<prior>") 'backward-page)
315 (define-key map [remap forward-page] 'doc-view-next-page)
316 (define-key map [remap backward-page] 'doc-view-previous-page)
317 (define-key map (kbd "SPC") 'doc-view-scroll-up-or-next-page)
318 (define-key map (kbd "DEL") 'doc-view-scroll-down-or-previous-page)
319 (define-key map (kbd "C-n") 'doc-view-next-line-or-next-page)
320 (define-key map (kbd "<down>") 'doc-view-next-line-or-next-page)
321 (define-key map (kbd "C-p") 'doc-view-previous-line-or-previous-page)
322 (define-key map (kbd "<up>") 'doc-view-previous-line-or-previous-page)
323 (define-key map (kbd "M-<") 'doc-view-first-page)
324 (define-key map (kbd "M->") 'doc-view-last-page)
325 (define-key map [remap goto-line] 'doc-view-goto-page)
326 (define-key map (kbd "RET") 'image-next-line)
327 ;; Zoom in/out.
328 (define-key map "+" 'doc-view-enlarge)
329 (define-key map "-" 'doc-view-shrink)
330 ;; Killing the buffer (and the process)
331 (define-key map (kbd "k") 'doc-view-kill-proc-and-buffer)
332 (define-key map (kbd "K") 'doc-view-kill-proc)
333 ;; Slicing the image
334 (define-key map (kbd "s s") 'doc-view-set-slice)
335 (define-key map (kbd "s m") 'doc-view-set-slice-using-mouse)
336 (define-key map (kbd "s r") 'doc-view-reset-slice)
337 ;; Searching
338 (define-key map (kbd "C-s") 'doc-view-search)
339 (define-key map (kbd "<find>") 'doc-view-search)
340 (define-key map (kbd "C-r") 'doc-view-search-backward)
341 ;; Show the tooltip
342 (define-key map (kbd "C-t") 'doc-view-show-tooltip)
343 ;; Toggle between text and image display or editing
344 (define-key map (kbd "C-c C-c") 'doc-view-toggle-display)
345 ;; Open a new buffer with doc's text contents
346 (define-key map (kbd "C-c C-t") 'doc-view-open-text)
347 ;; Reconvert the current document. Don't just use revert-buffer
348 ;; because that resets the scale factor, the page number, ...
349 (define-key map (kbd "g") 'doc-view-revert-buffer)
350 (define-key map (kbd "r") 'doc-view-revert-buffer)
351 map)
352 "Keymap used by `doc-view-mode' when displaying a doc as a set of images.")
354 (defun doc-view-revert-buffer (&optional ignore-auto noconfirm)
355 "Like `revert-buffer', but preserves the buffer's current modes."
356 ;; FIXME: this should probably be moved to files.el and used for
357 ;; most/all "g" bindings to revert-buffer.
358 (interactive (list (not current-prefix-arg)))
359 (revert-buffer ignore-auto noconfirm 'preserve-modes))
362 (easy-menu-define doc-view-menu doc-view-mode-map
363 "Menu for Doc View mode."
364 '("DocView"
365 ["Toggle display" doc-view-toggle-display]
366 ("Continuous"
367 ["Off" (setq doc-view-continuous nil)
368 :style radio :selected (eq doc-view-continuous nil)]
369 ["On" (setq doc-view-continuous t)
370 :style radio :selected (eq doc-view-continuous t)]
371 "---"
372 ["Save as Default"
373 (customize-save-variable 'doc-view-continuous doc-view-continuous) t]
375 "---"
376 ["Set Slice" doc-view-set-slice-using-mouse]
377 ["Set Slice (manual)" doc-view-set-slice]
378 ["Reset Slice" doc-view-reset-slice]
379 "---"
380 ["Search" doc-view-search]
381 ["Search Backwards" doc-view-search-backward]
384 (defvar doc-view-minor-mode-map
385 (let ((map (make-sparse-keymap)))
386 ;; Toggle between text and image display or editing
387 (define-key map (kbd "C-c C-c") 'doc-view-toggle-display)
388 map)
389 "Keymap used by `doc-minor-view-mode'.")
391 ;;;; Navigation Commands
393 (defmacro doc-view-current-page (&optional win)
394 `(image-mode-window-get 'page ,win))
395 (defmacro doc-view-current-info () `(image-mode-window-get 'info))
396 (defmacro doc-view-current-overlay () `(image-mode-window-get 'overlay))
397 (defmacro doc-view-current-image () `(image-mode-window-get 'image))
398 (defmacro doc-view-current-slice () `(image-mode-window-get 'slice))
400 (defun doc-view-last-page-number ()
401 (length doc-view-current-files))
403 (defun doc-view-goto-page (page)
404 "View the page given by PAGE."
405 (interactive "nPage: ")
406 (let ((len (doc-view-last-page-number))
407 (hscroll (window-hscroll)))
408 (if (< page 1)
409 (setq page 1)
410 (when (and (> page len)
411 ;; As long as the converter is running, we don't know
412 ;; how many pages will be available.
413 (null doc-view-current-converter-processes))
414 (setq page len)))
415 (setf (doc-view-current-page) page
416 (doc-view-current-info)
417 (concat
418 (propertize
419 (format "Page %d of %d." page len) 'face 'bold)
420 ;; Tell user if converting isn't finished yet
421 (if doc-view-current-converter-processes
422 " (still converting...)\n"
423 "\n")
424 ;; Display context infos if this page matches the last search
425 (when (and doc-view-current-search-matches
426 (assq page doc-view-current-search-matches))
427 (concat (propertize "Search matches:\n" 'face 'bold)
428 (let ((contexts ""))
429 (dolist (m (cdr (assq page
430 doc-view-current-search-matches)))
431 (setq contexts (concat contexts " - \"" m "\"\n")))
432 contexts)))))
433 ;; Update the buffer
434 ;; We used to find the file name from doc-view-current-files but
435 ;; that's not right if the pages are not generated sequentially
436 ;; or if the page isn't in doc-view-current-files yet.
437 (let ((file (expand-file-name (format "page-%d.png" page)
438 (doc-view-current-cache-dir))))
439 (doc-view-insert-image file :pointer 'arrow)
440 (set-window-hscroll (selected-window) hscroll)
441 (when (and (not (file-exists-p file))
442 doc-view-current-converter-processes)
443 ;; The PNG file hasn't been generated yet.
444 (doc-view-pdf->png-1 doc-view-buffer-file-name file page
445 (lexical-let ((page page)
446 (win (selected-window))
447 (file file))
448 (lambda ()
449 (and (eq (current-buffer) (window-buffer win))
450 ;; If we changed page in the mean
451 ;; time, don't mess things up.
452 (eq (doc-view-current-page win) page)
453 ;; Make sure we don't infloop.
454 (file-readable-p file)
455 (with-selected-window win
456 (doc-view-goto-page page))))))))
457 (overlay-put (doc-view-current-overlay)
458 'help-echo (doc-view-current-info))))
460 (defun doc-view-next-page (&optional arg)
461 "Browse ARG pages forward."
462 (interactive "p")
463 (doc-view-goto-page (+ (doc-view-current-page) (or arg 1))))
465 (defun doc-view-previous-page (&optional arg)
466 "Browse ARG pages backward."
467 (interactive "p")
468 (doc-view-goto-page (- (doc-view-current-page) (or arg 1))))
470 (defun doc-view-first-page ()
471 "View the first page."
472 (interactive)
473 (doc-view-goto-page 1))
475 (defun doc-view-last-page ()
476 "View the last page."
477 (interactive)
478 (doc-view-goto-page (doc-view-last-page-number)))
480 (defun doc-view-scroll-up-or-next-page (&optional arg)
481 "Scroll page up ARG lines if possible, else goto next page.
482 When `doc-view-continuous' is non-nil, scrolling upward
483 at the bottom edge of the page moves to the next page.
484 Otherwise, goto next page only on typing SPC (ARG is nil)."
485 (interactive "P")
486 (if (or doc-view-continuous (null arg))
487 (let ((hscroll (window-hscroll))
488 (cur-page (doc-view-current-page)))
489 (when (= (window-vscroll) (image-scroll-up arg))
490 (doc-view-next-page)
491 (when (/= cur-page (doc-view-current-page))
492 (image-bob)
493 (image-bol 1))
494 (set-window-hscroll (selected-window) hscroll)))
495 (image-scroll-up arg)))
497 (defun doc-view-scroll-down-or-previous-page (&optional arg)
498 "Scroll page down ARG lines if possible, else goto previous page.
499 When `doc-view-continuous' is non-nil, scrolling downward
500 at the top edge of the page moves to the previous page.
501 Otherwise, goto previous page only on typing DEL (ARG is nil)."
502 (interactive "P")
503 (if (or doc-view-continuous (null arg))
504 (let ((hscroll (window-hscroll))
505 (cur-page (doc-view-current-page)))
506 (when (= (window-vscroll) (image-scroll-down arg))
507 (doc-view-previous-page)
508 (when (/= cur-page (doc-view-current-page))
509 (image-eob)
510 (image-bol 1))
511 (set-window-hscroll (selected-window) hscroll)))
512 (image-scroll-down arg)))
514 (defun doc-view-next-line-or-next-page (&optional arg)
515 "Scroll upward by ARG lines if possible, else goto next page.
516 When `doc-view-continuous' is non-nil, scrolling a line upward
517 at the bottom edge of the page moves to the next page."
518 (interactive "p")
519 (if doc-view-continuous
520 (let ((hscroll (window-hscroll))
521 (cur-page (doc-view-current-page)))
522 (when (= (window-vscroll) (image-next-line arg))
523 (doc-view-next-page)
524 (when (/= cur-page (doc-view-current-page))
525 (image-bob)
526 (image-bol 1))
527 (set-window-hscroll (selected-window) hscroll)))
528 (image-next-line 1)))
530 (defun doc-view-previous-line-or-previous-page (&optional arg)
531 "Scroll downward by ARG lines if possible, else goto previous page.
532 When `doc-view-continuous' is non-nil, scrolling a line downward
533 at the top edge of the page moves to the previous page."
534 (interactive "p")
535 (if doc-view-continuous
536 (let ((hscroll (window-hscroll))
537 (cur-page (doc-view-current-page)))
538 (when (= (window-vscroll) (image-previous-line arg))
539 (doc-view-previous-page)
540 (when (/= cur-page (doc-view-current-page))
541 (image-eob)
542 (image-bol 1))
543 (set-window-hscroll (selected-window) hscroll)))
544 (image-previous-line arg)))
546 ;;;; Utility Functions
548 (defun doc-view-kill-proc ()
549 "Kill the current converter process(es)."
550 (interactive)
551 (while (consp doc-view-current-converter-processes)
552 (ignore-errors ;; Maybe it's dead already?
553 (kill-process (pop doc-view-current-converter-processes))))
554 (when doc-view-current-timer
555 (cancel-timer doc-view-current-timer)
556 (setq doc-view-current-timer nil))
557 (setq mode-line-process nil))
559 (defun doc-view-kill-proc-and-buffer ()
560 "Kill the current converter process and buffer."
561 (interactive)
562 (doc-view-kill-proc)
563 (when (eq major-mode 'doc-view-mode)
564 (kill-buffer (current-buffer))))
566 (defun doc-view-make-safe-dir (dir)
567 (condition-case nil
568 (let ((umask (default-file-modes)))
569 (unwind-protect
570 (progn
571 ;; Create temp files with strict access rights. It's easy to
572 ;; loosen them later, whereas it's impossible to close the
573 ;; time-window of loose permissions otherwise.
574 (set-default-file-modes #o0700)
575 (make-directory dir))
576 ;; Reset the umask.
577 (set-default-file-modes umask)))
578 (file-already-exists
579 (if (file-symlink-p dir)
580 (error "Danger: %s points to a symbolic link" dir))
581 ;; In case it was created earlier with looser rights.
582 ;; We could check the mode info returned by file-attributes, but it's
583 ;; a pain to parse and it may not tell you what we want under
584 ;; non-standard file-systems. So let's just say what we want and let
585 ;; the underlying C code and file-system figure it out.
586 ;; This also ends up checking a bunch of useful conditions: it makes
587 ;; sure we have write-access to the directory and that we own it, thus
588 ;; closing a bunch of security holes.
589 (set-file-modes dir #o0700))))
591 (defun doc-view-current-cache-dir ()
592 "Return the directory where the png files of the current doc should be saved.
593 It's a subdirectory of `doc-view-cache-directory'."
594 (if doc-view-current-cache-dir
595 doc-view-current-cache-dir
596 ;; Try and make sure doc-view-cache-directory exists and is safe.
597 (doc-view-make-safe-dir doc-view-cache-directory)
598 ;; Now compute the subdirectory to use.
599 (setq doc-view-current-cache-dir
600 (file-name-as-directory
601 (expand-file-name
602 (concat (file-name-nondirectory doc-view-buffer-file-name)
604 (let ((file doc-view-buffer-file-name))
605 (with-temp-buffer
606 (set-buffer-multibyte nil)
607 (insert-file-contents-literally file)
608 (md5 (current-buffer)))))
609 doc-view-cache-directory)))))
611 (defun doc-view-remove-if (predicate list)
612 "Return LIST with all items removed that satisfy PREDICATE."
613 (let (new-list)
614 (dolist (item list (nreverse new-list))
615 (when (not (funcall predicate item))
616 (setq new-list (cons item new-list))))))
618 ;;;###autoload
619 (defun doc-view-mode-p (type)
620 "Return non-nil if document type TYPE is available for `doc-view'.
621 Document types are symbols like `dvi', `ps', `pdf', or `odf' (any
622 OpenDocument format)."
623 (and (display-graphic-p)
624 (or (image-type-available-p 'imagemagick)
625 (image-type-available-p 'png))
626 (cond
627 ((eq type 'dvi)
628 (and (doc-view-mode-p 'pdf)
629 (or (and doc-view-dvipdf-program
630 (executable-find doc-view-dvipdf-program))
631 (and doc-view-dvipdfm-program
632 (executable-find doc-view-dvipdfm-program)))))
633 ((or (eq type 'postscript) (eq type 'ps) (eq type 'eps)
634 (eq type 'pdf))
635 (and doc-view-ghostscript-program
636 (executable-find doc-view-ghostscript-program)))
637 ((eq type 'odf)
638 (and doc-view-unoconv-program
639 (executable-find doc-view-unoconv-program)
640 (doc-view-mode-p 'pdf)))
641 (t ;; unknown image type
642 nil))))
644 ;;;; Conversion Functions
646 (defvar doc-view-shrink-factor 1.125)
648 (defun doc-view-enlarge (factor)
649 "Enlarge the document."
650 (interactive (list doc-view-shrink-factor))
651 (if (eq (plist-get (cdr (doc-view-current-image)) :type)
652 'imagemagick)
653 ;; ImageMagick supports on-the-fly-rescaling
654 (progn
655 (set (make-local-variable 'doc-view-image-width)
656 (ceiling (* factor doc-view-image-width)))
657 (doc-view-insert-image (plist-get (cdr (doc-view-current-image)) :file)
658 :width doc-view-image-width))
659 (set (make-local-variable 'doc-view-resolution)
660 (ceiling (* factor doc-view-resolution)))
661 (doc-view-reconvert-doc)))
663 (defun doc-view-shrink (factor)
664 "Shrink the document."
665 (interactive (list doc-view-shrink-factor))
666 (doc-view-enlarge (/ 1.0 factor)))
668 (defun doc-view-reconvert-doc ()
669 "Reconvert the current document.
670 Should be invoked when the cached images aren't up-to-date."
671 (interactive)
672 (doc-view-kill-proc)
673 ;; Clear the old cached files
674 (when (file-exists-p (doc-view-current-cache-dir))
675 (delete-directory (doc-view-current-cache-dir) 'recursive))
676 (doc-view-initiate-display))
678 (defun doc-view-sentinel (proc event)
679 "Generic sentinel for doc-view conversion processes."
680 (if (not (string-match "finished" event))
681 (message "DocView: process %s changed status to %s."
682 (process-name proc)
683 (if (string-match "\\(.+\\)\n?\\'" event)
684 (match-string 1 event)
685 event))
686 (when (buffer-live-p (process-get proc 'buffer))
687 (with-current-buffer (process-get proc 'buffer)
688 (setq doc-view-current-converter-processes
689 (delq proc doc-view-current-converter-processes))
690 (setq mode-line-process
691 (if doc-view-current-converter-processes
692 (format ":%s" (car doc-view-current-converter-processes))))
693 (funcall (process-get proc 'callback))))))
695 (defun doc-view-start-process (name program args callback)
696 ;; Make sure the process is started in an existing directory, (rather than
697 ;; some file-name-handler-managed dir, for example).
698 (let* ((default-directory (if (file-readable-p default-directory)
699 default-directory
700 (expand-file-name "~/")))
701 (proc (apply 'start-process name doc-view-conversion-buffer
702 program args)))
703 (push proc doc-view-current-converter-processes)
704 (setq mode-line-process (list (format ":%s" proc)))
705 (set-process-sentinel proc 'doc-view-sentinel)
706 (process-put proc 'buffer (current-buffer))
707 (process-put proc 'callback callback)))
709 (defun doc-view-dvi->pdf (dvi pdf callback)
710 "Convert DVI to PDF asynchronously and call CALLBACK when finished."
711 ;; Prefer dvipdf over dvipdfm, because the latter has problems if the DVI
712 ;; references and includes other PS files.
713 (if (and doc-view-dvipdf-program
714 (executable-find doc-view-dvipdf-program))
715 (doc-view-start-process "dvi->pdf" doc-view-dvipdf-program
716 (list dvi pdf)
717 callback)
718 (doc-view-start-process "dvi->pdf" doc-view-dvipdfm-program
719 (list "-o" pdf dvi)
720 callback)))
722 (defun doc-view-odf->pdf (odf callback)
723 "Convert ODF to PDF asynchronously and call CALLBACK when finished.
724 The converted PDF is put into the current cache directory, and it
725 is named like ODF with the extension turned to pdf."
726 (doc-view-start-process "odf->pdf" doc-view-unoconv-program
727 (list "-f" "pdf" "-o" (doc-view-current-cache-dir) odf)
728 callback))
730 (defun doc-view-pdf/ps->png (pdf-ps png)
731 "Convert PDF-PS to PNG asynchronously."
732 (doc-view-start-process
733 "pdf/ps->png" doc-view-ghostscript-program
734 (append doc-view-ghostscript-options
735 (list (format "-r%d" (round doc-view-resolution))
736 (concat "-sOutputFile=" png)
737 pdf-ps))
738 (lexical-let ((resolution doc-view-resolution))
739 (lambda ()
740 ;; Only create the resolution file when it's all done, so it also
741 ;; serves as a witness that the conversion is complete.
742 (write-region (prin1-to-string resolution) nil
743 (expand-file-name "resolution.el"
744 (doc-view-current-cache-dir))
745 nil 'silently)
746 (when doc-view-current-timer
747 (cancel-timer doc-view-current-timer)
748 (setq doc-view-current-timer nil))
749 (doc-view-display (current-buffer) 'force))))
750 ;; Update the displayed pages as soon as they're done generating.
751 (when doc-view-conversion-refresh-interval
752 (setq doc-view-current-timer
753 (run-at-time "1 secs" doc-view-conversion-refresh-interval
754 'doc-view-display
755 (current-buffer)))))
757 (defun doc-view-pdf->png-1 (pdf png page callback)
758 "Convert a PAGE of a PDF file to PNG asynchronously.
759 Call CALLBACK with no arguments when done."
760 (doc-view-start-process
761 "pdf->png-1" doc-view-ghostscript-program
762 (append doc-view-ghostscript-options
763 (list (format "-r%d" (round doc-view-resolution))
764 ;; Sadly, `gs' only supports the page-range
765 ;; for PDF files.
766 (format "-dFirstPage=%d" page)
767 (format "-dLastPage=%d" page)
768 (concat "-sOutputFile=" png)
769 pdf))
770 callback))
772 (declare-function clear-image-cache "image.c" (&optional filter))
774 (defun doc-view-pdf->png (pdf png pages)
775 "Convert a PDF file to PNG asynchronously.
776 Start by converting PAGES, and then the rest."
777 (if (null pages)
778 (doc-view-pdf/ps->png pdf png)
779 ;; We could render several `pages' with a single process if they're
780 ;; (almost) consecutive, but since in 99% of the cases, there'll be only
781 ;; a single page anyway, and of the remaining 1%, few cases will have
782 ;; consecutive pages, it's not worth the trouble.
783 (lexical-let ((pdf pdf) (png png) (rest (cdr pages)))
784 (doc-view-pdf->png-1
785 pdf (format png (car pages)) (car pages)
786 (lambda ()
787 (if rest
788 (doc-view-pdf->png pdf png rest)
789 ;; Yippie, the important pages are done, update the display.
790 (clear-image-cache)
791 ;; For the windows that have a message (like "Welcome to
792 ;; DocView") display property, clearing the image cache is
793 ;; not sufficient.
794 (dolist (win (get-buffer-window-list (current-buffer) nil 'visible))
795 (with-selected-window win
796 (when (stringp (get-char-property (point-min) 'display))
797 (doc-view-goto-page (doc-view-current-page)))))
798 ;; Convert the rest of the pages.
799 (doc-view-pdf/ps->png pdf png)))))))
801 (defun doc-view-pdf->txt (pdf txt callback)
802 "Convert PDF to TXT asynchronously and call CALLBACK when finished."
803 (or doc-view-pdftotext-program
804 (error "You need the `pdftotext' program to convert a PDF to text"))
805 (doc-view-start-process "pdf->txt" doc-view-pdftotext-program
806 (list "-raw" pdf txt)
807 callback))
809 (defun doc-view-doc->txt (txt callback)
810 "Convert the current document to text and call CALLBACK when done."
811 (make-directory (doc-view-current-cache-dir) t)
812 (case doc-view-doc-type
813 (pdf
814 ;; Doc is a PDF, so convert it to TXT
815 (doc-view-pdf->txt doc-view-buffer-file-name txt callback))
817 ;; Doc is a PS, so convert it to PDF (which will be converted to
818 ;; TXT thereafter).
819 (lexical-let ((pdf (expand-file-name "doc.pdf"
820 (doc-view-current-cache-dir)))
821 (txt txt)
822 (callback callback))
823 (doc-view-ps->pdf doc-view-buffer-file-name pdf
824 (lambda () (doc-view-pdf->txt pdf txt callback)))))
825 (dvi
826 ;; Doc is a DVI. This means that a doc.pdf already exists in its
827 ;; cache subdirectory.
828 (doc-view-pdf->txt (expand-file-name "doc.pdf"
829 (doc-view-current-cache-dir))
830 txt callback))
831 (odf
832 ;; Doc is some ODF (or MS Office) doc. This means that a doc.pdf
833 ;; already exists in its cache subdirectory.
834 (doc-view-pdf->txt (expand-file-name "doc.pdf"
835 (doc-view-current-cache-dir))
836 txt callback))
837 (t (error "DocView doesn't know what to do"))))
839 (defun doc-view-ps->pdf (ps pdf callback)
840 "Convert PS to PDF asynchronously and call CALLBACK when finished."
841 (or doc-view-ps2pdf-program
842 (error "You need the `ps2pdf' program to convert PS to PDF"))
843 (doc-view-start-process "ps->pdf" doc-view-ps2pdf-program
844 (list
845 ;; Avoid security problems when rendering files from
846 ;; untrusted sources.
847 "-dSAFER"
848 ;; in-file and out-file
849 ps pdf)
850 callback))
852 (defun doc-view-active-pages ()
853 (let ((pages ()))
854 (dolist (win (get-buffer-window-list (current-buffer) nil 'visible))
855 (let ((page (image-mode-window-get 'page win)))
856 (unless (memq page pages) (push page pages))))
857 pages))
859 (defun doc-view-convert-current-doc ()
860 "Convert `doc-view-buffer-file-name' to a set of png files, one file per page.
861 Those files are saved in the directory given by the function
862 `doc-view-current-cache-dir'."
863 ;; Let stale files still display while we recompute the new ones, so only
864 ;; flush the cache when the conversion is over. One of the reasons why it
865 ;; is important to keep displaying the stale page is so that revert-buffer
866 ;; preserves the horizontal/vertical scroll settings (which are otherwise
867 ;; resets during the redisplay).
868 (setq doc-view-pending-cache-flush t)
869 (let ((png-file (expand-file-name "page-%d.png"
870 (doc-view-current-cache-dir))))
871 (make-directory (doc-view-current-cache-dir) t)
872 (case doc-view-doc-type
873 (dvi
874 ;; DVI files have to be converted to PDF before Ghostscript can process
875 ;; it.
876 (lexical-let
877 ((pdf (expand-file-name "doc.pdf" doc-view-current-cache-dir))
878 (png-file png-file))
879 (doc-view-dvi->pdf doc-view-buffer-file-name pdf
880 (lambda () (doc-view-pdf/ps->png pdf png-file)))))
881 (odf
882 ;; ODF files have to be converted to PDF before Ghostscript can
883 ;; process it.
884 (lexical-let
885 ((pdf (expand-file-name "doc.pdf" doc-view-current-cache-dir))
886 (opdf (expand-file-name (concat (file-name-sans-extension
887 (file-name-nondirectory doc-view-buffer-file-name))
888 ".pdf")
889 doc-view-current-cache-dir))
890 (png-file png-file))
891 ;; The unoconv tool only supports a output directory, but no
892 ;; file name. It's named like the input file with the
893 ;; extension replaced by pdf.
894 (doc-view-odf->pdf doc-view-buffer-file-name
895 (lambda ()
896 ;; Rename to doc.pdf
897 (rename-file opdf pdf)
898 (doc-view-pdf/ps->png pdf png-file)))))
899 (pdf
900 (let ((pages (doc-view-active-pages)))
901 ;; Convert PDF to PNG images starting with the active pages.
902 (doc-view-pdf->png doc-view-buffer-file-name png-file pages)))
904 ;; Convert to PNG images.
905 (doc-view-pdf/ps->png doc-view-buffer-file-name png-file)))))
907 ;;;; Slicing
909 (declare-function image-size "image.c" (spec &optional pixels frame))
911 (defun doc-view-set-slice (x y width height)
912 "Set the slice of the images that should be displayed.
913 You can use this function to tell doc-view not to display the
914 margins of the document. It prompts for the top-left corner (X
915 and Y) of the slice to display and its WIDTH and HEIGHT.
917 See `doc-view-set-slice-using-mouse' for a more convenient way to
918 do that. To reset the slice use `doc-view-reset-slice'."
919 (interactive
920 (let* ((size (image-size (doc-view-current-image) t))
921 (a (read-number (format "Top-left X (0..%d): " (car size))))
922 (b (read-number (format "Top-left Y (0..%d): " (cdr size))))
923 (c (read-number (format "Width (0..%d): " (- (car size) a))))
924 (d (read-number (format "Height (0..%d): " (- (cdr size) b)))))
925 (list a b c d)))
926 (setf (doc-view-current-slice) (list x y width height))
927 ;; Redisplay
928 (doc-view-goto-page (doc-view-current-page)))
930 (defun doc-view-set-slice-using-mouse ()
931 "Set the slice of the images that should be displayed.
932 You set the slice by pressing mouse-1 at its top-left corner and
933 dragging it to its bottom-right corner. See also
934 `doc-view-set-slice' and `doc-view-reset-slice'."
935 (interactive)
936 (let (x y w h done)
937 (while (not done)
938 (let ((e (read-event
939 (concat "Press mouse-1 at the top-left corner and "
940 "drag it to the bottom-right corner!"))))
941 (when (eq (car e) 'drag-mouse-1)
942 (setq x (car (posn-object-x-y (event-start e))))
943 (setq y (cdr (posn-object-x-y (event-start e))))
944 (setq w (- (car (posn-object-x-y (event-end e))) x))
945 (setq h (- (cdr (posn-object-x-y (event-end e))) y))
946 (setq done t))))
947 (doc-view-set-slice x y w h)))
949 (defun doc-view-reset-slice ()
950 "Reset the current slice.
951 After calling this function whole pages will be visible again."
952 (interactive)
953 (setf (doc-view-current-slice) nil)
954 ;; Redisplay
955 (doc-view-goto-page (doc-view-current-page)))
957 ;;;; Display
959 (defun doc-view-insert-image (file &rest args)
960 "Insert the given png FILE.
961 ARGS is a list of image descriptors."
962 (when doc-view-pending-cache-flush
963 (clear-image-cache)
964 (setq doc-view-pending-cache-flush nil))
965 (let ((ol (doc-view-current-overlay))
966 (image (if (and file (file-readable-p file))
967 (if (not (fboundp 'imagemagick-types))
968 (apply 'create-image file 'png nil args)
969 (unless (member :width args)
970 (setq args (append args (list :width doc-view-image-width))))
971 (apply 'create-image file 'imagemagick nil args))))
972 (slice (doc-view-current-slice)))
973 (setf (doc-view-current-image) image)
974 (move-overlay ol (point-min) (point-max))
975 (overlay-put ol 'display
976 (cond
977 (image
978 (if slice
979 (list (cons 'slice slice) image)
980 image))
981 ;; We're trying to display a page that doesn't exist.
982 (doc-view-current-converter-processes
983 ;; Maybe the page doesn't exist *yet*.
984 "Cannot display this page (yet)!")
986 ;; Typically happens if the conversion process somehow
987 ;; failed. Better not signal an error here because it
988 ;; could prevent a subsequent reconversion from fixing
989 ;; the problem.
990 (concat "Cannot display this page!\n"
991 "Maybe because of a conversion failure!"))))
992 (let ((win (overlay-get ol 'window)))
993 (if (stringp (overlay-get ol 'display))
994 (progn ;Make sure the text is not scrolled out of view.
995 (set-window-hscroll win 0)
996 (set-window-vscroll win 0))
997 (let ((hscroll (image-mode-window-get 'hscroll win))
998 (vscroll (image-mode-window-get 'vscroll win)))
999 ;; Reset scroll settings, in case they were changed.
1000 (if hscroll (set-window-hscroll win hscroll))
1001 (if vscroll (set-window-vscroll win vscroll)))))))
1003 (defun doc-view-sort (a b)
1004 "Return non-nil if A should be sorted before B.
1005 Predicate for sorting `doc-view-current-files'."
1006 (or (< (length a) (length b))
1007 (and (= (length a) (length b))
1008 (string< a b))))
1010 (defun doc-view-display (buffer &optional force)
1011 "Start viewing the document in BUFFER.
1012 If FORCE is non-nil, start viewing even if the document does not
1013 have the page we want to view."
1014 (with-current-buffer buffer
1015 (let ((prev-pages doc-view-current-files))
1016 (setq doc-view-current-files
1017 (sort (directory-files (doc-view-current-cache-dir) t
1018 "page-[0-9]+\\.png" t)
1019 'doc-view-sort))
1020 (dolist (win (or (get-buffer-window-list buffer nil t)
1021 (list (selected-window))))
1022 (let* ((page (doc-view-current-page win))
1023 (pagefile (expand-file-name (format "page-%d.png" page)
1024 (doc-view-current-cache-dir))))
1025 (when (or force
1026 (and (not (member pagefile prev-pages))
1027 (member pagefile doc-view-current-files)))
1028 (with-selected-window win
1029 (assert (eq (current-buffer) buffer))
1030 (doc-view-goto-page page))))))))
1032 (defun doc-view-buffer-message ()
1033 ;; Only show this message initially, not when refreshing the buffer (in which
1034 ;; case it's better to keep displaying the "stale" page while computing
1035 ;; the fresh new ones).
1036 (unless (overlay-get (doc-view-current-overlay) 'display)
1037 (overlay-put (doc-view-current-overlay) 'display
1038 (concat (propertize "Welcome to DocView!" 'face 'bold)
1039 "\n"
1041 If you see this buffer it means that the document you want to view is being
1042 converted to PNG and the conversion of the first page hasn't finished yet or
1043 `doc-view-conversion-refresh-interval' is set to nil.
1045 For now these keys are useful:
1047 `q' : Bury this buffer. Conversion will go on in background.
1048 `k' : Kill the conversion process and this buffer.
1049 `K' : Kill the conversion process.\n"))))
1051 (declare-function tooltip-show "tooltip" (text &optional use-echo-area))
1053 (defun doc-view-show-tooltip ()
1054 (interactive)
1055 (tooltip-show (doc-view-current-info)))
1057 (defun doc-view-open-text ()
1058 "Open a buffer with the current doc's contents as text."
1059 (interactive)
1060 (if doc-view-current-converter-processes
1061 (message "DocView: please wait till conversion finished.")
1062 (let ((txt (expand-file-name "doc.txt" (doc-view-current-cache-dir))))
1063 (if (file-readable-p txt)
1064 (let ((name (concat "Text contents of "
1065 (file-name-nondirectory buffer-file-name)))
1066 (dir (file-name-directory buffer-file-name)))
1067 (with-current-buffer (find-file txt)
1068 (rename-buffer name)
1069 (setq default-directory dir)))
1070 (doc-view-doc->txt txt 'doc-view-open-text)))))
1072 ;;;;; Toggle between editing and viewing
1074 (defun doc-view-toggle-display ()
1075 "Toggle between editing a document as text or viewing it."
1076 (interactive)
1077 (if (eq major-mode 'doc-view-mode)
1078 ;; Switch to editing mode
1079 (progn
1080 (doc-view-kill-proc)
1081 (setq buffer-read-only nil)
1082 (remove-overlays (point-min) (point-max) 'doc-view t)
1083 (set (make-local-variable 'image-mode-winprops-alist) t)
1084 ;; Switch to the previously used major mode or fall back to
1085 ;; normal mode.
1086 (doc-view-fallback-mode)
1087 (doc-view-minor-mode 1))
1088 ;; Switch to doc-view-mode
1089 (when (and (buffer-modified-p)
1090 (y-or-n-p "The buffer has been modified. Save the changes? "))
1091 (save-buffer))
1092 (doc-view-mode)))
1094 ;;;; Searching
1097 (defun doc-view-search-internal (regexp file)
1098 "Return a list of FILE's pages that contain text matching REGEXP.
1099 The value is an alist of the form (PAGE CONTEXTS) where PAGE is
1100 the pagenumber and CONTEXTS are all lines of text containing a match."
1101 (with-temp-buffer
1102 (insert-file-contents file)
1103 (let ((page 1)
1104 (lastpage 1)
1105 matches)
1106 (while (re-search-forward (concat "\\(?:\\([\f]\\)\\|\\("
1107 regexp "\\)\\)") nil t)
1108 (when (match-string 1) (setq page (1+ page)))
1109 (when (match-string 2)
1110 (if (/= page lastpage)
1111 (push (cons page
1112 (list (buffer-substring
1113 (line-beginning-position)
1114 (line-end-position))))
1115 matches)
1116 (setq matches (cons
1117 (append
1119 ;; This page already is a match.
1120 (car matches)
1121 ;; This is the first match on page.
1122 (list page))
1123 (list (buffer-substring
1124 (line-beginning-position)
1125 (line-end-position))))
1126 (cdr matches))))
1127 (setq lastpage page)))
1128 (nreverse matches))))
1130 (defun doc-view-search-no-of-matches (list)
1131 "Extract the number of matches from the search result LIST."
1132 (let ((no 0))
1133 (dolist (p list)
1134 (setq no (+ no (1- (length p)))))
1135 no))
1137 (defun doc-view-search-backward (new-query)
1138 "Call `doc-view-search' for backward search.
1139 If prefix NEW-QUERY is given, ask for a new regexp."
1140 (interactive "P")
1141 (doc-view-search new-query t))
1143 (defun doc-view-search (new-query &optional backward)
1144 "Jump to the next match or initiate a new search if NEW-QUERY is given.
1145 If the current document hasn't been transformed to plain text
1146 till now do that first.
1147 If BACKWARD is non-nil, jump to the previous match."
1148 (interactive "P")
1149 (if (and (not new-query)
1150 doc-view-current-search-matches)
1151 (if backward
1152 (doc-view-search-previous-match 1)
1153 (doc-view-search-next-match 1))
1154 ;; New search, so forget the old results.
1155 (setq doc-view-current-search-matches nil)
1156 (let ((txt (expand-file-name "doc.txt"
1157 (doc-view-current-cache-dir))))
1158 (if (file-readable-p txt)
1159 (progn
1160 (setq doc-view-current-search-matches
1161 (doc-view-search-internal
1162 (read-from-minibuffer "Regexp: ")
1163 txt))
1164 (message "DocView: search yielded %d matches."
1165 (doc-view-search-no-of-matches
1166 doc-view-current-search-matches)))
1167 ;; We must convert to TXT first!
1168 (if doc-view-current-converter-processes
1169 (message "DocView: please wait till conversion finished.")
1170 (doc-view-doc->txt txt (lambda () (doc-view-search nil))))))))
1172 (defun doc-view-search-next-match (arg)
1173 "Go to the ARGth next matching page."
1174 (interactive "p")
1175 (let* ((next-pages (doc-view-remove-if
1176 (lambda (i) (<= (car i) (doc-view-current-page)))
1177 doc-view-current-search-matches))
1178 (page (car (nth (1- arg) next-pages))))
1179 (if page
1180 (doc-view-goto-page page)
1181 (when (and
1182 doc-view-current-search-matches
1183 (y-or-n-p "No more matches after current page. Wrap to first match? "))
1184 (doc-view-goto-page (caar doc-view-current-search-matches))))))
1186 (defun doc-view-search-previous-match (arg)
1187 "Go to the ARGth previous matching page."
1188 (interactive "p")
1189 (let* ((prev-pages (doc-view-remove-if
1190 (lambda (i) (>= (car i) (doc-view-current-page)))
1191 doc-view-current-search-matches))
1192 (page (car (nth (1- arg) (nreverse prev-pages)))))
1193 (if page
1194 (doc-view-goto-page page)
1195 (when (and
1196 doc-view-current-search-matches
1197 (y-or-n-p "No more matches before current page. Wrap to last match? "))
1198 (doc-view-goto-page (caar (last doc-view-current-search-matches)))))))
1200 ;;;; User interface commands and the mode
1202 (put 'doc-view-mode 'mode-class 'special)
1204 (defun doc-view-already-converted-p ()
1205 "Return non-nil if the current doc was already converted."
1206 (and (file-exists-p (doc-view-current-cache-dir))
1207 ;; Check that the resolution info is there, otherwise it means
1208 ;; the conversion is incomplete.
1209 (file-readable-p (expand-file-name "resolution.el"
1210 (doc-view-current-cache-dir)))
1211 (> (length (directory-files (doc-view-current-cache-dir)
1212 nil "\\.png\\'"))
1213 0)))
1215 (defun doc-view-initiate-display ()
1216 ;; Switch to image display if possible
1217 (if (doc-view-mode-p doc-view-doc-type)
1218 (progn
1219 (doc-view-buffer-message)
1220 (setf (doc-view-current-page) (or (doc-view-current-page) 1))
1221 (if (doc-view-already-converted-p)
1222 (progn
1223 (message "DocView: using cached files!")
1224 ;; Load the saved resolution
1225 (let* ((res-file (expand-file-name "resolution.el"
1226 (doc-view-current-cache-dir)))
1227 (res
1228 (with-temp-buffer
1229 (when (file-readable-p res-file)
1230 (insert-file-contents res-file)
1231 (read (current-buffer))))))
1232 (when (numberp res)
1233 (set (make-local-variable 'doc-view-resolution) res)))
1234 (doc-view-display (current-buffer) 'force))
1235 (doc-view-convert-current-doc))
1236 (message
1237 "%s"
1238 (substitute-command-keys
1239 (concat "Type \\[doc-view-toggle-display] to toggle between "
1240 "editing or viewing the document."))))
1241 (message
1242 "%s"
1243 (concat "No PNG support is available, or some conversion utility for "
1244 (file-name-extension doc-view-buffer-file-name)
1245 " files is missing."))
1246 (when (and (executable-find doc-view-pdftotext-program)
1247 (y-or-n-p
1248 "Unable to render file. View extracted text instead? "))
1249 (doc-view-open-text))
1250 (doc-view-toggle-display)))
1252 (defvar bookmark-make-record-function)
1254 (defun doc-view-clone-buffer-hook ()
1255 ;; FIXME: There are several potential problems linked with reconversion
1256 ;; and auto-revert when we have indirect buffers because they share their
1257 ;; /tmp cache directory. This sharing is good (you'd rather not reconvert
1258 ;; for each clone), but that means that clones need to collaborate a bit.
1259 ;; I guess it mostly means: detect when a reconversion process is already
1260 ;; running, and run the sentinel in all clones.
1262 ;; Maybe the clones should really have a separate /tmp directory
1263 ;; so they could have a different resolution and you could use clones
1264 ;; for zooming.
1265 (remove-overlays (point-min) (point-max) 'doc-view t)
1266 (if (consp image-mode-winprops-alist) (setq image-mode-winprops-alist nil)))
1268 (defun doc-view-intersection (l1 l2)
1269 (let ((l ()))
1270 (dolist (x l1) (if (memq x l2) (push x l)))
1273 (defun doc-view-set-doc-type ()
1274 "Figure out the current document type (`doc-view-doc-type')."
1275 (let ((name-types
1276 (when buffer-file-name
1277 (cdr (assoc (file-name-extension buffer-file-name)
1279 ;; DVI
1280 ("dvi" dvi)
1281 ;; PDF
1282 ("pdf" pdf) ("epdf" pdf)
1283 ;; PostScript
1284 ("ps" ps) ("eps" ps)
1285 ;; OpenDocument formats
1286 ("odt" odf) ("ods" odf) ("odp" odf) ("odg" odf)
1287 ("odc" odf) ("odi" odf) ("odm" odf) ("ott" odf)
1288 ("ots" odf) ("otp" odf) ("otg" odf)
1289 ;; Microsoft Office formats (also handled
1290 ;; by the odf conversion chain)
1291 ("doc" odf) ("docx" odf) ("xls" odf) ("xlsx" odf)
1292 ("ppt" odf) ("pptx" odf))))))
1293 (content-types
1294 (save-excursion
1295 (goto-char (point-min))
1296 (cond
1297 ((looking-at "%!") '(ps))
1298 ((looking-at "%PDF") '(pdf))
1299 ((looking-at "\367\002") '(dvi))))))
1300 (set (make-local-variable 'doc-view-doc-type)
1301 (car (or (doc-view-intersection name-types content-types)
1302 (when (and name-types content-types)
1303 (error "Conflicting types: name says %s but content says %s"
1304 name-types content-types))
1305 name-types content-types
1306 (error "Cannot determine the document type"))))))
1308 ;;;###autoload
1309 (defun doc-view-mode ()
1310 "Major mode in DocView buffers.
1312 DocView Mode is an Emacs document viewer. It displays PDF, PS
1313 and DVI files (as PNG images) in Emacs buffers.
1315 You can use \\<doc-view-mode-map>\\[doc-view-toggle-display] to
1316 toggle between displaying the document or editing it as text.
1317 \\{doc-view-mode-map}"
1318 (interactive)
1320 (if (= (point-min) (point-max))
1321 ;; The doc is empty or doesn't exist at all, so fallback to
1322 ;; another mode. We used to also check file-exists-p, but this
1323 ;; returns nil for tar members.
1324 (doc-view-fallback-mode)
1326 (let* ((prev-major-mode (if (eq major-mode 'doc-view-mode)
1327 doc-view-previous-major-mode
1328 (when (not (memq major-mode
1329 '(doc-view-mode fundamental-mode)))
1330 major-mode))))
1331 (kill-all-local-variables)
1332 (set (make-local-variable 'doc-view-previous-major-mode) prev-major-mode))
1334 ;; Figure out the document type.
1335 (unless doc-view-doc-type
1336 (doc-view-set-doc-type))
1338 (doc-view-make-safe-dir doc-view-cache-directory)
1339 ;; Handle compressed files, remote files, files inside archives
1340 (set (make-local-variable 'doc-view-buffer-file-name)
1341 (cond
1342 (jka-compr-really-do-compress
1343 ;; FIXME: there's a risk of name conflicts here.
1344 (expand-file-name
1345 (file-name-nondirectory
1346 (file-name-sans-extension buffer-file-name))
1347 doc-view-cache-directory))
1348 ;; Is the file readable by local processes?
1349 ;; We used to use `file-remote-p' but it's unclear what it's
1350 ;; supposed to return nil for things like local files accessed via
1351 ;; `su' or via file://...
1352 ((let ((file-name-handler-alist nil))
1353 (not (and buffer-file-name (file-readable-p buffer-file-name))))
1354 ;; FIXME: there's a risk of name conflicts here.
1355 (expand-file-name
1356 (if buffer-file-name
1357 (file-name-nondirectory buffer-file-name)
1358 (buffer-name))
1359 doc-view-cache-directory))
1360 (t buffer-file-name)))
1361 (when (not (string= doc-view-buffer-file-name buffer-file-name))
1362 (write-region nil nil doc-view-buffer-file-name))
1364 (add-hook 'change-major-mode-hook
1365 (lambda ()
1366 (doc-view-kill-proc)
1367 (remove-overlays (point-min) (point-max) 'doc-view t))
1368 nil t)
1369 (add-hook 'clone-indirect-buffer-hook 'doc-view-clone-buffer-hook nil t)
1370 (add-hook 'kill-buffer-hook 'doc-view-kill-proc nil t)
1372 (remove-overlays (point-min) (point-max) 'doc-view t) ;Just in case.
1373 ;; Keep track of display info ([vh]scroll, page number, overlay,
1374 ;; ...) for each window in which this document is shown.
1375 (add-hook 'image-mode-new-window-functions
1376 'doc-view-new-window-function nil t)
1377 (image-mode-setup-winprops)
1379 (set (make-local-variable 'mode-line-position)
1380 '(" P" (:eval (number-to-string (doc-view-current-page)))
1381 "/" (:eval (number-to-string (doc-view-last-page-number)))))
1382 ;; Don't scroll unless the user specifically asked for it.
1383 (set (make-local-variable 'auto-hscroll-mode) nil)
1384 (set (make-local-variable 'mwheel-scroll-up-function)
1385 'doc-view-scroll-up-or-next-page)
1386 (set (make-local-variable 'mwheel-scroll-down-function)
1387 'doc-view-scroll-down-or-previous-page)
1388 (set (make-local-variable 'cursor-type) nil)
1389 (use-local-map doc-view-mode-map)
1390 (set (make-local-variable 'after-revert-hook) 'doc-view-reconvert-doc)
1391 (set (make-local-variable 'bookmark-make-record-function)
1392 'doc-view-bookmark-make-record)
1393 (setq mode-name "DocView"
1394 buffer-read-only t
1395 major-mode 'doc-view-mode)
1396 (doc-view-initiate-display)
1397 ;; Switch off view-mode explicitly, because doc-view-mode is the
1398 ;; canonical view mode for PDF/PS/DVI files. This could be
1399 ;; switched on automatically depending on the value of
1400 ;; `view-read-only'.
1401 (set (make-local-variable 'view-read-only) nil)
1402 (run-mode-hooks 'doc-view-mode-hook)))
1404 (defun doc-view-fallback-mode ()
1405 "Fallback to the previous or next best major mode."
1406 (if doc-view-previous-major-mode
1407 (funcall doc-view-previous-major-mode)
1408 (let ((auto-mode-alist (rassq-delete-all
1409 'doc-view-mode-maybe
1410 (rassq-delete-all 'doc-view-mode
1411 (copy-alist auto-mode-alist)))))
1412 (normal-mode))))
1414 ;;;###autoload
1415 (defun doc-view-mode-maybe ()
1416 "Switch to `doc-view-mode' if possible.
1417 If the required external tools are not available, then fallback
1418 to the next best mode."
1419 (condition-case nil
1420 (doc-view-set-doc-type)
1421 (error (doc-view-fallback-mode)))
1422 (if (doc-view-mode-p doc-view-doc-type)
1423 (doc-view-mode)
1424 (doc-view-fallback-mode)))
1426 ;;;###autoload
1427 (define-minor-mode doc-view-minor-mode
1428 "Toggle Doc view minor mode.
1429 With arg, turn Doc view minor mode on if arg is positive, off otherwise.
1430 See the command `doc-view-mode' for more information on this mode."
1431 nil " DocView" doc-view-minor-mode-map
1432 :group 'doc-view
1433 (when doc-view-minor-mode
1434 (add-hook 'change-major-mode-hook (lambda () (doc-view-minor-mode -1)) nil t)
1435 (message
1436 "%s"
1437 (substitute-command-keys
1438 "Type \\[doc-view-toggle-display] to toggle between editing or viewing the document."))))
1440 (defun doc-view-clear-cache ()
1441 "Delete the whole cache (`doc-view-cache-directory')."
1442 (interactive)
1443 (dired-delete-file doc-view-cache-directory 'always))
1445 (defun doc-view-dired-cache ()
1446 "Open `dired' in `doc-view-cache-directory'."
1447 (interactive)
1448 (dired doc-view-cache-directory))
1451 ;;;; Bookmark integration
1453 (declare-function bookmark-make-record-default
1454 "bookmark" (&optional no-file no-context posn))
1455 (declare-function bookmark-prop-get "bookmark" (bookmark prop))
1456 (declare-function bookmark-default-handler "bookmark" (bmk))
1458 (defun doc-view-bookmark-make-record ()
1459 (nconc (bookmark-make-record-default)
1460 `((page . ,(doc-view-current-page))
1461 (handler . doc-view-bookmark-jump))))
1464 ;;;###autoload
1465 (defun doc-view-bookmark-jump (bmk)
1466 ;; This implements the `handler' function interface for record type
1467 ;; returned by `doc-view-bookmark-make-record', which see.
1468 (prog1 (bookmark-default-handler bmk)
1469 (let ((page (bookmark-prop-get bmk 'page)))
1470 (when (not (eq major-mode 'doc-view-mode))
1471 (doc-view-toggle-display))
1472 (with-selected-window
1473 (or (get-buffer-window (current-buffer) 0)
1474 (selected-window))
1475 (doc-view-goto-page page)))))
1478 (provide 'doc-view)
1480 ;; Local Variables:
1481 ;; mode: outline-minor
1482 ;; End:
1484 ;;; doc-view.el ends here