2008-01-10 Tassilo Horn <tassilo@member.fsf.org>
[emacs.git] / lisp / doc-view.el
blobf2bfb1c70fdd76f878f368257d8356f3878bfa5e
1 ;;; doc-view.el --- View PDF/PostScript/DVI files in Emacs
3 ;; Copyright (C) 2007, 2008 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, or (at your option)
14 ;; 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; see the file COPYING. If not, write to the
23 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
24 ;; Boston, MA 02110-1301, USA.
26 ;;; Requirements:
28 ;; doc-view.el requires GNU Emacs 22.1 or newer. You also need Ghostscript,
29 ;; `dvipdfm' which comes with teTeX and `pdftotext', which comes with xpdf
30 ;; (http://www.foolabs.com/xpdf/) or 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 invokation 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 invokation 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 ;; - better menu.
103 ;; - don't use `find-file'.
104 ;; - Bind slicing to a drag event.
105 ;; - doc-view-fit-doc-to-window and doc-view-fit-window-to-doc.
106 ;; - zoom a 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 (require 'dired)
136 (require 'image-mode)
137 (require 'jka-compr)
138 (require 'tramp) ;; would be better to make tramp-tramp-file-p autoloaded
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 'multimedia
148 :prefix "doc-view-")
150 (defcustom doc-view-ghostscript-program (executable-find "gs")
151 "Program to convert PS and PDF files to PNG."
152 :type 'file
153 :group 'doc-view)
155 (defcustom doc-view-ghostscript-options
156 '("-dSAFER" ;; Avoid security problems when rendering files from untrusted
157 ;; sources.
158 "-dNOPAUSE" "-sDEVICE=png16m" "-dTextAlphaBits=4"
159 "-dBATCH" "-dGraphicsAlphaBits=4" "-dQUIET")
160 "A list of options to give to ghostscript."
161 :type '(repeat string)
162 :group 'doc-view)
164 (defcustom doc-view-resolution 100
165 "Dots per inch resolution used to render the documents.
166 Higher values result in larger images."
167 :type 'number
168 :group 'doc-view)
170 (defcustom doc-view-dvipdfm-program (executable-find "dvipdfm")
171 "Program to convert DVI files to PDF.
173 DVI file will be converted to PDF before the resulting PDF is
174 converted to PNG."
175 :type 'file
176 :group 'doc-view)
178 (defcustom doc-view-ps2pdf-program (executable-find "ps2pdf")
179 "Program to convert PS files to PDF.
181 PS files will be converted to PDF before searching is possible."
182 :type 'file
183 :group 'doc-view)
185 (defcustom doc-view-pdftotext-program (executable-find "pdftotext")
186 "Program to convert PDF files to plain text.
188 Needed for searching."
189 :type 'file
190 :group 'doc-view)
192 (defcustom doc-view-cache-directory
193 (expand-file-name (format "docview%d" (user-uid))
194 temporary-file-directory)
195 "The base directory, where the PNG images will be saved."
196 :type 'directory
197 :group 'doc-view)
199 (defcustom doc-view-conversion-buffer "*doc-view conversion output*"
200 "The buffer where messages from the converter programs go to."
201 :type 'string
202 :group 'doc-view)
204 (defcustom doc-view-conversion-refresh-interval 3
205 "Interval in seconds between refreshes of the DocView buffer while converting.
206 After such a refresh newly converted pages will be available for
207 viewing. If set to nil there won't be any refreshes and the
208 pages won't be displayed before conversion of the whole document
209 has finished."
210 :type 'integer
211 :group 'doc-view)
213 ;;;; Internal Variables
215 (defvar doc-view-current-files nil
216 "Only used internally.")
218 (defvar doc-view-current-page nil
219 "Only used internally.")
221 (defvar doc-view-current-converter-process nil
222 "Only used internally.")
224 (defvar doc-view-current-timer nil
225 "Only used internally.")
227 (defvar doc-view-current-slice nil
228 "Only used internally.")
230 (defvar doc-view-current-cache-dir nil
231 "Only used internally.")
233 (defvar doc-view-current-search-matches nil
234 "Only used internally.")
236 (defvar doc-view-current-image nil
237 "Only used internally.")
239 (defvar doc-view-current-overlay nil
240 "Only used internally.")
242 (defvar doc-view-pending-cache-flush nil
243 "Only used internally.")
245 (defvar doc-view-current-info nil
246 "Only used internally.")
248 (defvar doc-view-previous-major-mode nil
249 "Only used internally.")
251 ;;;; DocView Keymaps
253 (defvar doc-view-mode-map
254 (let ((map (make-sparse-keymap)))
255 (suppress-keymap map)
256 ;; Navigation in the document
257 (define-key map (kbd "n") 'doc-view-next-page)
258 (define-key map (kbd "p") 'doc-view-previous-page)
259 (define-key map (kbd "<next>") 'forward-page)
260 (define-key map (kbd "<prior>") 'backward-page)
261 (define-key map [remap forward-page] 'doc-view-next-page)
262 (define-key map [remap backward-page] 'doc-view-previous-page)
263 (define-key map (kbd "SPC") 'doc-view-scroll-up-or-next-page)
264 (define-key map (kbd "DEL") 'doc-view-scroll-down-or-previous-page)
265 (define-key map (kbd "M-<") 'doc-view-first-page)
266 (define-key map (kbd "M->") 'doc-view-last-page)
267 (define-key map [remap goto-line] 'doc-view-goto-page)
268 (define-key map [remap scroll-up] 'image-scroll-up)
269 (define-key map [remap scroll-down] 'image-scroll-down)
270 ;; Zoom in/out.
271 (define-key map "+" 'doc-view-enlarge)
272 (define-key map "-" 'doc-view-shrink)
273 ;; Killing/burying the buffer (and the process)
274 (define-key map (kbd "q") 'bury-buffer)
275 (define-key map (kbd "k") 'doc-view-kill-proc-and-buffer)
276 (define-key map (kbd "K") 'doc-view-kill-proc)
277 ;; Slicing the image
278 (define-key map (kbd "s s") 'doc-view-set-slice)
279 (define-key map (kbd "s m") 'doc-view-set-slice-using-mouse)
280 (define-key map (kbd "s r") 'doc-view-reset-slice)
281 ;; Searching
282 (define-key map (kbd "C-s") 'doc-view-search)
283 (define-key map (kbd "<find>") 'doc-view-search)
284 (define-key map (kbd "C-r") 'doc-view-search-backward)
285 ;; Scrolling
286 (define-key map [remap forward-char] 'image-forward-hscroll)
287 (define-key map [remap backward-char] 'image-backward-hscroll)
288 (define-key map [remap next-line] 'image-next-line)
289 (define-key map [remap previous-line] 'image-previous-line)
290 ;; Show the tooltip
291 (define-key map (kbd "C-t") 'doc-view-show-tooltip)
292 ;; Toggle between text and image display or editing
293 (define-key map (kbd "C-c C-c") 'doc-view-toggle-display)
294 ;; Reconvert the current document
295 (define-key map (kbd "g") 'revert-buffer)
296 (define-key map (kbd "r") 'revert-buffer)
297 map)
298 "Keymap used by `doc-view-mode' when displaying a doc as a set of images.")
300 (easy-menu-define doc-view-menu doc-view-mode-map
301 "Menu for Doc View mode."
302 '("DocView"
303 ["Set Slice" doc-view-set-slice-using-mouse]
304 ["Set Slice (manual)" doc-view-set-slice]
305 ["Reset Slice" doc-view-reset-slice]
306 "---"
307 ["Search" doc-view-search]
308 ["Search Backwards" doc-view-search-backward]
309 ["Toggle display" doc-view-toggle-display]
312 (defvar doc-view-minor-mode-map
313 (let ((map (make-sparse-keymap)))
314 ;; Toggle between text and image display or editing
315 (define-key map (kbd "C-c C-c") 'doc-view-toggle-display)
316 map)
317 "Keymap used by `doc-minor-view-mode'.")
319 ;;;; Navigation Commands
321 (defun doc-view-goto-page (page)
322 "View the page given by PAGE."
323 (interactive "nPage: ")
324 (let ((len (length doc-view-current-files)))
325 (if (< page 1)
326 (setq page 1)
327 (when (> page len)
328 (setq page len)))
329 (setq doc-view-current-page page
330 doc-view-current-info
331 (concat
332 (propertize
333 (format "Page %d of %d."
334 doc-view-current-page
335 len) 'face 'bold)
336 ;; Tell user if converting isn't finished yet
337 (if doc-view-current-converter-process
338 " (still converting...)\n"
339 "\n")
340 ;; Display context infos if this page matches the last search
341 (when (and doc-view-current-search-matches
342 (assq doc-view-current-page
343 doc-view-current-search-matches))
344 (concat (propertize "Search matches:\n" 'face 'bold)
345 (let ((contexts ""))
346 (dolist (m (cdr (assq doc-view-current-page
347 doc-view-current-search-matches)))
348 (setq contexts (concat contexts " - \"" m "\"\n")))
349 contexts)))))
350 ;; Update the buffer
351 (doc-view-insert-image (nth (1- page) doc-view-current-files)
352 :pointer 'arrow)
353 (overlay-put doc-view-current-overlay 'help-echo doc-view-current-info)
354 (goto-char (point-min))
355 ;; This seems to be needed for set-window-hscroll (in
356 ;; image-forward-hscroll) to do something useful, I don't have time to
357 ;; debug this now. :-( --Stef
358 (forward-char)))
360 (defun doc-view-next-page (&optional arg)
361 "Browse ARG pages forward."
362 (interactive "p")
363 (doc-view-goto-page (+ doc-view-current-page (or arg 1))))
365 (defun doc-view-previous-page (&optional arg)
366 "Browse ARG pages backward."
367 (interactive "p")
368 (doc-view-goto-page (- doc-view-current-page (or arg 1))))
370 (defun doc-view-first-page ()
371 "View the first page."
372 (interactive)
373 (doc-view-goto-page 1))
375 (defun doc-view-last-page ()
376 "View the last page."
377 (interactive)
378 (doc-view-goto-page (length doc-view-current-files)))
380 (defun doc-view-scroll-up-or-next-page ()
381 "Scroll page up if possible, else goto next page."
382 (interactive)
383 (when (= (window-vscroll) (image-scroll-up nil))
384 (let ((cur-page doc-view-current-page))
385 (doc-view-next-page)
386 (when (/= cur-page doc-view-current-page)
387 (set-window-vscroll nil 0)))))
389 (defun doc-view-scroll-down-or-previous-page ()
390 "Scroll page down if possible, else goto previous page."
391 (interactive)
392 (when (= (window-vscroll) (image-scroll-down nil))
393 (let ((cur-page doc-view-current-page))
394 (doc-view-previous-page)
395 (when (/= cur-page doc-view-current-page)
396 (image-scroll-up nil)))))
398 ;;;; Utility Functions
400 (defun doc-view-kill-proc ()
401 "Kill the current converter process."
402 (interactive)
403 (when doc-view-current-converter-process
404 (kill-process doc-view-current-converter-process)
405 (setq doc-view-current-converter-process nil))
406 (when doc-view-current-timer
407 (cancel-timer doc-view-current-timer)
408 (setq doc-view-current-timer nil))
409 (setq mode-line-process nil))
411 (defun doc-view-kill-proc-and-buffer ()
412 "Kill the current converter process and buffer."
413 (interactive)
414 (doc-view-kill-proc)
415 (when (eq major-mode 'doc-view-mode)
416 (kill-buffer (current-buffer))))
418 (defun doc-view-make-safe-dir (dir)
419 (condition-case nil
420 (let ((umask (default-file-modes)))
421 (unwind-protect
422 (progn
423 ;; Create temp files with strict access rights. It's easy to
424 ;; loosen them later, whereas it's impossible to close the
425 ;; time-window of loose permissions otherwise.
426 (set-default-file-modes #o0700)
427 (make-directory dir))
428 ;; Reset the umask.
429 (set-default-file-modes umask)))
430 (file-already-exists
431 (if (file-symlink-p dir)
432 (error "Danger: %s points to a symbolic link" dir))
433 ;; In case it was created earlier with looser rights.
434 ;; We could check the mode info returned by file-attributes, but it's
435 ;; a pain to parse and it may not tell you what we want under
436 ;; non-standard file-systems. So let's just say what we want and let
437 ;; the underlying C code and file-system figure it out.
438 ;; This also ends up checking a bunch of useful conditions: it makes
439 ;; sure we have write-access to the directory and that we own it, thus
440 ;; closing a bunch of security holes.
441 (set-file-modes dir #o0700))))
443 (defun doc-view-current-cache-dir ()
444 "Return the directory where the png files of the current doc should be saved.
445 It's a subdirectory of `doc-view-cache-directory'."
446 (if doc-view-current-cache-dir
447 doc-view-current-cache-dir
448 ;; Try and make sure doc-view-cache-directory exists and is safe.
449 (doc-view-make-safe-dir doc-view-cache-directory)
450 ;; Now compute the subdirectory to use.
451 (setq doc-view-current-cache-dir
452 (file-name-as-directory
453 (expand-file-name
454 (let ((doc buffer-file-name))
455 (concat (file-name-nondirectory doc)
457 (with-temp-buffer
458 (insert-file-contents-literally doc)
459 (md5 (current-buffer)))))
460 doc-view-cache-directory)))))
462 (defun doc-view-remove-if (predicate list)
463 "Return LIST with all items removed that satisfy PREDICATE."
464 (let (new-list)
465 (dolist (item list (nreverse new-list))
466 (when (not (funcall predicate item))
467 (setq new-list (cons item new-list))))))
469 ;;;###autoload
470 (defun doc-view-mode-p (type)
471 "Return non-nil if image type TYPE is available for `doc-view'.
472 Image types are symbols like `dvi', `postscript' or `pdf'."
473 (and (display-graphic-p)
474 (image-type-available-p 'png)
475 (cond
476 ((eq type 'dvi)
477 (and (doc-view-mode-p 'pdf)
478 doc-view-dvipdfm-program
479 (executable-find doc-view-dvipdfm-program)))
480 ((or (eq type 'postscript) (eq type 'ps) (eq type 'eps)
481 (eq type 'pdf))
482 (and doc-view-ghostscript-program
483 (executable-find doc-view-ghostscript-program)))
484 (t ;; unknown image type
485 nil))))
487 ;;;; Conversion Functions
489 (defvar doc-view-shrink-factor 1.125)
491 (defun doc-view-enlarge (factor)
492 "Enlarge the document."
493 (interactive (list doc-view-shrink-factor))
494 (set (make-local-variable 'doc-view-resolution)
495 (* factor doc-view-resolution))
496 (doc-view-reconvert-doc))
498 (defun doc-view-shrink (factor)
499 "Shrink the document."
500 (interactive (list doc-view-shrink-factor))
501 (doc-view-enlarge (/ 1.0 factor)))
503 (defun doc-view-reconvert-doc ()
504 "Reconvert the current document.
505 Should be invoked when the cached images aren't up-to-date."
506 (interactive)
507 (doc-view-kill-proc)
508 ;; Clear the old cached files
509 (when (file-exists-p (doc-view-current-cache-dir))
510 (dired-delete-file (doc-view-current-cache-dir) 'always))
511 (doc-view-initiate-display))
513 (defun doc-view-dvi->pdf-sentinel (proc event)
514 "If DVI->PDF conversion was successful, convert the PDF to PNG now."
515 (if (not (string-match "finished" event))
516 (message "DocView: dvi->pdf process changed status to %s." event)
517 (with-current-buffer (process-get proc 'buffer)
518 (setq doc-view-current-converter-process nil
519 mode-line-process nil)
520 ;; Now go on converting this PDF to a set of PNG files.
521 (let* ((pdf (process-get proc 'pdf-file))
522 (png (expand-file-name "page-%d.png"
523 (doc-view-current-cache-dir))))
524 (doc-view-pdf/ps->png pdf png)))))
526 (defun doc-view-dvi->pdf (dvi pdf)
527 "Convert DVI to PDF asynchronously."
528 (setq doc-view-current-converter-process
529 (start-process "dvi->pdf" doc-view-conversion-buffer
530 doc-view-dvipdfm-program
531 "-o" pdf dvi)
532 mode-line-process (list (format ":%s" doc-view-current-converter-process)))
533 (set-process-sentinel doc-view-current-converter-process
534 'doc-view-dvi->pdf-sentinel)
535 (process-put doc-view-current-converter-process 'buffer (current-buffer))
536 (process-put doc-view-current-converter-process 'pdf-file pdf))
538 (defun doc-view-pdf/ps->png-sentinel (proc event)
539 "If PDF/PS->PNG conversion was successful, update the display."
540 (if (not (string-match "finished" event))
541 (message "DocView: converter process changed status to %s." event)
542 (with-current-buffer (process-get proc 'buffer)
543 (setq doc-view-current-converter-process nil
544 mode-line-process nil)
545 (when doc-view-current-timer
546 (cancel-timer doc-view-current-timer)
547 (setq doc-view-current-timer nil))
548 ;; Yippie, finished. Update the display!
549 (doc-view-display buffer-file-name 'force))))
551 (defun doc-view-pdf/ps->png (pdf-ps png)
552 "Convert PDF-PS to PNG asynchronously."
553 (setq doc-view-current-converter-process
554 (apply 'start-process
555 (append (list "pdf/ps->png" doc-view-conversion-buffer
556 doc-view-ghostscript-program)
557 doc-view-ghostscript-options
558 (list (format "-r%d" (round doc-view-resolution)))
559 (list (concat "-sOutputFile=" png))
560 (list pdf-ps)))
561 mode-line-process (list (format ":%s" doc-view-current-converter-process)))
562 (process-put doc-view-current-converter-process
563 'buffer (current-buffer))
564 (set-process-sentinel doc-view-current-converter-process
565 'doc-view-pdf/ps->png-sentinel)
566 (when doc-view-conversion-refresh-interval
567 (setq doc-view-current-timer
568 (run-at-time "1 secs" doc-view-conversion-refresh-interval
569 'doc-view-display
570 buffer-file-name))))
572 (defun doc-view-pdf->txt-sentinel (proc event)
573 (if (not (string-match "finished" event))
574 (message "DocView: converter process changed status to %s." event)
575 (let ((current-buffer (current-buffer))
576 (proc-buffer (process-get proc 'buffer)))
577 (with-current-buffer proc-buffer
578 (setq doc-view-current-converter-process nil
579 mode-line-process nil)
580 ;; If the user looks at the DocView buffer where the conversion was
581 ;; performed, search anew. This time it will be queried for a regexp.
582 (when (eq current-buffer proc-buffer)
583 (doc-view-search nil))))))
585 (defun doc-view-pdf->txt (pdf txt)
586 "Convert PDF to TXT asynchronously."
587 (setq doc-view-current-converter-process
588 (start-process "pdf->txt" doc-view-conversion-buffer
589 doc-view-pdftotext-program "-raw"
590 pdf txt)
591 mode-line-process (list (format ":%s" doc-view-current-converter-process)))
592 (set-process-sentinel doc-view-current-converter-process
593 'doc-view-pdf->txt-sentinel)
594 (process-put doc-view-current-converter-process 'buffer (current-buffer)))
596 (defun doc-view-ps->pdf-sentinel (proc event)
597 (if (not (string-match "finished" event))
598 (message "DocView: converter process changed status to %s." event)
599 (with-current-buffer (process-get proc 'buffer)
600 (setq doc-view-current-converter-process nil
601 mode-line-process nil)
602 ;; Now we can transform to plain text.
603 (doc-view-pdf->txt (process-get proc 'pdf-file)
604 (expand-file-name "doc.txt"
605 (doc-view-current-cache-dir))))))
607 (defun doc-view-ps->pdf (ps pdf)
608 "Convert PS to PDF asynchronously."
609 (setq doc-view-current-converter-process
610 (start-process "ps->pdf" doc-view-conversion-buffer
611 doc-view-ps2pdf-program
612 ;; Avoid security problems when rendering files from
613 ;; untrusted sources.
614 "-dSAFER"
615 ;; in-file and out-file
616 ps pdf)
617 mode-line-process (list (format ":%s" doc-view-current-converter-process)))
618 (set-process-sentinel doc-view-current-converter-process
619 'doc-view-ps->pdf-sentinel)
620 (process-put doc-view-current-converter-process 'buffer (current-buffer))
621 (process-put doc-view-current-converter-process 'pdf-file pdf))
623 (defun doc-view-convert-current-doc ()
624 "Convert `buffer-file-name' to a set of png files, one file per page.
625 Those files are saved in the directory given by the function
626 `doc-view-current-cache-dir'."
627 ;; Let stale files still display while we recompute the new ones, so only
628 ;; flush the cache when the conversion is over. One of the reasons why it
629 ;; is important to keep displaying the stale page is so that revert-buffer
630 ;; preserves the horizontal/vertical scroll settings (which are otherwise
631 ;; resets during the redisplay).
632 (setq doc-view-pending-cache-flush t)
633 (let ((png-file (expand-file-name "page-%d.png"
634 (doc-view-current-cache-dir))))
635 (make-directory (doc-view-current-cache-dir))
636 (if (not (string= (file-name-extension buffer-file-name) "dvi"))
637 ;; Convert to PNG images.
638 (doc-view-pdf/ps->png buffer-file-name png-file)
639 ;; DVI files have to be converted to PDF before Ghostscript can process
640 ;; it.
641 (doc-view-dvi->pdf buffer-file-name
642 (expand-file-name "doc.pdf"
643 doc-view-current-cache-dir)))))
645 ;;;; Slicing
647 (defun doc-view-set-slice (x y width height)
648 "Set the slice of the images that should be displayed.
649 You can use this function to tell doc-view not to display the
650 margins of the document. It prompts for the top-left corner (X
651 and Y) of the slice to display and its WIDTH and HEIGHT.
653 See `doc-view-set-slice-using-mouse' for a more convenient way to
654 do that. To reset the slice use `doc-view-reset-slice'."
655 (interactive
656 (let* ((size (image-size doc-view-current-image t))
657 (a (read-number (format "Top-left X (0..%d): " (car size))))
658 (b (read-number (format "Top-left Y (0..%d): " (cdr size))))
659 (c (read-number (format "Width (0..%d): " (- (car size) a))))
660 (d (read-number (format "Height (0..%d): " (- (cdr size) b)))))
661 (list a b c d)))
662 (setq doc-view-current-slice (list x y width height))
663 ;; Redisplay
664 (doc-view-goto-page doc-view-current-page))
666 (defun doc-view-set-slice-using-mouse ()
667 "Set the slice of the images that should be displayed.
668 You set the slice by pressing mouse-1 at its top-left corner and
669 dragging it to its bottom-right corner. See also
670 `doc-view-set-slice' and `doc-view-reset-slice'."
671 (interactive)
672 (let (x y w h done)
673 (while (not done)
674 (let ((e (read-event
675 (concat "Press mouse-1 at the top-left corner and "
676 "drag it to the bottom-right corner!"))))
677 (when (eq (car e) 'drag-mouse-1)
678 (setq x (car (posn-object-x-y (event-start e))))
679 (setq y (cdr (posn-object-x-y (event-start e))))
680 (setq w (- (car (posn-object-x-y (event-end e))) x))
681 (setq h (- (cdr (posn-object-x-y (event-end e))) y))
682 (setq done t))))
683 (doc-view-set-slice x y w h)))
685 (defun doc-view-reset-slice ()
686 "Reset the current slice.
687 After calling this function whole pages will be visible again."
688 (interactive)
689 (setq doc-view-current-slice nil)
690 ;; Redisplay
691 (doc-view-goto-page doc-view-current-page))
693 ;;;; Display
695 (defun doc-view-insert-image (file &rest args)
696 "Insert the given png FILE.
697 ARGS is a list of image descriptors."
698 (when doc-view-pending-cache-flush
699 (clear-image-cache)
700 (setq doc-view-pending-cache-flush nil))
701 (let ((image (apply 'create-image file 'png nil args)))
702 (setq doc-view-current-image image)
703 (move-overlay doc-view-current-overlay (point-min) (point-max))
704 (overlay-put doc-view-current-overlay 'display
705 (if doc-view-current-slice
706 (list (cons 'slice doc-view-current-slice) image)
707 image))))
709 (defun doc-view-sort (a b)
710 "Return non-nil if A should be sorted before B.
711 Predicate for sorting `doc-view-current-files'."
712 (or (< (length a) (length b))
713 (and (= (length a) (length b))
714 (string< a b))))
716 (defun doc-view-display (doc &optional force)
717 "Start viewing the document DOC.
718 If FORCE is non-nil, start viewing even if the document does not
719 have the page we want to view."
720 (with-current-buffer (get-file-buffer doc)
721 (setq doc-view-current-files
722 (sort (directory-files (doc-view-current-cache-dir) t
723 "page-[0-9]+\\.png" t)
724 'doc-view-sort))
725 (when (or force
726 (>= (length doc-view-current-files)
727 (or doc-view-current-page 1)))
728 (doc-view-goto-page doc-view-current-page))))
730 (defun doc-view-buffer-message ()
731 ;; Only show this message initially, not when refreshing the buffer (in which
732 ;; case it's better to keep displaying the "stale" page while computing
733 ;; the fresh new ones).
734 (unless (overlay-get doc-view-current-overlay 'display)
735 (overlay-put doc-view-current-overlay 'display
736 (concat (propertize "Welcome to DocView!" 'face 'bold)
737 "\n"
739 If you see this buffer it means that the document you want to view is being
740 converted to PNG and the conversion of the first page hasn't finished yet or
741 `doc-view-conversion-refresh-interval' is set to nil.
743 For now these keys are useful:
745 `q' : Bury this buffer. Conversion will go on in background.
746 `k' : Kill the conversion process and this buffer.
747 `K' : Kill the conversion process.\n"))))
749 (defun doc-view-show-tooltip ()
750 (interactive)
751 (tooltip-show doc-view-current-info))
753 ;;;;; Toggle between editing and viewing
755 (defun doc-view-toggle-display ()
756 "Toggle between editing a document as text or viewing it."
757 (interactive)
758 (if (eq major-mode 'doc-view-mode)
759 ;; Switch to editing mode
760 (progn
761 (doc-view-kill-proc)
762 (setq buffer-read-only nil)
763 (delete-overlay doc-view-current-overlay)
764 ;; Switch to the previously used major mode or fall back to fundamental
765 ;; mode.
766 (if doc-view-previous-major-mode
767 (funcall doc-view-previous-major-mode)
768 (fundamental-mode))
769 (doc-view-minor-mode 1))
770 ;; Switch to doc-view-mode
771 (when (and (buffer-modified-p)
772 (y-or-n-p "The buffer has been modified. Save the changes? "))
773 (save-buffer))
774 (doc-view-mode)))
776 ;;;; Searching
778 (defun doc-view-search-internal (regexp file)
779 "Return a list of FILE's pages that contain text matching REGEXP.
780 The value is an alist of the form (PAGE CONTEXTS) where PAGE is
781 the pagenumber and CONTEXTS are all lines of text containing a match."
782 (with-temp-buffer
783 (insert-file-contents file)
784 (let ((page 1)
785 (lastpage 1)
786 matches)
787 (while (re-search-forward (concat "\\(?:\\([\f]\\)\\|\\("
788 regexp "\\)\\)") nil t)
789 (when (match-string 1) (setq page (1+ page)))
790 (when (match-string 2)
791 (if (/= page lastpage)
792 (push (cons page
793 (list (buffer-substring
794 (line-beginning-position)
795 (line-end-position))))
796 matches)
797 (setq matches (cons
798 (append
800 ;; This page already is a match.
801 (car matches)
802 ;; This is the first match on page.
803 (list page))
804 (list (buffer-substring
805 (line-beginning-position)
806 (line-end-position))))
807 (cdr matches))))
808 (setq lastpage page)))
809 (nreverse matches))))
811 (defun doc-view-search-no-of-matches (list)
812 "Extract the number of matches from the search result LIST."
813 (let ((no 0))
814 (dolist (p list)
815 (setq no (+ no (1- (length p)))))
816 no))
818 (defun doc-view-search-backward (new-query)
819 "Call `doc-view-search' for backward search.
820 If prefix NEW-QUERY is given, ask for a new regexp."
821 (interactive "P")
822 (doc-view-search new-query t))
824 (defun doc-view-search (new-query &optional backward)
825 "Jump to the next match or initiate a new search if NEW-QUERY is given.
826 If the current document hasn't been transformed to plain text
827 till now do that first.
828 If BACKWARD is non-nil, jump to the previous match."
829 (interactive "P")
830 (if (and (not new-query)
831 doc-view-current-search-matches)
832 (if backward
833 (doc-view-search-previous-match 1)
834 (doc-view-search-next-match 1))
835 ;; New search, so forget the old results.
836 (setq doc-view-current-search-matches nil)
837 (let ((txt (expand-file-name "doc.txt"
838 (doc-view-current-cache-dir))))
839 (if (file-readable-p txt)
840 (progn
841 (setq doc-view-current-search-matches
842 (doc-view-search-internal
843 (read-from-minibuffer "Regexp: ")
844 txt))
845 (message "DocView: search yielded %d matches."
846 (doc-view-search-no-of-matches
847 doc-view-current-search-matches)))
848 ;; We must convert to TXT first!
849 (if doc-view-current-converter-process
850 (message "DocView: please wait till conversion finished.")
851 (let ((ext (file-name-extension buffer-file-name)))
852 (cond
853 ((string= ext "pdf")
854 ;; Doc is a PDF, so convert it to TXT
855 (doc-view-pdf->txt buffer-file-name txt))
856 ((string= ext "ps")
857 ;; Doc is a PS, so convert it to PDF (which will be converted to
858 ;; TXT thereafter).
859 (doc-view-ps->pdf buffer-file-name
860 (expand-file-name "doc.pdf"
861 (doc-view-current-cache-dir))))
862 ((string= ext "dvi")
863 ;; Doc is a DVI. This means that a doc.pdf already exists in its
864 ;; cache subdirectory.
865 (doc-view-pdf->txt (expand-file-name "doc.pdf"
866 (doc-view-current-cache-dir))
867 txt))
868 (t (error "DocView doesn't know what to do")))))))))
870 (defun doc-view-search-next-match (arg)
871 "Go to the ARGth next matching page."
872 (interactive "p")
873 (let* ((next-pages (doc-view-remove-if
874 (lambda (i) (<= (car i) doc-view-current-page))
875 doc-view-current-search-matches))
876 (page (car (nth (1- arg) next-pages))))
877 (if page
878 (doc-view-goto-page page)
879 (when (and
880 doc-view-current-search-matches
881 (y-or-n-p "No more matches after current page. Wrap to first match? "))
882 (doc-view-goto-page (caar doc-view-current-search-matches))))))
884 (defun doc-view-search-previous-match (arg)
885 "Go to the ARGth previous matching page."
886 (interactive "p")
887 (let* ((prev-pages (doc-view-remove-if
888 (lambda (i) (>= (car i) doc-view-current-page))
889 doc-view-current-search-matches))
890 (page (car (nth (1- arg) (nreverse prev-pages)))))
891 (if page
892 (doc-view-goto-page page)
893 (when (and
894 doc-view-current-search-matches
895 (y-or-n-p "No more matches before current page. Wrap to last match? "))
896 (doc-view-goto-page (caar (last doc-view-current-search-matches)))))))
898 ;;;; User interface commands and the mode
900 ;; (put 'doc-view-mode 'mode-class 'special)
902 (defun doc-view-initiate-display ()
903 ;; Switch to image display if possible
904 (if (doc-view-mode-p (intern (file-name-extension buffer-file-name)))
905 (progn
906 (doc-view-buffer-message)
907 (setq doc-view-current-page (or doc-view-current-page 1))
908 (if (file-exists-p (doc-view-current-cache-dir))
909 (progn
910 (message "DocView: using cached files!")
911 (doc-view-display buffer-file-name 'force))
912 (doc-view-convert-current-doc))
913 (message
914 "%s"
915 (substitute-command-keys
916 (concat "Type \\[doc-view-toggle-display] to toggle between "
917 "editing or viewing the document."))))
918 (message
919 "%s"
920 (substitute-command-keys
921 (concat "No image (png) support available or some conversion utility for "
922 (file-name-extension buffer-file-name)" files is missing. "
923 "Type \\[doc-view-toggle-display] to switch to an editing mode.")))))
925 (defvar bookmark-make-cell-function)
927 ;;;###autoload
928 (defun doc-view-mode ()
929 "Major mode in DocView buffers.
930 You can use \\<doc-view-mode-map>\\[doc-view-toggle-display] to
931 toggle between displaying the document or editing it as text."
932 (interactive)
933 ;; Handle compressed files, TRAMP files, files inside archives
934 (cond
935 (jka-compr-really-do-compress
936 (let ((file (expand-file-name
937 (file-name-nondirectory
938 (file-name-sans-extension buffer-file-name))
939 doc-view-cache-directory)))
940 (write-region nil nil file)
941 (setq buffer-file-name file)))
942 ((or
943 (not (file-exists-p buffer-file-name))
944 (tramp-tramp-file-p buffer-file-name))
945 (let ((file (expand-file-name
946 (file-name-nondirectory buffer-file-name)
947 doc-view-cache-directory)))
948 (write-region nil nil file)
949 (setq buffer-file-name file))))
951 (let* ((prev-major-mode (if (eq major-mode 'doc-view-mode)
952 doc-view-previous-major-mode
953 major-mode)))
954 (kill-all-local-variables)
955 (set (make-local-variable 'doc-view-previous-major-mode) prev-major-mode))
957 (make-local-variable 'doc-view-current-files)
958 (make-local-variable 'doc-view-current-image)
959 (make-local-variable 'doc-view-current-page)
960 (make-local-variable 'doc-view-current-converter-process)
961 (make-local-variable 'doc-view-current-timer)
962 (make-local-variable 'doc-view-current-slice)
963 (make-local-variable 'doc-view-current-cache-dir)
964 (make-local-variable 'doc-view-current-info)
965 (make-local-variable 'doc-view-current-search-matches)
966 (set (make-local-variable 'doc-view-current-overlay)
967 (make-overlay (point-min) (point-max) nil t))
968 (add-hook 'change-major-mode-hook
969 (lambda () (delete-overlay doc-view-current-overlay))
970 nil t)
971 (set (make-local-variable 'mode-line-position)
972 '(" P" (:eval (number-to-string doc-view-current-page))
973 "/" (:eval (number-to-string (length doc-view-current-files)))))
974 (set (make-local-variable 'cursor-type) nil)
975 (use-local-map doc-view-mode-map)
976 (set (make-local-variable 'after-revert-hook) 'doc-view-reconvert-doc)
977 (set (make-local-variable 'bookmark-make-cell-function)
978 'doc-view-bookmark-make-cell)
979 (setq mode-name "DocView"
980 buffer-read-only t
981 major-mode 'doc-view-mode)
982 (doc-view-initiate-display)
983 (run-mode-hooks 'doc-view-mode-hook))
985 ;;;###autoload
986 (define-minor-mode doc-view-minor-mode
987 "Toggle Doc view minor mode.
988 With arg, turn Doc view minor mode on if arg is positive, off otherwise.
989 See the command `doc-view-mode' for more information on this mode."
990 nil " DocView" doc-view-minor-mode-map
991 :group 'doc-view
992 (when doc-view-minor-mode
993 (add-hook 'change-major-mode-hook (lambda () (doc-view-minor-mode -1)) nil t)
994 (message
995 "%s"
996 (substitute-command-keys
997 "Type \\[doc-view-toggle-display] to toggle between editing or viewing the document."))))
999 (defun doc-view-clear-cache ()
1000 "Delete the whole cache (`doc-view-cache-directory')."
1001 (interactive)
1002 (dired-delete-file doc-view-cache-directory 'always)
1003 (make-directory doc-view-cache-directory))
1005 (defun doc-view-dired-cache ()
1006 "Open `dired' in `doc-view-cache-directory'."
1007 (interactive)
1008 (dired doc-view-cache-directory))
1011 ;;;; Bookmark integration
1013 (defun doc-view-bookmark-make-cell (annotation &rest args)
1014 (let ((the-record
1015 `((filename . ,(buffer-file-name))
1016 (page . ,doc-view-current-page)
1017 (handler . doc-view-bookmark-jump))))
1019 ;; Take no chances with text properties
1020 (set-text-properties 0 (length annotation) nil annotation)
1022 (when annotation
1023 (nconc the-record (list (cons 'annotation annotation))))
1025 ;; Finally, return the completed record.
1026 the-record))
1029 (declare-function bookmark-get-filename "bookmark" (bookmark))
1030 (declare-function bookmark-get-bookmark-record "bookmark" (bookmark))
1032 ;;;###autoload
1033 (defun doc-view-bookmark-jump (bmk)
1034 ;; This implements the `handler' function interface for record type
1035 ;; returned by `bookmark-make-cell-function', which see.
1036 (save-window-excursion
1037 (let ((filename (bookmark-get-filename bmk))
1038 (page (cdr (assq 'page (bookmark-get-bookmark-record bmk)))))
1039 (find-file filename)
1040 (when (not (eq major-mode 'doc-view-mode))
1041 (doc-view-toggle-display))
1042 (doc-view-goto-page page)
1043 `((buffer ,(current-buffer)) (position ,1)))))
1046 (provide 'doc-view)
1048 ;; Local Variables:
1049 ;; mode: outline-minor
1050 ;; End:
1052 ;; arch-tag: 5d6e5c5e-095f-489e-b4e4-1ca90a7d79be
1053 ;;; doc-view.el ends here