]> code.delx.au - gnu-emacs/blob - lisp/doc-view.el
Merge from emacs--devo--0
[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 ;; - share more code with image-mode again.
103 ;; - better menu.
104 ;; - Bind slicing to a drag event.
105 ;; - doc-view-fit-doc-to-window and doc-view-fit-window-to-doc.
106 ;; - zoom the region around the cursor (like xdvi).
107 ;; - get rid of the silly arrow in the fringe.
108 ;; - improve anti-aliasing (pdf-utils gets it better).
109
110 ;;;; About isearch support
111
112 ;; I tried implementing isearch by setting
113 ;; `isearch-search-fun-function' buffer-locally, but that didn't
114 ;; work too good. The function doing the real search was called
115 ;; endlessly somehow. But even if we'd get that working no real
116 ;; isearch feeling comes up due to the missing match highlighting.
117 ;; Currently I display all lines containing a match in a tooltip and
118 ;; each C-s or C-r jumps directly to the next/previous page with a
119 ;; match. With isearch we could only display the current match. So
120 ;; we had to decide if another C-s jumps to the next page with a
121 ;; match (thus only the first match in a page will be displayed in a
122 ;; tooltip) or to the next match, which would do nothing visible
123 ;; (except the tooltip) if the next match is on the same page.
124
125 ;; And it's much slower than the current search facility, because
126 ;; isearch really searches for each step forward or backward wheras
127 ;; the current approach searches once and then it knows to which
128 ;; pages to jump.
129
130 ;; Anyway, if someone with better isearch knowledge wants to give it a try,
131 ;; feel free to do it. --Tassilo
132
133 ;;; Code:
134
135 (require 'dired)
136 (require 'image-mode)
137 (require 'jka-compr)
138
139 ;;;; Customization Options
140
141 (defgroup doc-view nil
142 "In-buffer viewer for PDF, PostScript and DVI files."
143 :link '(function-link doc-view)
144 :version "22.2"
145 :group 'applications
146 :group 'multimedia
147 :prefix "doc-view-")
148
149 (defcustom doc-view-ghostscript-program (executable-find "gs")
150 "Program to convert PS and PDF files to PNG."
151 :type 'file
152 :group 'doc-view)
153
154 (defcustom doc-view-ghostscript-options
155 '("-dSAFER" ;; Avoid security problems when rendering files from untrusted
156 ;; sources.
157 "-dNOPAUSE" "-sDEVICE=png16m" "-dTextAlphaBits=4"
158 "-dBATCH" "-dGraphicsAlphaBits=4" "-dQUIET")
159 "A list of options to give to ghostscript."
160 :type '(repeat string)
161 :group 'doc-view)
162
163 (defcustom doc-view-resolution 100
164 "Dots per inch resolution used to render the documents.
165 Higher values result in larger images."
166 :type 'number
167 :group 'doc-view)
168
169 (defcustom doc-view-dvipdfm-program (executable-find "dvipdfm")
170 "Program to convert DVI files to PDF.
171
172 DVI file will be converted to PDF before the resulting PDF is
173 converted to PNG."
174 :type 'file
175 :group 'doc-view)
176
177 (defcustom doc-view-ps2pdf-program (executable-find "ps2pdf")
178 "Program to convert PS files to PDF.
179
180 PS files will be converted to PDF before searching is possible."
181 :type 'file
182 :group 'doc-view)
183
184 (defcustom doc-view-pdftotext-program (executable-find "pdftotext")
185 "Program to convert PDF files to plain text.
186
187 Needed for searching."
188 :type 'file
189 :group 'doc-view)
190
191 (defcustom doc-view-cache-directory
192 (expand-file-name (format "docview%d" (user-uid))
193 temporary-file-directory)
194 "The base directory, where the PNG images will be saved."
195 :type 'directory
196 :group 'doc-view)
197
198 (defcustom doc-view-conversion-buffer "*doc-view conversion output*"
199 "The buffer where messages from the converter programs go to."
200 :type 'string
201 :group 'doc-view)
202
203 (defcustom doc-view-conversion-refresh-interval 3
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)
211
212 ;;;; Internal Variables
213
214 (defvar doc-view-current-files nil
215 "Only used internally.")
216
217 (defvar doc-view-current-page nil
218 "Only used internally.")
219
220 (defvar doc-view-current-converter-process nil
221 "Only used internally.")
222
223 (defvar doc-view-current-timer nil
224 "Only used internally.")
225
226 (defvar doc-view-current-slice nil
227 "Only used internally.")
228
229 (defvar doc-view-current-cache-dir nil
230 "Only used internally.")
231
232 (defvar doc-view-current-search-matches nil
233 "Only used internally.")
234
235 (defvar doc-view-current-image nil
236 "Only used internally.")
237
238 (defvar doc-view-current-overlay nil
239 "Only used internally.")
240
241 (defvar doc-view-pending-cache-flush nil
242 "Only used internally.")
243
244 (defvar doc-view-current-info nil
245 "Only used internally.")
246
247 (defvar doc-view-previous-major-mode nil
248 "Only used internally.")
249
250 (defvar doc-view-buffer-file-name nil
251 "Only used internally.
252 The file name used for conversion. Normally it's the same as
253 `buffer-file-name', but for remote files, compressed files and
254 files inside an archive it is a temporary copy of
255 the (uncompressed, extracted) file residing in
256 `doc-view-cache-directory'.")
257
258 ;;;; DocView Keymaps
259
260 (defvar doc-view-mode-map
261 (let ((map (make-sparse-keymap)))
262 (suppress-keymap map)
263 ;; Navigation in the document
264 (define-key map (kbd "n") 'doc-view-next-page)
265 (define-key map (kbd "p") 'doc-view-previous-page)
266 (define-key map (kbd "<next>") 'forward-page)
267 (define-key map (kbd "<prior>") 'backward-page)
268 (define-key map [remap forward-page] 'doc-view-next-page)
269 (define-key map [remap backward-page] 'doc-view-previous-page)
270 (define-key map (kbd "SPC") 'doc-view-scroll-up-or-next-page)
271 (define-key map (kbd "DEL") 'doc-view-scroll-down-or-previous-page)
272 (define-key map (kbd "M-<") 'doc-view-first-page)
273 (define-key map (kbd "M->") 'doc-view-last-page)
274 (define-key map [remap goto-line] 'doc-view-goto-page)
275 (define-key map [remap scroll-up] 'image-scroll-up)
276 (define-key map [remap scroll-down] 'image-scroll-down)
277 ;; Zoom in/out.
278 (define-key map "+" 'doc-view-enlarge)
279 (define-key map "-" 'doc-view-shrink)
280 ;; Killing/burying the buffer (and the process)
281 (define-key map (kbd "q") 'bury-buffer)
282 (define-key map (kbd "k") 'doc-view-kill-proc-and-buffer)
283 (define-key map (kbd "K") 'doc-view-kill-proc)
284 ;; Slicing the image
285 (define-key map (kbd "s s") 'doc-view-set-slice)
286 (define-key map (kbd "s m") 'doc-view-set-slice-using-mouse)
287 (define-key map (kbd "s r") 'doc-view-reset-slice)
288 ;; Searching
289 (define-key map (kbd "C-s") 'doc-view-search)
290 (define-key map (kbd "<find>") 'doc-view-search)
291 (define-key map (kbd "C-r") 'doc-view-search-backward)
292 ;; Scrolling
293 (define-key map [remap forward-char] 'image-forward-hscroll)
294 (define-key map [remap backward-char] 'image-backward-hscroll)
295 (define-key map [remap next-line] 'image-next-line)
296 (define-key map [remap previous-line] 'image-previous-line)
297 ;; Show the tooltip
298 (define-key map (kbd "C-t") 'doc-view-show-tooltip)
299 ;; Toggle between text and image display or editing
300 (define-key map (kbd "C-c C-c") 'doc-view-toggle-display)
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 (defun doc-view-goto-page (page)
329 "View the page given by PAGE."
330 (interactive "nPage: ")
331 (let ((len (length doc-view-current-files)))
332 (if (< page 1)
333 (setq page 1)
334 (when (> page len)
335 (setq page len)))
336 (setq doc-view-current-page page
337 doc-view-current-info
338 (concat
339 (propertize
340 (format "Page %d of %d."
341 doc-view-current-page
342 len) 'face 'bold)
343 ;; Tell user if converting isn't finished yet
344 (if doc-view-current-converter-process
345 " (still converting...)\n"
346 "\n")
347 ;; Display context infos if this page matches the last search
348 (when (and doc-view-current-search-matches
349 (assq doc-view-current-page
350 doc-view-current-search-matches))
351 (concat (propertize "Search matches:\n" 'face 'bold)
352 (let ((contexts ""))
353 (dolist (m (cdr (assq doc-view-current-page
354 doc-view-current-search-matches)))
355 (setq contexts (concat contexts " - \"" m "\"\n")))
356 contexts)))))
357 ;; Update the buffer
358 (doc-view-insert-image (nth (1- page) doc-view-current-files)
359 :pointer 'arrow)
360 (overlay-put doc-view-current-overlay 'help-echo doc-view-current-info)))
361
362 (defun doc-view-next-page (&optional arg)
363 "Browse ARG pages forward."
364 (interactive "p")
365 (doc-view-goto-page (+ doc-view-current-page (or arg 1))))
366
367 (defun doc-view-previous-page (&optional arg)
368 "Browse ARG pages backward."
369 (interactive "p")
370 (doc-view-goto-page (- doc-view-current-page (or arg 1))))
371
372 (defun doc-view-first-page ()
373 "View the first page."
374 (interactive)
375 (doc-view-goto-page 1))
376
377 (defun doc-view-last-page ()
378 "View the last page."
379 (interactive)
380 (doc-view-goto-page (length doc-view-current-files)))
381
382 (defun doc-view-scroll-up-or-next-page ()
383 "Scroll page up if possible, else goto next page."
384 (interactive)
385 (when (= (window-vscroll) (image-scroll-up nil))
386 (let ((cur-page doc-view-current-page))
387 (doc-view-next-page)
388 (when (/= cur-page doc-view-current-page)
389 (set-window-vscroll nil 0)))))
390
391 (defun doc-view-scroll-down-or-previous-page ()
392 "Scroll page down if possible, else goto previous page."
393 (interactive)
394 (when (= (window-vscroll) (image-scroll-down nil))
395 (let ((cur-page doc-view-current-page))
396 (doc-view-previous-page)
397 (when (/= cur-page doc-view-current-page)
398 (image-scroll-up nil)))))
399
400 ;;;; Utility Functions
401
402 (defun doc-view-kill-proc ()
403 "Kill the current converter process."
404 (interactive)
405 (when doc-view-current-converter-process
406 (kill-process doc-view-current-converter-process)
407 (setq doc-view-current-converter-process nil))
408 (when doc-view-current-timer
409 (cancel-timer doc-view-current-timer)
410 (setq doc-view-current-timer nil))
411 (setq mode-line-process nil))
412
413 (defun doc-view-kill-proc-and-buffer ()
414 "Kill the current converter process and buffer."
415 (interactive)
416 (doc-view-kill-proc)
417 (when (eq major-mode 'doc-view-mode)
418 (kill-buffer (current-buffer))))
419
420 (defun doc-view-make-safe-dir (dir)
421 (condition-case nil
422 (let ((umask (default-file-modes)))
423 (unwind-protect
424 (progn
425 ;; Create temp files with strict access rights. It's easy to
426 ;; loosen them later, whereas it's impossible to close the
427 ;; time-window of loose permissions otherwise.
428 (set-default-file-modes #o0700)
429 (make-directory dir))
430 ;; Reset the umask.
431 (set-default-file-modes umask)))
432 (file-already-exists
433 (if (file-symlink-p dir)
434 (error "Danger: %s points to a symbolic link" dir))
435 ;; In case it was created earlier with looser rights.
436 ;; We could check the mode info returned by file-attributes, but it's
437 ;; a pain to parse and it may not tell you what we want under
438 ;; non-standard file-systems. So let's just say what we want and let
439 ;; the underlying C code and file-system figure it out.
440 ;; This also ends up checking a bunch of useful conditions: it makes
441 ;; sure we have write-access to the directory and that we own it, thus
442 ;; closing a bunch of security holes.
443 (set-file-modes dir #o0700))))
444
445 (defun doc-view-current-cache-dir ()
446 "Return the directory where the png files of the current doc should be saved.
447 It's a subdirectory of `doc-view-cache-directory'."
448 (if doc-view-current-cache-dir
449 doc-view-current-cache-dir
450 ;; Try and make sure doc-view-cache-directory exists and is safe.
451 (doc-view-make-safe-dir doc-view-cache-directory)
452 ;; Now compute the subdirectory to use.
453 (setq doc-view-current-cache-dir
454 (file-name-as-directory
455 (expand-file-name
456 (concat (file-name-nondirectory buffer-file-name)
457 "-"
458 (let ((file doc-view-buffer-file-name))
459 (with-temp-buffer
460 (insert-file-contents-literally file)
461 (md5 (current-buffer)))))
462 doc-view-cache-directory)))))
463
464 (defun doc-view-remove-if (predicate list)
465 "Return LIST with all items removed that satisfy PREDICATE."
466 (let (new-list)
467 (dolist (item list (nreverse new-list))
468 (when (not (funcall predicate item))
469 (setq new-list (cons item new-list))))))
470
471 ;;;###autoload
472 (defun doc-view-mode-p (type)
473 "Return non-nil if image type TYPE is available for `doc-view'.
474 Image types are symbols like `dvi', `postscript' or `pdf'."
475 (and (display-graphic-p)
476 (image-type-available-p 'png)
477 (cond
478 ((eq type 'dvi)
479 (and (doc-view-mode-p 'pdf)
480 doc-view-dvipdfm-program
481 (executable-find doc-view-dvipdfm-program)))
482 ((or (eq type 'postscript) (eq type 'ps) (eq type 'eps)
483 (eq type 'pdf))
484 (and doc-view-ghostscript-program
485 (executable-find doc-view-ghostscript-program)))
486 (t ;; unknown image type
487 nil))))
488
489 ;;;; Conversion Functions
490
491 (defvar doc-view-shrink-factor 1.125)
492
493 (defun doc-view-enlarge (factor)
494 "Enlarge the document."
495 (interactive (list doc-view-shrink-factor))
496 (set (make-local-variable 'doc-view-resolution)
497 (* factor doc-view-resolution))
498 (doc-view-reconvert-doc))
499
500 (defun doc-view-shrink (factor)
501 "Shrink the document."
502 (interactive (list doc-view-shrink-factor))
503 (doc-view-enlarge (/ 1.0 factor)))
504
505 (defun doc-view-reconvert-doc ()
506 "Reconvert the current document.
507 Should be invoked when the cached images aren't up-to-date."
508 (interactive)
509 (doc-view-kill-proc)
510 ;; Clear the old cached files
511 (when (file-exists-p (doc-view-current-cache-dir))
512 (dired-delete-file (doc-view-current-cache-dir) 'always))
513 (doc-view-initiate-display))
514
515 (defun doc-view-dvi->pdf-sentinel (proc event)
516 "If DVI->PDF conversion was successful, convert the PDF to PNG now."
517 (if (not (string-match "finished" event))
518 (message "DocView: dvi->pdf process changed status to %s." event)
519 (with-current-buffer (process-get proc 'buffer)
520 (setq doc-view-current-converter-process nil
521 mode-line-process nil)
522 ;; Now go on converting this PDF to a set of PNG files.
523 (let* ((pdf (process-get proc 'pdf-file))
524 (png (expand-file-name "page-%d.png"
525 (doc-view-current-cache-dir))))
526 (doc-view-pdf/ps->png pdf png)))))
527
528 (defun doc-view-dvi->pdf (dvi pdf)
529 "Convert DVI to PDF asynchronously."
530 (setq doc-view-current-converter-process
531 (start-process "dvi->pdf" doc-view-conversion-buffer
532 doc-view-dvipdfm-program
533 "-o" pdf dvi)
534 mode-line-process (list (format ":%s" doc-view-current-converter-process)))
535 (set-process-sentinel doc-view-current-converter-process
536 'doc-view-dvi->pdf-sentinel)
537 (process-put doc-view-current-converter-process 'buffer (current-buffer))
538 (process-put doc-view-current-converter-process 'pdf-file pdf))
539
540 (defun doc-view-pdf/ps->png-sentinel (proc event)
541 "If PDF/PS->PNG conversion was successful, update the display."
542 (if (not (string-match "finished" event))
543 (message "DocView: converter process changed status to %s." event)
544 (with-current-buffer (process-get proc 'buffer)
545 (setq doc-view-current-converter-process nil
546 mode-line-process nil)
547 (when doc-view-current-timer
548 (cancel-timer doc-view-current-timer)
549 (setq doc-view-current-timer nil))
550 ;; Yippie, finished. Update the display!
551 (doc-view-display buffer-file-name 'force))))
552
553 (defun doc-view-pdf/ps->png (pdf-ps png)
554 "Convert PDF-PS to PNG asynchronously."
555 (setq doc-view-current-converter-process
556 ;; Make sure the process is started in an existing directory,
557 ;; (rather than some file-name-handler-managed dir, for example).
558 (let ((default-directory (file-name-directory pdf-ps)))
559 (apply 'start-process
560 (append (list "pdf/ps->png" doc-view-conversion-buffer
561 doc-view-ghostscript-program)
562 doc-view-ghostscript-options
563 (list (format "-r%d" (round doc-view-resolution)))
564 (list (concat "-sOutputFile=" png))
565 (list pdf-ps))))
566 mode-line-process (list (format ":%s" doc-view-current-converter-process)))
567 (process-put doc-view-current-converter-process
568 'buffer (current-buffer))
569 (set-process-sentinel doc-view-current-converter-process
570 'doc-view-pdf/ps->png-sentinel)
571 (when doc-view-conversion-refresh-interval
572 (setq doc-view-current-timer
573 (run-at-time "1 secs" doc-view-conversion-refresh-interval
574 'doc-view-display
575 buffer-file-name))))
576
577 (defun doc-view-pdf->txt-sentinel (proc event)
578 (if (not (string-match "finished" event))
579 (message "DocView: converter process changed status to %s." event)
580 (let ((current-buffer (current-buffer))
581 (proc-buffer (process-get proc 'buffer)))
582 (with-current-buffer proc-buffer
583 (setq doc-view-current-converter-process nil
584 mode-line-process nil)
585 ;; If the user looks at the DocView buffer where the conversion was
586 ;; performed, search anew. This time it will be queried for a regexp.
587 (when (eq current-buffer proc-buffer)
588 (doc-view-search nil))))))
589
590 (defun doc-view-pdf->txt (pdf txt)
591 "Convert PDF to TXT asynchronously."
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-pdf->txt-sentinel)
599 (process-put doc-view-current-converter-process 'buffer (current-buffer)))
600
601 (defun doc-view-ps->pdf-sentinel (proc event)
602 (if (not (string-match "finished" event))
603 (message "DocView: converter process changed status to %s." event)
604 (with-current-buffer (process-get proc 'buffer)
605 (setq doc-view-current-converter-process nil
606 mode-line-process nil)
607 ;; Now we can transform to plain text.
608 (doc-view-pdf->txt (process-get proc 'pdf-file)
609 (expand-file-name "doc.txt"
610 (doc-view-current-cache-dir))))))
611
612 (defun doc-view-ps->pdf (ps pdf)
613 "Convert PS to PDF asynchronously."
614 (setq doc-view-current-converter-process
615 (start-process "ps->pdf" doc-view-conversion-buffer
616 doc-view-ps2pdf-program
617 ;; Avoid security problems when rendering files from
618 ;; untrusted sources.
619 "-dSAFER"
620 ;; in-file and out-file
621 ps pdf)
622 mode-line-process (list (format ":%s" doc-view-current-converter-process)))
623 (set-process-sentinel doc-view-current-converter-process
624 'doc-view-ps->pdf-sentinel)
625 (process-put doc-view-current-converter-process 'buffer (current-buffer))
626 (process-put doc-view-current-converter-process 'pdf-file pdf))
627
628 (defun doc-view-convert-current-doc ()
629 "Convert `doc-view-buffer-file-name' to a set of png files, one file per page.
630 Those files are saved in the directory given by the function
631 `doc-view-current-cache-dir'."
632 ;; Let stale files still display while we recompute the new ones, so only
633 ;; flush the cache when the conversion is over. One of the reasons why it
634 ;; is important to keep displaying the stale page is so that revert-buffer
635 ;; preserves the horizontal/vertical scroll settings (which are otherwise
636 ;; resets during the redisplay).
637 (setq doc-view-pending-cache-flush t)
638 (let ((png-file (expand-file-name "page-%d.png"
639 (doc-view-current-cache-dir))))
640 (make-directory (doc-view-current-cache-dir))
641 (if (not (string= (file-name-extension doc-view-buffer-file-name) "dvi"))
642 ;; Convert to PNG images.
643 (doc-view-pdf/ps->png doc-view-buffer-file-name png-file)
644 ;; DVI files have to be converted to PDF before Ghostscript can process
645 ;; it.
646 (doc-view-dvi->pdf doc-view-buffer-file-name
647 (expand-file-name "doc.pdf"
648 doc-view-current-cache-dir)))))
649
650 ;;;; Slicing
651
652 (defun doc-view-set-slice (x y width height)
653 "Set the slice of the images that should be displayed.
654 You can use this function to tell doc-view not to display the
655 margins of the document. It prompts for the top-left corner (X
656 and Y) of the slice to display and its WIDTH and HEIGHT.
657
658 See `doc-view-set-slice-using-mouse' for a more convenient way to
659 do that. To reset the slice use `doc-view-reset-slice'."
660 (interactive
661 (let* ((size (image-size doc-view-current-image t))
662 (a (read-number (format "Top-left X (0..%d): " (car size))))
663 (b (read-number (format "Top-left Y (0..%d): " (cdr size))))
664 (c (read-number (format "Width (0..%d): " (- (car size) a))))
665 (d (read-number (format "Height (0..%d): " (- (cdr size) b)))))
666 (list a b c d)))
667 (setq doc-view-current-slice (list x y width height))
668 ;; Redisplay
669 (doc-view-goto-page doc-view-current-page))
670
671 (defun doc-view-set-slice-using-mouse ()
672 "Set the slice of the images that should be displayed.
673 You set the slice by pressing mouse-1 at its top-left corner and
674 dragging it to its bottom-right corner. See also
675 `doc-view-set-slice' and `doc-view-reset-slice'."
676 (interactive)
677 (let (x y w h done)
678 (while (not done)
679 (let ((e (read-event
680 (concat "Press mouse-1 at the top-left corner and "
681 "drag it to the bottom-right corner!"))))
682 (when (eq (car e) 'drag-mouse-1)
683 (setq x (car (posn-object-x-y (event-start e))))
684 (setq y (cdr (posn-object-x-y (event-start e))))
685 (setq w (- (car (posn-object-x-y (event-end e))) x))
686 (setq h (- (cdr (posn-object-x-y (event-end e))) y))
687 (setq done t))))
688 (doc-view-set-slice x y w h)))
689
690 (defun doc-view-reset-slice ()
691 "Reset the current slice.
692 After calling this function whole pages will be visible again."
693 (interactive)
694 (setq doc-view-current-slice nil)
695 ;; Redisplay
696 (doc-view-goto-page doc-view-current-page))
697
698 ;;;; Display
699
700 (defun doc-view-insert-image (file &rest args)
701 "Insert the given png FILE.
702 ARGS is a list of image descriptors."
703 (when doc-view-pending-cache-flush
704 (clear-image-cache)
705 (setq doc-view-pending-cache-flush nil))
706 (if (null file)
707 ;; We're trying to display a page that doesn't exist. Typically happens
708 ;; if the conversion process somehow failed. Better not signal an
709 ;; error here because it could prevent a subsequent reconversion from
710 ;; fixing the problem.
711 (progn
712 (setq doc-view-current-image nil)
713 (move-overlay doc-view-current-overlay (point-min) (point-max))
714 (overlay-put doc-view-current-overlay 'display
715 "Cannot display this page! Probably a conversion failure!"))
716 (let ((image (apply 'create-image file 'png nil args)))
717 (setq doc-view-current-image image)
718 (move-overlay doc-view-current-overlay (point-min) (point-max))
719 (overlay-put doc-view-current-overlay 'display
720 (if doc-view-current-slice
721 (list (cons 'slice doc-view-current-slice) image)
722 image)))))
723
724 (defun doc-view-sort (a b)
725 "Return non-nil if A should be sorted before B.
726 Predicate for sorting `doc-view-current-files'."
727 (or (< (length a) (length b))
728 (and (= (length a) (length b))
729 (string< a b))))
730
731 (defun doc-view-display (doc &optional force)
732 "Start viewing the document DOC.
733 If FORCE is non-nil, start viewing even if the document does not
734 have the page we want to view."
735 (with-current-buffer (get-file-buffer doc)
736 (setq doc-view-current-files
737 (sort (directory-files (doc-view-current-cache-dir) t
738 "page-[0-9]+\\.png" t)
739 'doc-view-sort))
740 (when (or force
741 (>= (length doc-view-current-files)
742 (or doc-view-current-page 1)))
743 (doc-view-goto-page doc-view-current-page))))
744
745 (defun doc-view-buffer-message ()
746 ;; Only show this message initially, not when refreshing the buffer (in which
747 ;; case it's better to keep displaying the "stale" page while computing
748 ;; the fresh new ones).
749 (unless (overlay-get doc-view-current-overlay 'display)
750 (overlay-put doc-view-current-overlay 'display
751 (concat (propertize "Welcome to DocView!" 'face 'bold)
752 "\n"
753 "
754 If you see this buffer it means that the document you want to view is being
755 converted to PNG and the conversion of the first page hasn't finished yet or
756 `doc-view-conversion-refresh-interval' is set to nil.
757
758 For now these keys are useful:
759
760 `q' : Bury this buffer. Conversion will go on in background.
761 `k' : Kill the conversion process and this buffer.
762 `K' : Kill the conversion process.\n"))))
763
764 (defun doc-view-show-tooltip ()
765 (interactive)
766 (tooltip-show doc-view-current-info))
767
768 ;;;;; Toggle between editing and viewing
769
770 (defun doc-view-toggle-display ()
771 "Toggle between editing a document as text or viewing it."
772 (interactive)
773 (if (eq major-mode 'doc-view-mode)
774 ;; Switch to editing mode
775 (progn
776 (doc-view-kill-proc)
777 (setq buffer-read-only nil)
778 (delete-overlay doc-view-current-overlay)
779 ;; Switch to the previously used major mode or fall back to fundamental
780 ;; mode.
781 (if doc-view-previous-major-mode
782 (funcall doc-view-previous-major-mode)
783 (fundamental-mode))
784 (doc-view-minor-mode 1))
785 ;; Switch to doc-view-mode
786 (when (and (buffer-modified-p)
787 (y-or-n-p "The buffer has been modified. Save the changes? "))
788 (save-buffer))
789 (doc-view-mode)))
790
791 ;;;; Searching
792
793 (defun doc-view-search-internal (regexp file)
794 "Return a list of FILE's pages that contain text matching REGEXP.
795 The value is an alist of the form (PAGE CONTEXTS) where PAGE is
796 the pagenumber and CONTEXTS are all lines of text containing a match."
797 (with-temp-buffer
798 (insert-file-contents file)
799 (let ((page 1)
800 (lastpage 1)
801 matches)
802 (while (re-search-forward (concat "\\(?:\\([\f]\\)\\|\\("
803 regexp "\\)\\)") nil t)
804 (when (match-string 1) (setq page (1+ page)))
805 (when (match-string 2)
806 (if (/= page lastpage)
807 (push (cons page
808 (list (buffer-substring
809 (line-beginning-position)
810 (line-end-position))))
811 matches)
812 (setq matches (cons
813 (append
814 (or
815 ;; This page already is a match.
816 (car matches)
817 ;; This is the first match on page.
818 (list page))
819 (list (buffer-substring
820 (line-beginning-position)
821 (line-end-position))))
822 (cdr matches))))
823 (setq lastpage page)))
824 (nreverse matches))))
825
826 (defun doc-view-search-no-of-matches (list)
827 "Extract the number of matches from the search result LIST."
828 (let ((no 0))
829 (dolist (p list)
830 (setq no (+ no (1- (length p)))))
831 no))
832
833 (defun doc-view-search-backward (new-query)
834 "Call `doc-view-search' for backward search.
835 If prefix NEW-QUERY is given, ask for a new regexp."
836 (interactive "P")
837 (doc-view-search new-query t))
838
839 (defun doc-view-search (new-query &optional backward)
840 "Jump to the next match or initiate a new search if NEW-QUERY is given.
841 If the current document hasn't been transformed to plain text
842 till now do that first.
843 If BACKWARD is non-nil, jump to the previous match."
844 (interactive "P")
845 (if (and (not new-query)
846 doc-view-current-search-matches)
847 (if backward
848 (doc-view-search-previous-match 1)
849 (doc-view-search-next-match 1))
850 ;; New search, so forget the old results.
851 (setq doc-view-current-search-matches nil)
852 (let ((txt (expand-file-name "doc.txt"
853 (doc-view-current-cache-dir))))
854 (if (file-readable-p txt)
855 (progn
856 (setq doc-view-current-search-matches
857 (doc-view-search-internal
858 (read-from-minibuffer "Regexp: ")
859 txt))
860 (message "DocView: search yielded %d matches."
861 (doc-view-search-no-of-matches
862 doc-view-current-search-matches)))
863 ;; We must convert to TXT first!
864 (if doc-view-current-converter-process
865 (message "DocView: please wait till conversion finished.")
866 (let ((ext (file-name-extension doc-view-buffer-file-name)))
867 (cond
868 ((string= ext "pdf")
869 ;; Doc is a PDF, so convert it to TXT
870 (doc-view-pdf->txt doc-view-buffer-file-name txt))
871 ((string= ext "ps")
872 ;; Doc is a PS, so convert it to PDF (which will be converted to
873 ;; TXT thereafter).
874 (doc-view-ps->pdf doc-view-buffer-file-name
875 (expand-file-name "doc.pdf"
876 (doc-view-current-cache-dir))))
877 ((string= ext "dvi")
878 ;; Doc is a DVI. This means that a doc.pdf already exists in its
879 ;; cache subdirectory.
880 (doc-view-pdf->txt (expand-file-name "doc.pdf"
881 (doc-view-current-cache-dir))
882 txt))
883 (t (error "DocView doesn't know what to do")))))))))
884
885 (defun doc-view-search-next-match (arg)
886 "Go to the ARGth next matching page."
887 (interactive "p")
888 (let* ((next-pages (doc-view-remove-if
889 (lambda (i) (<= (car i) doc-view-current-page))
890 doc-view-current-search-matches))
891 (page (car (nth (1- arg) next-pages))))
892 (if page
893 (doc-view-goto-page page)
894 (when (and
895 doc-view-current-search-matches
896 (y-or-n-p "No more matches after current page. Wrap to first match? "))
897 (doc-view-goto-page (caar doc-view-current-search-matches))))))
898
899 (defun doc-view-search-previous-match (arg)
900 "Go to the ARGth previous matching page."
901 (interactive "p")
902 (let* ((prev-pages (doc-view-remove-if
903 (lambda (i) (>= (car i) doc-view-current-page))
904 doc-view-current-search-matches))
905 (page (car (nth (1- arg) (nreverse prev-pages)))))
906 (if page
907 (doc-view-goto-page page)
908 (when (and
909 doc-view-current-search-matches
910 (y-or-n-p "No more matches before current page. Wrap to last match? "))
911 (doc-view-goto-page (caar (last doc-view-current-search-matches)))))))
912
913 ;;;; User interface commands and the mode
914
915 ;; (put 'doc-view-mode 'mode-class 'special)
916
917 (defun doc-view-initiate-display ()
918 ;; Switch to image display if possible
919 (if (doc-view-mode-p (intern (file-name-extension doc-view-buffer-file-name)))
920 (progn
921 (doc-view-buffer-message)
922 (setq doc-view-current-page (or doc-view-current-page 1))
923 (if (file-exists-p (doc-view-current-cache-dir))
924 (progn
925 (message "DocView: using cached files!")
926 (doc-view-display buffer-file-name 'force))
927 (doc-view-convert-current-doc))
928 (message
929 "%s"
930 (substitute-command-keys
931 (concat "Type \\[doc-view-toggle-display] to toggle between "
932 "editing or viewing the document."))))
933 (message
934 "%s"
935 (substitute-command-keys
936 (concat "No image (png) support available or some conversion utility for "
937 (file-name-extension doc-view-buffer-file-name)" files is missing. "
938 "Type \\[doc-view-toggle-display] to switch to an editing mode.")))))
939
940 (defvar bookmark-make-cell-function)
941
942 ;;;###autoload
943 (defun doc-view-mode ()
944 "Major mode in DocView buffers.
945 You can use \\<doc-view-mode-map>\\[doc-view-toggle-display] to
946 toggle between displaying the document or editing it as text."
947 (interactive)
948
949 (let* ((prev-major-mode (if (eq major-mode 'doc-view-mode)
950 doc-view-previous-major-mode
951 major-mode)))
952 (kill-all-local-variables)
953 (set (make-local-variable 'doc-view-previous-major-mode) prev-major-mode))
954
955 ;; Handle compressed files, remote files, files inside archives
956 (set (make-local-variable 'doc-view-buffer-file-name)
957 (cond
958 (jka-compr-really-do-compress
959 (expand-file-name
960 (file-name-nondirectory
961 (file-name-sans-extension buffer-file-name))
962 doc-view-cache-directory))
963 ;; Is the file readable by local processes?
964 ;; We used to use `file-remote-p' but it's unclear what it's
965 ;; supposed to return nil for things like local files accessed via
966 ;; `su' or via file://...
967 ((let ((file-name-handler-alist nil))
968 (not (file-readable-p buffer-file-name)))
969 (expand-file-name
970 (file-name-nondirectory buffer-file-name)
971 doc-view-cache-directory))
972 (t buffer-file-name)))
973 (when (not (string= doc-view-buffer-file-name buffer-file-name))
974 (write-region nil nil doc-view-buffer-file-name))
975
976 (make-local-variable 'doc-view-current-files)
977 (make-local-variable 'doc-view-current-image)
978 (make-local-variable 'doc-view-current-page)
979 (make-local-variable 'doc-view-current-converter-process)
980 (make-local-variable 'doc-view-current-timer)
981 (make-local-variable 'doc-view-current-slice)
982 (make-local-variable 'doc-view-current-cache-dir)
983 (make-local-variable 'doc-view-current-info)
984 (make-local-variable 'doc-view-current-search-matches)
985 (set (make-local-variable 'doc-view-current-overlay)
986 (make-overlay (point-min) (point-max) nil t))
987 (add-hook 'change-major-mode-hook
988 (lambda () (delete-overlay doc-view-current-overlay))
989 nil t)
990
991 ;; Keep track of [vh]scroll when switching buffers
992 (make-local-variable 'image-mode-current-hscroll)
993 (make-local-variable 'image-mode-current-vscroll)
994 (image-set-window-hscroll (selected-window) (window-hscroll))
995 (image-set-window-vscroll (selected-window) (window-vscroll))
996 (add-hook 'window-configuration-change-hook
997 'image-reset-current-vhscroll nil t)
998
999 (set (make-local-variable 'mode-line-position)
1000 '(" P" (:eval (number-to-string doc-view-current-page))
1001 "/" (:eval (number-to-string (length doc-view-current-files)))))
1002 ;; Don't scroll unless the user specifically asked for it.
1003 (set (make-local-variable 'auto-hscroll-mode) nil)
1004 (set (make-local-variable 'cursor-type) nil)
1005 (use-local-map doc-view-mode-map)
1006 (set (make-local-variable 'after-revert-hook) 'doc-view-reconvert-doc)
1007 (set (make-local-variable 'bookmark-make-cell-function)
1008 'doc-view-bookmark-make-cell)
1009 (setq mode-name "DocView"
1010 buffer-read-only t
1011 major-mode 'doc-view-mode)
1012 (doc-view-initiate-display)
1013 (run-mode-hooks 'doc-view-mode-hook))
1014
1015 ;;;###autoload
1016 (define-minor-mode doc-view-minor-mode
1017 "Toggle Doc view minor mode.
1018 With arg, turn Doc view minor mode on if arg is positive, off otherwise.
1019 See the command `doc-view-mode' for more information on this mode."
1020 nil " DocView" doc-view-minor-mode-map
1021 :group 'doc-view
1022 (when doc-view-minor-mode
1023 (add-hook 'change-major-mode-hook (lambda () (doc-view-minor-mode -1)) nil t)
1024 (message
1025 "%s"
1026 (substitute-command-keys
1027 "Type \\[doc-view-toggle-display] to toggle between editing or viewing the document."))))
1028
1029 (defun doc-view-clear-cache ()
1030 "Delete the whole cache (`doc-view-cache-directory')."
1031 (interactive)
1032 (dired-delete-file doc-view-cache-directory 'always)
1033 (make-directory doc-view-cache-directory))
1034
1035 (defun doc-view-dired-cache ()
1036 "Open `dired' in `doc-view-cache-directory'."
1037 (interactive)
1038 (dired doc-view-cache-directory))
1039
1040
1041 ;;;; Bookmark integration
1042
1043 (defun doc-view-bookmark-make-cell (annotation &rest args)
1044 (let ((the-record
1045 `((filename . ,buffer-file-name)
1046 (page . ,doc-view-current-page)
1047 (handler . doc-view-bookmark-jump))))
1048
1049 ;; Take no chances with text properties
1050 (set-text-properties 0 (length annotation) nil annotation)
1051
1052 (when annotation
1053 (nconc the-record (list (cons 'annotation annotation))))
1054
1055 ;; Finally, return the completed record.
1056 the-record))
1057
1058
1059 (declare-function bookmark-get-filename "bookmark" (bookmark))
1060 (declare-function bookmark-get-bookmark-record "bookmark" (bookmark))
1061
1062 ;;;###autoload
1063 (defun doc-view-bookmark-jump (bmk)
1064 ;; This implements the `handler' function interface for record type
1065 ;; returned by `bookmark-make-cell-function', which see.
1066 (save-window-excursion
1067 (let ((filename (bookmark-get-filename bmk))
1068 (page (cdr (assq 'page (bookmark-get-bookmark-record bmk)))))
1069 (find-file filename)
1070 (when (not (eq major-mode 'doc-view-mode))
1071 (doc-view-toggle-display))
1072 (doc-view-goto-page page)
1073 `((buffer ,(current-buffer)) (position ,1)))))
1074
1075
1076 (provide 'doc-view)
1077
1078 ;; Local Variables:
1079 ;; mode: outline-minor
1080 ;; End:
1081
1082 ;; arch-tag: 5d6e5c5e-095f-489e-b4e4-1ca90a7d79be
1083 ;;; doc-view.el ends here