Remove all cb-args, use closures instead.
[emacs.git] / lisp / doc-view.el
blob0ffc0471024a58d0fe857aa7ba4ed394795c3998
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 (assert (not (get-char-property (point-min) 'display (car winprops))))
218 (setq ol (make-overlay (point-min) (point-max) nil t))
219 (overlay-put ol 'doc-view t))
220 (overlay-put ol 'window (car winprops))
221 (image-mode-window-put 'overlay ol winprops)))
223 (defvar doc-view-current-files nil
224 "Only used internally.")
226 (defvar doc-view-current-converter-process nil
227 "Only used internally.")
229 (defvar doc-view-current-timer nil
230 "Only used internally.")
232 (defvar doc-view-current-cache-dir nil
233 "Only used internally.")
235 (defvar doc-view-current-search-matches nil
236 "Only used internally.")
238 (defvar doc-view-pending-cache-flush nil
239 "Only used internally.")
241 (defvar doc-view-previous-major-mode nil
242 "Only used internally.")
244 (defvar doc-view-buffer-file-name nil
245 "Only used internally.
246 The file name used for conversion. Normally it's the same as
247 `buffer-file-name', but for remote files, compressed files and
248 files inside an archive it is a temporary copy of
249 the (uncompressed, extracted) file residing in
250 `doc-view-cache-directory'.")
252 (defvar doc-view-doc-type nil
253 "The type of document in the current buffer.
254 Can be `dvi', `pdf', or `ps'.")
256 ;;;; DocView Keymaps
258 (defvar doc-view-mode-map
259 (let ((map (make-sparse-keymap)))
260 (suppress-keymap map)
261 ;; Navigation in the document
262 (define-key map (kbd "n") 'doc-view-next-page)
263 (define-key map (kbd "p") 'doc-view-previous-page)
264 (define-key map (kbd "<next>") 'forward-page)
265 (define-key map (kbd "<prior>") 'backward-page)
266 (define-key map [remap forward-page] 'doc-view-next-page)
267 (define-key map [remap backward-page] 'doc-view-previous-page)
268 (define-key map (kbd "SPC") 'doc-view-scroll-up-or-next-page)
269 (define-key map (kbd "DEL") 'doc-view-scroll-down-or-previous-page)
270 (define-key map (kbd "M-<") 'doc-view-first-page)
271 (define-key map (kbd "M->") 'doc-view-last-page)
272 (define-key map [remap goto-line] 'doc-view-goto-page)
273 (define-key map [remap scroll-up] 'image-scroll-up)
274 (define-key map [remap scroll-down] 'image-scroll-down)
275 ;; Zoom in/out.
276 (define-key map "+" 'doc-view-enlarge)
277 (define-key map "-" 'doc-view-shrink)
278 ;; Killing/burying the buffer (and the process)
279 (define-key map (kbd "q") 'bury-buffer)
280 (define-key map (kbd "k") 'doc-view-kill-proc-and-buffer)
281 (define-key map (kbd "K") 'doc-view-kill-proc)
282 ;; Slicing the image
283 (define-key map (kbd "s s") 'doc-view-set-slice)
284 (define-key map (kbd "s m") 'doc-view-set-slice-using-mouse)
285 (define-key map (kbd "s r") 'doc-view-reset-slice)
286 ;; Searching
287 (define-key map (kbd "C-s") 'doc-view-search)
288 (define-key map (kbd "<find>") 'doc-view-search)
289 (define-key map (kbd "C-r") 'doc-view-search-backward)
290 ;; Scrolling
291 (define-key map [remap forward-char] 'image-forward-hscroll)
292 (define-key map [remap backward-char] 'image-backward-hscroll)
293 (define-key map [remap next-line] 'image-next-line)
294 (define-key map [remap previous-line] 'image-previous-line)
295 ;; Show the tooltip
296 (define-key map (kbd "C-t") 'doc-view-show-tooltip)
297 ;; Toggle between text and image display or editing
298 (define-key map (kbd "C-c C-c") 'doc-view-toggle-display)
299 ;; Open a new buffer with doc's text contents
300 (define-key map (kbd "C-c C-t") 'doc-view-open-text)
301 ;; Reconvert the current document
302 (define-key map (kbd "g") 'revert-buffer)
303 (define-key map (kbd "r") 'revert-buffer)
304 map)
305 "Keymap used by `doc-view-mode' when displaying a doc as a set of images.")
307 (easy-menu-define doc-view-menu doc-view-mode-map
308 "Menu for Doc View mode."
309 '("DocView"
310 ["Set Slice" doc-view-set-slice-using-mouse]
311 ["Set Slice (manual)" doc-view-set-slice]
312 ["Reset Slice" doc-view-reset-slice]
313 "---"
314 ["Search" doc-view-search]
315 ["Search Backwards" doc-view-search-backward]
316 ["Toggle display" doc-view-toggle-display]
319 (defvar doc-view-minor-mode-map
320 (let ((map (make-sparse-keymap)))
321 ;; Toggle between text and image display or editing
322 (define-key map (kbd "C-c C-c") 'doc-view-toggle-display)
323 map)
324 "Keymap used by `doc-minor-view-mode'.")
326 ;;;; Navigation Commands
328 (defmacro doc-view-current-page (&optional win)
329 `(image-mode-window-get 'page ,win))
330 (defmacro doc-view-current-info () `(image-mode-window-get 'info))
331 (defmacro doc-view-current-overlay () `(image-mode-window-get 'overlay))
332 (defmacro doc-view-current-image () `(image-mode-window-get 'image))
333 (defmacro doc-view-current-slice () `(image-mode-window-get 'slice))
335 (defun doc-view-goto-page (page)
336 "View the page given by PAGE."
337 (interactive "nPage: ")
338 (let ((len (length doc-view-current-files)))
339 (if (< page 1)
340 (setq page 1)
341 (when (and (> page len)
342 ;; As long as the converter is running, we don't know
343 ;; how many pages will be available.
344 (null doc-view-current-converter-process))
345 (setq page len)))
346 (setf (doc-view-current-page) page
347 (doc-view-current-info)
348 (concat
349 (propertize
350 (format "Page %d of %d." page len) 'face 'bold)
351 ;; Tell user if converting isn't finished yet
352 (if doc-view-current-converter-process
353 " (still converting...)\n"
354 "\n")
355 ;; Display context infos if this page matches the last search
356 (when (and doc-view-current-search-matches
357 (assq page doc-view-current-search-matches))
358 (concat (propertize "Search matches:\n" 'face 'bold)
359 (let ((contexts ""))
360 (dolist (m (cdr (assq page
361 doc-view-current-search-matches)))
362 (setq contexts (concat contexts " - \"" m "\"\n")))
363 contexts)))))
364 ;; Update the buffer
365 ;; We used to find the file name from doc-view-current-files but
366 ;; that's not right if the pages are not generated sequentially
367 ;; or if the page isn't in doc-view-current-files yet.
368 (doc-view-insert-image (expand-file-name (format "page-%d.png" page)
369 (doc-view-current-cache-dir))
370 :pointer 'arrow)
371 (overlay-put (doc-view-current-overlay)
372 'help-echo (doc-view-current-info))))
374 (defun doc-view-next-page (&optional arg)
375 "Browse ARG pages forward."
376 (interactive "p")
377 (doc-view-goto-page (+ (doc-view-current-page) (or arg 1))))
379 (defun doc-view-previous-page (&optional arg)
380 "Browse ARG pages backward."
381 (interactive "p")
382 (doc-view-goto-page (- (doc-view-current-page) (or arg 1))))
384 (defun doc-view-first-page ()
385 "View the first page."
386 (interactive)
387 (doc-view-goto-page 1))
389 (defun doc-view-last-page ()
390 "View the last page."
391 (interactive)
392 (doc-view-goto-page (length doc-view-current-files)))
394 (defun doc-view-scroll-up-or-next-page ()
395 "Scroll page up if possible, else goto next page."
396 (interactive)
397 (when (= (window-vscroll) (image-scroll-up nil))
398 (let ((cur-page (doc-view-current-page)))
399 (doc-view-next-page)
400 (when (/= cur-page (doc-view-current-page))
401 (set-window-vscroll nil 0)))))
403 (defun doc-view-scroll-down-or-previous-page ()
404 "Scroll page down if possible, else goto previous page."
405 (interactive)
406 (when (= (window-vscroll) (image-scroll-down nil))
407 (let ((cur-page (doc-view-current-page)))
408 (doc-view-previous-page)
409 (when (/= cur-page (doc-view-current-page))
410 (image-scroll-up nil)))))
412 ;;;; Utility Functions
414 (defun doc-view-kill-proc ()
415 "Kill the current converter process."
416 (interactive)
417 (when doc-view-current-converter-process
418 (ignore-errors ;; Maybe it's dead already?
419 (kill-process doc-view-current-converter-process))
420 (setq doc-view-current-converter-process nil))
421 (when doc-view-current-timer
422 (cancel-timer doc-view-current-timer)
423 (setq doc-view-current-timer nil))
424 (setq mode-line-process nil))
426 (defun doc-view-kill-proc-and-buffer ()
427 "Kill the current converter process and buffer."
428 (interactive)
429 (doc-view-kill-proc)
430 (when (eq major-mode 'doc-view-mode)
431 (kill-buffer (current-buffer))))
433 (defun doc-view-make-safe-dir (dir)
434 (condition-case nil
435 (let ((umask (default-file-modes)))
436 (unwind-protect
437 (progn
438 ;; Create temp files with strict access rights. It's easy to
439 ;; loosen them later, whereas it's impossible to close the
440 ;; time-window of loose permissions otherwise.
441 (set-default-file-modes #o0700)
442 (make-directory dir))
443 ;; Reset the umask.
444 (set-default-file-modes umask)))
445 (file-already-exists
446 (if (file-symlink-p dir)
447 (error "Danger: %s points to a symbolic link" dir))
448 ;; In case it was created earlier with looser rights.
449 ;; We could check the mode info returned by file-attributes, but it's
450 ;; a pain to parse and it may not tell you what we want under
451 ;; non-standard file-systems. So let's just say what we want and let
452 ;; the underlying C code and file-system figure it out.
453 ;; This also ends up checking a bunch of useful conditions: it makes
454 ;; sure we have write-access to the directory and that we own it, thus
455 ;; closing a bunch of security holes.
456 (set-file-modes dir #o0700))))
458 (defun doc-view-current-cache-dir ()
459 "Return the directory where the png files of the current doc should be saved.
460 It's a subdirectory of `doc-view-cache-directory'."
461 (if doc-view-current-cache-dir
462 doc-view-current-cache-dir
463 ;; Try and make sure doc-view-cache-directory exists and is safe.
464 (doc-view-make-safe-dir doc-view-cache-directory)
465 ;; Now compute the subdirectory to use.
466 (setq doc-view-current-cache-dir
467 (file-name-as-directory
468 (expand-file-name
469 (concat (file-name-nondirectory buffer-file-name)
471 (let ((file doc-view-buffer-file-name))
472 (with-temp-buffer
473 (set-buffer-multibyte nil)
474 (insert-file-contents-literally file)
475 (md5 (current-buffer)))))
476 doc-view-cache-directory)))))
478 (defun doc-view-remove-if (predicate list)
479 "Return LIST with all items removed that satisfy PREDICATE."
480 (let (new-list)
481 (dolist (item list (nreverse new-list))
482 (when (not (funcall predicate item))
483 (setq new-list (cons item new-list))))))
485 ;;;###autoload
486 (defun doc-view-mode-p (type)
487 "Return non-nil if image type TYPE is available for `doc-view'.
488 Image types are symbols like `dvi', `postscript' or `pdf'."
489 (and (display-graphic-p)
490 (image-type-available-p 'png)
491 (cond
492 ((eq type 'dvi)
493 (and (doc-view-mode-p 'pdf)
494 doc-view-dvipdfm-program
495 (executable-find doc-view-dvipdfm-program)))
496 ((or (eq type 'postscript) (eq type 'ps) (eq type 'eps)
497 (eq type 'pdf))
498 (and doc-view-ghostscript-program
499 (executable-find doc-view-ghostscript-program)))
500 (t ;; unknown image type
501 nil))))
503 ;;;; Conversion Functions
505 (defvar doc-view-shrink-factor 1.125)
507 (defun doc-view-enlarge (factor)
508 "Enlarge the document."
509 (interactive (list doc-view-shrink-factor))
510 (set (make-local-variable 'doc-view-resolution)
511 (* factor doc-view-resolution))
512 (doc-view-reconvert-doc))
514 (defun doc-view-shrink (factor)
515 "Shrink the document."
516 (interactive (list doc-view-shrink-factor))
517 (doc-view-enlarge (/ 1.0 factor)))
519 (defun doc-view-reconvert-doc ()
520 "Reconvert the current document.
521 Should be invoked when the cached images aren't up-to-date."
522 (interactive)
523 (doc-view-kill-proc)
524 ;; Clear the old cached files
525 (when (file-exists-p (doc-view-current-cache-dir))
526 (dired-delete-file (doc-view-current-cache-dir) 'always))
527 (doc-view-initiate-display))
529 (defun doc-view-sentinel (proc event)
530 "Generic sentinel for doc-view conversion processes."
531 (if (not (string-match "finished" event))
532 (message "DocView: process %s changed status to %s."
533 (process-name proc) event)
534 (with-current-buffer (process-get proc 'buffer)
535 (setq doc-view-current-converter-process nil
536 mode-line-process nil)
537 (funcall (process-get proc 'callback)))))
539 (defun doc-view-dvi->pdf (dvi pdf callback)
540 "Convert DVI to PDF asynchronously and call CALLBACK when finished."
541 (setq doc-view-current-converter-process
542 (start-process "dvi->pdf" doc-view-conversion-buffer
543 doc-view-dvipdfm-program
544 "-o" pdf dvi)
545 mode-line-process (list (format ":%s" doc-view-current-converter-process)))
546 (set-process-sentinel doc-view-current-converter-process 'doc-view-sentinel)
547 (process-put doc-view-current-converter-process 'buffer (current-buffer))
548 (process-put doc-view-current-converter-process 'callback callback))
550 (defun doc-view-pdf/ps->png-sentinel (proc event)
551 "If PDF/PS->PNG conversion was successful, update the display."
552 (if (not (string-match "finished" event))
553 (message "DocView: converter process changed status to %s." event)
554 ;; FIXME: kill the process if we kill the buffer?
555 (when (buffer-live-p (process-get proc 'buffer))
556 (with-current-buffer (process-get proc 'buffer)
557 (setq doc-view-current-converter-process nil
558 mode-line-process nil)
559 (when doc-view-current-timer
560 (cancel-timer doc-view-current-timer)
561 (setq doc-view-current-timer nil))
562 ;; Yippie, finished. Update the display!
563 (doc-view-display (current-buffer) 'force)))))
565 (defun doc-view-pdf/ps->png (pdf-ps png)
566 "Convert PDF-PS to PNG asynchronously."
567 (setq doc-view-current-converter-process
568 ;; Make sure the process is started in an existing directory,
569 ;; (rather than some file-name-handler-managed dir, for example).
570 (let ((default-directory (file-name-directory pdf-ps)))
571 (apply 'start-process
572 (append (list "pdf/ps->png" doc-view-conversion-buffer
573 doc-view-ghostscript-program)
574 doc-view-ghostscript-options
575 (list (format "-r%d" (round doc-view-resolution)))
576 (list (concat "-sOutputFile=" png))
577 (list pdf-ps))))
578 mode-line-process (list (format ":%s" doc-view-current-converter-process)))
579 (process-put doc-view-current-converter-process
580 'buffer (current-buffer))
581 (set-process-sentinel doc-view-current-converter-process
582 'doc-view-pdf/ps->png-sentinel)
583 (when doc-view-conversion-refresh-interval
584 (setq doc-view-current-timer
585 (run-at-time "1 secs" doc-view-conversion-refresh-interval
586 'doc-view-display
587 (current-buffer)))))
589 (defun doc-view-pdf->txt (pdf txt callback)
590 "Convert PDF to TXT asynchronously and call CALLBACK when finished."
591 (setq doc-view-current-converter-process
592 (start-process "pdf->txt" doc-view-conversion-buffer
593 doc-view-pdftotext-program "-raw"
594 pdf txt)
595 mode-line-process (list (format ":%s" doc-view-current-converter-process)))
596 (set-process-sentinel doc-view-current-converter-process
597 'doc-view-sentinel)
598 (process-put doc-view-current-converter-process 'buffer (current-buffer))
599 (process-put doc-view-current-converter-process 'callback callback))
601 (defun doc-view-doc->txt (txt callback)
602 "Convert the current document to text and call CALLBACK when done."
603 (make-directory (doc-view-current-cache-dir))
604 (case doc-view-doc-type
605 (pdf
606 ;; Doc is a PDF, so convert it to TXT
607 (doc-view-pdf->txt doc-view-buffer-file-name txt callback))
609 ;; Doc is a PS, so convert it to PDF (which will be converted to
610 ;; TXT thereafter).
611 (lexical-let ((pdf (expand-file-name "doc.pdf"
612 (doc-view-current-cache-dir)))
613 (txt txt)
614 (callback callback))
615 (doc-view-ps->pdf doc-view-buffer-file-name pdf
616 (lambda () (doc-view-pdf->txt pdf txt callback)))))
617 (dvi
618 ;; Doc is a DVI. This means that a doc.pdf already exists in its
619 ;; cache subdirectory.
620 (doc-view-pdf->txt (expand-file-name "doc.pdf"
621 (doc-view-current-cache-dir))
622 txt callback))
623 (t (error "DocView doesn't know what to do"))))
625 (defun doc-view-ps->pdf (ps pdf callback)
626 "Convert PS to PDF asynchronously and call CALLBACK when finished."
627 (setq doc-view-current-converter-process
628 (start-process "ps->pdf" doc-view-conversion-buffer
629 doc-view-ps2pdf-program
630 ;; Avoid security problems when rendering files from
631 ;; untrusted sources.
632 "-dSAFER"
633 ;; in-file and out-file
634 ps pdf)
635 mode-line-process (list (format ":%s" doc-view-current-converter-process)))
636 (set-process-sentinel doc-view-current-converter-process 'doc-view-sentinel)
637 (process-put doc-view-current-converter-process 'buffer (current-buffer))
638 (process-put doc-view-current-converter-process 'callback callback))
640 (defun doc-view-convert-current-doc ()
641 "Convert `doc-view-buffer-file-name' to a set of png files, one file per page.
642 Those files are saved in the directory given by the function
643 `doc-view-current-cache-dir'."
644 ;; Let stale files still display while we recompute the new ones, so only
645 ;; flush the cache when the conversion is over. One of the reasons why it
646 ;; is important to keep displaying the stale page is so that revert-buffer
647 ;; preserves the horizontal/vertical scroll settings (which are otherwise
648 ;; resets during the redisplay).
649 (setq doc-view-pending-cache-flush t)
650 (let ((png-file (expand-file-name "page-%d.png"
651 (doc-view-current-cache-dir))))
652 (make-directory (doc-view-current-cache-dir))
653 (case doc-view-doc-type
654 (dvi
655 ;; DVI files have to be converted to PDF before Ghostscript can process
656 ;; it.
657 (lexical-let
658 ((pdf (expand-file-name "doc.pdf" doc-view-current-cache-dir))
659 (png-file png-file))
660 (doc-view-dvi->pdf doc-view-buffer-file-name pdf
661 (lambda () (doc-view-pdf/ps->png pdf png-file)))))
663 ;; Convert to PNG images.
664 (doc-view-pdf/ps->png doc-view-buffer-file-name png-file)))))
666 ;;;; Slicing
668 (defun doc-view-set-slice (x y width height)
669 "Set the slice of the images that should be displayed.
670 You can use this function to tell doc-view not to display the
671 margins of the document. It prompts for the top-left corner (X
672 and Y) of the slice to display and its WIDTH and HEIGHT.
674 See `doc-view-set-slice-using-mouse' for a more convenient way to
675 do that. To reset the slice use `doc-view-reset-slice'."
676 (interactive
677 (let* ((size (image-size (doc-view-current-image) t))
678 (a (read-number (format "Top-left X (0..%d): " (car size))))
679 (b (read-number (format "Top-left Y (0..%d): " (cdr size))))
680 (c (read-number (format "Width (0..%d): " (- (car size) a))))
681 (d (read-number (format "Height (0..%d): " (- (cdr size) b)))))
682 (list a b c d)))
683 (setf (doc-view-current-slice) (list x y width height))
684 ;; Redisplay
685 (doc-view-goto-page (doc-view-current-page)))
687 (defun doc-view-set-slice-using-mouse ()
688 "Set the slice of the images that should be displayed.
689 You set the slice by pressing mouse-1 at its top-left corner and
690 dragging it to its bottom-right corner. See also
691 `doc-view-set-slice' and `doc-view-reset-slice'."
692 (interactive)
693 (let (x y w h done)
694 (while (not done)
695 (let ((e (read-event
696 (concat "Press mouse-1 at the top-left corner and "
697 "drag it to the bottom-right corner!"))))
698 (when (eq (car e) 'drag-mouse-1)
699 (setq x (car (posn-object-x-y (event-start e))))
700 (setq y (cdr (posn-object-x-y (event-start e))))
701 (setq w (- (car (posn-object-x-y (event-end e))) x))
702 (setq h (- (cdr (posn-object-x-y (event-end e))) y))
703 (setq done t))))
704 (doc-view-set-slice x y w h)))
706 (defun doc-view-reset-slice ()
707 "Reset the current slice.
708 After calling this function whole pages will be visible again."
709 (interactive)
710 (setf (doc-view-current-slice) nil)
711 ;; Redisplay
712 (doc-view-goto-page (doc-view-current-page)))
714 ;;;; Display
716 (defun doc-view-insert-image (file &rest args)
717 "Insert the given png FILE.
718 ARGS is a list of image descriptors."
719 (when doc-view-pending-cache-flush
720 (clear-image-cache)
721 (setq doc-view-pending-cache-flush nil))
722 (let ((ol (doc-view-current-overlay))
723 (image (if (and file (file-readable-p file))
724 (apply 'create-image file 'png nil args)))
725 (slice (doc-view-current-slice)))
726 (setf (doc-view-current-image) image)
727 (move-overlay ol (point-min) (point-max))
728 (overlay-put ol 'display
729 (cond
730 (image
731 (if slice
732 (list (cons 'slice slice) image)
733 image))
734 ;; We're trying to display a page that doesn't exist.
735 (doc-view-current-converter-process
736 ;; Maybe the page doesn't exist *yet*.
737 "Cannot display this page (yet)!")
739 ;; Typically happens if the conversion process somehow
740 ;; failed. Better not signal an error here because it
741 ;; could prevent a subsequent reconversion from fixing
742 ;; the problem.
743 (concat "Cannot display this page!\n"
744 "Maybe because of a conversion failure!"))))
745 (let ((win (overlay-get ol 'window)))
746 (if (stringp (overlay-get ol 'display))
747 (progn ;Make sure the text is not scrolled out of view.
748 (set-window-hscroll win 0)
749 (set-window-vscroll win 0))
750 (let ((hscroll (image-mode-window-get 'hscroll win))
751 (vscroll (image-mode-window-get 'vscroll win)))
752 ;; Reset scroll settings, in case they were changed.
753 (if hscroll (set-window-hscroll win hscroll))
754 (if vscroll (set-window-vscroll win vscroll)))))))
756 (defun doc-view-sort (a b)
757 "Return non-nil if A should be sorted before B.
758 Predicate for sorting `doc-view-current-files'."
759 (or (< (length a) (length b))
760 (and (= (length a) (length b))
761 (string< a b))))
763 (defun doc-view-display (buffer &optional force)
764 "Start viewing the document in BUFFER.
765 If FORCE is non-nil, start viewing even if the document does not
766 have the page we want to view."
767 (with-current-buffer buffer
768 (let ((prev-pages doc-view-current-files))
769 (setq doc-view-current-files
770 (sort (directory-files (doc-view-current-cache-dir) t
771 "page-[0-9]+\\.png" t)
772 'doc-view-sort))
773 (dolist (win (get-buffer-window-list buffer nil t))
774 (let* ((page (doc-view-current-page win))
775 (pagefile (expand-file-name (format "page-%d.png" page)
776 (doc-view-current-cache-dir))))
777 (when (or force
778 (and (not (member pagefile prev-pages))
779 (member pagefile doc-view-current-files)))
780 (with-selected-window win
781 (assert (eq (current-buffer) buffer))
782 (doc-view-goto-page page))))))))
784 (defun doc-view-buffer-message ()
785 ;; Only show this message initially, not when refreshing the buffer (in which
786 ;; case it's better to keep displaying the "stale" page while computing
787 ;; the fresh new ones).
788 (unless (overlay-get (doc-view-current-overlay) 'display)
789 (overlay-put (doc-view-current-overlay) 'display
790 (concat (propertize "Welcome to DocView!" 'face 'bold)
791 "\n"
793 If you see this buffer it means that the document you want to view is being
794 converted to PNG and the conversion of the first page hasn't finished yet or
795 `doc-view-conversion-refresh-interval' is set to nil.
797 For now these keys are useful:
799 `q' : Bury this buffer. Conversion will go on in background.
800 `k' : Kill the conversion process and this buffer.
801 `K' : Kill the conversion process.\n"))))
803 (defun doc-view-show-tooltip ()
804 (interactive)
805 (tooltip-show (doc-view-current-info)))
807 (defun doc-view-open-text ()
808 "Open a buffer with the current doc's contents as text."
809 (interactive)
810 (if doc-view-current-converter-process
811 (message "DocView: please wait till conversion finished.")
812 (let ((txt (expand-file-name "doc.txt" (doc-view-current-cache-dir))))
813 (if (file-readable-p txt)
814 (find-file txt)
815 (doc-view-doc->txt txt 'doc-view-open-text)))))
817 ;;;;; Toggle between editing and viewing
820 (defun doc-view-toggle-display ()
821 "Toggle between editing a document as text or viewing it."
822 (interactive)
823 (if (eq major-mode 'doc-view-mode)
824 ;; Switch to editing mode
825 (progn
826 (doc-view-kill-proc)
827 (setq buffer-read-only nil)
828 (remove-overlays (point-min) (point-max) 'doc-view t)
829 (set (make-local-variable 'image-mode-winprops-alist) t)
830 ;; Switch to the previously used major mode or fall back to fundamental
831 ;; mode.
832 (if doc-view-previous-major-mode
833 (funcall doc-view-previous-major-mode)
834 (fundamental-mode))
835 (doc-view-minor-mode 1))
836 ;; Switch to doc-view-mode
837 (when (and (buffer-modified-p)
838 (y-or-n-p "The buffer has been modified. Save the changes? "))
839 (save-buffer))
840 (doc-view-mode)))
842 ;;;; Searching
845 (defun doc-view-search-internal (regexp file)
846 "Return a list of FILE's pages that contain text matching REGEXP.
847 The value is an alist of the form (PAGE CONTEXTS) where PAGE is
848 the pagenumber and CONTEXTS are all lines of text containing a match."
849 (with-temp-buffer
850 (insert-file-contents file)
851 (let ((page 1)
852 (lastpage 1)
853 matches)
854 (while (re-search-forward (concat "\\(?:\\([\f]\\)\\|\\("
855 regexp "\\)\\)") nil t)
856 (when (match-string 1) (setq page (1+ page)))
857 (when (match-string 2)
858 (if (/= page lastpage)
859 (push (cons page
860 (list (buffer-substring
861 (line-beginning-position)
862 (line-end-position))))
863 matches)
864 (setq matches (cons
865 (append
867 ;; This page already is a match.
868 (car matches)
869 ;; This is the first match on page.
870 (list page))
871 (list (buffer-substring
872 (line-beginning-position)
873 (line-end-position))))
874 (cdr matches))))
875 (setq lastpage page)))
876 (nreverse matches))))
878 (defun doc-view-search-no-of-matches (list)
879 "Extract the number of matches from the search result LIST."
880 (let ((no 0))
881 (dolist (p list)
882 (setq no (+ no (1- (length p)))))
883 no))
885 (defun doc-view-search-backward (new-query)
886 "Call `doc-view-search' for backward search.
887 If prefix NEW-QUERY is given, ask for a new regexp."
888 (interactive "P")
889 (doc-view-search new-query t))
891 (defun doc-view-search (new-query &optional backward)
892 "Jump to the next match or initiate a new search if NEW-QUERY is given.
893 If the current document hasn't been transformed to plain text
894 till now do that first.
895 If BACKWARD is non-nil, jump to the previous match."
896 (interactive "P")
897 (if (and (not new-query)
898 doc-view-current-search-matches)
899 (if backward
900 (doc-view-search-previous-match 1)
901 (doc-view-search-next-match 1))
902 ;; New search, so forget the old results.
903 (setq doc-view-current-search-matches nil)
904 (let ((txt (expand-file-name "doc.txt"
905 (doc-view-current-cache-dir))))
906 (if (file-readable-p txt)
907 (progn
908 (setq doc-view-current-search-matches
909 (doc-view-search-internal
910 (read-from-minibuffer "Regexp: ")
911 txt))
912 (message "DocView: search yielded %d matches."
913 (doc-view-search-no-of-matches
914 doc-view-current-search-matches)))
915 ;; We must convert to TXT first!
916 (if doc-view-current-converter-process
917 (message "DocView: please wait till conversion finished.")
918 (doc-view-doc->txt txt (lambda () (doc-view-search nil))))))))
920 (defun doc-view-search-next-match (arg)
921 "Go to the ARGth next matching page."
922 (interactive "p")
923 (let* ((next-pages (doc-view-remove-if
924 (lambda (i) (<= (car i) (doc-view-current-page)))
925 doc-view-current-search-matches))
926 (page (car (nth (1- arg) next-pages))))
927 (if page
928 (doc-view-goto-page page)
929 (when (and
930 doc-view-current-search-matches
931 (y-or-n-p "No more matches after current page. Wrap to first match? "))
932 (doc-view-goto-page (caar doc-view-current-search-matches))))))
934 (defun doc-view-search-previous-match (arg)
935 "Go to the ARGth previous matching page."
936 (interactive "p")
937 (let* ((prev-pages (doc-view-remove-if
938 (lambda (i) (>= (car i) (doc-view-current-page)))
939 doc-view-current-search-matches))
940 (page (car (nth (1- arg) (nreverse prev-pages)))))
941 (if page
942 (doc-view-goto-page page)
943 (when (and
944 doc-view-current-search-matches
945 (y-or-n-p "No more matches before current page. Wrap to last match? "))
946 (doc-view-goto-page (caar (last doc-view-current-search-matches)))))))
948 ;;;; User interface commands and the mode
950 ;; (put 'doc-view-mode 'mode-class 'special)
952 (defun doc-view-already-converted-p ()
953 "Return non-nil if the current doc was already converted."
954 (and (file-exists-p (doc-view-current-cache-dir))
955 (> 0 (length (directory-files (doc-view-current-cache-dir) nil "\\.png$")))))
957 (defun doc-view-initiate-display ()
958 ;; Switch to image display if possible
959 (if (doc-view-mode-p (intern (file-name-extension doc-view-buffer-file-name)))
960 (progn
961 (doc-view-buffer-message)
962 (setf (doc-view-current-page) (or (doc-view-current-page) 1))
963 (if (doc-view-already-converted-p)
964 (progn
965 (message "DocView: using cached files!")
966 (doc-view-display (current-buffer) 'force))
967 (doc-view-convert-current-doc))
968 (message
969 "%s"
970 (substitute-command-keys
971 (concat "Type \\[doc-view-toggle-display] to toggle between "
972 "editing or viewing the document."))))
973 (message
974 "%s"
975 (substitute-command-keys
976 (concat "No image (png) support available or some conversion utility for "
977 (file-name-extension doc-view-buffer-file-name)" files is missing. "
978 "Type \\[doc-view-toggle-display] to switch to an editing mode or "
979 "\\[doc-view-open-text] to open a buffer showing the doc as text.")))))
981 (defvar bookmark-make-record-function)
983 (defun doc-view-clone-buffer-hook ()
984 ;; FIXME: There are several potential problems linked with reconversion
985 ;; and auto-revert when we have indirect buffers because they share their
986 ;; /tmp cache directory. This sharing is good (you'd rather not reconvert
987 ;; for each clone), but that means that clones need to collaborate a bit.
988 ;; I guess it mostly means: detect when a reconversion process is already
989 ;; running, and run the sentinel in all clones.
991 ;; Maybe the clones should really have a separate /tmp directory
992 ;; so they could have a different resolution and you could use clones
993 ;; for zooming.
994 (remove-overlays (point-min) (point-max) 'doc-view t)
995 (if (consp image-mode-winprops-alist) (setq image-mode-winprops-alist nil)))
997 (defun doc-view-intersection (l1 l2)
998 (let ((l ()))
999 (dolist (x l1) (if (memq x l2) (push x l)))
1002 ;;;###autoload
1003 (defun doc-view-mode ()
1004 "Major mode in DocView buffers.
1005 You can use \\<doc-view-mode-map>\\[doc-view-toggle-display] to
1006 toggle between displaying the document or editing it as text.
1007 \\{doc-view-mode-map}"
1008 (interactive)
1010 (let* ((prev-major-mode (if (eq major-mode 'doc-view-mode)
1011 doc-view-previous-major-mode
1012 major-mode)))
1013 (kill-all-local-variables)
1014 (set (make-local-variable 'doc-view-previous-major-mode) prev-major-mode))
1016 ;; Figure out the document type.
1017 (let ((name-types
1018 (when buffer-file-name
1019 (cdr (assoc (file-name-extension buffer-file-name)
1020 '(("dvi" dvi)
1021 ("pdf" pdf)
1022 ("epdf" pdf)
1023 ("ps" ps)
1024 ("eps" ps))))))
1025 (content-types
1026 (save-excursion
1027 (goto-char (point-min))
1028 (cond
1029 ((looking-at "%!") '(ps))
1030 ((looking-at "%PDF") '(pdf))
1031 ((looking-at "\367\002") '(dvi))))))
1032 (set (make-local-variable 'doc-view-doc-type)
1033 (car (or (doc-view-intersection name-types content-types)
1034 (when (and name-types content-types)
1035 (error "Conflicting types: name says %s but content says %s"
1036 name-types content-types))
1037 name-types content-types
1038 (error "Cannot determine the document type")))))
1040 (doc-view-make-safe-dir doc-view-cache-directory)
1041 ;; Handle compressed files, remote files, files inside archives
1042 (set (make-local-variable 'doc-view-buffer-file-name)
1043 (cond
1044 (jka-compr-really-do-compress
1045 (expand-file-name
1046 (file-name-nondirectory
1047 (file-name-sans-extension buffer-file-name))
1048 doc-view-cache-directory))
1049 ;; Is the file readable by local processes?
1050 ;; We used to use `file-remote-p' but it's unclear what it's
1051 ;; supposed to return nil for things like local files accessed via
1052 ;; `su' or via file://...
1053 ((let ((file-name-handler-alist nil))
1054 (not (file-readable-p buffer-file-name)))
1055 (expand-file-name
1056 (file-name-nondirectory buffer-file-name)
1057 doc-view-cache-directory))
1058 (t buffer-file-name)))
1059 (when (not (string= doc-view-buffer-file-name buffer-file-name))
1060 (write-region nil nil doc-view-buffer-file-name))
1062 (make-local-variable 'doc-view-current-files)
1063 (make-local-variable 'doc-view-current-converter-process)
1064 (make-local-variable 'doc-view-current-timer)
1065 (make-local-variable 'doc-view-current-cache-dir)
1066 (make-local-variable 'doc-view-current-search-matches)
1067 (add-hook 'change-major-mode-hook
1068 (lambda () (remove-overlays (point-min) (point-max) 'doc-view t))
1069 nil t)
1070 (add-hook 'clone-indirect-buffer-hook 'doc-view-clone-buffer-hook nil t)
1072 (remove-overlays (point-min) (point-max) 'doc-view t) ;Just in case.
1073 ;; Keep track of display info ([vh]scroll, page number, overlay, ...)
1074 ;; for each window in which this document is shown.
1075 (add-hook 'image-mode-new-window-functions
1076 'doc-view-new-window-function nil t)
1077 (image-mode-setup-winprops)
1079 (set (make-local-variable 'mode-line-position)
1080 '(" P" (:eval (number-to-string (doc-view-current-page)))
1081 "/" (:eval (number-to-string (length doc-view-current-files)))))
1082 ;; Don't scroll unless the user specifically asked for it.
1083 (set (make-local-variable 'auto-hscroll-mode) nil)
1084 (set (make-local-variable 'cursor-type) nil)
1085 (use-local-map doc-view-mode-map)
1086 (set (make-local-variable 'after-revert-hook) 'doc-view-reconvert-doc)
1087 (set (make-local-variable 'bookmark-make-record-function)
1088 'doc-view-bookmark-make-record)
1089 (setq mode-name "DocView"
1090 buffer-read-only t
1091 major-mode 'doc-view-mode)
1092 (doc-view-initiate-display)
1093 (run-mode-hooks 'doc-view-mode-hook))
1095 ;;;###autoload
1096 (define-minor-mode doc-view-minor-mode
1097 "Toggle Doc view minor mode.
1098 With arg, turn Doc view minor mode on if arg is positive, off otherwise.
1099 See the command `doc-view-mode' for more information on this mode."
1100 nil " DocView" doc-view-minor-mode-map
1101 :group 'doc-view
1102 (when doc-view-minor-mode
1103 (add-hook 'change-major-mode-hook (lambda () (doc-view-minor-mode -1)) nil t)
1104 (message
1105 "%s"
1106 (substitute-command-keys
1107 "Type \\[doc-view-toggle-display] to toggle between editing or viewing the document."))))
1109 (defun doc-view-clear-cache ()
1110 "Delete the whole cache (`doc-view-cache-directory')."
1111 (interactive)
1112 (dired-delete-file doc-view-cache-directory 'always))
1114 (defun doc-view-dired-cache ()
1115 "Open `dired' in `doc-view-cache-directory'."
1116 (interactive)
1117 (dired doc-view-cache-directory))
1120 ;;;; Bookmark integration
1122 (declare-function bookmark-buffer-file-name "bookmark" ())
1123 (declare-function bookmark-prop-get "bookmark" (bookmark prop))
1125 (defun doc-view-bookmark-make-record ()
1126 `((filename . ,(bookmark-buffer-file-name))
1127 (page . ,(doc-view-current-page))
1128 (handler . doc-view-bookmark-jump)))
1131 ;;;###autoload
1132 (defun doc-view-bookmark-jump (bmk)
1133 ;; This implements the `handler' function interface for record type
1134 ;; returned by `doc-view-bookmark-make-record', which see.
1135 (let ((filename (bookmark-prop-get bmk 'filename))
1136 (page (bookmark-prop-get bmk 'page)))
1137 (with-current-buffer (find-file-noselect filename)
1138 (when (not (eq major-mode 'doc-view-mode))
1139 (doc-view-toggle-display))
1140 (with-selected-window
1141 (or (get-buffer-window (current-buffer) 0)
1142 (selected-window))
1143 (doc-view-goto-page page))
1144 `((buffer ,(current-buffer)) (position ,1)))))
1147 (provide 'doc-view)
1149 ;; Local Variables:
1150 ;; mode: outline-minor
1151 ;; End:
1153 ;; arch-tag: 5d6e5c5e-095f-489e-b4e4-1ca90a7d79be
1154 ;;; doc-view.el ends here