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