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