]> code.delx.au - gnu-emacs/blob - lisp/doc-view.el
* doc-view.el (doc-view-mode-p): Check for png or imagemagick
[gnu-emacs] / lisp / doc-view.el
1 ;;; doc-view.el --- View PDF/PostScript/DVI files in Emacs
2
3 ;; Copyright (C) 2007, 2008, 2009, 2010 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 of the License, or
14 ;; (at your option) 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. If not, see <http://www.gnu.org/licenses/>.
23
24 ;;; Requirements:
25
26 ;; doc-view.el requires GNU Emacs 22.1 or newer. You also need Ghostscript,
27 ;; `dvipdf' (comes with Ghostscript) or `dvipdfm' (comes with teTeX or TeXLive)
28 ;; and `pdftotext', which comes with xpdf (http://www.foolabs.com/xpdf/) or
29 ;; poppler (http://poppler.freedesktop.org/).
30
31 ;;; Commentary:
32
33 ;; DocView is a document viewer for Emacs. It converts PDF, PS and DVI files
34 ;; to a set of PNG files, one PNG for each page, and displays the PNG images
35 ;; inside an Emacs buffer. This buffer uses `doc-view-mode' which provides
36 ;; convenient key bindings for browsing the document.
37 ;;
38 ;; To use it simply open a document file with
39 ;;
40 ;; C-x C-f ~/path/to/document RET
41 ;;
42 ;; and the document will be converted and displayed, if your emacs supports png
43 ;; images. With `C-c C-c' you can toggle between the rendered images
44 ;; representation and the source text representation of the document.
45 ;;
46 ;; Since conversion may take some time all the PNG images are cached in a
47 ;; subdirectory of `doc-view-cache-directory' and reused when you want to view
48 ;; that file again. To reconvert a document hit `g' (`doc-view-reconvert-doc')
49 ;; when displaying the document. To delete all cached files use
50 ;; `doc-view-clear-cache'. To open the cache with dired, so that you can tidy
51 ;; it out use `doc-view-dired-cache'.
52 ;;
53 ;; When conversion in underway the first page will be displayed as soon as it
54 ;; is available and the available pages are refreshed every
55 ;; `doc-view-conversion-refresh-interval' seconds. If that variable is nil the
56 ;; pages won't be displayed before conversion of the document finished
57 ;; completely.
58 ;;
59 ;; DocView lets you select a slice of the displayed pages. This slice will be
60 ;; remembered and applied to all pages of the current document. This enables
61 ;; you to cut away the margins of a document to save some space. To select a
62 ;; slice you can use `doc-view-set-slice' (bound to `s s') which will query you
63 ;; for the coordinates of the slice's top-left corner and its width and height.
64 ;; A much more convenient way to do the same is offered by the command
65 ;; `doc-view-set-slice-using-mouse' (bound to `s m'). After invocation you
66 ;; only have to press mouse-1 at the top-left corner and drag it to the
67 ;; bottom-right corner of the desired slice. To reset the slice use
68 ;; `doc-view-reset-slice' (bound to `s r').
69 ;;
70 ;; You can also search within the document. The command `doc-view-search'
71 ;; (bound to `C-s') queries for a search regexp and initializes a list of all
72 ;; matching pages and messages how many match-pages were found. After that you
73 ;; can jump to the next page containing a match with an additional `C-s'. With
74 ;; `C-r' you can do the same, but backwards. To search for a new regexp give a
75 ;; prefix arg to one of the search functions, e.g. by typing `C-u C-s'. The
76 ;; searching works by using a plain text representation of the document. If
77 ;; that doesn't already exist the first invocation of `doc-view-search' (or
78 ;; `doc-view-search-backward') starts the conversion. When that finishes and
79 ;; you're still viewing the document (i.e. you didn't switch to another buffer)
80 ;; you're queried for the regexp then.
81 ;;
82 ;; Dired users can simply hit `v' on a document file. If it's a PS, PDF or DVI
83 ;; it will be opened using `doc-view-mode'.
84 ;;
85
86 ;;; Configuration:
87
88 ;; If the images are too small or too big you should set the "-rXXX" option in
89 ;; `doc-view-ghostscript-options' to another value. (The bigger your screen,
90 ;; the higher the value.)
91 ;;
92 ;; This and all other options can be set with the customization interface.
93 ;; Simply do
94 ;;
95 ;; M-x customize-group RET doc-view RET
96 ;;
97 ;; and modify them to your needs.
98
99 ;;; Todo:
100
101 ;; - add print command.
102 ;; - share more code with image-mode.
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 (eval-when-compile (require 'cl))
136 (require 'dired)
137 (require 'image-mode)
138 (require 'jka-compr)
139
140 ;;;; Customization Options
141
142 (defgroup doc-view nil
143 "In-buffer viewer for PDF, PostScript and DVI files."
144 :link '(function-link doc-view)
145 :version "22.2"
146 :group 'applications
147 :group 'data
148 :group 'multimedia
149 :prefix "doc-view-")
150
151 (defcustom doc-view-ghostscript-program (executable-find "gs")
152 "Program to convert PS and PDF files to PNG."
153 :type 'file
154 :group 'doc-view)
155
156 (defcustom doc-view-ghostscript-options
157 '("-dSAFER" ;; Avoid security problems when rendering files from untrusted
158 ;; sources.
159 "-dNOPAUSE" "-sDEVICE=png16m" "-dTextAlphaBits=4"
160 "-dBATCH" "-dGraphicsAlphaBits=4" "-dQUIET")
161 "A list of options to give to ghostscript."
162 :type '(repeat string)
163 :group 'doc-view)
164
165 (defcustom doc-view-resolution 100
166 "Dots per inch resolution used to render the documents.
167 Higher values result in larger images."
168 :type 'number
169 :group 'doc-view)
170
171 (defcustom doc-view-image-width 850
172 "Default image width.
173 Has only an effect if imagemagick support is compiled into emacs."
174 :type 'number
175 :group 'doc-view)
176
177 (defcustom doc-view-dvipdfm-program (executable-find "dvipdfm")
178 "Program to convert DVI files to PDF.
179
180 DVI file will be converted to PDF before the resulting PDF is
181 converted to PNG.
182
183 If this and `doc-view-dvipdf-program' are set,
184 `doc-view-dvipdf-program' will be preferred."
185 :type 'file
186 :group 'doc-view)
187
188 (defcustom doc-view-dvipdf-program (executable-find "dvipdf")
189 "Program to convert DVI files to PDF.
190
191 DVI file will be converted to PDF before the resulting PDF is
192 converted to PNG.
193
194 If this and `doc-view-dvipdfm-program' are set,
195 `doc-view-dvipdf-program' will be preferred."
196 :type 'file
197 :group 'doc-view)
198
199 (defcustom doc-view-unoconv-program (executable-find "unoconv")
200 "Program to convert any file type readable by OpenOffice.org to PDF.
201
202 Needed for viewing OpenOffice.org (and MS Office) files."
203 :type 'file
204 :group 'doc-view)
205
206 (defcustom doc-view-ps2pdf-program (executable-find "ps2pdf")
207 "Program to convert PS files to PDF.
208
209 PS files will be converted to PDF before searching is possible."
210 :type 'file
211 :group 'doc-view)
212
213 (defcustom doc-view-pdftotext-program (executable-find "pdftotext")
214 "Program to convert PDF files to plain text.
215
216 Needed for searching."
217 :type 'file
218 :group 'doc-view)
219
220 (defcustom doc-view-cache-directory
221 (expand-file-name (format "docview%d" (user-uid))
222 temporary-file-directory)
223 "The base directory, where the PNG images will be saved."
224 :type 'directory
225 :group 'doc-view)
226
227 (defvar doc-view-conversion-buffer " *doc-view conversion output*"
228 "The buffer where messages from the converter programs go to.")
229
230 (defcustom doc-view-conversion-refresh-interval 1
231 "Interval in seconds between refreshes of the DocView buffer while converting.
232 After such a refresh newly converted pages will be available for
233 viewing. If set to nil there won't be any refreshes and the
234 pages won't be displayed before conversion of the whole document
235 has finished."
236 :type 'integer
237 :group 'doc-view)
238
239 (defcustom doc-view-continuous nil
240 "In Continuous mode reaching the page edge advances to next/previous page.
241 When non-nil, scrolling a line upward at the bottom edge of the page
242 moves to the next page, and scrolling a line downward at the top edge
243 of the page moves to the previous page."
244 :type 'boolean
245 :group 'doc-view
246 :version "23.2")
247
248 ;;;; Internal Variables
249
250 (defun doc-view-new-window-function (winprops)
251 (let ((ol (image-mode-window-get 'overlay winprops)))
252 (when (and ol (not (overlay-buffer ol)))
253 ;; I've seen `ol' be a dead overlay. I do not yet know how this
254 ;; happened, so maybe the bug is elsewhere, but in the mean time,
255 ;; this seems like a safe approach.
256 (setq ol nil))
257 (if ol
258 (progn
259 (assert (eq (overlay-buffer ol) (current-buffer)))
260 (setq ol (copy-overlay ol)))
261 (assert (not (get-char-property (point-min) 'display)))
262 (setq ol (make-overlay (point-min) (point-max) nil t))
263 (overlay-put ol 'doc-view t))
264 (overlay-put ol 'window (car winprops))
265 (image-mode-window-put 'overlay ol winprops)))
266
267 (defvar doc-view-current-files nil
268 "Only used internally.")
269 (make-variable-buffer-local 'doc-view-current-files)
270
271 (defvar doc-view-current-converter-processes nil
272 "Only used internally.")
273 (make-variable-buffer-local 'doc-view-current-converter-processes)
274
275 (defvar doc-view-current-timer nil
276 "Only used internally.")
277 (make-variable-buffer-local 'doc-view-current-timer)
278
279 (defvar doc-view-current-cache-dir nil
280 "Only used internally.")
281 (make-variable-buffer-local 'doc-view-current-cache-dir)
282
283 (defvar doc-view-current-search-matches nil
284 "Only used internally.")
285 (make-variable-buffer-local 'doc-view-current-search-matches)
286
287 (defvar doc-view-pending-cache-flush nil
288 "Only used internally.")
289
290 (defvar doc-view-previous-major-mode nil
291 "Only used internally.")
292
293 (defvar doc-view-buffer-file-name nil
294 "Only used internally.
295 The file name used for conversion. Normally it's the same as
296 `buffer-file-name', but for remote files, compressed files and
297 files inside an archive it is a temporary copy of
298 the (uncompressed, extracted) file residing in
299 `doc-view-cache-directory'.")
300
301 (defvar doc-view-doc-type nil
302 "The type of document in the current buffer.
303 Can be `dvi', `pdf', or `ps'.")
304
305 ;;;; DocView Keymaps
306
307 (defvar doc-view-mode-map
308 (let ((map (make-sparse-keymap)))
309 (set-keymap-parent map image-mode-map)
310 ;; Navigation in the document
311 (define-key map (kbd "n") 'doc-view-next-page)
312 (define-key map (kbd "p") 'doc-view-previous-page)
313 (define-key map (kbd "<next>") 'forward-page)
314 (define-key map (kbd "<prior>") 'backward-page)
315 (define-key map [remap forward-page] 'doc-view-next-page)
316 (define-key map [remap backward-page] 'doc-view-previous-page)
317 (define-key map (kbd "SPC") 'doc-view-scroll-up-or-next-page)
318 (define-key map (kbd "DEL") 'doc-view-scroll-down-or-previous-page)
319 (define-key map (kbd "C-n") 'doc-view-next-line-or-next-page)
320 (define-key map (kbd "<down>") 'doc-view-next-line-or-next-page)
321 (define-key map (kbd "C-p") 'doc-view-previous-line-or-previous-page)
322 (define-key map (kbd "<up>") 'doc-view-previous-line-or-previous-page)
323 (define-key map (kbd "M-<") 'doc-view-first-page)
324 (define-key map (kbd "M->") 'doc-view-last-page)
325 (define-key map [remap goto-line] 'doc-view-goto-page)
326 (define-key map (kbd "RET") 'image-next-line)
327 ;; Zoom in/out.
328 (define-key map "+" 'doc-view-enlarge)
329 (define-key map "-" 'doc-view-shrink)
330 ;; Killing the buffer (and the process)
331 (define-key map (kbd "k") 'doc-view-kill-proc-and-buffer)
332 (define-key map (kbd "K") 'doc-view-kill-proc)
333 ;; Slicing the image
334 (define-key map (kbd "s s") 'doc-view-set-slice)
335 (define-key map (kbd "s m") 'doc-view-set-slice-using-mouse)
336 (define-key map (kbd "s r") 'doc-view-reset-slice)
337 ;; Searching
338 (define-key map (kbd "C-s") 'doc-view-search)
339 (define-key map (kbd "<find>") 'doc-view-search)
340 (define-key map (kbd "C-r") 'doc-view-search-backward)
341 ;; Show the tooltip
342 (define-key map (kbd "C-t") 'doc-view-show-tooltip)
343 ;; Toggle between text and image display or editing
344 (define-key map (kbd "C-c C-c") 'doc-view-toggle-display)
345 ;; Open a new buffer with doc's text contents
346 (define-key map (kbd "C-c C-t") 'doc-view-open-text)
347 ;; Reconvert the current document. Don't just use revert-buffer
348 ;; because that resets the scale factor, the page number, ...
349 (define-key map (kbd "g") 'doc-view-revert-buffer)
350 (define-key map (kbd "r") 'doc-view-revert-buffer)
351 map)
352 "Keymap used by `doc-view-mode' when displaying a doc as a set of images.")
353
354 (defun doc-view-revert-buffer (&optional ignore-auto noconfirm)
355 "Like `revert-buffer', but preserves the buffer's current modes."
356 ;; FIXME: this should probably be moved to files.el and used for
357 ;; most/all "g" bindings to revert-buffer.
358 (interactive (list (not current-prefix-arg)))
359 (revert-buffer ignore-auto noconfirm 'preserve-modes))
360
361
362 (easy-menu-define doc-view-menu doc-view-mode-map
363 "Menu for Doc View mode."
364 '("DocView"
365 ["Toggle display" doc-view-toggle-display]
366 ("Continuous"
367 ["Off" (setq doc-view-continuous nil)
368 :style radio :selected (eq doc-view-continuous nil)]
369 ["On" (setq doc-view-continuous t)
370 :style radio :selected (eq doc-view-continuous t)]
371 "---"
372 ["Save as Default"
373 (customize-save-variable 'doc-view-continuous doc-view-continuous) t]
374 )
375 "---"
376 ["Set Slice" doc-view-set-slice-using-mouse]
377 ["Set Slice (manual)" doc-view-set-slice]
378 ["Reset Slice" doc-view-reset-slice]
379 "---"
380 ["Search" doc-view-search]
381 ["Search Backwards" doc-view-search-backward]
382 ))
383
384 (defvar doc-view-minor-mode-map
385 (let ((map (make-sparse-keymap)))
386 ;; Toggle between text and image display or editing
387 (define-key map (kbd "C-c C-c") 'doc-view-toggle-display)
388 map)
389 "Keymap used by `doc-minor-view-mode'.")
390
391 ;;;; Navigation Commands
392
393 (defmacro doc-view-current-page (&optional win)
394 `(image-mode-window-get 'page ,win))
395 (defmacro doc-view-current-info () `(image-mode-window-get 'info))
396 (defmacro doc-view-current-overlay () `(image-mode-window-get 'overlay))
397 (defmacro doc-view-current-image () `(image-mode-window-get 'image))
398 (defmacro doc-view-current-slice () `(image-mode-window-get 'slice))
399
400 (defun doc-view-last-page-number ()
401 (length doc-view-current-files))
402
403 (defun doc-view-goto-page (page)
404 "View the page given by PAGE."
405 (interactive "nPage: ")
406 (let ((len (doc-view-last-page-number))
407 (hscroll (window-hscroll)))
408 (if (< page 1)
409 (setq page 1)
410 (when (and (> page len)
411 ;; As long as the converter is running, we don't know
412 ;; how many pages will be available.
413 (null doc-view-current-converter-processes))
414 (setq page len)))
415 (setf (doc-view-current-page) page
416 (doc-view-current-info)
417 (concat
418 (propertize
419 (format "Page %d of %d." page len) 'face 'bold)
420 ;; Tell user if converting isn't finished yet
421 (if doc-view-current-converter-processes
422 " (still converting...)\n"
423 "\n")
424 ;; Display context infos if this page matches the last search
425 (when (and doc-view-current-search-matches
426 (assq page doc-view-current-search-matches))
427 (concat (propertize "Search matches:\n" 'face 'bold)
428 (let ((contexts ""))
429 (dolist (m (cdr (assq page
430 doc-view-current-search-matches)))
431 (setq contexts (concat contexts " - \"" m "\"\n")))
432 contexts)))))
433 ;; Update the buffer
434 ;; We used to find the file name from doc-view-current-files but
435 ;; that's not right if the pages are not generated sequentially
436 ;; or if the page isn't in doc-view-current-files yet.
437 (let ((file (expand-file-name (format "page-%d.png" page)
438 (doc-view-current-cache-dir))))
439 (doc-view-insert-image file :pointer 'arrow)
440 (set-window-hscroll (selected-window) hscroll)
441 (when (and (not (file-exists-p file))
442 doc-view-current-converter-processes)
443 ;; The PNG file hasn't been generated yet.
444 (doc-view-pdf->png-1 doc-view-buffer-file-name file page
445 (lexical-let ((page page)
446 (win (selected-window))
447 (file file))
448 (lambda ()
449 (and (eq (current-buffer) (window-buffer win))
450 ;; If we changed page in the mean
451 ;; time, don't mess things up.
452 (eq (doc-view-current-page win) page)
453 ;; Make sure we don't infloop.
454 (file-readable-p file)
455 (with-selected-window win
456 (doc-view-goto-page page))))))))
457 (overlay-put (doc-view-current-overlay)
458 'help-echo (doc-view-current-info))))
459
460 (defun doc-view-next-page (&optional arg)
461 "Browse ARG pages forward."
462 (interactive "p")
463 (doc-view-goto-page (+ (doc-view-current-page) (or arg 1))))
464
465 (defun doc-view-previous-page (&optional arg)
466 "Browse ARG pages backward."
467 (interactive "p")
468 (doc-view-goto-page (- (doc-view-current-page) (or arg 1))))
469
470 (defun doc-view-first-page ()
471 "View the first page."
472 (interactive)
473 (doc-view-goto-page 1))
474
475 (defun doc-view-last-page ()
476 "View the last page."
477 (interactive)
478 (doc-view-goto-page (doc-view-last-page-number)))
479
480 (defun doc-view-scroll-up-or-next-page (&optional arg)
481 "Scroll page up ARG lines if possible, else goto next page.
482 When `doc-view-continuous' is non-nil, scrolling upward
483 at the bottom edge of the page moves to the next page.
484 Otherwise, goto next page only on typing SPC (ARG is nil)."
485 (interactive "P")
486 (if (or doc-view-continuous (null arg))
487 (let ((hscroll (window-hscroll))
488 (cur-page (doc-view-current-page)))
489 (when (= (window-vscroll) (image-scroll-up arg))
490 (doc-view-next-page)
491 (when (/= cur-page (doc-view-current-page))
492 (image-bob)
493 (image-bol 1))
494 (set-window-hscroll (selected-window) hscroll)))
495 (image-scroll-up arg)))
496
497 (defun doc-view-scroll-down-or-previous-page (&optional arg)
498 "Scroll page down ARG lines if possible, else goto previous page.
499 When `doc-view-continuous' is non-nil, scrolling downward
500 at the top edge of the page moves to the previous page.
501 Otherwise, goto previous page only on typing DEL (ARG is nil)."
502 (interactive "P")
503 (if (or doc-view-continuous (null arg))
504 (let ((hscroll (window-hscroll))
505 (cur-page (doc-view-current-page)))
506 (when (= (window-vscroll) (image-scroll-down arg))
507 (doc-view-previous-page)
508 (when (/= cur-page (doc-view-current-page))
509 (image-eob)
510 (image-bol 1))
511 (set-window-hscroll (selected-window) hscroll)))
512 (image-scroll-down arg)))
513
514 (defun doc-view-next-line-or-next-page (&optional arg)
515 "Scroll upward by ARG lines if possible, else goto next page.
516 When `doc-view-continuous' is non-nil, scrolling a line upward
517 at the bottom edge of the page moves to the next page."
518 (interactive "p")
519 (if doc-view-continuous
520 (let ((hscroll (window-hscroll))
521 (cur-page (doc-view-current-page)))
522 (when (= (window-vscroll) (image-next-line arg))
523 (doc-view-next-page)
524 (when (/= cur-page (doc-view-current-page))
525 (image-bob)
526 (image-bol 1))
527 (set-window-hscroll (selected-window) hscroll)))
528 (image-next-line 1)))
529
530 (defun doc-view-previous-line-or-previous-page (&optional arg)
531 "Scroll downward by ARG lines if possible, else goto previous page.
532 When `doc-view-continuous' is non-nil, scrolling a line downward
533 at the top edge of the page moves to the previous page."
534 (interactive "p")
535 (if doc-view-continuous
536 (let ((hscroll (window-hscroll))
537 (cur-page (doc-view-current-page)))
538 (when (= (window-vscroll) (image-previous-line arg))
539 (doc-view-previous-page)
540 (when (/= cur-page (doc-view-current-page))
541 (image-eob)
542 (image-bol 1))
543 (set-window-hscroll (selected-window) hscroll)))
544 (image-previous-line arg)))
545
546 ;;;; Utility Functions
547
548 (defun doc-view-kill-proc ()
549 "Kill the current converter process(es)."
550 (interactive)
551 (while (consp doc-view-current-converter-processes)
552 (ignore-errors ;; Maybe it's dead already?
553 (kill-process (pop doc-view-current-converter-processes))))
554 (when doc-view-current-timer
555 (cancel-timer doc-view-current-timer)
556 (setq doc-view-current-timer nil))
557 (setq mode-line-process nil))
558
559 (defun doc-view-kill-proc-and-buffer ()
560 "Kill the current converter process and buffer."
561 (interactive)
562 (doc-view-kill-proc)
563 (when (eq major-mode 'doc-view-mode)
564 (kill-buffer (current-buffer))))
565
566 (defun doc-view-make-safe-dir (dir)
567 (condition-case nil
568 (let ((umask (default-file-modes)))
569 (unwind-protect
570 (progn
571 ;; Create temp files with strict access rights. It's easy to
572 ;; loosen them later, whereas it's impossible to close the
573 ;; time-window of loose permissions otherwise.
574 (set-default-file-modes #o0700)
575 (make-directory dir))
576 ;; Reset the umask.
577 (set-default-file-modes umask)))
578 (file-already-exists
579 (if (file-symlink-p dir)
580 (error "Danger: %s points to a symbolic link" dir))
581 ;; In case it was created earlier with looser rights.
582 ;; We could check the mode info returned by file-attributes, but it's
583 ;; a pain to parse and it may not tell you what we want under
584 ;; non-standard file-systems. So let's just say what we want and let
585 ;; the underlying C code and file-system figure it out.
586 ;; This also ends up checking a bunch of useful conditions: it makes
587 ;; sure we have write-access to the directory and that we own it, thus
588 ;; closing a bunch of security holes.
589 (set-file-modes dir #o0700))))
590
591 (defun doc-view-current-cache-dir ()
592 "Return the directory where the png files of the current doc should be saved.
593 It's a subdirectory of `doc-view-cache-directory'."
594 (if doc-view-current-cache-dir
595 doc-view-current-cache-dir
596 ;; Try and make sure doc-view-cache-directory exists and is safe.
597 (doc-view-make-safe-dir doc-view-cache-directory)
598 ;; Now compute the subdirectory to use.
599 (setq doc-view-current-cache-dir
600 (file-name-as-directory
601 (expand-file-name
602 (concat (file-name-nondirectory doc-view-buffer-file-name)
603 "-"
604 (let ((file doc-view-buffer-file-name))
605 (with-temp-buffer
606 (set-buffer-multibyte nil)
607 (insert-file-contents-literally file)
608 (md5 (current-buffer)))))
609 doc-view-cache-directory)))))
610
611 (defun doc-view-remove-if (predicate list)
612 "Return LIST with all items removed that satisfy PREDICATE."
613 (let (new-list)
614 (dolist (item list (nreverse new-list))
615 (when (not (funcall predicate item))
616 (setq new-list (cons item new-list))))))
617
618 ;;;###autoload
619 (defun doc-view-mode-p (type)
620 "Return non-nil if document type TYPE is available for `doc-view'.
621 Document types are symbols like `dvi', `ps', `pdf', or `odf' (any
622 OpenDocument format)."
623 (and (display-graphic-p)
624 (or (image-type-available-p 'imagemagick)
625 (image-type-available-p 'png))
626 (cond
627 ((eq type 'dvi)
628 (and (doc-view-mode-p 'pdf)
629 (or (and doc-view-dvipdf-program
630 (executable-find doc-view-dvipdf-program))
631 (and doc-view-dvipdfm-program
632 (executable-find doc-view-dvipdfm-program)))))
633 ((or (eq type 'postscript) (eq type 'ps) (eq type 'eps)
634 (eq type 'pdf))
635 (and doc-view-ghostscript-program
636 (executable-find doc-view-ghostscript-program)))
637 ((eq type 'odf)
638 (and doc-view-unoconv-program
639 (executable-find doc-view-unoconv-program)
640 (doc-view-mode-p 'pdf)))
641 (t ;; unknown image type
642 nil))))
643
644 ;;;; Conversion Functions
645
646 (defvar doc-view-shrink-factor 1.125)
647
648 (defun doc-view-enlarge (factor)
649 "Enlarge the document."
650 (interactive (list doc-view-shrink-factor))
651 (if (eq (plist-get (cdr (doc-view-current-image)) :type)
652 'imagemagick)
653 ;; ImageMagick supports on-the-fly-rescaling
654 (progn
655 (set (make-local-variable 'doc-view-image-width)
656 (ceiling (* factor doc-view-image-width)))
657 (doc-view-insert-image (plist-get (cdr (doc-view-current-image)) :file)
658 :width doc-view-image-width))
659 (set (make-local-variable 'doc-view-resolution)
660 (ceiling (* factor doc-view-resolution)))
661 (doc-view-reconvert-doc)))
662
663 (defun doc-view-shrink (factor)
664 "Shrink the document."
665 (interactive (list doc-view-shrink-factor))
666 (doc-view-enlarge (/ 1.0 factor)))
667
668 (defun doc-view-reconvert-doc ()
669 "Reconvert the current document.
670 Should be invoked when the cached images aren't up-to-date."
671 (interactive)
672 (doc-view-kill-proc)
673 ;; Clear the old cached files
674 (when (file-exists-p (doc-view-current-cache-dir))
675 (delete-directory (doc-view-current-cache-dir) 'recursive))
676 (doc-view-initiate-display))
677
678 (defun doc-view-sentinel (proc event)
679 "Generic sentinel for doc-view conversion processes."
680 (if (not (string-match "finished" event))
681 (message "DocView: process %s changed status to %s."
682 (process-name proc)
683 (if (string-match "\\(.+\\)\n?\\'" event)
684 (match-string 1 event)
685 event))
686 (when (buffer-live-p (process-get proc 'buffer))
687 (with-current-buffer (process-get proc 'buffer)
688 (setq doc-view-current-converter-processes
689 (delq proc doc-view-current-converter-processes))
690 (setq mode-line-process
691 (if doc-view-current-converter-processes
692 (format ":%s" (car doc-view-current-converter-processes))))
693 (funcall (process-get proc 'callback))))))
694
695 (defun doc-view-start-process (name program args callback)
696 ;; Make sure the process is started in an existing directory, (rather than
697 ;; some file-name-handler-managed dir, for example).
698 (let* ((default-directory (if (file-readable-p default-directory)
699 default-directory
700 (expand-file-name "~/")))
701 (proc (apply 'start-process name doc-view-conversion-buffer
702 program args)))
703 (push proc doc-view-current-converter-processes)
704 (setq mode-line-process (list (format ":%s" proc)))
705 (set-process-sentinel proc 'doc-view-sentinel)
706 (process-put proc 'buffer (current-buffer))
707 (process-put proc 'callback callback)))
708
709 (defun doc-view-dvi->pdf (dvi pdf callback)
710 "Convert DVI to PDF asynchronously and call CALLBACK when finished."
711 ;; Prefer dvipdf over dvipdfm, because the latter has problems if the DVI
712 ;; references and includes other PS files.
713 (if (and doc-view-dvipdf-program
714 (executable-find doc-view-dvipdf-program))
715 (doc-view-start-process "dvi->pdf" doc-view-dvipdf-program
716 (list dvi pdf)
717 callback)
718 (doc-view-start-process "dvi->pdf" doc-view-dvipdfm-program
719 (list "-o" pdf dvi)
720 callback)))
721
722 (defun doc-view-odf->pdf (odf callback)
723 "Convert ODF to PDF asynchronously and call CALLBACK when finished.
724 The converted PDF is put into the current cache directory, and it
725 is named like ODF with the extension turned to pdf."
726 (doc-view-start-process "odf->pdf" doc-view-unoconv-program
727 (list "-f" "pdf" "-o" (doc-view-current-cache-dir) odf)
728 callback))
729
730 (defun doc-view-pdf/ps->png (pdf-ps png)
731 "Convert PDF-PS to PNG asynchronously."
732 (doc-view-start-process
733 "pdf/ps->png" doc-view-ghostscript-program
734 (append doc-view-ghostscript-options
735 (list (format "-r%d" (round doc-view-resolution))
736 (concat "-sOutputFile=" png)
737 pdf-ps))
738 (lexical-let ((resolution doc-view-resolution))
739 (lambda ()
740 ;; Only create the resolution file when it's all done, so it also
741 ;; serves as a witness that the conversion is complete.
742 (write-region (prin1-to-string resolution) nil
743 (expand-file-name "resolution.el"
744 (doc-view-current-cache-dir))
745 nil 'silently)
746 (when doc-view-current-timer
747 (cancel-timer doc-view-current-timer)
748 (setq doc-view-current-timer nil))
749 (doc-view-display (current-buffer) 'force))))
750 ;; Update the displayed pages as soon as they're done generating.
751 (when doc-view-conversion-refresh-interval
752 (setq doc-view-current-timer
753 (run-at-time "1 secs" doc-view-conversion-refresh-interval
754 'doc-view-display
755 (current-buffer)))))
756
757 (defun doc-view-pdf->png-1 (pdf png page callback)
758 "Convert a PAGE of a PDF file to PNG asynchronously.
759 Call CALLBACK with no arguments when done."
760 (doc-view-start-process
761 "pdf->png-1" doc-view-ghostscript-program
762 (append doc-view-ghostscript-options
763 (list (format "-r%d" (round doc-view-resolution))
764 ;; Sadly, `gs' only supports the page-range
765 ;; for PDF files.
766 (format "-dFirstPage=%d" page)
767 (format "-dLastPage=%d" page)
768 (concat "-sOutputFile=" png)
769 pdf))
770 callback))
771
772 (declare-function clear-image-cache "image.c" (&optional filter))
773
774 (defun doc-view-pdf->png (pdf png pages)
775 "Convert a PDF file to PNG asynchronously.
776 Start by converting PAGES, and then the rest."
777 (if (null pages)
778 (doc-view-pdf/ps->png pdf png)
779 ;; We could render several `pages' with a single process if they're
780 ;; (almost) consecutive, but since in 99% of the cases, there'll be only
781 ;; a single page anyway, and of the remaining 1%, few cases will have
782 ;; consecutive pages, it's not worth the trouble.
783 (lexical-let ((pdf pdf) (png png) (rest (cdr pages)))
784 (doc-view-pdf->png-1
785 pdf (format png (car pages)) (car pages)
786 (lambda ()
787 (if rest
788 (doc-view-pdf->png pdf png rest)
789 ;; Yippie, the important pages are done, update the display.
790 (clear-image-cache)
791 ;; For the windows that have a message (like "Welcome to
792 ;; DocView") display property, clearing the image cache is
793 ;; not sufficient.
794 (dolist (win (get-buffer-window-list (current-buffer) nil 'visible))
795 (with-selected-window win
796 (when (stringp (get-char-property (point-min) 'display))
797 (doc-view-goto-page (doc-view-current-page)))))
798 ;; Convert the rest of the pages.
799 (doc-view-pdf/ps->png pdf png)))))))
800
801 (defun doc-view-pdf->txt (pdf txt callback)
802 "Convert PDF to TXT asynchronously and call CALLBACK when finished."
803 (or doc-view-pdftotext-program
804 (error "You need the `pdftotext' program to convert a PDF to text"))
805 (doc-view-start-process "pdf->txt" doc-view-pdftotext-program
806 (list "-raw" pdf txt)
807 callback))
808
809 (defun doc-view-doc->txt (txt callback)
810 "Convert the current document to text and call CALLBACK when done."
811 (make-directory (doc-view-current-cache-dir) t)
812 (case doc-view-doc-type
813 (pdf
814 ;; Doc is a PDF, so convert it to TXT
815 (doc-view-pdf->txt doc-view-buffer-file-name txt callback))
816 (ps
817 ;; Doc is a PS, so convert it to PDF (which will be converted to
818 ;; TXT thereafter).
819 (lexical-let ((pdf (expand-file-name "doc.pdf"
820 (doc-view-current-cache-dir)))
821 (txt txt)
822 (callback callback))
823 (doc-view-ps->pdf doc-view-buffer-file-name pdf
824 (lambda () (doc-view-pdf->txt pdf txt callback)))))
825 (dvi
826 ;; Doc is a DVI. This means that a doc.pdf already exists in its
827 ;; cache subdirectory.
828 (doc-view-pdf->txt (expand-file-name "doc.pdf"
829 (doc-view-current-cache-dir))
830 txt callback))
831 (odf
832 ;; Doc is some ODF (or MS Office) doc. This means that a doc.pdf
833 ;; already exists in its cache subdirectory.
834 (doc-view-pdf->txt (expand-file-name "doc.pdf"
835 (doc-view-current-cache-dir))
836 txt callback))
837 (t (error "DocView doesn't know what to do"))))
838
839 (defun doc-view-ps->pdf (ps pdf callback)
840 "Convert PS to PDF asynchronously and call CALLBACK when finished."
841 (or doc-view-ps2pdf-program
842 (error "You need the `ps2pdf' program to convert PS to PDF"))
843 (doc-view-start-process "ps->pdf" doc-view-ps2pdf-program
844 (list
845 ;; Avoid security problems when rendering files from
846 ;; untrusted sources.
847 "-dSAFER"
848 ;; in-file and out-file
849 ps pdf)
850 callback))
851
852 (defun doc-view-active-pages ()
853 (let ((pages ()))
854 (dolist (win (get-buffer-window-list (current-buffer) nil 'visible))
855 (let ((page (image-mode-window-get 'page win)))
856 (unless (memq page pages) (push page pages))))
857 pages))
858
859 (defun doc-view-convert-current-doc ()
860 "Convert `doc-view-buffer-file-name' to a set of png files, one file per page.
861 Those files are saved in the directory given by the function
862 `doc-view-current-cache-dir'."
863 ;; Let stale files still display while we recompute the new ones, so only
864 ;; flush the cache when the conversion is over. One of the reasons why it
865 ;; is important to keep displaying the stale page is so that revert-buffer
866 ;; preserves the horizontal/vertical scroll settings (which are otherwise
867 ;; resets during the redisplay).
868 (setq doc-view-pending-cache-flush t)
869 (let ((png-file (expand-file-name "page-%d.png"
870 (doc-view-current-cache-dir))))
871 (make-directory (doc-view-current-cache-dir) t)
872 (case doc-view-doc-type
873 (dvi
874 ;; DVI files have to be converted to PDF before Ghostscript can process
875 ;; it.
876 (lexical-let
877 ((pdf (expand-file-name "doc.pdf" doc-view-current-cache-dir))
878 (png-file png-file))
879 (doc-view-dvi->pdf doc-view-buffer-file-name pdf
880 (lambda () (doc-view-pdf/ps->png pdf png-file)))))
881 (odf
882 ;; ODF files have to be converted to PDF before Ghostscript can
883 ;; process it.
884 (lexical-let
885 ((pdf (expand-file-name "doc.pdf" doc-view-current-cache-dir))
886 (opdf (expand-file-name (concat (file-name-sans-extension
887 (file-name-nondirectory doc-view-buffer-file-name))
888 ".pdf")
889 doc-view-current-cache-dir))
890 (png-file png-file))
891 ;; The unoconv tool only supports a output directory, but no
892 ;; file name. It's named like the input file with the
893 ;; extension replaced by pdf.
894 (doc-view-odf->pdf doc-view-buffer-file-name
895 (lambda ()
896 ;; Rename to doc.pdf
897 (rename-file opdf pdf)
898 (doc-view-pdf/ps->png pdf png-file)))))
899 (pdf
900 (let ((pages (doc-view-active-pages)))
901 ;; Convert PDF to PNG images starting with the active pages.
902 (doc-view-pdf->png doc-view-buffer-file-name png-file pages)))
903 (t
904 ;; Convert to PNG images.
905 (doc-view-pdf/ps->png doc-view-buffer-file-name png-file)))))
906
907 ;;;; Slicing
908
909 (declare-function image-size "image.c" (spec &optional pixels frame))
910
911 (defun doc-view-set-slice (x y width height)
912 "Set the slice of the images that should be displayed.
913 You can use this function to tell doc-view not to display the
914 margins of the document. It prompts for the top-left corner (X
915 and Y) of the slice to display and its WIDTH and HEIGHT.
916
917 See `doc-view-set-slice-using-mouse' for a more convenient way to
918 do that. To reset the slice use `doc-view-reset-slice'."
919 (interactive
920 (let* ((size (image-size (doc-view-current-image) t))
921 (a (read-number (format "Top-left X (0..%d): " (car size))))
922 (b (read-number (format "Top-left Y (0..%d): " (cdr size))))
923 (c (read-number (format "Width (0..%d): " (- (car size) a))))
924 (d (read-number (format "Height (0..%d): " (- (cdr size) b)))))
925 (list a b c d)))
926 (setf (doc-view-current-slice) (list x y width height))
927 ;; Redisplay
928 (doc-view-goto-page (doc-view-current-page)))
929
930 (defun doc-view-set-slice-using-mouse ()
931 "Set the slice of the images that should be displayed.
932 You set the slice by pressing mouse-1 at its top-left corner and
933 dragging it to its bottom-right corner. See also
934 `doc-view-set-slice' and `doc-view-reset-slice'."
935 (interactive)
936 (let (x y w h done)
937 (while (not done)
938 (let ((e (read-event
939 (concat "Press mouse-1 at the top-left corner and "
940 "drag it to the bottom-right corner!"))))
941 (when (eq (car e) 'drag-mouse-1)
942 (setq x (car (posn-object-x-y (event-start e))))
943 (setq y (cdr (posn-object-x-y (event-start e))))
944 (setq w (- (car (posn-object-x-y (event-end e))) x))
945 (setq h (- (cdr (posn-object-x-y (event-end e))) y))
946 (setq done t))))
947 (doc-view-set-slice x y w h)))
948
949 (defun doc-view-reset-slice ()
950 "Reset the current slice.
951 After calling this function whole pages will be visible again."
952 (interactive)
953 (setf (doc-view-current-slice) nil)
954 ;; Redisplay
955 (doc-view-goto-page (doc-view-current-page)))
956
957 ;;;; Display
958
959 (defun doc-view-insert-image (file &rest args)
960 "Insert the given png FILE.
961 ARGS is a list of image descriptors."
962 (when doc-view-pending-cache-flush
963 (clear-image-cache)
964 (setq doc-view-pending-cache-flush nil))
965 (let ((ol (doc-view-current-overlay))
966 (image (if (and file (file-readable-p file))
967 (if (not (fboundp 'imagemagick-types))
968 (apply 'create-image file 'png nil args)
969 (unless (member :width args)
970 (setq args (append args (list :width doc-view-image-width))))
971 (apply 'create-image file 'imagemagick nil args))))
972 (slice (doc-view-current-slice)))
973 (setf (doc-view-current-image) image)
974 (move-overlay ol (point-min) (point-max))
975 (overlay-put ol 'display
976 (cond
977 (image
978 (if slice
979 (list (cons 'slice slice) image)
980 image))
981 ;; We're trying to display a page that doesn't exist.
982 (doc-view-current-converter-processes
983 ;; Maybe the page doesn't exist *yet*.
984 "Cannot display this page (yet)!")
985 (t
986 ;; Typically happens if the conversion process somehow
987 ;; failed. Better not signal an error here because it
988 ;; could prevent a subsequent reconversion from fixing
989 ;; the problem.
990 (concat "Cannot display this page!\n"
991 "Maybe because of a conversion failure!"))))
992 (let ((win (overlay-get ol 'window)))
993 (if (stringp (overlay-get ol 'display))
994 (progn ;Make sure the text is not scrolled out of view.
995 (set-window-hscroll win 0)
996 (set-window-vscroll win 0))
997 (let ((hscroll (image-mode-window-get 'hscroll win))
998 (vscroll (image-mode-window-get 'vscroll win)))
999 ;; Reset scroll settings, in case they were changed.
1000 (if hscroll (set-window-hscroll win hscroll))
1001 (if vscroll (set-window-vscroll win vscroll)))))))
1002
1003 (defun doc-view-sort (a b)
1004 "Return non-nil if A should be sorted before B.
1005 Predicate for sorting `doc-view-current-files'."
1006 (or (< (length a) (length b))
1007 (and (= (length a) (length b))
1008 (string< a b))))
1009
1010 (defun doc-view-display (buffer &optional force)
1011 "Start viewing the document in BUFFER.
1012 If FORCE is non-nil, start viewing even if the document does not
1013 have the page we want to view."
1014 (with-current-buffer buffer
1015 (let ((prev-pages doc-view-current-files))
1016 (setq doc-view-current-files
1017 (sort (directory-files (doc-view-current-cache-dir) t
1018 "page-[0-9]+\\.png" t)
1019 'doc-view-sort))
1020 (dolist (win (or (get-buffer-window-list buffer nil t)
1021 (list (selected-window))))
1022 (let* ((page (doc-view-current-page win))
1023 (pagefile (expand-file-name (format "page-%d.png" page)
1024 (doc-view-current-cache-dir))))
1025 (when (or force
1026 (and (not (member pagefile prev-pages))
1027 (member pagefile doc-view-current-files)))
1028 (with-selected-window win
1029 (assert (eq (current-buffer) buffer))
1030 (doc-view-goto-page page))))))))
1031
1032 (defun doc-view-buffer-message ()
1033 ;; Only show this message initially, not when refreshing the buffer (in which
1034 ;; case it's better to keep displaying the "stale" page while computing
1035 ;; the fresh new ones).
1036 (unless (overlay-get (doc-view-current-overlay) 'display)
1037 (overlay-put (doc-view-current-overlay) 'display
1038 (concat (propertize "Welcome to DocView!" 'face 'bold)
1039 "\n"
1040 "
1041 If you see this buffer it means that the document you want to view is being
1042 converted to PNG and the conversion of the first page hasn't finished yet or
1043 `doc-view-conversion-refresh-interval' is set to nil.
1044
1045 For now these keys are useful:
1046
1047 `q' : Bury this buffer. Conversion will go on in background.
1048 `k' : Kill the conversion process and this buffer.
1049 `K' : Kill the conversion process.\n"))))
1050
1051 (declare-function tooltip-show "tooltip" (text &optional use-echo-area))
1052
1053 (defun doc-view-show-tooltip ()
1054 (interactive)
1055 (tooltip-show (doc-view-current-info)))
1056
1057 (defun doc-view-open-text ()
1058 "Open a buffer with the current doc's contents as text."
1059 (interactive)
1060 (if doc-view-current-converter-processes
1061 (message "DocView: please wait till conversion finished.")
1062 (let ((txt (expand-file-name "doc.txt" (doc-view-current-cache-dir))))
1063 (if (file-readable-p txt)
1064 (find-file txt)
1065 (doc-view-doc->txt txt 'doc-view-open-text)))))
1066
1067 ;;;;; Toggle between editing and viewing
1068
1069 (defun doc-view-toggle-display ()
1070 "Toggle between editing a document as text or viewing it."
1071 (interactive)
1072 (if (eq major-mode 'doc-view-mode)
1073 ;; Switch to editing mode
1074 (progn
1075 (doc-view-kill-proc)
1076 (setq buffer-read-only nil)
1077 (remove-overlays (point-min) (point-max) 'doc-view t)
1078 (set (make-local-variable 'image-mode-winprops-alist) t)
1079 ;; Switch to the previously used major mode or fall back to
1080 ;; normal mode.
1081 (doc-view-fallback-mode)
1082 (doc-view-minor-mode 1))
1083 ;; Switch to doc-view-mode
1084 (when (and (buffer-modified-p)
1085 (y-or-n-p "The buffer has been modified. Save the changes? "))
1086 (save-buffer))
1087 (doc-view-mode)))
1088
1089 ;;;; Searching
1090
1091
1092 (defun doc-view-search-internal (regexp file)
1093 "Return a list of FILE's pages that contain text matching REGEXP.
1094 The value is an alist of the form (PAGE CONTEXTS) where PAGE is
1095 the pagenumber and CONTEXTS are all lines of text containing a match."
1096 (with-temp-buffer
1097 (insert-file-contents file)
1098 (let ((page 1)
1099 (lastpage 1)
1100 matches)
1101 (while (re-search-forward (concat "\\(?:\\([\f]\\)\\|\\("
1102 regexp "\\)\\)") nil t)
1103 (when (match-string 1) (setq page (1+ page)))
1104 (when (match-string 2)
1105 (if (/= page lastpage)
1106 (push (cons page
1107 (list (buffer-substring
1108 (line-beginning-position)
1109 (line-end-position))))
1110 matches)
1111 (setq matches (cons
1112 (append
1113 (or
1114 ;; This page already is a match.
1115 (car matches)
1116 ;; This is the first match on page.
1117 (list page))
1118 (list (buffer-substring
1119 (line-beginning-position)
1120 (line-end-position))))
1121 (cdr matches))))
1122 (setq lastpage page)))
1123 (nreverse matches))))
1124
1125 (defun doc-view-search-no-of-matches (list)
1126 "Extract the number of matches from the search result LIST."
1127 (let ((no 0))
1128 (dolist (p list)
1129 (setq no (+ no (1- (length p)))))
1130 no))
1131
1132 (defun doc-view-search-backward (new-query)
1133 "Call `doc-view-search' for backward search.
1134 If prefix NEW-QUERY is given, ask for a new regexp."
1135 (interactive "P")
1136 (doc-view-search new-query t))
1137
1138 (defun doc-view-search (new-query &optional backward)
1139 "Jump to the next match or initiate a new search if NEW-QUERY is given.
1140 If the current document hasn't been transformed to plain text
1141 till now do that first.
1142 If BACKWARD is non-nil, jump to the previous match."
1143 (interactive "P")
1144 (if (and (not new-query)
1145 doc-view-current-search-matches)
1146 (if backward
1147 (doc-view-search-previous-match 1)
1148 (doc-view-search-next-match 1))
1149 ;; New search, so forget the old results.
1150 (setq doc-view-current-search-matches nil)
1151 (let ((txt (expand-file-name "doc.txt"
1152 (doc-view-current-cache-dir))))
1153 (if (file-readable-p txt)
1154 (progn
1155 (setq doc-view-current-search-matches
1156 (doc-view-search-internal
1157 (read-from-minibuffer "Regexp: ")
1158 txt))
1159 (message "DocView: search yielded %d matches."
1160 (doc-view-search-no-of-matches
1161 doc-view-current-search-matches)))
1162 ;; We must convert to TXT first!
1163 (if doc-view-current-converter-processes
1164 (message "DocView: please wait till conversion finished.")
1165 (doc-view-doc->txt txt (lambda () (doc-view-search nil))))))))
1166
1167 (defun doc-view-search-next-match (arg)
1168 "Go to the ARGth next matching page."
1169 (interactive "p")
1170 (let* ((next-pages (doc-view-remove-if
1171 (lambda (i) (<= (car i) (doc-view-current-page)))
1172 doc-view-current-search-matches))
1173 (page (car (nth (1- arg) next-pages))))
1174 (if page
1175 (doc-view-goto-page page)
1176 (when (and
1177 doc-view-current-search-matches
1178 (y-or-n-p "No more matches after current page. Wrap to first match? "))
1179 (doc-view-goto-page (caar doc-view-current-search-matches))))))
1180
1181 (defun doc-view-search-previous-match (arg)
1182 "Go to the ARGth previous matching page."
1183 (interactive "p")
1184 (let* ((prev-pages (doc-view-remove-if
1185 (lambda (i) (>= (car i) (doc-view-current-page)))
1186 doc-view-current-search-matches))
1187 (page (car (nth (1- arg) (nreverse prev-pages)))))
1188 (if page
1189 (doc-view-goto-page page)
1190 (when (and
1191 doc-view-current-search-matches
1192 (y-or-n-p "No more matches before current page. Wrap to last match? "))
1193 (doc-view-goto-page (caar (last doc-view-current-search-matches)))))))
1194
1195 ;;;; User interface commands and the mode
1196
1197 (put 'doc-view-mode 'mode-class 'special)
1198
1199 (defun doc-view-already-converted-p ()
1200 "Return non-nil if the current doc was already converted."
1201 (and (file-exists-p (doc-view-current-cache-dir))
1202 ;; Check that the resolution info is there, otherwise it means
1203 ;; the conversion is incomplete.
1204 (file-readable-p (expand-file-name "resolution.el"
1205 (doc-view-current-cache-dir)))
1206 (> (length (directory-files (doc-view-current-cache-dir)
1207 nil "\\.png\\'"))
1208 0)))
1209
1210 (defun doc-view-initiate-display ()
1211 ;; Switch to image display if possible
1212 (if (doc-view-mode-p doc-view-doc-type)
1213 (progn
1214 (doc-view-buffer-message)
1215 (setf (doc-view-current-page) (or (doc-view-current-page) 1))
1216 (if (doc-view-already-converted-p)
1217 (progn
1218 (message "DocView: using cached files!")
1219 ;; Load the saved resolution
1220 (let* ((res-file (expand-file-name "resolution.el"
1221 (doc-view-current-cache-dir)))
1222 (res
1223 (with-temp-buffer
1224 (when (file-readable-p res-file)
1225 (insert-file-contents res-file)
1226 (read (current-buffer))))))
1227 (when (numberp res)
1228 (set (make-local-variable 'doc-view-resolution) res)))
1229 (doc-view-display (current-buffer) 'force))
1230 (doc-view-convert-current-doc))
1231 (message
1232 "%s"
1233 (substitute-command-keys
1234 (concat "Type \\[doc-view-toggle-display] to toggle between "
1235 "editing or viewing the document."))))
1236 (message
1237 "%s"
1238 (concat "No PNG support is available, or some conversion utility for "
1239 (file-name-extension doc-view-buffer-file-name)
1240 " files is missing."))
1241 (if (and (executable-find doc-view-pdftotext-program)
1242 (y-or-n-p
1243 "Unable to render file. View extracted text instead? "))
1244 (doc-view-open-text)
1245 (doc-view-toggle-display))))
1246
1247 (defvar bookmark-make-record-function)
1248
1249 (defun doc-view-clone-buffer-hook ()
1250 ;; FIXME: There are several potential problems linked with reconversion
1251 ;; and auto-revert when we have indirect buffers because they share their
1252 ;; /tmp cache directory. This sharing is good (you'd rather not reconvert
1253 ;; for each clone), but that means that clones need to collaborate a bit.
1254 ;; I guess it mostly means: detect when a reconversion process is already
1255 ;; running, and run the sentinel in all clones.
1256 ;;
1257 ;; Maybe the clones should really have a separate /tmp directory
1258 ;; so they could have a different resolution and you could use clones
1259 ;; for zooming.
1260 (remove-overlays (point-min) (point-max) 'doc-view t)
1261 (if (consp image-mode-winprops-alist) (setq image-mode-winprops-alist nil)))
1262
1263 (defun doc-view-intersection (l1 l2)
1264 (let ((l ()))
1265 (dolist (x l1) (if (memq x l2) (push x l)))
1266 l))
1267
1268 (defun doc-view-set-doc-type ()
1269 "Figure out the current document type (`doc-view-doc-type')."
1270 (let ((name-types
1271 (when buffer-file-name
1272 (cdr (assoc (file-name-extension buffer-file-name)
1273 '(
1274 ;; DVI
1275 ("dvi" dvi)
1276 ;; PDF
1277 ("pdf" pdf) ("epdf" pdf)
1278 ;; PostScript
1279 ("ps" ps) ("eps" ps)
1280 ;; OpenDocument formats
1281 ("odt" odf) ("ods" odf) ("odp" odf) ("odg" odf)
1282 ("odc" odf) ("odi" odf) ("odm" odf) ("ott" odf)
1283 ("ots" odf) ("otp" odf) ("otg" odf)
1284 ;; Microsoft Office formats (also handled
1285 ;; by the odf conversion chain)
1286 ("doc" odf) ("docx" odf) ("xls" odf) ("xlsx" odf)
1287 ("ppt" odf) ("pptx" odf))))))
1288 (content-types
1289 (save-excursion
1290 (goto-char (point-min))
1291 (cond
1292 ((looking-at "%!") '(ps))
1293 ((looking-at "%PDF") '(pdf))
1294 ((looking-at "\367\002") '(dvi))))))
1295 (set (make-local-variable 'doc-view-doc-type)
1296 (car (or (doc-view-intersection name-types content-types)
1297 (when (and name-types content-types)
1298 (error "Conflicting types: name says %s but content says %s"
1299 name-types content-types))
1300 name-types content-types
1301 (error "Cannot determine the document type"))))))
1302
1303 ;;;###autoload
1304 (defun doc-view-mode ()
1305 "Major mode in DocView buffers.
1306
1307 DocView Mode is an Emacs document viewer. It displays PDF, PS
1308 and DVI files (as PNG images) in Emacs buffers.
1309
1310 You can use \\<doc-view-mode-map>\\[doc-view-toggle-display] to
1311 toggle between displaying the document or editing it as text.
1312 \\{doc-view-mode-map}"
1313 (interactive)
1314
1315 (if (= (point-min) (point-max))
1316 ;; The doc is empty or doesn't exist at all, so fallback to
1317 ;; another mode. We used to also check file-exists-p, but this
1318 ;; returns nil for tar members.
1319 (doc-view-fallback-mode)
1320
1321 (let* ((prev-major-mode (if (eq major-mode 'doc-view-mode)
1322 doc-view-previous-major-mode
1323 (when (not (memq major-mode
1324 '(doc-view-mode fundamental-mode)))
1325 major-mode))))
1326 (kill-all-local-variables)
1327 (set (make-local-variable 'doc-view-previous-major-mode) prev-major-mode))
1328
1329 ;; Figure out the document type.
1330 (unless doc-view-doc-type
1331 (doc-view-set-doc-type))
1332
1333 (doc-view-make-safe-dir doc-view-cache-directory)
1334 ;; Handle compressed files, remote files, files inside archives
1335 (set (make-local-variable 'doc-view-buffer-file-name)
1336 (cond
1337 (jka-compr-really-do-compress
1338 ;; FIXME: there's a risk of name conflicts here.
1339 (expand-file-name
1340 (file-name-nondirectory
1341 (file-name-sans-extension buffer-file-name))
1342 doc-view-cache-directory))
1343 ;; Is the file readable by local processes?
1344 ;; We used to use `file-remote-p' but it's unclear what it's
1345 ;; supposed to return nil for things like local files accessed via
1346 ;; `su' or via file://...
1347 ((let ((file-name-handler-alist nil))
1348 (not (and buffer-file-name (file-readable-p buffer-file-name))))
1349 ;; FIXME: there's a risk of name conflicts here.
1350 (expand-file-name
1351 (if buffer-file-name
1352 (file-name-nondirectory buffer-file-name)
1353 (buffer-name))
1354 doc-view-cache-directory))
1355 (t buffer-file-name)))
1356 (when (not (string= doc-view-buffer-file-name buffer-file-name))
1357 (write-region nil nil doc-view-buffer-file-name))
1358
1359 (add-hook 'change-major-mode-hook
1360 (lambda ()
1361 (doc-view-kill-proc)
1362 (remove-overlays (point-min) (point-max) 'doc-view t))
1363 nil t)
1364 (add-hook 'clone-indirect-buffer-hook 'doc-view-clone-buffer-hook nil t)
1365 (add-hook 'kill-buffer-hook 'doc-view-kill-proc nil t)
1366
1367 (remove-overlays (point-min) (point-max) 'doc-view t) ;Just in case.
1368 ;; Keep track of display info ([vh]scroll, page number, overlay,
1369 ;; ...) for each window in which this document is shown.
1370 (add-hook 'image-mode-new-window-functions
1371 'doc-view-new-window-function nil t)
1372 (image-mode-setup-winprops)
1373
1374 (set (make-local-variable 'mode-line-position)
1375 '(" P" (:eval (number-to-string (doc-view-current-page)))
1376 "/" (:eval (number-to-string (doc-view-last-page-number)))))
1377 ;; Don't scroll unless the user specifically asked for it.
1378 (set (make-local-variable 'auto-hscroll-mode) nil)
1379 (set (make-local-variable 'mwheel-scroll-up-function)
1380 'doc-view-scroll-up-or-next-page)
1381 (set (make-local-variable 'mwheel-scroll-down-function)
1382 'doc-view-scroll-down-or-previous-page)
1383 (set (make-local-variable 'cursor-type) nil)
1384 (use-local-map doc-view-mode-map)
1385 (set (make-local-variable 'after-revert-hook) 'doc-view-reconvert-doc)
1386 (set (make-local-variable 'bookmark-make-record-function)
1387 'doc-view-bookmark-make-record)
1388 (setq mode-name "DocView"
1389 buffer-read-only t
1390 major-mode 'doc-view-mode)
1391 (doc-view-initiate-display)
1392 ;; Switch off view-mode explicitly, because doc-view-mode is the
1393 ;; canonical view mode for PDF/PS/DVI files. This could be
1394 ;; switched on automatically depending on the value of
1395 ;; `view-read-only'.
1396 (set (make-local-variable 'view-read-only) nil)
1397 (run-mode-hooks 'doc-view-mode-hook)))
1398
1399 (defun doc-view-fallback-mode ()
1400 "Fallback to the previous or next best major mode."
1401 (if doc-view-previous-major-mode
1402 (funcall doc-view-previous-major-mode)
1403 (let ((auto-mode-alist (rassq-delete-all
1404 'doc-view-mode-maybe
1405 (rassq-delete-all 'doc-view-mode
1406 (copy-alist auto-mode-alist)))))
1407 (normal-mode))))
1408
1409 ;;;###autoload
1410 (defun doc-view-mode-maybe ()
1411 "Switch to `doc-view-mode' if possible.
1412 If the required external tools are not available, then fallback
1413 to the next best mode."
1414 (condition-case nil
1415 (doc-view-set-doc-type)
1416 (error (doc-view-fallback-mode)))
1417 (if (doc-view-mode-p doc-view-doc-type)
1418 (doc-view-mode)
1419 (doc-view-fallback-mode)))
1420
1421 ;;;###autoload
1422 (define-minor-mode doc-view-minor-mode
1423 "Toggle Doc view minor mode.
1424 With arg, turn Doc view minor mode on if arg is positive, off otherwise.
1425 See the command `doc-view-mode' for more information on this mode."
1426 nil " DocView" doc-view-minor-mode-map
1427 :group 'doc-view
1428 (when doc-view-minor-mode
1429 (add-hook 'change-major-mode-hook (lambda () (doc-view-minor-mode -1)) nil t)
1430 (message
1431 "%s"
1432 (substitute-command-keys
1433 "Type \\[doc-view-toggle-display] to toggle between editing or viewing the document."))))
1434
1435 (defun doc-view-clear-cache ()
1436 "Delete the whole cache (`doc-view-cache-directory')."
1437 (interactive)
1438 (dired-delete-file doc-view-cache-directory 'always))
1439
1440 (defun doc-view-dired-cache ()
1441 "Open `dired' in `doc-view-cache-directory'."
1442 (interactive)
1443 (dired doc-view-cache-directory))
1444
1445
1446 ;;;; Bookmark integration
1447
1448 (declare-function bookmark-make-record-default
1449 "bookmark" (&optional no-file no-context posn))
1450 (declare-function bookmark-prop-get "bookmark" (bookmark prop))
1451 (declare-function bookmark-default-handler "bookmark" (bmk))
1452
1453 (defun doc-view-bookmark-make-record ()
1454 (nconc (bookmark-make-record-default)
1455 `((page . ,(doc-view-current-page))
1456 (handler . doc-view-bookmark-jump))))
1457
1458
1459 ;;;###autoload
1460 (defun doc-view-bookmark-jump (bmk)
1461 ;; This implements the `handler' function interface for record type
1462 ;; returned by `doc-view-bookmark-make-record', which see.
1463 (prog1 (bookmark-default-handler bmk)
1464 (let ((page (bookmark-prop-get bmk 'page)))
1465 (when (not (eq major-mode 'doc-view-mode))
1466 (doc-view-toggle-display))
1467 (with-selected-window
1468 (or (get-buffer-window (current-buffer) 0)
1469 (selected-window))
1470 (doc-view-goto-page page)))))
1471
1472
1473 (provide 'doc-view)
1474
1475 ;; Local Variables:
1476 ;; mode: outline-minor
1477 ;; End:
1478
1479 ;; arch-tag: 5d6e5c5e-095f-489e-b4e4-1ca90a7d79be
1480 ;;; doc-view.el ends here