(Compiler Errors): Mention declaring functions, defvar with no
[emacs.git] / lisp / doc-view.el
blob5443bc3672ed6bbb9866843aee7fcfe2a8703b3f
1 ;;; doc-view.el --- View PDF/PostScript/DVI files in Emacs
3 ;; Copyright (C) 2007 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 ;; - better menu.
103 ;; - don't use `find-file'.
104 ;; - Bind slicing to a drag event.
105 ;; - doc-view-fit-doc-to-window and doc-view-fit-window-to-doc.
106 ;; - zoom a 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).
110 ;;;; About isearch support
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.
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.
130 ;; Anyway, if someone with better isearch knowledge wants to give it a try,
131 ;; feel free to do it. --Tassilo
133 ;;; Code:
135 (require 'dired)
136 (require 'image-mode)
137 (require 'jka-compr)
139 ;;;; Customization Options
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-")
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)
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)
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)
169 (defcustom doc-view-dvipdfm-program (executable-find "dvipdfm")
170 "Program to convert DVI files to PDF.
172 DVI file will be converted to PDF before the resulting PDF is
173 converted to PNG."
174 :type 'file
175 :group 'doc-view)
177 (defcustom doc-view-ps2pdf-program (executable-find "ps2pdf")
178 "Program to convert PS files to PDF.
180 PS files will be converted to PDF before searching is possible."
181 :type 'file
182 :group 'doc-view)
184 (defcustom doc-view-pdftotext-program (executable-find "pdftotext")
185 "Program to convert PDF files to plain text.
187 Needed for searching."
188 :type 'file
189 :group 'doc-view)
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)
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)
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)
212 ;;;; Internal Variables
214 (defvar doc-view-current-files nil
215 "Only used internally.")
217 (defvar doc-view-current-page nil
218 "Only used internally.")
220 (defvar doc-view-current-converter-process nil
221 "Only used internally.")
223 (defvar doc-view-current-timer nil
224 "Only used internally.")
226 (defvar doc-view-current-slice nil
227 "Only used internally.")
229 (defvar doc-view-current-cache-dir nil
230 "Only used internally.")
232 (defvar doc-view-current-search-matches nil
233 "Only used internally.")
235 (defvar doc-view-current-image nil
236 "Only used internally.")
237 (defvar doc-view-current-overlay)
238 (defvar doc-view-pending-cache-flush nil)
240 (defvar doc-view-current-info nil
241 "Only used internally.")
243 (defvar doc-view-previous-major-mode nil
244 "Only used internally.")
246 ;;;; DocView Keymaps
248 (defvar doc-view-mode-map
249 (let ((map (make-sparse-keymap)))
250 (suppress-keymap map)
251 ;; Navigation in the document
252 (define-key map (kbd "n") 'doc-view-next-page)
253 (define-key map (kbd "p") 'doc-view-previous-page)
254 (define-key map (kbd "<next>") 'forward-page)
255 (define-key map (kbd "<prior>") 'backward-page)
256 (define-key map [remap forward-page] 'doc-view-next-page)
257 (define-key map [remap backward-page] 'doc-view-previous-page)
258 (define-key map (kbd "SPC") 'doc-view-scroll-up-or-next-page)
259 (define-key map (kbd "DEL") 'doc-view-scroll-down-or-previous-page)
260 (define-key map (kbd "M-<") 'doc-view-first-page)
261 (define-key map (kbd "M->") 'doc-view-last-page)
262 (define-key map [remap goto-line] 'doc-view-goto-page)
263 ;; Zoom in/out.
264 (define-key map "+" 'doc-view-enlarge)
265 (define-key map "-" 'doc-view-shrink)
266 ;; Killing/burying the buffer (and the process)
267 (define-key map (kbd "q") 'bury-buffer)
268 (define-key map (kbd "k") 'doc-view-kill-proc-and-buffer)
269 (define-key map (kbd "K") 'doc-view-kill-proc)
270 ;; Slicing the image
271 (define-key map (kbd "s s") 'doc-view-set-slice)
272 (define-key map (kbd "s m") 'doc-view-set-slice-using-mouse)
273 (define-key map (kbd "s r") 'doc-view-reset-slice)
274 ;; Searching
275 (define-key map (kbd "C-s") 'doc-view-search)
276 (define-key map (kbd "<find>") 'doc-view-search)
277 (define-key map (kbd "C-r") 'doc-view-search-backward)
278 ;; Scrolling
279 (define-key map [remap forward-char] 'image-forward-hscroll)
280 (define-key map [remap backward-char] 'image-backward-hscroll)
281 (define-key map [remap next-line] 'image-next-line)
282 (define-key map [remap previous-line] 'image-previous-line)
283 ;; Show the tooltip
284 (define-key map (kbd "C-t") 'doc-view-show-tooltip)
285 ;; Toggle between text and image display or editing
286 (define-key map (kbd "C-c C-c") 'doc-view-toggle-display)
287 ;; Reconvert the current document
288 (define-key map (kbd "g") 'revert-buffer)
289 (define-key map (kbd "r") 'revert-buffer)
290 map)
291 "Keymap used by `doc-view-mode' when displaying a doc as a set of images.")
293 (easy-menu-define doc-view-menu doc-view-mode-map
294 "Menu for Doc View mode."
295 '("DocView"
296 ["Set Slice" doc-view-set-slice-using-mouse]
297 ["Set Slice (manual)" doc-view-set-slice]
298 ["Reset Slice" doc-view-reset-slice]
299 "---"
300 ["Search" doc-view-search]
301 ["Search Backwards" doc-view-search-backward]
302 ["Toggle display" doc-view-toggle-display]
305 (defvar doc-view-minor-mode-map
306 (let ((map (make-sparse-keymap)))
307 ;; Toggle between text and image display or editing
308 (define-key map (kbd "C-c C-c") 'doc-view-toggle-display)
309 map)
310 "Keymap used by `doc-minor-view-mode'.")
312 ;;;; Navigation Commands
314 (defun doc-view-goto-page (page)
315 "View the page given by PAGE."
316 (interactive "nPage: ")
317 (let ((len (length doc-view-current-files)))
318 (if (< page 1)
319 (setq page 1)
320 (when (> page len)
321 (setq page len)))
322 (setq doc-view-current-page page
323 doc-view-current-info
324 (concat
325 (propertize
326 (format "Page %d of %d."
327 doc-view-current-page
328 len) 'face 'bold)
329 ;; Tell user if converting isn't finished yet
330 (if doc-view-current-converter-process
331 " (still converting...)\n"
332 "\n")
333 ;; Display context infos if this page matches the last search
334 (when (and doc-view-current-search-matches
335 (assq doc-view-current-page
336 doc-view-current-search-matches))
337 (concat (propertize "Search matches:\n" 'face 'bold)
338 (let ((contexts ""))
339 (dolist (m (cdr (assq doc-view-current-page
340 doc-view-current-search-matches)))
341 (setq contexts (concat contexts " - \"" m "\"\n")))
342 contexts)))))
343 ;; Update the buffer
344 (doc-view-insert-image (nth (1- page) doc-view-current-files)
345 :pointer 'arrow)
346 (overlay-put doc-view-current-overlay 'help-echo doc-view-current-info)
347 (goto-char (point-min))
348 ;; This seems to be needed for set-window-hscroll (in
349 ;; image-forward-hscroll) to do something useful, I don't have time to
350 ;; debug this now. :-( --Stef
351 (forward-char)))
353 (defun doc-view-next-page (&optional arg)
354 "Browse ARG pages forward."
355 (interactive "p")
356 (doc-view-goto-page (+ doc-view-current-page (or arg 1))))
358 (defun doc-view-previous-page (&optional arg)
359 "Browse ARG pages backward."
360 (interactive "p")
361 (doc-view-goto-page (- doc-view-current-page (or arg 1))))
363 (defun doc-view-first-page ()
364 "View the first page."
365 (interactive)
366 (doc-view-goto-page 1))
368 (defun doc-view-last-page ()
369 "View the last page."
370 (interactive)
371 (doc-view-goto-page (length doc-view-current-files)))
373 (defun doc-view-scroll-up-or-next-page ()
374 "Scroll page up if possible, else goto next page."
375 (interactive)
376 (condition-case nil
377 (scroll-up)
378 (error (doc-view-next-page))))
380 (defun doc-view-scroll-down-or-previous-page ()
381 "Scroll page down if possible, else goto previous page."
382 (interactive)
383 (condition-case nil
384 (scroll-down)
385 (error (doc-view-previous-page)
386 (goto-char (point-max)))))
388 ;;;; Utility Functions
390 (defun doc-view-kill-proc ()
391 "Kill the current converter process."
392 (interactive)
393 (when doc-view-current-converter-process
394 (kill-process doc-view-current-converter-process)
395 (setq doc-view-current-converter-process nil))
396 (when doc-view-current-timer
397 (cancel-timer doc-view-current-timer)
398 (setq doc-view-current-timer nil))
399 (setq mode-line-process nil))
401 (defun doc-view-kill-proc-and-buffer ()
402 "Kill the current converter process and buffer."
403 (interactive)
404 (doc-view-kill-proc)
405 (when (eq major-mode 'doc-view-mode)
406 (kill-buffer (current-buffer))))
408 (defun doc-view-make-safe-dir (dir)
409 (condition-case nil
410 (let ((umask (default-file-modes)))
411 (unwind-protect
412 (progn
413 ;; Create temp files with strict access rights. It's easy to
414 ;; loosen them later, whereas it's impossible to close the
415 ;; time-window of loose permissions otherwise.
416 (set-default-file-modes #o0700)
417 (make-directory dir))
418 ;; Reset the umask.
419 (set-default-file-modes umask)))
420 (file-already-exists
421 (if (file-symlink-p dir)
422 (error "Danger: %s points to a symbolic link" dir))
423 ;; In case it was created earlier with looser rights.
424 ;; We could check the mode info returned by file-attributes, but it's
425 ;; a pain to parse and it may not tell you what we want under
426 ;; non-standard file-systems. So let's just say what we want and let
427 ;; the underlying C code and file-system figure it out.
428 ;; This also ends up checking a bunch of useful conditions: it makes
429 ;; sure we have write-access to the directory and that we own it, thus
430 ;; closing a bunch of security holes.
431 (set-file-modes dir #o0700))))
433 (defun doc-view-current-cache-dir ()
434 "Return the directory where the png files of the current doc should be saved.
435 It's a subdirectory of `doc-view-cache-directory'."
436 (if doc-view-current-cache-dir
437 doc-view-current-cache-dir
438 ;; Try and make sure doc-view-cache-directory exists and is safe.
439 (doc-view-make-safe-dir doc-view-cache-directory)
440 ;; Now compute the subdirectory to use.
441 (setq doc-view-current-cache-dir
442 (file-name-as-directory
443 (expand-file-name
444 (let ((doc buffer-file-name))
445 (concat (file-name-nondirectory doc)
447 (with-temp-buffer
448 (insert-file-contents-literally doc)
449 (md5 (current-buffer)))))
450 doc-view-cache-directory)))))
452 (defun doc-view-remove-if (predicate list)
453 "Return LIST with all items removed that satisfy PREDICATE."
454 (let (new-list)
455 (dolist (item list (nreverse new-list))
456 (when (not (funcall predicate item))
457 (setq new-list (cons item new-list))))))
459 ;;;; Conversion Functions
461 (defvar doc-view-shrink-factor 1.125)
463 (defun doc-view-enlarge (factor)
464 "Enlarge the document."
465 (interactive (list doc-view-shrink-factor))
466 (set (make-local-variable 'doc-view-resolution)
467 (* factor doc-view-resolution))
468 (doc-view-reconvert-doc))
470 (defun doc-view-shrink (factor)
471 "Shrink the document."
472 (interactive (list doc-view-shrink-factor))
473 (doc-view-enlarge (/ 1.0 factor)))
475 (defun doc-view-reconvert-doc ()
476 "Reconvert the current document.
477 Should be invoked when the cached images aren't up-to-date."
478 (interactive)
479 (doc-view-kill-proc)
480 ;; Clear the old cached files
481 (when (file-exists-p (doc-view-current-cache-dir))
482 (dired-delete-file (doc-view-current-cache-dir) 'always))
483 (doc-view-initiate-display))
485 (defun doc-view-dvi->pdf-sentinel (proc event)
486 "If DVI->PDF conversion was successful, convert the PDF to PNG now."
487 (if (not (string-match "finished" event))
488 (message "DocView: dvi->pdf process changed status to %s." event)
489 (set-buffer (process-get proc 'buffer))
490 (setq doc-view-current-converter-process nil
491 mode-line-process nil)
492 ;; Now go on converting this PDF to a set of PNG files.
493 (let* ((pdf (process-get proc 'pdf-file))
494 (png (expand-file-name "page-%d.png"
495 (doc-view-current-cache-dir))))
496 (doc-view-pdf/ps->png pdf png))))
498 (defun doc-view-dvi->pdf (dvi pdf)
499 "Convert DVI to PDF asynchronously."
500 (setq doc-view-current-converter-process
501 (start-process "dvi->pdf" doc-view-conversion-buffer
502 doc-view-dvipdfm-program
503 "-o" pdf dvi)
504 mode-line-process (list (format ":%s" doc-view-current-converter-process)))
505 (set-process-sentinel doc-view-current-converter-process
506 'doc-view-dvi->pdf-sentinel)
507 (process-put doc-view-current-converter-process 'buffer (current-buffer))
508 (process-put doc-view-current-converter-process 'pdf-file pdf))
510 (defun doc-view-pdf/ps->png-sentinel (proc event)
511 "If PDF/PS->PNG conversion was successful, update the display."
512 (if (not (string-match "finished" event))
513 (message "DocView: converter process changed status to %s." event)
514 (set-buffer (process-get proc 'buffer))
515 (setq doc-view-current-converter-process nil
516 mode-line-process nil)
517 (when doc-view-current-timer
518 (cancel-timer doc-view-current-timer)
519 (setq doc-view-current-timer nil))
520 ;; Yippie, finished. Update the display!
521 (doc-view-display buffer-file-name)))
523 (defun doc-view-pdf/ps->png (pdf-ps png)
524 "Convert PDF-PS to PNG asynchronously."
525 (setq doc-view-current-converter-process
526 (apply 'start-process
527 (append (list "pdf/ps->png" doc-view-conversion-buffer
528 doc-view-ghostscript-program)
529 doc-view-ghostscript-options
530 (list (format "-r%d" (round doc-view-resolution)))
531 (list (concat "-sOutputFile=" png))
532 (list pdf-ps)))
533 mode-line-process (list (format ":%s" doc-view-current-converter-process)))
534 (process-put doc-view-current-converter-process
535 'buffer (current-buffer))
536 (set-process-sentinel doc-view-current-converter-process
537 'doc-view-pdf/ps->png-sentinel)
538 (when doc-view-conversion-refresh-interval
539 (setq doc-view-current-timer
540 (run-at-time "1 secs" doc-view-conversion-refresh-interval
541 'doc-view-display
542 buffer-file-name))))
544 (defun doc-view-pdf->txt-sentinel (proc event)
545 (if (not (string-match "finished" event))
546 (message "DocView: converter process changed status to %s." event)
547 (let ((current-buffer (current-buffer))
548 (proc-buffer (process-get proc 'buffer)))
549 (set-buffer proc-buffer)
550 (setq doc-view-current-converter-process nil
551 mode-line-process nil)
552 ;; If the user looks at the DocView buffer where the conversion was
553 ;; performed, search anew. This time it will be queried for a regexp.
554 (when (eq current-buffer proc-buffer)
555 (doc-view-search nil)))))
557 (defun doc-view-pdf->txt (pdf txt)
558 "Convert PDF to TXT asynchronously."
559 (setq doc-view-current-converter-process
560 (start-process "pdf->txt" doc-view-conversion-buffer
561 doc-view-pdftotext-program "-raw"
562 pdf txt)
563 mode-line-process (list (format ":%s" doc-view-current-converter-process)))
564 (set-process-sentinel doc-view-current-converter-process
565 'doc-view-pdf->txt-sentinel)
566 (process-put doc-view-current-converter-process 'buffer (current-buffer)))
568 (defun doc-view-ps->pdf-sentinel (proc event)
569 (if (not (string-match "finished" event))
570 (message "DocView: converter process changed status to %s." event)
571 (set-buffer (process-get proc 'buffer))
572 (setq doc-view-current-converter-process nil
573 mode-line-process nil)
574 ;; Now we can transform to plain text.
575 (doc-view-pdf->txt (process-get proc 'pdf-file)
576 (expand-file-name "doc.txt"
577 (doc-view-current-cache-dir)))))
579 (defun doc-view-ps->pdf (ps pdf)
580 "Convert PS to PDF asynchronously."
581 (setq doc-view-current-converter-process
582 (start-process "ps->pdf" doc-view-conversion-buffer
583 doc-view-ps2pdf-program
584 ;; Avoid security problems when rendering files from
585 ;; untrusted sources.
586 "-dSAFER"
587 ;; in-file and out-file
588 ps pdf)
589 mode-line-process (list (format ":%s" doc-view-current-converter-process)))
590 (set-process-sentinel doc-view-current-converter-process
591 'doc-view-ps->pdf-sentinel)
592 (process-put doc-view-current-converter-process 'buffer (current-buffer))
593 (process-put doc-view-current-converter-process 'pdf-file pdf))
595 (defun doc-view-convert-current-doc ()
596 "Convert `buffer-file-name' to a set of png files, one file per page.
597 Those files are saved in the directory given by the function
598 `doc-view-current-cache-dir'."
599 ;; Let stale files still display while we recompute the new ones, so only
600 ;; flush the cache when the conversion is over. One of the reasons why it
601 ;; is important to keep displaying the stale page is so that revert-buffer
602 ;; preserves the horizontal/vertical scroll settings (which are otherwise
603 ;; resets during the redisplay).
604 (setq doc-view-pending-cache-flush t)
605 (let ((png-file (expand-file-name "page-%d.png"
606 (doc-view-current-cache-dir))))
607 (make-directory (doc-view-current-cache-dir))
608 (if (not (string= (file-name-extension buffer-file-name) "dvi"))
609 ;; Convert to PNG images.
610 (doc-view-pdf/ps->png buffer-file-name png-file)
611 ;; DVI files have to be converted to PDF before Ghostscript can process
612 ;; it.
613 (doc-view-dvi->pdf buffer-file-name
614 (expand-file-name "doc.pdf"
615 doc-view-current-cache-dir)))))
617 ;;;; Slicing
619 (defun doc-view-set-slice (x y width height)
620 "Set the slice of the images that should be displayed.
621 You can use this function to tell doc-view not to display the
622 margins of the document. It prompts for the top-left corner (X
623 and Y) of the slice to display and its WIDTH and HEIGHT.
625 See `doc-view-set-slice-using-mouse' for a more convenient way to
626 do that. To reset the slice use `doc-view-reset-slice'."
627 (interactive
628 (let* ((size (image-size doc-view-current-image t))
629 (a (read-number (format "Top-left X (0..%d): " (car size))))
630 (b (read-number (format "Top-left Y (0..%d): " (cdr size))))
631 (c (read-number (format "Width (0..%d): " (- (car size) a))))
632 (d (read-number (format "Height (0..%d): " (- (cdr size) b)))))
633 (list a b c d)))
634 (setq doc-view-current-slice (list x y width height))
635 ;; Redisplay
636 (doc-view-goto-page doc-view-current-page))
638 (defun doc-view-set-slice-using-mouse ()
639 "Set the slice of the images that should be displayed.
640 You set the slice by pressing mouse-1 at its top-left corner and
641 dragging it to its bottom-right corner. See also
642 `doc-view-set-slice' and `doc-view-reset-slice'."
643 (interactive)
644 (let (x y w h done)
645 (while (not done)
646 (let ((e (read-event
647 (concat "Press mouse-1 at the top-left corner and "
648 "drag it to the bottom-right corner!"))))
649 (when (eq (car e) 'drag-mouse-1)
650 (setq x (car (posn-object-x-y (event-start e))))
651 (setq y (cdr (posn-object-x-y (event-start e))))
652 (setq w (- (car (posn-object-x-y (event-end e))) x))
653 (setq h (- (cdr (posn-object-x-y (event-end e))) y))
654 (setq done t))))
655 (doc-view-set-slice x y w h)))
657 (defun doc-view-reset-slice ()
658 "Reset the current slice.
659 After calling this function whole pages will be visible again."
660 (interactive)
661 (setq doc-view-current-slice nil)
662 ;; Redisplay
663 (doc-view-goto-page doc-view-current-page))
665 ;;;; Display
667 (defun doc-view-insert-image (file &rest args)
668 "Insert the given png FILE.
669 ARGS is a list of image descriptors."
670 (when doc-view-pending-cache-flush
671 (clear-image-cache)
672 (setq doc-view-pending-cache-flush nil))
673 (let ((image (apply 'create-image file 'png nil args)))
674 (setq doc-view-current-image image)
675 (move-overlay doc-view-current-overlay (point-min) (point-max))
676 (overlay-put doc-view-current-overlay 'display
677 (if doc-view-current-slice
678 (list (cons 'slice doc-view-current-slice) image)
679 image))))
681 (defun doc-view-sort (a b)
682 "Return non-nil if A should be sorted before B.
683 Predicate for sorting `doc-view-current-files'."
684 (or (< (length a) (length b))
685 (and (= (length a) (length b))
686 (string< a b))))
688 (defun doc-view-display (doc)
689 "Start viewing the document DOC."
690 (set-buffer (get-file-buffer doc))
691 (setq doc-view-current-files
692 (sort (directory-files (doc-view-current-cache-dir) t
693 "page-[0-9]+\\.png" t)
694 'doc-view-sort))
695 (when (> (length doc-view-current-files) 0)
696 (doc-view-goto-page doc-view-current-page)))
698 (defun doc-view-buffer-message ()
699 ;; Only show this message initially, not when refreshing the buffer (in which
700 ;; case it's better to keep displaying the "stale" page while computing
701 ;; the fresh new ones).
702 (unless (overlay-get doc-view-current-overlay 'display)
703 (overlay-put doc-view-current-overlay 'display
704 (concat (propertize "Welcome to DocView!" 'face 'bold)
705 "\n"
707 If you see this buffer it means that the document you want to view is being
708 converted to PNG and the conversion of the first page hasn't finished yet or
709 `doc-view-conversion-refresh-interval' is set to nil.
711 For now these keys are useful:
713 `q' : Bury this buffer. Conversion will go on in background.
714 `k' : Kill the conversion process and this buffer.
715 `K' : Kill the conversion process.\n"))))
717 (defun doc-view-show-tooltip ()
718 (interactive)
719 (tooltip-show doc-view-current-info))
721 ;;;;; Toggle between editing and viewing
723 (defun doc-view-toggle-display ()
724 "Toggle between editing a document as text or viewing it."
725 (interactive)
726 (if (eq major-mode 'doc-view-mode)
727 ;; Switch to editing mode
728 (progn
729 (doc-view-kill-proc)
730 (setq buffer-read-only nil)
731 (delete-overlay doc-view-current-overlay)
732 ;; Switch to the previously used major mode or fall back to fundamental
733 ;; mode.
734 (if doc-view-previous-major-mode
735 (funcall doc-view-previous-major-mode)
736 (fundamental-mode))
737 (doc-view-minor-mode 1))
738 ;; Switch to doc-view-mode
739 (when (and (buffer-modified-p)
740 (y-or-n-p "The buffer has been modified. Save the changes? "))
741 (save-buffer))
742 (doc-view-mode)))
744 ;;;; Searching
746 (defun doc-view-search-internal (regexp file)
747 "Return a list of FILE's pages that contain text matching REGEXP.
748 The value is an alist of the form (PAGE CONTEXTS) where PAGE is
749 the pagenumber and CONTEXTS are all lines of text containing a match."
750 (with-temp-buffer
751 (insert-file-contents file)
752 (let ((page 1)
753 (lastpage 1)
754 matches)
755 (while (re-search-forward (concat "\\(?:\\([\f]\\)\\|\\("
756 regexp "\\)\\)") nil t)
757 (when (match-string 1) (incf page))
758 (when (match-string 2)
759 (if (/= page lastpage)
760 (push (cons page
761 (list (buffer-substring
762 (line-beginning-position)
763 (line-end-position))))
764 matches)
765 (setq matches (cons
766 (append
768 ;; This page already is a match.
769 (car matches)
770 ;; This is the first match on page.
771 (list page))
772 (list (buffer-substring
773 (line-beginning-position)
774 (line-end-position))))
775 (cdr matches))))
776 (setq lastpage page)))
777 (nreverse matches))))
779 (defun doc-view-search-no-of-matches (list)
780 "Extract the number of matches from the search result LIST."
781 (let ((no 0))
782 (dolist (p list)
783 (setq no (+ no (1- (length p)))))
784 no))
786 (defun doc-view-search-backward (new-query)
787 "Call `doc-view-search' for backward search.
788 If prefix NEW-QUERY is given, ask for a new regexp."
789 (interactive "P")
790 (doc-view-search new-query t))
792 (defun doc-view-search (new-query &optional backward)
793 "Jump to the next match or initiate a new search if NEW-QUERY is given.
794 If the current document hasn't been transformed to plain text
795 till now do that first.
796 If BACKWARD is non-nil, jump to the previous match."
797 (interactive "P")
798 (if (and (not new-query)
799 doc-view-current-search-matches)
800 (if backward
801 (doc-view-search-previous-match 1)
802 (doc-view-search-next-match 1))
803 ;; New search, so forget the old results.
804 (setq doc-view-current-search-matches nil)
805 (let ((txt (expand-file-name "doc.txt"
806 (doc-view-current-cache-dir))))
807 (if (file-readable-p txt)
808 (progn
809 (setq doc-view-current-search-matches
810 (doc-view-search-internal
811 (read-from-minibuffer "Regexp: ")
812 txt))
813 (message "DocView: search yielded %d matches."
814 (doc-view-search-no-of-matches
815 doc-view-current-search-matches)))
816 ;; We must convert to TXT first!
817 (if doc-view-current-converter-process
818 (message "DocView: please wait till conversion finished.")
819 (let ((ext (file-name-extension buffer-file-name)))
820 (cond
821 ((string= ext "pdf")
822 ;; Doc is a PDF, so convert it to TXT
823 (doc-view-pdf->txt buffer-file-name txt))
824 ((string= ext "ps")
825 ;; Doc is a PS, so convert it to PDF (which will be converted to
826 ;; TXT thereafter).
827 (doc-view-ps->pdf buffer-file-name
828 (expand-file-name "doc.pdf"
829 (doc-view-current-cache-dir))))
830 ((string= ext "dvi")
831 ;; Doc is a DVI. This means that a doc.pdf already exists in its
832 ;; cache subdirectory.
833 (doc-view-pdf->txt (expand-file-name "doc.pdf"
834 (doc-view-current-cache-dir))
835 txt))
836 (t (error "DocView doesn't know what to do")))))))))
838 (defun doc-view-search-next-match (arg)
839 "Go to the ARGth next matching page."
840 (interactive "p")
841 (let* ((next-pages (doc-view-remove-if
842 (lambda (i) (<= (car i) doc-view-current-page))
843 doc-view-current-search-matches))
844 (page (car (nth (1- arg) next-pages))))
845 (if page
846 (doc-view-goto-page page)
847 (when (and
848 doc-view-current-search-matches
849 (y-or-n-p "No more matches after current page. Wrap to first match? "))
850 (doc-view-goto-page (caar doc-view-current-search-matches))))))
852 (defun doc-view-search-previous-match (arg)
853 "Go to the ARGth previous matching page."
854 (interactive "p")
855 (let* ((prev-pages (doc-view-remove-if
856 (lambda (i) (>= (car i) doc-view-current-page))
857 doc-view-current-search-matches))
858 (page (car (nth (1- arg) (nreverse prev-pages)))))
859 (if page
860 (doc-view-goto-page page)
861 (when (and
862 doc-view-current-search-matches
863 (y-or-n-p "No more matches before current page. Wrap to last match? "))
864 (doc-view-goto-page (caar (last doc-view-current-search-matches)))))))
866 ;;;; User interface commands and the mode
868 ;; (put 'doc-view-mode 'mode-class 'special)
870 (defun doc-view-initiate-display ()
871 ;; Switch to image display if possible
872 (if (and (display-images-p)
873 (image-type-available-p 'png))
874 (progn
875 (doc-view-buffer-message)
876 (setq doc-view-current-page (or doc-view-current-page 1))
877 (if (file-exists-p (doc-view-current-cache-dir))
878 (progn
879 (message "DocView: using cached files!")
880 (doc-view-display buffer-file-name))
881 (doc-view-convert-current-doc))
882 (message
883 "%s"
884 (substitute-command-keys
885 (concat "Type \\[doc-view-toggle-display] to toggle between "
886 "editing or viewing the document."))))
887 (message
888 "%s"
889 (substitute-command-keys
890 (concat "No image (png) support available. Type \\[doc-view-toggle-display] "
891 "to switch to an editing mode.")))))
893 ;;;###autoload
894 (defun doc-view-mode ()
895 "Major mode in DocView buffers.
896 You can use \\<doc-view-mode-map>\\[doc-view-toggle-display] to
897 toggle between displaying the document or editing it as text."
898 (interactive)
899 (if jka-compr-really-do-compress
900 ;; This is a compressed file uncompressed by auto-compression-mode.
901 (when (y-or-n-p (concat "DocView: Cannot convert compressed file. "
902 "Save it uncompressed first? "))
903 (let ((file (read-file-name
904 "File: "
905 (file-name-directory buffer-file-name))))
906 (write-region (point-min) (point-max) file)
907 (kill-buffer nil)
908 (find-file file)
909 (doc-view-mode)))
910 (let* ((prev-major-mode (if (eq major-mode 'doc-view-mode)
911 doc-view-previous-major-mode
912 major-mode)))
913 (kill-all-local-variables)
914 (set (make-local-variable 'doc-view-previous-major-mode) prev-major-mode))
915 (make-local-variable 'doc-view-current-files)
916 (make-local-variable 'doc-view-current-image)
917 (make-local-variable 'doc-view-current-page)
918 (make-local-variable 'doc-view-current-converter-process)
919 (make-local-variable 'doc-view-current-timer)
920 (make-local-variable 'doc-view-current-slice)
921 (make-local-variable 'doc-view-current-cache-dir)
922 (make-local-variable 'doc-view-current-info)
923 (make-local-variable 'doc-view-current-search-matches)
924 (set (make-local-variable 'doc-view-current-overlay)
925 (make-overlay (point-min) (point-max) nil t))
926 (add-hook 'change-major-mode-hook
927 (lambda () (delete-overlay doc-view-current-overlay))
928 nil t)
929 (set (make-local-variable 'mode-line-position)
930 '(" P" (:eval (number-to-string doc-view-current-page))
931 "/" (:eval (number-to-string (length doc-view-current-files)))))
932 (set (make-local-variable 'cursor-type) nil)
933 (use-local-map doc-view-mode-map)
934 (set (make-local-variable 'after-revert-hook) 'doc-view-reconvert-doc)
935 (setq mode-name "DocView"
936 buffer-read-only t
937 major-mode 'doc-view-mode)
938 (doc-view-initiate-display)
939 (run-mode-hooks 'doc-view-mode-hook)))
941 ;;;###autoload
942 (define-minor-mode doc-view-minor-mode
943 "Toggle Doc view minor mode.
944 With arg, turn Doc view minor mode on if arg is positive, off otherwise.
945 See the command `doc-view-mode' for more information on this mode."
946 nil " DocView" doc-view-minor-mode-map
947 :group 'doc-view
948 (when doc-view-minor-mode
949 (add-hook 'change-major-mode-hook (lambda () (doc-view-minor-mode -1)) nil t)
950 (message
951 "%s"
952 (substitute-command-keys
953 "Type \\[doc-view-toggle-display] to toggle between editing or viewing the document."))))
955 (defun doc-view-clear-cache ()
956 "Delete the whole cache (`doc-view-cache-directory')."
957 (interactive)
958 (dired-delete-file doc-view-cache-directory 'always)
959 (make-directory doc-view-cache-directory))
961 (defun doc-view-dired-cache ()
962 "Open `dired' in `doc-view-cache-directory'."
963 (interactive)
964 (dired doc-view-cache-directory))
966 (provide 'doc-view)
968 ;; Local Variables:
969 ;; mode: outline-minor
970 ;; End:
972 ;; arch-tag: 5d6e5c5e-095f-489e-b4e4-1ca90a7d79be
973 ;;; doc-view.el ends here