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