(while-no-input): Don't splice BODY directly into the `or' form.
[emacs.git] / lisp / doc-view.el
blob83420c72731cc63833446344bbb259fa82e5a2ec
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 ;; - 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 (require 'dired)
137 (require 'image-mode)
138 (require 'jka-compr)
140 ;;;; Customization Options
142 (defgroup doc-view nil
143 "In-buffer viewer for PDF, PostScript and DVI files."
144 :link '(function-link doc-view)
145 :version "22.2"
146 :group 'applications
147 :group '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 (defvar doc-view-conversion-buffer " *doc-view conversion output*"
200 "The buffer where messages from the converter programs go to.")
202 (defcustom doc-view-conversion-refresh-interval 1
203 "Interval in seconds between refreshes of the DocView buffer while converting.
204 After such a refresh newly converted pages will be available for
205 viewing. If set to nil there won't be any refreshes and the
206 pages won't be displayed before conversion of the whole document
207 has finished."
208 :type 'integer
209 :group 'doc-view)
211 ;;;; Internal Variables
213 (defun doc-view-new-window-function (winprops)
214 (let ((ol (image-mode-window-get 'overlay winprops)))
215 (if ol
216 (setq ol (copy-overlay ol))
217 (setq ol (make-overlay (point-min) (point-max) nil t))
218 (overlay-put ol 'doc-view t))
219 (overlay-put ol 'window (car winprops))
220 (image-mode-window-put 'overlay ol winprops)))
222 (defvar doc-view-current-files nil
223 "Only used internally.")
225 (defvar doc-view-current-converter-process nil
226 "Only used internally.")
228 (defvar doc-view-current-timer nil
229 "Only used internally.")
231 (defvar doc-view-current-cache-dir nil
232 "Only used internally.")
234 (defvar doc-view-current-search-matches nil
235 "Only used internally.")
237 (defvar doc-view-pending-cache-flush nil
238 "Only used internally.")
240 (defvar doc-view-previous-major-mode nil
241 "Only used internally.")
243 (defvar doc-view-buffer-file-name nil
244 "Only used internally.
245 The file name used for conversion. Normally it's the same as
246 `buffer-file-name', but for remote files, compressed files and
247 files inside an archive it is a temporary copy of
248 the (uncompressed, extracted) file residing in
249 `doc-view-cache-directory'.")
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 (defmacro doc-view-current-page (&optional win)
322 `(image-mode-window-get 'page ,win))
323 (defmacro doc-view-current-info () `(image-mode-window-get 'info))
324 (defmacro doc-view-current-overlay () `(image-mode-window-get 'overlay))
325 (defmacro doc-view-current-image () `(image-mode-window-get 'image))
326 (defmacro doc-view-current-slice () `(image-mode-window-get 'slice))
328 (defun doc-view-goto-page (page)
329 "View the page given by PAGE."
330 (interactive "nPage: ")
331 (let ((len (length doc-view-current-files)))
332 (if (< page 1)
333 (setq page 1)
334 (when (and (> page len)
335 ;; As long as the converter is running, we don't know
336 ;; how many pages will be available.
337 (null doc-view-current-converter-process))
338 (setq page len)))
339 (setf (doc-view-current-page) page
340 (doc-view-current-info)
341 (concat
342 (propertize
343 (format "Page %d of %d." page len) 'face 'bold)
344 ;; Tell user if converting isn't finished yet
345 (if doc-view-current-converter-process
346 " (still converting...)\n"
347 "\n")
348 ;; Display context infos if this page matches the last search
349 (when (and doc-view-current-search-matches
350 (assq page doc-view-current-search-matches))
351 (concat (propertize "Search matches:\n" 'face 'bold)
352 (let ((contexts ""))
353 (dolist (m (cdr (assq page
354 doc-view-current-search-matches)))
355 (setq contexts (concat contexts " - \"" m "\"\n")))
356 contexts)))))
357 ;; Update the buffer
358 ;; We used to find the file name from doc-view-current-files but
359 ;; that's not right if the pages are not generated sequentially
360 ;; or if the page isn't in doc-view-current-files yet.
361 (doc-view-insert-image (expand-file-name (format "page-%d.png" page)
362 (doc-view-current-cache-dir))
363 :pointer 'arrow)
364 (overlay-put (doc-view-current-overlay)
365 'help-echo (doc-view-current-info))))
367 (defun doc-view-next-page (&optional arg)
368 "Browse ARG pages forward."
369 (interactive "p")
370 (doc-view-goto-page (+ (doc-view-current-page) (or arg 1))))
372 (defun doc-view-previous-page (&optional arg)
373 "Browse ARG pages backward."
374 (interactive "p")
375 (doc-view-goto-page (- (doc-view-current-page) (or arg 1))))
377 (defun doc-view-first-page ()
378 "View the first page."
379 (interactive)
380 (doc-view-goto-page 1))
382 (defun doc-view-last-page ()
383 "View the last page."
384 (interactive)
385 (doc-view-goto-page (length doc-view-current-files)))
387 (defun doc-view-scroll-up-or-next-page ()
388 "Scroll page up if possible, else goto next page."
389 (interactive)
390 (when (= (window-vscroll) (image-scroll-up nil))
391 (let ((cur-page (doc-view-current-page)))
392 (doc-view-next-page)
393 (when (/= cur-page (doc-view-current-page))
394 (set-window-vscroll nil 0)))))
396 (defun doc-view-scroll-down-or-previous-page ()
397 "Scroll page down if possible, else goto previous page."
398 (interactive)
399 (when (= (window-vscroll) (image-scroll-down nil))
400 (let ((cur-page (doc-view-current-page)))
401 (doc-view-previous-page)
402 (when (/= cur-page (doc-view-current-page))
403 (image-scroll-up nil)))))
405 ;;;; Utility Functions
407 (defun doc-view-kill-proc ()
408 "Kill the current converter process."
409 (interactive)
410 (when doc-view-current-converter-process
411 (ignore-errors ;; Maybe it's dead already?
412 (kill-process doc-view-current-converter-process))
413 (setq doc-view-current-converter-process nil))
414 (when doc-view-current-timer
415 (cancel-timer doc-view-current-timer)
416 (setq doc-view-current-timer nil))
417 (setq mode-line-process nil))
419 (defun doc-view-kill-proc-and-buffer ()
420 "Kill the current converter process and buffer."
421 (interactive)
422 (doc-view-kill-proc)
423 (when (eq major-mode 'doc-view-mode)
424 (kill-buffer (current-buffer))))
426 (defun doc-view-make-safe-dir (dir)
427 (condition-case nil
428 (let ((umask (default-file-modes)))
429 (unwind-protect
430 (progn
431 ;; Create temp files with strict access rights. It's easy to
432 ;; loosen them later, whereas it's impossible to close the
433 ;; time-window of loose permissions otherwise.
434 (set-default-file-modes #o0700)
435 (make-directory dir))
436 ;; Reset the umask.
437 (set-default-file-modes umask)))
438 (file-already-exists
439 (if (file-symlink-p dir)
440 (error "Danger: %s points to a symbolic link" dir))
441 ;; In case it was created earlier with looser rights.
442 ;; We could check the mode info returned by file-attributes, but it's
443 ;; a pain to parse and it may not tell you what we want under
444 ;; non-standard file-systems. So let's just say what we want and let
445 ;; the underlying C code and file-system figure it out.
446 ;; This also ends up checking a bunch of useful conditions: it makes
447 ;; sure we have write-access to the directory and that we own it, thus
448 ;; closing a bunch of security holes.
449 (set-file-modes dir #o0700))))
451 (defun doc-view-current-cache-dir ()
452 "Return the directory where the png files of the current doc should be saved.
453 It's a subdirectory of `doc-view-cache-directory'."
454 (if doc-view-current-cache-dir
455 doc-view-current-cache-dir
456 ;; Try and make sure doc-view-cache-directory exists and is safe.
457 (doc-view-make-safe-dir doc-view-cache-directory)
458 ;; Now compute the subdirectory to use.
459 (setq doc-view-current-cache-dir
460 (file-name-as-directory
461 (expand-file-name
462 (concat (file-name-nondirectory buffer-file-name)
464 (let ((file doc-view-buffer-file-name))
465 (with-temp-buffer
466 (insert-file-contents-literally file)
467 (md5 (current-buffer)))))
468 doc-view-cache-directory)))))
470 (defun doc-view-remove-if (predicate list)
471 "Return LIST with all items removed that satisfy PREDICATE."
472 (let (new-list)
473 (dolist (item list (nreverse new-list))
474 (when (not (funcall predicate item))
475 (setq new-list (cons item new-list))))))
477 ;;;###autoload
478 (defun doc-view-mode-p (type)
479 "Return non-nil if image type TYPE is available for `doc-view'.
480 Image types are symbols like `dvi', `postscript' or `pdf'."
481 (and (display-graphic-p)
482 (image-type-available-p 'png)
483 (cond
484 ((eq type 'dvi)
485 (and (doc-view-mode-p 'pdf)
486 doc-view-dvipdfm-program
487 (executable-find doc-view-dvipdfm-program)))
488 ((or (eq type 'postscript) (eq type 'ps) (eq type 'eps)
489 (eq type 'pdf))
490 (and doc-view-ghostscript-program
491 (executable-find doc-view-ghostscript-program)))
492 (t ;; unknown image type
493 nil))))
495 ;;;; Conversion Functions
497 (defvar doc-view-shrink-factor 1.125)
499 (defun doc-view-enlarge (factor)
500 "Enlarge the document."
501 (interactive (list doc-view-shrink-factor))
502 (set (make-local-variable 'doc-view-resolution)
503 (* factor doc-view-resolution))
504 (doc-view-reconvert-doc))
506 (defun doc-view-shrink (factor)
507 "Shrink the document."
508 (interactive (list doc-view-shrink-factor))
509 (doc-view-enlarge (/ 1.0 factor)))
511 (defun doc-view-reconvert-doc ()
512 "Reconvert the current document.
513 Should be invoked when the cached images aren't up-to-date."
514 (interactive)
515 (doc-view-kill-proc)
516 ;; Clear the old cached files
517 (when (file-exists-p (doc-view-current-cache-dir))
518 (dired-delete-file (doc-view-current-cache-dir) 'always))
519 (doc-view-initiate-display))
521 (defun doc-view-dvi->pdf-sentinel (proc event)
522 "If DVI->PDF conversion was successful, convert the PDF to PNG now."
523 (if (not (string-match "finished" event))
524 (message "DocView: dvi->pdf process changed status to %s." event)
525 (with-current-buffer (process-get proc 'buffer)
526 (setq doc-view-current-converter-process nil
527 mode-line-process nil)
528 ;; Now go on converting this PDF to a set of PNG files.
529 (let* ((pdf (process-get proc 'pdf-file))
530 (png (expand-file-name "page-%d.png"
531 (doc-view-current-cache-dir))))
532 (doc-view-pdf/ps->png pdf png)))))
534 (defun doc-view-dvi->pdf (dvi pdf)
535 "Convert DVI to PDF asynchronously."
536 (setq doc-view-current-converter-process
537 (start-process "dvi->pdf" doc-view-conversion-buffer
538 doc-view-dvipdfm-program
539 "-o" pdf dvi)
540 mode-line-process (list (format ":%s" doc-view-current-converter-process)))
541 (set-process-sentinel doc-view-current-converter-process
542 'doc-view-dvi->pdf-sentinel)
543 (process-put doc-view-current-converter-process 'buffer (current-buffer))
544 (process-put doc-view-current-converter-process 'pdf-file pdf))
546 (defun doc-view-pdf/ps->png-sentinel (proc event)
547 "If PDF/PS->PNG conversion was successful, update the display."
548 (if (not (string-match "finished" event))
549 (message "DocView: converter process changed status to %s." event)
550 ;; FIXME: kill the process if we kill the buffer?
551 (when (buffer-live-p (process-get proc 'buffer))
552 (with-current-buffer (process-get proc 'buffer)
553 (setq doc-view-current-converter-process nil
554 mode-line-process nil)
555 (when doc-view-current-timer
556 (cancel-timer doc-view-current-timer)
557 (setq doc-view-current-timer nil))
558 ;; Yippie, finished. Update the display!
559 (doc-view-display (current-buffer) 'force)))))
561 (defun doc-view-pdf/ps->png (pdf-ps png)
562 "Convert PDF-PS to PNG asynchronously."
563 (setq doc-view-current-converter-process
564 ;; Make sure the process is started in an existing directory,
565 ;; (rather than some file-name-handler-managed dir, for example).
566 (let ((default-directory (file-name-directory pdf-ps)))
567 (apply 'start-process
568 (append (list "pdf/ps->png" doc-view-conversion-buffer
569 doc-view-ghostscript-program)
570 doc-view-ghostscript-options
571 (list (format "-r%d" (round doc-view-resolution)))
572 (list (concat "-sOutputFile=" png))
573 (list pdf-ps))))
574 mode-line-process (list (format ":%s" doc-view-current-converter-process)))
575 (process-put doc-view-current-converter-process
576 'buffer (current-buffer))
577 (set-process-sentinel doc-view-current-converter-process
578 'doc-view-pdf/ps->png-sentinel)
579 (when doc-view-conversion-refresh-interval
580 (setq doc-view-current-timer
581 (run-at-time "1 secs" doc-view-conversion-refresh-interval
582 'doc-view-display
583 (current-buffer)))))
585 (defun doc-view-pdf->txt-sentinel (proc event)
586 (if (not (string-match "finished" event))
587 (message "DocView: converter process changed status to %s." event)
588 (let ((current-buffer (current-buffer))
589 (proc-buffer (process-get proc 'buffer)))
590 (with-current-buffer proc-buffer
591 (setq doc-view-current-converter-process nil
592 mode-line-process nil)
593 ;; If the user looks at the DocView buffer where the conversion was
594 ;; performed, search anew. This time it will be queried for a regexp.
595 (when (eq current-buffer proc-buffer)
596 (doc-view-search nil))))))
598 (defun doc-view-pdf->txt (pdf txt)
599 "Convert PDF to TXT asynchronously."
600 (setq doc-view-current-converter-process
601 (start-process "pdf->txt" doc-view-conversion-buffer
602 doc-view-pdftotext-program "-raw"
603 pdf txt)
604 mode-line-process (list (format ":%s" doc-view-current-converter-process)))
605 (set-process-sentinel doc-view-current-converter-process
606 'doc-view-pdf->txt-sentinel)
607 (process-put doc-view-current-converter-process 'buffer (current-buffer)))
609 (defun doc-view-ps->pdf-sentinel (proc event)
610 (if (not (string-match "finished" event))
611 (message "DocView: converter process changed status to %s." event)
612 (with-current-buffer (process-get proc 'buffer)
613 (setq doc-view-current-converter-process nil
614 mode-line-process nil)
615 ;; Now we can transform to plain text.
616 (doc-view-pdf->txt (process-get proc 'pdf-file)
617 (expand-file-name "doc.txt"
618 (doc-view-current-cache-dir))))))
620 (defun doc-view-ps->pdf (ps pdf)
621 "Convert PS to PDF asynchronously."
622 (setq doc-view-current-converter-process
623 (start-process "ps->pdf" doc-view-conversion-buffer
624 doc-view-ps2pdf-program
625 ;; Avoid security problems when rendering files from
626 ;; untrusted sources.
627 "-dSAFER"
628 ;; in-file and out-file
629 ps pdf)
630 mode-line-process (list (format ":%s" doc-view-current-converter-process)))
631 (set-process-sentinel doc-view-current-converter-process
632 'doc-view-ps->pdf-sentinel)
633 (process-put doc-view-current-converter-process 'buffer (current-buffer))
634 (process-put doc-view-current-converter-process 'pdf-file pdf))
636 (defun doc-view-convert-current-doc ()
637 "Convert `doc-view-buffer-file-name' to a set of png files, one file per page.
638 Those files are saved in the directory given by the function
639 `doc-view-current-cache-dir'."
640 ;; Let stale files still display while we recompute the new ones, so only
641 ;; flush the cache when the conversion is over. One of the reasons why it
642 ;; is important to keep displaying the stale page is so that revert-buffer
643 ;; preserves the horizontal/vertical scroll settings (which are otherwise
644 ;; resets during the redisplay).
645 (setq doc-view-pending-cache-flush t)
646 (let ((png-file (expand-file-name "page-%d.png"
647 (doc-view-current-cache-dir))))
648 (make-directory (doc-view-current-cache-dir))
649 (if (not (string= (file-name-extension doc-view-buffer-file-name) "dvi"))
650 ;; Convert to PNG images.
651 (doc-view-pdf/ps->png doc-view-buffer-file-name png-file)
652 ;; DVI files have to be converted to PDF before Ghostscript can process
653 ;; it.
654 (doc-view-dvi->pdf doc-view-buffer-file-name
655 (expand-file-name "doc.pdf"
656 doc-view-current-cache-dir)))))
658 ;;;; Slicing
660 (defun doc-view-set-slice (x y width height)
661 "Set the slice of the images that should be displayed.
662 You can use this function to tell doc-view not to display the
663 margins of the document. It prompts for the top-left corner (X
664 and Y) of the slice to display and its WIDTH and HEIGHT.
666 See `doc-view-set-slice-using-mouse' for a more convenient way to
667 do that. To reset the slice use `doc-view-reset-slice'."
668 (interactive
669 (let* ((size (image-size (doc-view-current-image) t))
670 (a (read-number (format "Top-left X (0..%d): " (car size))))
671 (b (read-number (format "Top-left Y (0..%d): " (cdr size))))
672 (c (read-number (format "Width (0..%d): " (- (car size) a))))
673 (d (read-number (format "Height (0..%d): " (- (cdr size) b)))))
674 (list a b c d)))
675 (setf (doc-view-current-slice) (list x y width height))
676 ;; Redisplay
677 (doc-view-goto-page (doc-view-current-page)))
679 (defun doc-view-set-slice-using-mouse ()
680 "Set the slice of the images that should be displayed.
681 You set the slice by pressing mouse-1 at its top-left corner and
682 dragging it to its bottom-right corner. See also
683 `doc-view-set-slice' and `doc-view-reset-slice'."
684 (interactive)
685 (let (x y w h done)
686 (while (not done)
687 (let ((e (read-event
688 (concat "Press mouse-1 at the top-left corner and "
689 "drag it to the bottom-right corner!"))))
690 (when (eq (car e) 'drag-mouse-1)
691 (setq x (car (posn-object-x-y (event-start e))))
692 (setq y (cdr (posn-object-x-y (event-start e))))
693 (setq w (- (car (posn-object-x-y (event-end e))) x))
694 (setq h (- (cdr (posn-object-x-y (event-end e))) y))
695 (setq done t))))
696 (doc-view-set-slice x y w h)))
698 (defun doc-view-reset-slice ()
699 "Reset the current slice.
700 After calling this function whole pages will be visible again."
701 (interactive)
702 (setf (doc-view-current-slice) nil)
703 ;; Redisplay
704 (doc-view-goto-page (doc-view-current-page)))
706 ;;;; Display
708 (defun doc-view-insert-image (file &rest args)
709 "Insert the given png FILE.
710 ARGS is a list of image descriptors."
711 (when doc-view-pending-cache-flush
712 (clear-image-cache)
713 (setq doc-view-pending-cache-flush nil))
714 (let ((ol (doc-view-current-overlay))
715 (image (if (and file (file-readable-p file))
716 (apply 'create-image file 'png nil args)))
717 (slice (doc-view-current-slice)))
718 (setf (doc-view-current-image) image)
719 (move-overlay ol (point-min) (point-max))
720 (overlay-put ol 'display
721 (cond
722 (image
723 (if slice
724 (list (cons 'slice slice) image)
725 image))
726 ;; We're trying to display a page that doesn't exist.
727 (doc-view-current-converter-process
728 ;; Maybe the page doesn't exist *yet*.
729 "Cannot display this page (yet)!")
731 ;; Typically happens if the conversion process somehow
732 ;; failed. Better not signal an error here because it
733 ;; could prevent a subsequent reconversion from fixing
734 ;; the problem.
735 (concat "Cannot display this page!\n"
736 "Maybe because of a conversion failure!"))))
737 (let ((win (overlay-get ol 'window)))
738 (if (stringp (overlay-get ol 'display))
739 (progn ;Make sure the text is not scrolled out of view.
740 (set-window-hscroll win 0)
741 (set-window-vscroll win 0))
742 (let ((hscroll (image-mode-window-get 'hscroll win))
743 (vscroll (image-mode-window-get 'vscroll win)))
744 ;; Reset scroll settings, in case they were changed.
745 (if hscroll (set-window-hscroll win hscroll))
746 (if vscroll (set-window-vscroll win vscroll)))))))
748 (defun doc-view-sort (a b)
749 "Return non-nil if A should be sorted before B.
750 Predicate for sorting `doc-view-current-files'."
751 (or (< (length a) (length b))
752 (and (= (length a) (length b))
753 (string< a b))))
755 (defun doc-view-display (buffer &optional force)
756 "Start viewing the document in BUFFER.
757 If FORCE is non-nil, start viewing even if the document does not
758 have the page we want to view."
759 (with-current-buffer buffer
760 (let ((prev-pages doc-view-current-files))
761 (setq doc-view-current-files
762 (sort (directory-files (doc-view-current-cache-dir) t
763 "page-[0-9]+\\.png" t)
764 'doc-view-sort))
765 (dolist (win (get-buffer-window-list buffer nil t))
766 (let* ((page (doc-view-current-page win))
767 (pagefile (expand-file-name (format "page-%d.png" page)
768 (doc-view-current-cache-dir))))
769 (when (or force
770 (and (not (member pagefile prev-pages))
771 (member pagefile doc-view-current-files)))
772 (with-selected-window win
773 (assert (eq (current-buffer) buffer))
774 (doc-view-goto-page page))))))))
776 (defun doc-view-buffer-message ()
777 ;; Only show this message initially, not when refreshing the buffer (in which
778 ;; case it's better to keep displaying the "stale" page while computing
779 ;; the fresh new ones).
780 (unless (overlay-get (doc-view-current-overlay) 'display)
781 (overlay-put (doc-view-current-overlay) 'display
782 (concat (propertize "Welcome to DocView!" 'face 'bold)
783 "\n"
785 If you see this buffer it means that the document you want to view is being
786 converted to PNG and the conversion of the first page hasn't finished yet or
787 `doc-view-conversion-refresh-interval' is set to nil.
789 For now these keys are useful:
791 `q' : Bury this buffer. Conversion will go on in background.
792 `k' : Kill the conversion process and this buffer.
793 `K' : Kill the conversion process.\n"))))
795 (defun doc-view-show-tooltip ()
796 (interactive)
797 (tooltip-show (doc-view-current-info)))
799 ;;;;; Toggle between editing and viewing
801 (defun doc-view-toggle-display ()
802 "Toggle between editing a document as text or viewing it."
803 (interactive)
804 (if (eq major-mode 'doc-view-mode)
805 ;; Switch to editing mode
806 (progn
807 (doc-view-kill-proc)
808 (setq buffer-read-only nil)
809 (remove-overlays (point-min) (point-max) 'doc-view t)
810 (set (make-local-variable 'image-mode-winprops-alist) t)
811 ;; Switch to the previously used major mode or fall back to fundamental
812 ;; mode.
813 (if doc-view-previous-major-mode
814 (funcall doc-view-previous-major-mode)
815 (fundamental-mode))
816 (doc-view-minor-mode 1))
817 ;; Switch to doc-view-mode
818 (when (and (buffer-modified-p)
819 (y-or-n-p "The buffer has been modified. Save the changes? "))
820 (save-buffer))
821 (doc-view-mode)))
823 ;;;; Searching
825 (defun doc-view-search-internal (regexp file)
826 "Return a list of FILE's pages that contain text matching REGEXP.
827 The value is an alist of the form (PAGE CONTEXTS) where PAGE is
828 the pagenumber and CONTEXTS are all lines of text containing a match."
829 (with-temp-buffer
830 (insert-file-contents file)
831 (let ((page 1)
832 (lastpage 1)
833 matches)
834 (while (re-search-forward (concat "\\(?:\\([\f]\\)\\|\\("
835 regexp "\\)\\)") nil t)
836 (when (match-string 1) (setq page (1+ page)))
837 (when (match-string 2)
838 (if (/= page lastpage)
839 (push (cons page
840 (list (buffer-substring
841 (line-beginning-position)
842 (line-end-position))))
843 matches)
844 (setq matches (cons
845 (append
847 ;; This page already is a match.
848 (car matches)
849 ;; This is the first match on page.
850 (list page))
851 (list (buffer-substring
852 (line-beginning-position)
853 (line-end-position))))
854 (cdr matches))))
855 (setq lastpage page)))
856 (nreverse matches))))
858 (defun doc-view-search-no-of-matches (list)
859 "Extract the number of matches from the search result LIST."
860 (let ((no 0))
861 (dolist (p list)
862 (setq no (+ no (1- (length p)))))
863 no))
865 (defun doc-view-search-backward (new-query)
866 "Call `doc-view-search' for backward search.
867 If prefix NEW-QUERY is given, ask for a new regexp."
868 (interactive "P")
869 (doc-view-search new-query t))
871 (defun doc-view-search (new-query &optional backward)
872 "Jump to the next match or initiate a new search if NEW-QUERY is given.
873 If the current document hasn't been transformed to plain text
874 till now do that first.
875 If BACKWARD is non-nil, jump to the previous match."
876 (interactive "P")
877 (if (and (not new-query)
878 doc-view-current-search-matches)
879 (if backward
880 (doc-view-search-previous-match 1)
881 (doc-view-search-next-match 1))
882 ;; New search, so forget the old results.
883 (setq doc-view-current-search-matches nil)
884 (let ((txt (expand-file-name "doc.txt"
885 (doc-view-current-cache-dir))))
886 (if (file-readable-p txt)
887 (progn
888 (setq doc-view-current-search-matches
889 (doc-view-search-internal
890 (read-from-minibuffer "Regexp: ")
891 txt))
892 (message "DocView: search yielded %d matches."
893 (doc-view-search-no-of-matches
894 doc-view-current-search-matches)))
895 ;; We must convert to TXT first!
896 (if doc-view-current-converter-process
897 (message "DocView: please wait till conversion finished.")
898 (let ((ext (file-name-extension doc-view-buffer-file-name)))
899 (cond
900 ((string= ext "pdf")
901 ;; Doc is a PDF, so convert it to TXT
902 (doc-view-pdf->txt doc-view-buffer-file-name txt))
903 ((string= ext "ps")
904 ;; Doc is a PS, so convert it to PDF (which will be converted to
905 ;; TXT thereafter).
906 (doc-view-ps->pdf doc-view-buffer-file-name
907 (expand-file-name "doc.pdf"
908 (doc-view-current-cache-dir))))
909 ((string= ext "dvi")
910 ;; Doc is a DVI. This means that a doc.pdf already exists in its
911 ;; cache subdirectory.
912 (doc-view-pdf->txt (expand-file-name "doc.pdf"
913 (doc-view-current-cache-dir))
914 txt))
915 (t (error "DocView doesn't know what to do")))))))))
917 (defun doc-view-search-next-match (arg)
918 "Go to the ARGth next matching page."
919 (interactive "p")
920 (let* ((next-pages (doc-view-remove-if
921 (lambda (i) (<= (car i) (doc-view-current-page)))
922 doc-view-current-search-matches))
923 (page (car (nth (1- arg) next-pages))))
924 (if page
925 (doc-view-goto-page page)
926 (when (and
927 doc-view-current-search-matches
928 (y-or-n-p "No more matches after current page. Wrap to first match? "))
929 (doc-view-goto-page (caar doc-view-current-search-matches))))))
931 (defun doc-view-search-previous-match (arg)
932 "Go to the ARGth previous matching page."
933 (interactive "p")
934 (let* ((prev-pages (doc-view-remove-if
935 (lambda (i) (>= (car i) (doc-view-current-page)))
936 doc-view-current-search-matches))
937 (page (car (nth (1- arg) (nreverse prev-pages)))))
938 (if page
939 (doc-view-goto-page page)
940 (when (and
941 doc-view-current-search-matches
942 (y-or-n-p "No more matches before current page. Wrap to last match? "))
943 (doc-view-goto-page (caar (last doc-view-current-search-matches)))))))
945 ;;;; User interface commands and the mode
947 ;; (put 'doc-view-mode 'mode-class 'special)
949 (defun doc-view-initiate-display ()
950 ;; Switch to image display if possible
951 (if (doc-view-mode-p (intern (file-name-extension doc-view-buffer-file-name)))
952 (progn
953 (doc-view-buffer-message)
954 (setf (doc-view-current-page) (or (doc-view-current-page) 1))
955 (if (file-exists-p (doc-view-current-cache-dir))
956 (progn
957 (message "DocView: using cached files!")
958 (doc-view-display (current-buffer) 'force))
959 (doc-view-convert-current-doc))
960 (message
961 "%s"
962 (substitute-command-keys
963 (concat "Type \\[doc-view-toggle-display] to toggle between "
964 "editing or viewing the document."))))
965 (message
966 "%s"
967 (substitute-command-keys
968 (concat "No image (png) support available or some conversion utility for "
969 (file-name-extension doc-view-buffer-file-name)" files is missing. "
970 "Type \\[doc-view-toggle-display] to switch to an editing mode.")))))
972 (defvar bookmark-make-record-function)
974 (defun doc-view-clone-buffer-hook ()
975 ;; FIXME: There are several potential problems linked with reconversion
976 ;; and auto-revert when we have indirect buffers because they share their
977 ;; /tmp cache directory. This sharing is good (you'd rather not reconvert
978 ;; for each clone), but that means that clones need to collaborate a bit.
979 ;; I guess it mostly means: detect when a reconversion process is already
980 ;; running, and run the sentinel in all clones.
982 ;; Maybe the clones should really have a separate /tmp directory
983 ;; so they could have a different resolution and you could use clones
984 ;; for zooming.
985 (remove-overlays (point-min) (point-max) 'doc-view t)
986 (if (consp image-mode-winprops-alist) (setq image-mode-winprops-alist nil)))
988 ;;;###autoload
989 (defun doc-view-mode ()
990 "Major mode in DocView buffers.
991 You can use \\<doc-view-mode-map>\\[doc-view-toggle-display] to
992 toggle between displaying the document or editing it as text.
993 \\{doc-view-mode-map}"
994 (interactive)
996 (let* ((prev-major-mode (if (eq major-mode 'doc-view-mode)
997 doc-view-previous-major-mode
998 major-mode)))
999 (kill-all-local-variables)
1000 (set (make-local-variable 'doc-view-previous-major-mode) prev-major-mode))
1002 (doc-view-make-safe-dir doc-view-cache-directory)
1003 ;; Handle compressed files, remote files, files inside archives
1004 (set (make-local-variable 'doc-view-buffer-file-name)
1005 (cond
1006 (jka-compr-really-do-compress
1007 (expand-file-name
1008 (file-name-nondirectory
1009 (file-name-sans-extension buffer-file-name))
1010 doc-view-cache-directory))
1011 ;; Is the file readable by local processes?
1012 ;; We used to use `file-remote-p' but it's unclear what it's
1013 ;; supposed to return nil for things like local files accessed via
1014 ;; `su' or via file://...
1015 ((let ((file-name-handler-alist nil))
1016 (not (file-readable-p buffer-file-name)))
1017 (expand-file-name
1018 (file-name-nondirectory buffer-file-name)
1019 doc-view-cache-directory))
1020 (t buffer-file-name)))
1021 (when (not (string= doc-view-buffer-file-name buffer-file-name))
1022 (write-region nil nil doc-view-buffer-file-name))
1024 (make-local-variable 'doc-view-current-files)
1025 (make-local-variable 'doc-view-current-converter-process)
1026 (make-local-variable 'doc-view-current-timer)
1027 (make-local-variable 'doc-view-current-cache-dir)
1028 (make-local-variable 'doc-view-current-search-matches)
1029 (add-hook 'change-major-mode-hook
1030 (lambda () (remove-overlays (point-min) (point-max) 'doc-view t))
1031 nil t)
1032 (add-hook 'clone-indirect-buffer-hook 'doc-view-clone-buffer-hook nil t)
1034 (remove-overlays (point-min) (point-max) 'doc-view t) ;Just in case.
1035 ;; Keep track of display info ([vh]scroll, page number, overlay, ...)
1036 ;; for each window in which this document is shown.
1037 (add-hook 'image-mode-new-window-functions
1038 'doc-view-new-window-function nil t)
1039 (image-mode-setup-winprops)
1041 (set (make-local-variable 'mode-line-position)
1042 '(" P" (:eval (number-to-string (doc-view-current-page)))
1043 "/" (:eval (number-to-string (length doc-view-current-files)))))
1044 ;; Don't scroll unless the user specifically asked for it.
1045 (set (make-local-variable 'auto-hscroll-mode) nil)
1046 (set (make-local-variable 'cursor-type) nil)
1047 (use-local-map doc-view-mode-map)
1048 (set (make-local-variable 'after-revert-hook) 'doc-view-reconvert-doc)
1049 (set (make-local-variable 'bookmark-make-record-function)
1050 'doc-view-bookmark-make-record)
1051 (setq mode-name "DocView"
1052 buffer-read-only t
1053 major-mode 'doc-view-mode)
1054 (doc-view-initiate-display)
1055 (run-mode-hooks 'doc-view-mode-hook))
1057 ;;;###autoload
1058 (define-minor-mode doc-view-minor-mode
1059 "Toggle Doc view minor mode.
1060 With arg, turn Doc view minor mode on if arg is positive, off otherwise.
1061 See the command `doc-view-mode' for more information on this mode."
1062 nil " DocView" doc-view-minor-mode-map
1063 :group 'doc-view
1064 (when doc-view-minor-mode
1065 (add-hook 'change-major-mode-hook (lambda () (doc-view-minor-mode -1)) nil t)
1066 (message
1067 "%s"
1068 (substitute-command-keys
1069 "Type \\[doc-view-toggle-display] to toggle between editing or viewing the document."))))
1071 (defun doc-view-clear-cache ()
1072 "Delete the whole cache (`doc-view-cache-directory')."
1073 (interactive)
1074 (dired-delete-file doc-view-cache-directory 'always)
1075 (make-directory doc-view-cache-directory))
1077 (defun doc-view-dired-cache ()
1078 "Open `dired' in `doc-view-cache-directory'."
1079 (interactive)
1080 (dired doc-view-cache-directory))
1083 ;;;; Bookmark integration
1085 (defun doc-view-bookmark-make-record (annotation)
1086 (let ((the-record
1087 `((filename . ,buffer-file-name)
1088 (page . ,(doc-view-current-page))
1089 (handler . doc-view-bookmark-jump))))
1091 ;; Take no chances with text properties
1092 (set-text-properties 0 (length annotation) nil annotation)
1094 (when annotation
1095 (nconc the-record (list (cons 'annotation annotation))))
1097 ;; Finally, return the completed record.
1098 the-record))
1101 (declare-function bookmark-get-filename "bookmark" (bookmark))
1102 (declare-function bookmark-get-bookmark-record "bookmark" (bookmark))
1104 ;;;###autoload
1105 (defun doc-view-bookmark-jump (bmk)
1106 ;; This implements the `handler' function interface for record type
1107 ;; returned by `doc-view-bookmark-make-record', which see.
1108 (save-window-excursion
1109 (let ((filename (bookmark-get-filename bmk))
1110 (page (cdr (assq 'page (bookmark-get-bookmark-record bmk)))))
1111 (find-file filename)
1112 (when (not (eq major-mode 'doc-view-mode))
1113 (doc-view-toggle-display))
1114 (doc-view-goto-page page)
1115 `((buffer ,(current-buffer)) (position ,1)))))
1118 (provide 'doc-view)
1120 ;; Local Variables:
1121 ;; mode: outline-minor
1122 ;; End:
1124 ;; arch-tag: 5d6e5c5e-095f-489e-b4e4-1ca90a7d79be
1125 ;;; doc-view.el ends here