]> code.delx.au - gnu-emacs/blob - lisp/doc-view.el
(doc-view-doc->txt, doc-view-convert-current-doc):
[gnu-emacs] / lisp / doc-view.el
1 ;;; doc-view.el --- View PDF/PostScript/DVI files in Emacs
2
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
8
9 ;; This file is part of GNU Emacs.
10
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.
15
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.
20
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.
25
26 ;;; Requirements:
27
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/).
31
32 ;;; Commentary:
33
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.
38 ;;
39 ;; To use it simply open a document file with
40 ;;
41 ;; C-x C-f ~/path/to/document RET
42 ;;
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.
46 ;;
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'.
53 ;;
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.
59 ;;
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').
70 ;;
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.
82 ;;
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'.
85 ;;
86
87 ;;; Configuration:
88
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.)
92 ;;
93 ;; This and all other options can be set with the customization interface.
94 ;; Simply do
95 ;;
96 ;; M-x customize-group RET doc-view RET
97 ;;
98 ;; and modify them to your needs.
99
100 ;;; Todo:
101
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).
110
111 ;;;; About isearch support
112
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.
125
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.
130
131 ;; Anyway, if someone with better isearch knowledge wants to give it a try,
132 ;; feel free to do it. --Tassilo
133
134 ;;; Code:
135
136 (require 'dired)
137 (require 'image-mode)
138 (require 'jka-compr)
139
140 ;;;; Customization Options
141
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-")
149
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)
154
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)
163
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)
169
170 (defcustom doc-view-dvipdfm-program (executable-find "dvipdfm")
171 "Program to convert DVI files to PDF.
172
173 DVI file will be converted to PDF before the resulting PDF is
174 converted to PNG."
175 :type 'file
176 :group 'doc-view)
177
178 (defcustom doc-view-ps2pdf-program (executable-find "ps2pdf")
179 "Program to convert PS files to PDF.
180
181 PS files will be converted to PDF before searching is possible."
182 :type 'file
183 :group 'doc-view)
184
185 (defcustom doc-view-pdftotext-program (executable-find "pdftotext")
186 "Program to convert PDF files to plain text.
187
188 Needed for searching."
189 :type 'file
190 :group 'doc-view)
191
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)
198
199 (defvar doc-view-conversion-buffer " *doc-view conversion output*"
200 "The buffer where messages from the converter programs go to.")
201
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)
210
211 ;;;; Internal Variables
212
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)))
222
223 (defvar doc-view-current-files nil
224 "Only used internally.")
225
226 (defvar doc-view-current-converter-process nil
227 "Only used internally.")
228
229 (defvar doc-view-current-timer nil
230 "Only used internally.")
231
232 (defvar doc-view-current-cache-dir nil
233 "Only used internally.")
234
235 (defvar doc-view-current-search-matches nil
236 "Only used internally.")
237
238 (defvar doc-view-pending-cache-flush nil
239 "Only used internally.")
240
241 (defvar doc-view-previous-major-mode nil
242 "Only used internally.")
243
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'.")
251
252 (defvar doc-view-doc-type nil
253 "The type of document in the current buffer.
254 Can be `dvi', `pdf', or `ps'.")
255
256 ;;;; DocView Keymaps
257
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.")
306
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]
317 ))
318
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'.")
325
326 ;;;; Navigation Commands
327
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))
334
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))))
373
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))))
378
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))))
383
384 (defun doc-view-first-page ()
385 "View the first page."
386 (interactive)
387 (doc-view-goto-page 1))
388
389 (defun doc-view-last-page ()
390 "View the last page."
391 (interactive)
392 (doc-view-goto-page (length doc-view-current-files)))
393
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)))))
402
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)))))
411
412 ;;;; Utility Functions
413
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))
425
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))))
432
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))))
457
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)
470 "-"
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)))))
477
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))))))
484
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))))
502
503 ;;;; Conversion Functions
504
505 (defvar doc-view-shrink-factor 1.125)
506
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))
513
514 (defun doc-view-shrink (factor)
515 "Shrink the document."
516 (interactive (list doc-view-shrink-factor))
517 (doc-view-enlarge (/ 1.0 factor)))
518
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))
528
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)))))
538
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))
549
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)))))
564
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)))))
588
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))
600
601 (defun doc-view-doc->txt (txt callback)
602 "Convert the current document to text and call CALLBACK when done."
603 (unless (file-exists-p (doc-view-current-cache-dir))
604 (make-directory (doc-view-current-cache-dir)))
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))
609 (ps
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"))))
625
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))
640
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 (unless (file-exists-p (doc-view-current-cache-dir))
654 (make-directory (doc-view-current-cache-dir)))
655 (case doc-view-doc-type
656 (dvi
657 ;; DVI files have to be converted to PDF before Ghostscript can process
658 ;; it.
659 (lexical-let
660 ((pdf (expand-file-name "doc.pdf" doc-view-current-cache-dir))
661 (png-file png-file))
662 (doc-view-dvi->pdf doc-view-buffer-file-name pdf
663 (lambda () (doc-view-pdf/ps->png pdf png-file)))))
664 (t
665 ;; Convert to PNG images.
666 (doc-view-pdf/ps->png doc-view-buffer-file-name png-file)))))
667
668 ;;;; Slicing
669
670 (defun doc-view-set-slice (x y width height)
671 "Set the slice of the images that should be displayed.
672 You can use this function to tell doc-view not to display the
673 margins of the document. It prompts for the top-left corner (X
674 and Y) of the slice to display and its WIDTH and HEIGHT.
675
676 See `doc-view-set-slice-using-mouse' for a more convenient way to
677 do that. To reset the slice use `doc-view-reset-slice'."
678 (interactive
679 (let* ((size (image-size (doc-view-current-image) t))
680 (a (read-number (format "Top-left X (0..%d): " (car size))))
681 (b (read-number (format "Top-left Y (0..%d): " (cdr size))))
682 (c (read-number (format "Width (0..%d): " (- (car size) a))))
683 (d (read-number (format "Height (0..%d): " (- (cdr size) b)))))
684 (list a b c d)))
685 (setf (doc-view-current-slice) (list x y width height))
686 ;; Redisplay
687 (doc-view-goto-page (doc-view-current-page)))
688
689 (defun doc-view-set-slice-using-mouse ()
690 "Set the slice of the images that should be displayed.
691 You set the slice by pressing mouse-1 at its top-left corner and
692 dragging it to its bottom-right corner. See also
693 `doc-view-set-slice' and `doc-view-reset-slice'."
694 (interactive)
695 (let (x y w h done)
696 (while (not done)
697 (let ((e (read-event
698 (concat "Press mouse-1 at the top-left corner and "
699 "drag it to the bottom-right corner!"))))
700 (when (eq (car e) 'drag-mouse-1)
701 (setq x (car (posn-object-x-y (event-start e))))
702 (setq y (cdr (posn-object-x-y (event-start e))))
703 (setq w (- (car (posn-object-x-y (event-end e))) x))
704 (setq h (- (cdr (posn-object-x-y (event-end e))) y))
705 (setq done t))))
706 (doc-view-set-slice x y w h)))
707
708 (defun doc-view-reset-slice ()
709 "Reset the current slice.
710 After calling this function whole pages will be visible again."
711 (interactive)
712 (setf (doc-view-current-slice) nil)
713 ;; Redisplay
714 (doc-view-goto-page (doc-view-current-page)))
715
716 ;;;; Display
717
718 (defun doc-view-insert-image (file &rest args)
719 "Insert the given png FILE.
720 ARGS is a list of image descriptors."
721 (when doc-view-pending-cache-flush
722 (clear-image-cache)
723 (setq doc-view-pending-cache-flush nil))
724 (let ((ol (doc-view-current-overlay))
725 (image (if (and file (file-readable-p file))
726 (apply 'create-image file 'png nil args)))
727 (slice (doc-view-current-slice)))
728 (setf (doc-view-current-image) image)
729 (move-overlay ol (point-min) (point-max))
730 (overlay-put ol 'display
731 (cond
732 (image
733 (if slice
734 (list (cons 'slice slice) image)
735 image))
736 ;; We're trying to display a page that doesn't exist.
737 (doc-view-current-converter-process
738 ;; Maybe the page doesn't exist *yet*.
739 "Cannot display this page (yet)!")
740 (t
741 ;; Typically happens if the conversion process somehow
742 ;; failed. Better not signal an error here because it
743 ;; could prevent a subsequent reconversion from fixing
744 ;; the problem.
745 (concat "Cannot display this page!\n"
746 "Maybe because of a conversion failure!"))))
747 (let ((win (overlay-get ol 'window)))
748 (if (stringp (overlay-get ol 'display))
749 (progn ;Make sure the text is not scrolled out of view.
750 (set-window-hscroll win 0)
751 (set-window-vscroll win 0))
752 (let ((hscroll (image-mode-window-get 'hscroll win))
753 (vscroll (image-mode-window-get 'vscroll win)))
754 ;; Reset scroll settings, in case they were changed.
755 (if hscroll (set-window-hscroll win hscroll))
756 (if vscroll (set-window-vscroll win vscroll)))))))
757
758 (defun doc-view-sort (a b)
759 "Return non-nil if A should be sorted before B.
760 Predicate for sorting `doc-view-current-files'."
761 (or (< (length a) (length b))
762 (and (= (length a) (length b))
763 (string< a b))))
764
765 (defun doc-view-display (buffer &optional force)
766 "Start viewing the document in BUFFER.
767 If FORCE is non-nil, start viewing even if the document does not
768 have the page we want to view."
769 (with-current-buffer buffer
770 (let ((prev-pages doc-view-current-files))
771 (setq doc-view-current-files
772 (sort (directory-files (doc-view-current-cache-dir) t
773 "page-[0-9]+\\.png" t)
774 'doc-view-sort))
775 (dolist (win (get-buffer-window-list buffer nil t))
776 (let* ((page (doc-view-current-page win))
777 (pagefile (expand-file-name (format "page-%d.png" page)
778 (doc-view-current-cache-dir))))
779 (when (or force
780 (and (not (member pagefile prev-pages))
781 (member pagefile doc-view-current-files)))
782 (with-selected-window win
783 (assert (eq (current-buffer) buffer))
784 (doc-view-goto-page page))))))))
785
786 (defun doc-view-buffer-message ()
787 ;; Only show this message initially, not when refreshing the buffer (in which
788 ;; case it's better to keep displaying the "stale" page while computing
789 ;; the fresh new ones).
790 (unless (overlay-get (doc-view-current-overlay) 'display)
791 (overlay-put (doc-view-current-overlay) 'display
792 (concat (propertize "Welcome to DocView!" 'face 'bold)
793 "\n"
794 "
795 If you see this buffer it means that the document you want to view is being
796 converted to PNG and the conversion of the first page hasn't finished yet or
797 `doc-view-conversion-refresh-interval' is set to nil.
798
799 For now these keys are useful:
800
801 `q' : Bury this buffer. Conversion will go on in background.
802 `k' : Kill the conversion process and this buffer.
803 `K' : Kill the conversion process.\n"))))
804
805 (defun doc-view-show-tooltip ()
806 (interactive)
807 (tooltip-show (doc-view-current-info)))
808
809 (defun doc-view-open-text ()
810 "Open a buffer with the current doc's contents as text."
811 (interactive)
812 (if doc-view-current-converter-process
813 (message "DocView: please wait till conversion finished.")
814 (let ((txt (expand-file-name "doc.txt" (doc-view-current-cache-dir))))
815 (if (file-readable-p txt)
816 (find-file txt)
817 (doc-view-doc->txt txt 'doc-view-open-text)))))
818
819 ;;;;; Toggle between editing and viewing
820
821
822 (defun doc-view-toggle-display ()
823 "Toggle between editing a document as text or viewing it."
824 (interactive)
825 (if (eq major-mode 'doc-view-mode)
826 ;; Switch to editing mode
827 (progn
828 (doc-view-kill-proc)
829 (setq buffer-read-only nil)
830 (remove-overlays (point-min) (point-max) 'doc-view t)
831 (set (make-local-variable 'image-mode-winprops-alist) t)
832 ;; Switch to the previously used major mode or fall back to fundamental
833 ;; mode.
834 (if doc-view-previous-major-mode
835 (funcall doc-view-previous-major-mode)
836 (fundamental-mode))
837 (doc-view-minor-mode 1))
838 ;; Switch to doc-view-mode
839 (when (and (buffer-modified-p)
840 (y-or-n-p "The buffer has been modified. Save the changes? "))
841 (save-buffer))
842 (doc-view-mode)))
843
844 ;;;; Searching
845
846
847 (defun doc-view-search-internal (regexp file)
848 "Return a list of FILE's pages that contain text matching REGEXP.
849 The value is an alist of the form (PAGE CONTEXTS) where PAGE is
850 the pagenumber and CONTEXTS are all lines of text containing a match."
851 (with-temp-buffer
852 (insert-file-contents file)
853 (let ((page 1)
854 (lastpage 1)
855 matches)
856 (while (re-search-forward (concat "\\(?:\\([\f]\\)\\|\\("
857 regexp "\\)\\)") nil t)
858 (when (match-string 1) (setq page (1+ page)))
859 (when (match-string 2)
860 (if (/= page lastpage)
861 (push (cons page
862 (list (buffer-substring
863 (line-beginning-position)
864 (line-end-position))))
865 matches)
866 (setq matches (cons
867 (append
868 (or
869 ;; This page already is a match.
870 (car matches)
871 ;; This is the first match on page.
872 (list page))
873 (list (buffer-substring
874 (line-beginning-position)
875 (line-end-position))))
876 (cdr matches))))
877 (setq lastpage page)))
878 (nreverse matches))))
879
880 (defun doc-view-search-no-of-matches (list)
881 "Extract the number of matches from the search result LIST."
882 (let ((no 0))
883 (dolist (p list)
884 (setq no (+ no (1- (length p)))))
885 no))
886
887 (defun doc-view-search-backward (new-query)
888 "Call `doc-view-search' for backward search.
889 If prefix NEW-QUERY is given, ask for a new regexp."
890 (interactive "P")
891 (doc-view-search new-query t))
892
893 (defun doc-view-search (new-query &optional backward)
894 "Jump to the next match or initiate a new search if NEW-QUERY is given.
895 If the current document hasn't been transformed to plain text
896 till now do that first.
897 If BACKWARD is non-nil, jump to the previous match."
898 (interactive "P")
899 (if (and (not new-query)
900 doc-view-current-search-matches)
901 (if backward
902 (doc-view-search-previous-match 1)
903 (doc-view-search-next-match 1))
904 ;; New search, so forget the old results.
905 (setq doc-view-current-search-matches nil)
906 (let ((txt (expand-file-name "doc.txt"
907 (doc-view-current-cache-dir))))
908 (if (file-readable-p txt)
909 (progn
910 (setq doc-view-current-search-matches
911 (doc-view-search-internal
912 (read-from-minibuffer "Regexp: ")
913 txt))
914 (message "DocView: search yielded %d matches."
915 (doc-view-search-no-of-matches
916 doc-view-current-search-matches)))
917 ;; We must convert to TXT first!
918 (if doc-view-current-converter-process
919 (message "DocView: please wait till conversion finished.")
920 (doc-view-doc->txt txt (lambda () (doc-view-search nil))))))))
921
922 (defun doc-view-search-next-match (arg)
923 "Go to the ARGth next matching page."
924 (interactive "p")
925 (let* ((next-pages (doc-view-remove-if
926 (lambda (i) (<= (car i) (doc-view-current-page)))
927 doc-view-current-search-matches))
928 (page (car (nth (1- arg) next-pages))))
929 (if page
930 (doc-view-goto-page page)
931 (when (and
932 doc-view-current-search-matches
933 (y-or-n-p "No more matches after current page. Wrap to first match? "))
934 (doc-view-goto-page (caar doc-view-current-search-matches))))))
935
936 (defun doc-view-search-previous-match (arg)
937 "Go to the ARGth previous matching page."
938 (interactive "p")
939 (let* ((prev-pages (doc-view-remove-if
940 (lambda (i) (>= (car i) (doc-view-current-page)))
941 doc-view-current-search-matches))
942 (page (car (nth (1- arg) (nreverse prev-pages)))))
943 (if page
944 (doc-view-goto-page page)
945 (when (and
946 doc-view-current-search-matches
947 (y-or-n-p "No more matches before current page. Wrap to last match? "))
948 (doc-view-goto-page (caar (last doc-view-current-search-matches)))))))
949
950 ;;;; User interface commands and the mode
951
952 ;; (put 'doc-view-mode 'mode-class 'special)
953
954 (defun doc-view-already-converted-p ()
955 "Return non-nil if the current doc was already converted."
956 (and (file-exists-p (doc-view-current-cache-dir))
957 (> 0 (length (directory-files (doc-view-current-cache-dir) nil "\\.png$")))))
958
959 (defun doc-view-initiate-display ()
960 ;; Switch to image display if possible
961 (if (doc-view-mode-p (intern (file-name-extension doc-view-buffer-file-name)))
962 (progn
963 (doc-view-buffer-message)
964 (setf (doc-view-current-page) (or (doc-view-current-page) 1))
965 (if (doc-view-already-converted-p)
966 (progn
967 (message "DocView: using cached files!")
968 (doc-view-display (current-buffer) 'force))
969 (doc-view-convert-current-doc))
970 (message
971 "%s"
972 (substitute-command-keys
973 (concat "Type \\[doc-view-toggle-display] to toggle between "
974 "editing or viewing the document."))))
975 (message
976 "%s"
977 (substitute-command-keys
978 (concat "No image (png) support available or some conversion utility for "
979 (file-name-extension doc-view-buffer-file-name)" files is missing. "
980 "Type \\[doc-view-toggle-display] to switch to an editing mode or "
981 "\\[doc-view-open-text] to open a buffer showing the doc as text.")))))
982
983 (defvar bookmark-make-record-function)
984
985 (defun doc-view-clone-buffer-hook ()
986 ;; FIXME: There are several potential problems linked with reconversion
987 ;; and auto-revert when we have indirect buffers because they share their
988 ;; /tmp cache directory. This sharing is good (you'd rather not reconvert
989 ;; for each clone), but that means that clones need to collaborate a bit.
990 ;; I guess it mostly means: detect when a reconversion process is already
991 ;; running, and run the sentinel in all clones.
992 ;;
993 ;; Maybe the clones should really have a separate /tmp directory
994 ;; so they could have a different resolution and you could use clones
995 ;; for zooming.
996 (remove-overlays (point-min) (point-max) 'doc-view t)
997 (if (consp image-mode-winprops-alist) (setq image-mode-winprops-alist nil)))
998
999 (defun doc-view-intersection (l1 l2)
1000 (let ((l ()))
1001 (dolist (x l1) (if (memq x l2) (push x l)))
1002 l))
1003
1004 ;;;###autoload
1005 (defun doc-view-mode ()
1006 "Major mode in DocView buffers.
1007 You can use \\<doc-view-mode-map>\\[doc-view-toggle-display] to
1008 toggle between displaying the document or editing it as text.
1009 \\{doc-view-mode-map}"
1010 (interactive)
1011
1012 (let* ((prev-major-mode (if (eq major-mode 'doc-view-mode)
1013 doc-view-previous-major-mode
1014 major-mode)))
1015 (kill-all-local-variables)
1016 (set (make-local-variable 'doc-view-previous-major-mode) prev-major-mode))
1017
1018 ;; Figure out the document type.
1019 (let ((name-types
1020 (when buffer-file-name
1021 (cdr (assoc (file-name-extension buffer-file-name)
1022 '(("dvi" dvi)
1023 ("pdf" pdf)
1024 ("epdf" pdf)
1025 ("ps" ps)
1026 ("eps" ps))))))
1027 (content-types
1028 (save-excursion
1029 (goto-char (point-min))
1030 (cond
1031 ((looking-at "%!") '(ps))
1032 ((looking-at "%PDF") '(pdf))
1033 ((looking-at "\367\002") '(dvi))))))
1034 (set (make-local-variable 'doc-view-doc-type)
1035 (car (or (doc-view-intersection name-types content-types)
1036 (when (and name-types content-types)
1037 (error "Conflicting types: name says %s but content says %s"
1038 name-types content-types))
1039 name-types content-types
1040 (error "Cannot determine the document type")))))
1041
1042 (doc-view-make-safe-dir doc-view-cache-directory)
1043 ;; Handle compressed files, remote files, files inside archives
1044 (set (make-local-variable 'doc-view-buffer-file-name)
1045 (cond
1046 (jka-compr-really-do-compress
1047 (expand-file-name
1048 (file-name-nondirectory
1049 (file-name-sans-extension buffer-file-name))
1050 doc-view-cache-directory))
1051 ;; Is the file readable by local processes?
1052 ;; We used to use `file-remote-p' but it's unclear what it's
1053 ;; supposed to return nil for things like local files accessed via
1054 ;; `su' or via file://...
1055 ((let ((file-name-handler-alist nil))
1056 (not (file-readable-p buffer-file-name)))
1057 (expand-file-name
1058 (file-name-nondirectory buffer-file-name)
1059 doc-view-cache-directory))
1060 (t buffer-file-name)))
1061 (when (not (string= doc-view-buffer-file-name buffer-file-name))
1062 (write-region nil nil doc-view-buffer-file-name))
1063
1064 (make-local-variable 'doc-view-current-files)
1065 (make-local-variable 'doc-view-current-converter-process)
1066 (make-local-variable 'doc-view-current-timer)
1067 (make-local-variable 'doc-view-current-cache-dir)
1068 (make-local-variable 'doc-view-current-search-matches)
1069 (add-hook 'change-major-mode-hook
1070 (lambda () (remove-overlays (point-min) (point-max) 'doc-view t))
1071 nil t)
1072 (add-hook 'clone-indirect-buffer-hook 'doc-view-clone-buffer-hook nil t)
1073
1074 (remove-overlays (point-min) (point-max) 'doc-view t) ;Just in case.
1075 ;; Keep track of display info ([vh]scroll, page number, overlay, ...)
1076 ;; for each window in which this document is shown.
1077 (add-hook 'image-mode-new-window-functions
1078 'doc-view-new-window-function nil t)
1079 (image-mode-setup-winprops)
1080
1081 (set (make-local-variable 'mode-line-position)
1082 '(" P" (:eval (number-to-string (doc-view-current-page)))
1083 "/" (:eval (number-to-string (length doc-view-current-files)))))
1084 ;; Don't scroll unless the user specifically asked for it.
1085 (set (make-local-variable 'auto-hscroll-mode) nil)
1086 (set (make-local-variable 'cursor-type) nil)
1087 (use-local-map doc-view-mode-map)
1088 (set (make-local-variable 'after-revert-hook) 'doc-view-reconvert-doc)
1089 (set (make-local-variable 'bookmark-make-record-function)
1090 'doc-view-bookmark-make-record)
1091 (setq mode-name "DocView"
1092 buffer-read-only t
1093 major-mode 'doc-view-mode)
1094 (doc-view-initiate-display)
1095 (run-mode-hooks 'doc-view-mode-hook))
1096
1097 ;;;###autoload
1098 (define-minor-mode doc-view-minor-mode
1099 "Toggle Doc view minor mode.
1100 With arg, turn Doc view minor mode on if arg is positive, off otherwise.
1101 See the command `doc-view-mode' for more information on this mode."
1102 nil " DocView" doc-view-minor-mode-map
1103 :group 'doc-view
1104 (when doc-view-minor-mode
1105 (add-hook 'change-major-mode-hook (lambda () (doc-view-minor-mode -1)) nil t)
1106 (message
1107 "%s"
1108 (substitute-command-keys
1109 "Type \\[doc-view-toggle-display] to toggle between editing or viewing the document."))))
1110
1111 (defun doc-view-clear-cache ()
1112 "Delete the whole cache (`doc-view-cache-directory')."
1113 (interactive)
1114 (dired-delete-file doc-view-cache-directory 'always))
1115
1116 (defun doc-view-dired-cache ()
1117 "Open `dired' in `doc-view-cache-directory'."
1118 (interactive)
1119 (dired doc-view-cache-directory))
1120
1121
1122 ;;;; Bookmark integration
1123
1124 (declare-function bookmark-buffer-file-name "bookmark" ())
1125 (declare-function bookmark-prop-get "bookmark" (bookmark prop))
1126
1127 (defun doc-view-bookmark-make-record ()
1128 `((filename . ,(bookmark-buffer-file-name))
1129 (page . ,(doc-view-current-page))
1130 (handler . doc-view-bookmark-jump)))
1131
1132
1133 ;;;###autoload
1134 (defun doc-view-bookmark-jump (bmk)
1135 ;; This implements the `handler' function interface for record type
1136 ;; returned by `doc-view-bookmark-make-record', which see.
1137 (let ((filename (bookmark-prop-get bmk 'filename))
1138 (page (bookmark-prop-get bmk 'page)))
1139 (with-current-buffer (find-file-noselect filename)
1140 (when (not (eq major-mode 'doc-view-mode))
1141 (doc-view-toggle-display))
1142 (with-selected-window
1143 (or (get-buffer-window (current-buffer) 0)
1144 (selected-window))
1145 (doc-view-goto-page page))
1146 `((buffer ,(current-buffer)) (position ,1)))))
1147
1148
1149 (provide 'doc-view)
1150
1151 ;; Local Variables:
1152 ;; mode: outline-minor
1153 ;; End:
1154
1155 ;; arch-tag: 5d6e5c5e-095f-489e-b4e4-1ca90a7d79be
1156 ;;; doc-view.el ends here