(menu-bar-tools-menu): Read and send mail entries are not constants. (Bug#4913)
[bpt/emacs.git] / lisp / doc-view.el
CommitLineData
94dbe99c
TTN
1;;; doc-view.el --- View PDF/PostScript/DVI files in Emacs
2
ae940284 3;; Copyright (C) 2007, 2008, 2009 Free Software Foundation, Inc.
94dbe99c
TTN
4;;
5;; Author: Tassilo Horn <tassilo@member.fsf.org>
6;; Maintainer: Tassilo Horn <tassilo@member.fsf.org>
7;; Keywords: files, pdf, ps, dvi
94dbe99c
TTN
8
9;; This file is part of GNU Emacs.
10
eb3fa2cf 11;; GNU Emacs is free software: you can redistribute it and/or modify
94dbe99c 12;; it under the terms of the GNU General Public License as published by
eb3fa2cf
GM
13;; the Free Software Foundation, either version 3 of the License, or
14;; (at your option) any later version.
94dbe99c
TTN
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
eb3fa2cf 22;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
94dbe99c
TTN
23
24;;; Requirements:
25
4b378e75 26;; doc-view.el requires GNU Emacs 22.1 or newer. You also need Ghostscript,
1ecc9da7
TH
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/).
94dbe99c
TTN
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;;
640602f7 38;; To use it simply open a document file with
94dbe99c 39;;
640602f7 40;; C-x C-f ~/path/to/document RET
94dbe99c 41;;
640602f7
RS
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
1f75e53d 44;; representation and the source text representation of the document.
94dbe99c
TTN
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
640602f7
RS
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
94dbe99c
TTN
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
a8ce3d17 65;; `doc-view-set-slice-using-mouse' (bound to `s m'). After invocation you
94dbe99c
TTN
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;;
94dbe99c
TTN
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
7baca0fa
JL
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
a8ce3d17 77;; that doesn't already exist the first invocation of `doc-view-search' (or
7baca0fa
JL
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.
640602f7
RS
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;;
94dbe99c
TTN
85
86;;; Configuration:
87
640602f7
RS
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.)
94dbe99c
TTN
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
34065e5e 99;;; Todo:
94dbe99c 100
56741510
SM
101;; - add print command.
102;; - share more code with image-mode.
f4c75497 103;; - better menu.
f4c75497 104;; - Bind slicing to a drag event.
eb79098b 105;; - doc-view-fit-doc-to-window and doc-view-fit-window-to-doc?
cec1df02 106;; - zoom the region around the cursor (like xdvi).
c17587fe
SM
107;; - get rid of the silly arrow in the fringe.
108;; - improve anti-aliasing (pdf-utils gets it better).
f4c75497 109
34065e5e
JL
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
23cda572 135(eval-when-compile (require 'cl))
94dbe99c 136(require 'dired)
414dd971 137(require 'image-mode)
7baca0fa 138(require 'jka-compr)
94dbe99c
TTN
139
140;;;; Customization Options
141
142(defgroup doc-view nil
143 "In-buffer viewer for PDF, PostScript and DVI files."
144 :link '(function-link doc-view)
145 :version "22.2"
146 :group 'applications
147 :group 'multimedia
148 :prefix "doc-view-")
149
c9a9a5e3 150(defcustom doc-view-ghostscript-program (executable-find "gs")
94dbe99c 151 "Program to convert PS and PDF files to PNG."
c9a9a5e3 152 :type 'file
94dbe99c
TTN
153 :group 'doc-view)
154
155(defcustom doc-view-ghostscript-options
6a658a30
RS
156 '("-dSAFER" ;; Avoid security problems when rendering files from untrusted
157 ;; sources.
158 "-dNOPAUSE" "-sDEVICE=png16m" "-dTextAlphaBits=4"
05477667 159 "-dBATCH" "-dGraphicsAlphaBits=4" "-dQUIET")
4b378e75 160 "A list of options to give to ghostscript."
c9a9a5e3 161 :type '(repeat string)
94dbe99c
TTN
162 :group 'doc-view)
163
05477667
SM
164(defcustom doc-view-resolution 100
165 "Dots per inch resolution used to render the documents.
166Higher values result in larger images."
9efa445f
DN
167 :type 'number
168 :group 'doc-view)
05477667 169
c9a9a5e3 170(defcustom doc-view-dvipdfm-program (executable-find "dvipdfm")
94dbe99c
TTN
171 "Program to convert DVI files to PDF.
172
173DVI file will be converted to PDF before the resulting PDF is
53d4c024
TH
174converted to PNG.
175
176If this and `doc-view-dvipdf-program' are set,
177`doc-view-dvipdf-program' will be preferred."
178 :type 'file
179 :group 'doc-view)
180
181(defcustom doc-view-dvipdf-program (executable-find "dvipdf")
182 "Program to convert DVI files to PDF.
183
184DVI file will be converted to PDF before the resulting PDF is
185converted to PNG.
186
187If this and `doc-view-dvipdfm-program' are set,
188`doc-view-dvipdf-program' will be preferred."
c9a9a5e3 189 :type 'file
94dbe99c
TTN
190 :group 'doc-view)
191
c9a9a5e3 192(defcustom doc-view-ps2pdf-program (executable-find "ps2pdf")
94dbe99c
TTN
193 "Program to convert PS files to PDF.
194
195PS files will be converted to PDF before searching is possible."
c9a9a5e3 196 :type 'file
94dbe99c
TTN
197 :group 'doc-view)
198
c9a9a5e3 199(defcustom doc-view-pdftotext-program (executable-find "pdftotext")
94dbe99c
TTN
200 "Program to convert PDF files to plain text.
201
202Needed for searching."
c9a9a5e3 203 :type 'file
94dbe99c
TTN
204 :group 'doc-view)
205
c17587fe 206(defcustom doc-view-cache-directory
8aafd651 207 (expand-file-name (format "docview%d" (user-uid))
bce6be12 208 temporary-file-directory)
94dbe99c 209 "The base directory, where the PNG images will be saved."
c9a9a5e3 210 :type 'directory
94dbe99c
TTN
211 :group 'doc-view)
212
56741510
SM
213(defvar doc-view-conversion-buffer " *doc-view conversion output*"
214 "The buffer where messages from the converter programs go to.")
94dbe99c 215
56741510 216(defcustom doc-view-conversion-refresh-interval 1
1f75e53d
GM
217 "Interval in seconds between refreshes of the DocView buffer while converting.
218After such a refresh newly converted pages will be available for
94dbe99c
TTN
219viewing. If set to nil there won't be any refreshes and the
220pages won't be displayed before conversion of the whole document
221has finished."
c9a9a5e3 222 :type 'integer
94dbe99c
TTN
223 :group 'doc-view)
224
225;;;; Internal Variables
226
de171465
SM
227(defun doc-view-new-window-function (winprops)
228 (let ((ol (image-mode-window-get 'overlay winprops)))
229 (if ol
230 (setq ol (copy-overlay ol))
10b6e7c1 231 (assert (not (get-char-property (point-min) 'display)))
de171465
SM
232 (setq ol (make-overlay (point-min) (point-max) nil t))
233 (overlay-put ol 'doc-view t))
234 (overlay-put ol 'window (car winprops))
235 (image-mode-window-put 'overlay ol winprops)))
94dbe99c 236
de171465 237(defvar doc-view-current-files nil
94dbe99c 238 "Only used internally.")
ec4853ab 239(make-variable-buffer-local 'doc-view-current-files)
94dbe99c 240
ec4853ab 241(defvar doc-view-current-converter-processes nil
94dbe99c 242 "Only used internally.")
ec4853ab 243(make-variable-buffer-local 'doc-view-current-converter-processes)
94dbe99c
TTN
244
245(defvar doc-view-current-timer nil
246 "Only used internally.")
ec4853ab 247(make-variable-buffer-local 'doc-view-current-timer)
94dbe99c 248
94dbe99c
TTN
249(defvar doc-view-current-cache-dir nil
250 "Only used internally.")
ec4853ab 251(make-variable-buffer-local 'doc-view-current-cache-dir)
94dbe99c
TTN
252
253(defvar doc-view-current-search-matches nil
254 "Only used internally.")
ec4853ab 255(make-variable-buffer-local 'doc-view-current-search-matches)
94dbe99c 256
d99abf1b
RS
257(defvar doc-view-pending-cache-flush nil
258 "Only used internally.")
94dbe99c 259
937cb3fb 260(defvar doc-view-previous-major-mode nil
640602f7
RS
261 "Only used internally.")
262
39a402e3
TH
263(defvar doc-view-buffer-file-name nil
264 "Only used internally.
265The file name used for conversion. Normally it's the same as
266`buffer-file-name', but for remote files, compressed files and
267files inside an archive it is a temporary copy of
268the (uncompressed, extracted) file residing in
269`doc-view-cache-directory'.")
270
eb79098b
SM
271(defvar doc-view-doc-type nil
272 "The type of document in the current buffer.
273Can be `dvi', `pdf', or `ps'.")
274
640602f7 275;;;; DocView Keymaps
94dbe99c
TTN
276
277(defvar doc-view-mode-map
278 (let ((map (make-sparse-keymap)))
d2d7e96c 279 (set-keymap-parent map image-mode-map)
94dbe99c
TTN
280 ;; Navigation in the document
281 (define-key map (kbd "n") 'doc-view-next-page)
282 (define-key map (kbd "p") 'doc-view-previous-page)
eb8d0216
SM
283 (define-key map (kbd "<next>") 'forward-page)
284 (define-key map (kbd "<prior>") 'backward-page)
285 (define-key map [remap forward-page] 'doc-view-next-page)
286 (define-key map [remap backward-page] 'doc-view-previous-page)
94dbe99c
TTN
287 (define-key map (kbd "SPC") 'doc-view-scroll-up-or-next-page)
288 (define-key map (kbd "DEL") 'doc-view-scroll-down-or-previous-page)
289 (define-key map (kbd "M-<") 'doc-view-first-page)
290 (define-key map (kbd "M->") 'doc-view-last-page)
7656fe61 291 (define-key map [remap goto-line] 'doc-view-goto-page)
4376876e 292 (define-key map (kbd "RET") 'image-next-line)
05477667
SM
293 ;; Zoom in/out.
294 (define-key map "+" 'doc-view-enlarge)
295 (define-key map "-" 'doc-view-shrink)
d2d7e96c 296 ;; Killing the buffer (and the process)
94dbe99c 297 (define-key map (kbd "k") 'doc-view-kill-proc-and-buffer)
937cb3fb 298 (define-key map (kbd "K") 'doc-view-kill-proc)
94dbe99c
TTN
299 ;; Slicing the image
300 (define-key map (kbd "s s") 'doc-view-set-slice)
301 (define-key map (kbd "s m") 'doc-view-set-slice-using-mouse)
302 (define-key map (kbd "s r") 'doc-view-reset-slice)
303 ;; Searching
304 (define-key map (kbd "C-s") 'doc-view-search)
305 (define-key map (kbd "<find>") 'doc-view-search)
7baca0fa 306 (define-key map (kbd "C-r") 'doc-view-search-backward)
94dbe99c
TTN
307 ;; Show the tooltip
308 (define-key map (kbd "C-t") 'doc-view-show-tooltip)
640602f7
RS
309 ;; Toggle between text and image display or editing
310 (define-key map (kbd "C-c C-c") 'doc-view-toggle-display)
515357c2
TH
311 ;; Open a new buffer with doc's text contents
312 (define-key map (kbd "C-c C-t") 'doc-view-open-text)
640602f7 313 ;; Reconvert the current document
7656fe61
SM
314 (define-key map (kbd "g") 'revert-buffer)
315 (define-key map (kbd "r") 'revert-buffer)
94dbe99c 316 map)
640602f7
RS
317 "Keymap used by `doc-view-mode' when displaying a doc as a set of images.")
318
f4c75497
SM
319(easy-menu-define doc-view-menu doc-view-mode-map
320 "Menu for Doc View mode."
321 '("DocView"
322 ["Set Slice" doc-view-set-slice-using-mouse]
323 ["Set Slice (manual)" doc-view-set-slice]
324 ["Reset Slice" doc-view-reset-slice]
325 "---"
326 ["Search" doc-view-search]
7baca0fa 327 ["Search Backwards" doc-view-search-backward]
f4c75497 328 ["Toggle display" doc-view-toggle-display]
f4c75497
SM
329 ))
330
937cb3fb 331(defvar doc-view-minor-mode-map
640602f7
RS
332 (let ((map (make-sparse-keymap)))
333 ;; Toggle between text and image display or editing
334 (define-key map (kbd "C-c C-c") 'doc-view-toggle-display)
640602f7 335 map)
937cb3fb 336 "Keymap used by `doc-minor-view-mode'.")
94dbe99c
TTN
337
338;;;; Navigation Commands
339
160dfe43
SM
340(defmacro doc-view-current-page (&optional win)
341 `(image-mode-window-get 'page ,win))
de171465
SM
342(defmacro doc-view-current-info () `(image-mode-window-get 'info))
343(defmacro doc-view-current-overlay () `(image-mode-window-get 'overlay))
344(defmacro doc-view-current-image () `(image-mode-window-get 'image))
345(defmacro doc-view-current-slice () `(image-mode-window-get 'slice))
346
94dbe99c
TTN
347(defun doc-view-goto-page (page)
348 "View the page given by PAGE."
349 (interactive "nPage: ")
bc19637d
TH
350 (let ((len (length doc-view-current-files))
351 (hscroll (window-hscroll)))
94dbe99c 352 (if (< page 1)
1ca678aa 353 (setq page 1)
56741510
SM
354 (when (and (> page len)
355 ;; As long as the converter is running, we don't know
356 ;; how many pages will be available.
ec4853ab 357 (null doc-view-current-converter-processes))
1ca678aa 358 (setq page len)))
de171465
SM
359 (setf (doc-view-current-page) page
360 (doc-view-current-info)
1ca678aa
MC
361 (concat
362 (propertize
de171465 363 (format "Page %d of %d." page len) 'face 'bold)
1ca678aa 364 ;; Tell user if converting isn't finished yet
ec4853ab 365 (if doc-view-current-converter-processes
1ca678aa
MC
366 " (still converting...)\n"
367 "\n")
368 ;; Display context infos if this page matches the last search
369 (when (and doc-view-current-search-matches
de171465 370 (assq page doc-view-current-search-matches))
1ca678aa
MC
371 (concat (propertize "Search matches:\n" 'face 'bold)
372 (let ((contexts ""))
de171465 373 (dolist (m (cdr (assq page
1ca678aa
MC
374 doc-view-current-search-matches)))
375 (setq contexts (concat contexts " - \"" m "\"\n")))
376 contexts)))))
94dbe99c 377 ;; Update the buffer
56741510
SM
378 ;; We used to find the file name from doc-view-current-files but
379 ;; that's not right if the pages are not generated sequentially
380 ;; or if the page isn't in doc-view-current-files yet.
ec4853ab
SM
381 (let ((file (expand-file-name (format "page-%d.png" page)
382 (doc-view-current-cache-dir))))
383 (doc-view-insert-image file :pointer 'arrow)
bc19637d 384 (set-window-hscroll (selected-window) hscroll)
ec4853ab
SM
385 (when (and (not (file-exists-p file))
386 doc-view-current-converter-processes)
387 ;; The PNG file hasn't been generated yet.
388 (doc-view-pdf->png-1 doc-view-buffer-file-name file page
389 (lexical-let ((page page)
390 (win (selected-window)))
391 (lambda ()
392 (and (eq (current-buffer) (window-buffer win))
393 ;; If we changed page in the mean
394 ;; time, don't mess things up.
395 (eq (doc-view-current-page win) page)
396 (with-selected-window win
397 (doc-view-goto-page page))))))))
de171465
SM
398 (overlay-put (doc-view-current-overlay)
399 'help-echo (doc-view-current-info))))
94dbe99c
TTN
400
401(defun doc-view-next-page (&optional arg)
402 "Browse ARG pages forward."
403 (interactive "p")
de171465 404 (doc-view-goto-page (+ (doc-view-current-page) (or arg 1))))
94dbe99c
TTN
405
406(defun doc-view-previous-page (&optional arg)
407 "Browse ARG pages backward."
408 (interactive "p")
de171465 409 (doc-view-goto-page (- (doc-view-current-page) (or arg 1))))
94dbe99c
TTN
410
411(defun doc-view-first-page ()
412 "View the first page."
413 (interactive)
414 (doc-view-goto-page 1))
415
416(defun doc-view-last-page ()
417 "View the last page."
418 (interactive)
419 (doc-view-goto-page (length doc-view-current-files)))
420
421(defun doc-view-scroll-up-or-next-page ()
422 "Scroll page up if possible, else goto next page."
423 (interactive)
bc19637d
TH
424 (let ((hscroll (window-hscroll))
425 (cur-page (doc-view-current-page)))
426 (when (= (window-vscroll) (image-scroll-up nil))
bcc758ec 427 (doc-view-next-page)
de171465 428 (when (/= cur-page (doc-view-current-page))
c36f0e17 429 (image-bob)
bc19637d
TH
430 (image-bol 1))
431 (set-window-hscroll (selected-window) hscroll))))
94dbe99c
TTN
432
433(defun doc-view-scroll-down-or-previous-page ()
434 "Scroll page down if possible, else goto previous page."
435 (interactive)
bc19637d
TH
436 (let ((hscroll (window-hscroll))
437 (cur-page (doc-view-current-page)))
438 (when (= (window-vscroll) (image-scroll-down nil))
bcc758ec 439 (doc-view-previous-page)
de171465 440 (when (/= cur-page (doc-view-current-page))
c36f0e17 441 (image-eob)
bc19637d
TH
442 (image-bol 1))
443 (set-window-hscroll (selected-window) hscroll))))
94dbe99c 444
937cb3fb
GM
445;;;; Utility Functions
446
640602f7 447(defun doc-view-kill-proc ()
ec4853ab 448 "Kill the current converter process(es)."
640602f7 449 (interactive)
ec4853ab 450 (while doc-view-current-converter-processes
56741510 451 (ignore-errors ;; Maybe it's dead already?
ec4853ab 452 (kill-process (pop doc-view-current-converter-processes))))
640602f7
RS
453 (when doc-view-current-timer
454 (cancel-timer doc-view-current-timer)
455 (setq doc-view-current-timer nil))
456 (setq mode-line-process nil))
457
94dbe99c
TTN
458(defun doc-view-kill-proc-and-buffer ()
459 "Kill the current converter process and buffer."
460 (interactive)
640602f7 461 (doc-view-kill-proc)
94dbe99c 462 (when (eq major-mode 'doc-view-mode)
94dbe99c
TTN
463 (kill-buffer (current-buffer))))
464
c17587fe
SM
465(defun doc-view-make-safe-dir (dir)
466 (condition-case nil
467 (let ((umask (default-file-modes)))
468 (unwind-protect
469 (progn
470 ;; Create temp files with strict access rights. It's easy to
471 ;; loosen them later, whereas it's impossible to close the
472 ;; time-window of loose permissions otherwise.
473 (set-default-file-modes #o0700)
474 (make-directory dir))
475 ;; Reset the umask.
476 (set-default-file-modes umask)))
477 (file-already-exists
478 (if (file-symlink-p dir)
479 (error "Danger: %s points to a symbolic link" dir))
480 ;; In case it was created earlier with looser rights.
481 ;; We could check the mode info returned by file-attributes, but it's
482 ;; a pain to parse and it may not tell you what we want under
483 ;; non-standard file-systems. So let's just say what we want and let
484 ;; the underlying C code and file-system figure it out.
485 ;; This also ends up checking a bunch of useful conditions: it makes
486 ;; sure we have write-access to the directory and that we own it, thus
487 ;; closing a bunch of security holes.
488 (set-file-modes dir #o0700))))
489
937cb3fb
GM
490(defun doc-view-current-cache-dir ()
491 "Return the directory where the png files of the current doc should be saved.
492It's a subdirectory of `doc-view-cache-directory'."
493 (if doc-view-current-cache-dir
494 doc-view-current-cache-dir
c17587fe
SM
495 ;; Try and make sure doc-view-cache-directory exists and is safe.
496 (doc-view-make-safe-dir doc-view-cache-directory)
497 ;; Now compute the subdirectory to use.
937cb3fb
GM
498 (setq doc-view-current-cache-dir
499 (file-name-as-directory
c17587fe 500 (expand-file-name
39a402e3
TH
501 (concat (file-name-nondirectory buffer-file-name)
502 "-"
503 (let ((file doc-view-buffer-file-name))
504 (with-temp-buffer
86903c81 505 (set-buffer-multibyte nil)
39a402e3
TH
506 (insert-file-contents-literally file)
507 (md5 (current-buffer)))))
c17587fe 508 doc-view-cache-directory)))))
937cb3fb
GM
509
510(defun doc-view-remove-if (predicate list)
511 "Return LIST with all items removed that satisfy PREDICATE."
512 (let (new-list)
513 (dolist (item list (nreverse new-list))
514 (when (not (funcall predicate item))
515 (setq new-list (cons item new-list))))))
516
789ab9d4
RS
517;;;###autoload
518(defun doc-view-mode-p (type)
519 "Return non-nil if image type TYPE is available for `doc-view'.
520Image types are symbols like `dvi', `postscript' or `pdf'."
521 (and (display-graphic-p)
522 (image-type-available-p 'png)
523 (cond
524 ((eq type 'dvi)
525 (and (doc-view-mode-p 'pdf)
53d4c024
TH
526 (or (and doc-view-dvipdf-program
527 (executable-find doc-view-dvipdf-program))
528 (and doc-view-dvipdfm-program
529 (executable-find doc-view-dvipdfm-program)))))
622face2 530 ((or (eq type 'postscript) (eq type 'ps) (eq type 'eps)
789ab9d4
RS
531 (eq type 'pdf))
532 (and doc-view-ghostscript-program
533 (executable-find doc-view-ghostscript-program)))
534 (t ;; unknown image type
535 nil))))
536
94dbe99c
TTN
537;;;; Conversion Functions
538
05477667
SM
539(defvar doc-view-shrink-factor 1.125)
540
541(defun doc-view-enlarge (factor)
542 "Enlarge the document."
543 (interactive (list doc-view-shrink-factor))
544 (set (make-local-variable 'doc-view-resolution)
545 (* factor doc-view-resolution))
546 (doc-view-reconvert-doc))
547
548(defun doc-view-shrink (factor)
549 "Shrink the document."
550 (interactive (list doc-view-shrink-factor))
551 (doc-view-enlarge (/ 1.0 factor)))
552
c17587fe 553(defun doc-view-reconvert-doc ()
640602f7
RS
554 "Reconvert the current document.
555Should be invoked when the cached images aren't up-to-date."
556 (interactive)
f4c75497
SM
557 (doc-view-kill-proc)
558 ;; Clear the old cached files
559 (when (file-exists-p (doc-view-current-cache-dir))
560 (dired-delete-file (doc-view-current-cache-dir) 'always))
c17587fe 561 (doc-view-initiate-display))
94dbe99c 562
b4cb319f
SM
563(defun doc-view-sentinel (proc event)
564 "Generic sentinel for doc-view conversion processes."
94dbe99c 565 (if (not (string-match "finished" event))
b4cb319f 566 (message "DocView: process %s changed status to %s."
405ee48d
CY
567 (process-name proc)
568 (if (string-match "\\(.+\\)\n?\\'" event)
569 (match-string 1 event)
570 event))
ec4853ab
SM
571 (when (buffer-live-p (process-get proc 'buffer))
572 (with-current-buffer (process-get proc 'buffer)
573 (setq doc-view-current-converter-processes
574 (delq proc doc-view-current-converter-processes))
575 (setq mode-line-process
576 (if doc-view-current-converter-processes
577 (format ":%s" (car doc-view-current-converter-processes))))
578 (funcall (process-get proc 'callback))))))
579
580(defun doc-view-start-process (name program args callback)
3c03f2ce
TH
581 ;; Make sure the process is started in an existing directory, (rather than
582 ;; some file-name-handler-managed dir, for example).
583 (let* ((default-directory (if (file-readable-p default-directory)
584 default-directory
585 (expand-file-name "~/")))
ec4853ab
SM
586 (proc (apply 'start-process name doc-view-conversion-buffer
587 program args)))
588 (push proc doc-view-current-converter-processes)
589 (setq mode-line-process (list (format ":%s" proc)))
590 (set-process-sentinel proc 'doc-view-sentinel)
591 (process-put proc 'buffer (current-buffer))
592 (process-put proc 'callback callback)))
b4cb319f
SM
593
594(defun doc-view-dvi->pdf (dvi pdf callback)
595 "Convert DVI to PDF asynchronously and call CALLBACK when finished."
53d4c024
TH
596 ;; Prefer dvipdf over dvipdfm, because the latter has problems if the DVI
597 ;; references and includes other PS files.
598 (if (and doc-view-dvipdf-program
599 (executable-find doc-view-dvipdf-program))
600 (doc-view-start-process "dvi->pdf" doc-view-dvipdf-program
601 (list dvi pdf)
602 callback)
603 (doc-view-start-process "dvi->pdf" doc-view-dvipdfm-program
604 (list "-o" pdf dvi)
605 callback)))
ec4853ab 606
94dbe99c
TTN
607
608(defun doc-view-pdf/ps->png (pdf-ps png)
1f75e53d 609 "Convert PDF-PS to PNG asynchronously."
ec4853ab
SM
610 (doc-view-start-process
611 "pdf/ps->png" doc-view-ghostscript-program
612 (append doc-view-ghostscript-options
613 (list (format "-r%d" (round doc-view-resolution))
614 (concat "-sOutputFile=" png)
615 pdf-ps))
3c03f2ce 616 (lambda ()
ec4853ab
SM
617 (when doc-view-current-timer
618 (cancel-timer doc-view-current-timer)
619 (setq doc-view-current-timer nil))
620 (doc-view-display (current-buffer) 'force)))
621 ;; Update the displayed pages as soon as they're done generating.
94dbe99c
TTN
622 (when doc-view-conversion-refresh-interval
623 (setq doc-view-current-timer
ec4853ab
SM
624 (run-at-time "1 secs" doc-view-conversion-refresh-interval
625 'doc-view-display
626 (current-buffer)))))
627
628(defun doc-view-pdf->png-1 (pdf png page callback)
629 "Convert a PAGE of a PDF file to PNG asynchronously.
630Call CALLBACK with no arguments when done."
631 (doc-view-start-process
632 "pdf->png-1" doc-view-ghostscript-program
633 (append doc-view-ghostscript-options
634 (list (format "-r%d" (round doc-view-resolution))
635 ;; Sadly, `gs' only supports the page-range
636 ;; for PDF files.
637 (format "-dFirstPage=%d" page)
638 (format "-dLastPage=%d" page)
639 (concat "-sOutputFile=" png)
640 pdf))
641 callback))
642
aa360da1
GM
643(declare-function clear-image-cache "image.c" (&optional filter))
644
ec4853ab
SM
645(defun doc-view-pdf->png (pdf png pages)
646 "Convert a PDF file to PNG asynchronously.
647Start by converting PAGES, and then the rest."
648 (if (null pages)
649 (doc-view-pdf/ps->png pdf png)
650 ;; We could render several `pages' with a single process if they're
651 ;; (almost) consecutive, but since in 99% of the cases, there'll be only
652 ;; a single page anyway, and of the remaining 1%, few cases will have
653 ;; consecutive pages, it's not worth the trouble.
654 (lexical-let ((pdf pdf) (png png) (rest (cdr pages)))
655 (doc-view-pdf->png-1
656 pdf (format png (car pages)) (car pages)
657 (lambda ()
658 (if rest
659 (doc-view-pdf->png pdf png rest)
660 ;; Yippie, the important pages are done, update the display.
661 (clear-image-cache)
662 ;; Convert the rest of the pages.
663 (doc-view-pdf/ps->png pdf png)))))))
94dbe99c 664
b4cb319f
SM
665(defun doc-view-pdf->txt (pdf txt callback)
666 "Convert PDF to TXT asynchronously and call CALLBACK when finished."
ca32d854
GM
667 (or doc-view-pdftotext-program
668 (error "You need the `pdftotext' program to convert a PDF to text"))
ec4853ab
SM
669 (doc-view-start-process "pdf->txt" doc-view-pdftotext-program
670 (list "-raw" pdf txt)
671 callback))
515357c2 672
b4cb319f
SM
673(defun doc-view-doc->txt (txt callback)
674 "Convert the current document to text and call CALLBACK when done."
7edd6b92 675 (make-directory (doc-view-current-cache-dir) t)
b4cb319f
SM
676 (case doc-view-doc-type
677 (pdf
678 ;; Doc is a PDF, so convert it to TXT
679 (doc-view-pdf->txt doc-view-buffer-file-name txt callback))
680 (ps
681 ;; Doc is a PS, so convert it to PDF (which will be converted to
682 ;; TXT thereafter).
683 (lexical-let ((pdf (expand-file-name "doc.pdf"
684 (doc-view-current-cache-dir)))
685 (txt txt)
686 (callback callback))
687 (doc-view-ps->pdf doc-view-buffer-file-name pdf
688 (lambda () (doc-view-pdf->txt pdf txt callback)))))
689 (dvi
690 ;; Doc is a DVI. This means that a doc.pdf already exists in its
691 ;; cache subdirectory.
692 (doc-view-pdf->txt (expand-file-name "doc.pdf"
693 (doc-view-current-cache-dir))
694 txt callback))
695 (t (error "DocView doesn't know what to do"))))
696
697(defun doc-view-ps->pdf (ps pdf callback)
698 "Convert PS to PDF asynchronously and call CALLBACK when finished."
ca32d854
GM
699 (or doc-view-ps2pdf-program
700 (error "You need the `ps2pdf' program to convert PS to PDF"))
ec4853ab
SM
701 (doc-view-start-process "ps->pdf" doc-view-ps2pdf-program
702 (list
703 ;; Avoid security problems when rendering files from
704 ;; untrusted sources.
705 "-dSAFER"
706 ;; in-file and out-file
707 ps pdf)
708 callback))
709
710(defun doc-view-active-pages ()
711 (let ((pages ()))
712 (dolist (win (get-buffer-window-list (current-buffer) nil 'visible))
713 (let ((page (image-mode-window-get 'page win)))
714 (unless (memq page pages) (push page pages))))
715 pages))
94dbe99c 716
640602f7 717(defun doc-view-convert-current-doc ()
39a402e3 718 "Convert `doc-view-buffer-file-name' to a set of png files, one file per page.
640602f7
RS
719Those files are saved in the directory given by the function
720`doc-view-current-cache-dir'."
c17587fe
SM
721 ;; Let stale files still display while we recompute the new ones, so only
722 ;; flush the cache when the conversion is over. One of the reasons why it
723 ;; is important to keep displaying the stale page is so that revert-buffer
724 ;; preserves the horizontal/vertical scroll settings (which are otherwise
725 ;; resets during the redisplay).
726 (setq doc-view-pending-cache-flush t)
727 (let ((png-file (expand-file-name "page-%d.png"
cde4c3f1
TH
728 (doc-view-current-cache-dir)))
729 (res-file (expand-file-name "resolution.el"
c17587fe 730 (doc-view-current-cache-dir))))
7edd6b92 731 (make-directory (doc-view-current-cache-dir) t)
cde4c3f1
TH
732 ;; Save the used resolution so that it can be restored when
733 ;; reading the cached files.
734 (let ((res doc-view-resolution))
735 (with-temp-buffer
736 (princ res (current-buffer))
bba79a9c
SM
737 ;; Don't use write-file, so as to avoid prompts for `require-newline',
738 ;; or for pre-existing buffers with the same name, ...
739 (write-region nil nil res-file nil 'silently)))
eb79098b
SM
740 (case doc-view-doc-type
741 (dvi
742 ;; DVI files have to be converted to PDF before Ghostscript can process
743 ;; it.
b4cb319f
SM
744 (lexical-let
745 ((pdf (expand-file-name "doc.pdf" doc-view-current-cache-dir))
746 (png-file png-file))
747 (doc-view-dvi->pdf doc-view-buffer-file-name pdf
748 (lambda () (doc-view-pdf/ps->png pdf png-file)))))
ec4853ab
SM
749 (pdf
750 (let ((pages (doc-view-active-pages)))
751 ;; Convert PDF to PNG images starting with the active pages.
752 (doc-view-pdf->png doc-view-buffer-file-name png-file pages)))
eb79098b
SM
753 (t
754 ;; Convert to PNG images.
755 (doc-view-pdf/ps->png doc-view-buffer-file-name png-file)))))
94dbe99c 756
94dbe99c
TTN
757;;;; Slicing
758
aa360da1
GM
759(declare-function image-size "image.c" (spec &optional pixels frame))
760
94dbe99c
TTN
761(defun doc-view-set-slice (x y width height)
762 "Set the slice of the images that should be displayed.
763You can use this function to tell doc-view not to display the
764margins of the document. It prompts for the top-left corner (X
765and Y) of the slice to display and its WIDTH and HEIGHT.
766
767See `doc-view-set-slice-using-mouse' for a more convenient way to
768do that. To reset the slice use `doc-view-reset-slice'."
769 (interactive
de171465 770 (let* ((size (image-size (doc-view-current-image) t))
1ca678aa
MC
771 (a (read-number (format "Top-left X (0..%d): " (car size))))
772 (b (read-number (format "Top-left Y (0..%d): " (cdr size))))
773 (c (read-number (format "Width (0..%d): " (- (car size) a))))
774 (d (read-number (format "Height (0..%d): " (- (cdr size) b)))))
94dbe99c 775 (list a b c d)))
de171465 776 (setf (doc-view-current-slice) (list x y width height))
94dbe99c 777 ;; Redisplay
de171465 778 (doc-view-goto-page (doc-view-current-page)))
94dbe99c
TTN
779
780(defun doc-view-set-slice-using-mouse ()
781 "Set the slice of the images that should be displayed.
782You set the slice by pressing mouse-1 at its top-left corner and
783dragging it to its bottom-right corner. See also
784`doc-view-set-slice' and `doc-view-reset-slice'."
785 (interactive)
786 (let (x y w h done)
787 (while (not done)
788 (let ((e (read-event
1ca678aa
MC
789 (concat "Press mouse-1 at the top-left corner and "
790 "drag it to the bottom-right corner!"))))
791 (when (eq (car e) 'drag-mouse-1)
792 (setq x (car (posn-object-x-y (event-start e))))
793 (setq y (cdr (posn-object-x-y (event-start e))))
794 (setq w (- (car (posn-object-x-y (event-end e))) x))
795 (setq h (- (cdr (posn-object-x-y (event-end e))) y))
796 (setq done t))))
94dbe99c
TTN
797 (doc-view-set-slice x y w h)))
798
799(defun doc-view-reset-slice ()
e48a5bf9 800 "Reset the current slice.
1f75e53d 801After calling this function whole pages will be visible again."
94dbe99c 802 (interactive)
de171465 803 (setf (doc-view-current-slice) nil)
94dbe99c 804 ;; Redisplay
de171465 805 (doc-view-goto-page (doc-view-current-page)))
94dbe99c
TTN
806
807;;;; Display
808
809(defun doc-view-insert-image (file &rest args)
810 "Insert the given png FILE.
e48a5bf9 811ARGS is a list of image descriptors."
c17587fe
SM
812 (when doc-view-pending-cache-flush
813 (clear-image-cache)
814 (setq doc-view-pending-cache-flush nil))
de171465 815 (let ((ol (doc-view-current-overlay))
56741510
SM
816 (image (if (and file (file-readable-p file))
817 (apply 'create-image file 'png nil args)))
de171465
SM
818 (slice (doc-view-current-slice)))
819 (setf (doc-view-current-image) image)
56741510 820 (move-overlay ol (point-min) (point-max))
de171465 821 (overlay-put ol 'display
56741510
SM
822 (cond
823 (image
de171465
SM
824 (if slice
825 (list (cons 'slice slice) image)
56741510
SM
826 image))
827 ;; We're trying to display a page that doesn't exist.
ec4853ab 828 (doc-view-current-converter-processes
56741510
SM
829 ;; Maybe the page doesn't exist *yet*.
830 "Cannot display this page (yet)!")
831 (t
832 ;; Typically happens if the conversion process somehow
833 ;; failed. Better not signal an error here because it
834 ;; could prevent a subsequent reconversion from fixing
835 ;; the problem.
836 (concat "Cannot display this page!\n"
837 "Maybe because of a conversion failure!"))))
838 (let ((win (overlay-get ol 'window)))
839 (if (stringp (overlay-get ol 'display))
840 (progn ;Make sure the text is not scrolled out of view.
841 (set-window-hscroll win 0)
842 (set-window-vscroll win 0))
843 (let ((hscroll (image-mode-window-get 'hscroll win))
844 (vscroll (image-mode-window-get 'vscroll win)))
845 ;; Reset scroll settings, in case they were changed.
846 (if hscroll (set-window-hscroll win hscroll))
847 (if vscroll (set-window-vscroll win vscroll)))))))
94dbe99c
TTN
848
849(defun doc-view-sort (a b)
850 "Return non-nil if A should be sorted before B.
851Predicate for sorting `doc-view-current-files'."
f4c75497
SM
852 (or (< (length a) (length b))
853 (and (= (length a) (length b))
854 (string< a b))))
94dbe99c 855
65073003
SM
856(defun doc-view-display (buffer &optional force)
857 "Start viewing the document in BUFFER.
214abdd4
SM
858If FORCE is non-nil, start viewing even if the document does not
859have the page we want to view."
65073003 860 (with-current-buffer buffer
56741510
SM
861 (let ((prev-pages doc-view-current-files))
862 (setq doc-view-current-files
863 (sort (directory-files (doc-view-current-cache-dir) t
864 "page-[0-9]+\\.png" t)
865 'doc-view-sort))
10b6e7c1
CY
866 (dolist (win (or (get-buffer-window-list buffer nil t)
867 (list (selected-window))))
868 (let* ((page (doc-view-current-page win))
869 (pagefile (expand-file-name (format "page-%d.png" page)
870 (doc-view-current-cache-dir))))
871 (when (or force
872 (and (not (member pagefile prev-pages))
873 (member pagefile doc-view-current-files)))
874 (with-selected-window win
875 (assert (eq (current-buffer) buffer))
876 (doc-view-goto-page page))))))))
94dbe99c
TTN
877
878(defun doc-view-buffer-message ()
c17587fe
SM
879 ;; Only show this message initially, not when refreshing the buffer (in which
880 ;; case it's better to keep displaying the "stale" page while computing
881 ;; the fresh new ones).
de171465
SM
882 (unless (overlay-get (doc-view-current-overlay) 'display)
883 (overlay-put (doc-view-current-overlay) 'display
c17587fe
SM
884 (concat (propertize "Welcome to DocView!" 'face 'bold)
885 "\n"
886 "
1f75e53d 887If you see this buffer it means that the document you want to view is being
f4c75497 888converted to PNG and the conversion of the first page hasn't finished yet or
94dbe99c
TTN
889`doc-view-conversion-refresh-interval' is set to nil.
890
891For now these keys are useful:
892
1ca678aa 893`q' : Bury this buffer. Conversion will go on in background.
937cb3fb 894`k' : Kill the conversion process and this buffer.
c17587fe 895`K' : Kill the conversion process.\n"))))
94dbe99c 896
aa360da1
GM
897(declare-function tooltip-show "tooltip" (text &optional use-echo-area))
898
94dbe99c
TTN
899(defun doc-view-show-tooltip ()
900 (interactive)
de171465 901 (tooltip-show (doc-view-current-info)))
94dbe99c 902
515357c2
TH
903(defun doc-view-open-text ()
904 "Open a buffer with the current doc's contents as text."
905 (interactive)
ec4853ab 906 (if doc-view-current-converter-processes
515357c2
TH
907 (message "DocView: please wait till conversion finished.")
908 (let ((txt (expand-file-name "doc.txt" (doc-view-current-cache-dir))))
909 (if (file-readable-p txt)
910 (find-file txt)
b4cb319f 911 (doc-view-doc->txt txt 'doc-view-open-text)))))
515357c2 912
937cb3fb 913;;;;; Toggle between editing and viewing
640602f7 914
515357c2 915
640602f7 916(defun doc-view-toggle-display ()
937cb3fb 917 "Toggle between editing a document as text or viewing it."
640602f7 918 (interactive)
937cb3fb
GM
919 (if (eq major-mode 'doc-view-mode)
920 ;; Switch to editing mode
921 (progn
922 (doc-view-kill-proc)
923 (setq buffer-read-only nil)
515357c2
TH
924 (remove-overlays (point-min) (point-max) 'doc-view t)
925 (set (make-local-variable 'image-mode-winprops-alist) t)
937cb3fb
GM
926 ;; Switch to the previously used major mode or fall back to fundamental
927 ;; mode.
928 (if doc-view-previous-major-mode
929 (funcall doc-view-previous-major-mode)
930 (fundamental-mode))
c17587fe 931 (doc-view-minor-mode 1))
937cb3fb
GM
932 ;; Switch to doc-view-mode
933 (when (and (buffer-modified-p)
934 (y-or-n-p "The buffer has been modified. Save the changes? "))
935 (save-buffer))
937cb3fb 936 (doc-view-mode)))
640602f7 937
94dbe99c
TTN
938;;;; Searching
939
515357c2 940
94dbe99c
TTN
941(defun doc-view-search-internal (regexp file)
942 "Return a list of FILE's pages that contain text matching REGEXP.
1ca678aa
MC
943The value is an alist of the form (PAGE CONTEXTS) where PAGE is
944the pagenumber and CONTEXTS are all lines of text containing a match."
94dbe99c
TTN
945 (with-temp-buffer
946 (insert-file-contents file)
947 (let ((page 1)
1ca678aa
MC
948 (lastpage 1)
949 matches)
94dbe99c 950 (while (re-search-forward (concat "\\(?:\\([\f]\\)\\|\\("
1ca678aa 951 regexp "\\)\\)") nil t)
069b4ce3 952 (when (match-string 1) (setq page (1+ page)))
1ca678aa
MC
953 (when (match-string 2)
954 (if (/= page lastpage)
c17587fe 955 (push (cons page
515357c2
TH
956 (list (buffer-substring
957 (line-beginning-position)
958 (line-end-position))))
959 matches)
1ca678aa
MC
960 (setq matches (cons
961 (append
962 (or
963 ;; This page already is a match.
964 (car matches)
965 ;; This is the first match on page.
966 (list page))
967 (list (buffer-substring
968 (line-beginning-position)
969 (line-end-position))))
970 (cdr matches))))
971 (setq lastpage page)))
94dbe99c
TTN
972 (nreverse matches))))
973
974(defun doc-view-search-no-of-matches (list)
975 "Extract the number of matches from the search result LIST."
976 (let ((no 0))
977 (dolist (p list)
978 (setq no (+ no (1- (length p)))))
979 no))
980
7baca0fa
JL
981(defun doc-view-search-backward (new-query)
982 "Call `doc-view-search' for backward search.
983If prefix NEW-QUERY is given, ask for a new regexp."
984 (interactive "P")
da99b369 985 (doc-view-search new-query t))
7baca0fa
JL
986
987(defun doc-view-search (new-query &optional backward)
988 "Jump to the next match or initiate a new search if NEW-QUERY is given.
94dbe99c 989If the current document hasn't been transformed to plain text
7baca0fa
JL
990till now do that first.
991If BACKWARD is non-nil, jump to the previous match."
992 (interactive "P")
da99b369 993 (if (and (not new-query)
7baca0fa
JL
994 doc-view-current-search-matches)
995 (if backward
996 (doc-view-search-previous-match 1)
997 (doc-view-search-next-match 1))
998 ;; New search, so forget the old results.
999 (setq doc-view-current-search-matches nil)
1000 (let ((txt (expand-file-name "doc.txt"
1001 (doc-view-current-cache-dir))))
1002 (if (file-readable-p txt)
1003 (progn
1004 (setq doc-view-current-search-matches
1005 (doc-view-search-internal
1006 (read-from-minibuffer "Regexp: ")
1007 txt))
1008 (message "DocView: search yielded %d matches."
1009 (doc-view-search-no-of-matches
1010 doc-view-current-search-matches)))
1011 ;; We must convert to TXT first!
ec4853ab 1012 (if doc-view-current-converter-processes
7baca0fa 1013 (message "DocView: please wait till conversion finished.")
b4cb319f 1014 (doc-view-doc->txt txt (lambda () (doc-view-search nil))))))))
94dbe99c
TTN
1015
1016(defun doc-view-search-next-match (arg)
1017 "Go to the ARGth next matching page."
1018 (interactive "p")
937cb3fb 1019 (let* ((next-pages (doc-view-remove-if
de171465 1020 (lambda (i) (<= (car i) (doc-view-current-page)))
937cb3fb 1021 doc-view-current-search-matches))
1ca678aa 1022 (page (car (nth (1- arg) next-pages))))
94dbe99c 1023 (if page
1ca678aa 1024 (doc-view-goto-page page)
94dbe99c 1025 (when (and
1ca678aa
MC
1026 doc-view-current-search-matches
1027 (y-or-n-p "No more matches after current page. Wrap to first match? "))
1028 (doc-view-goto-page (caar doc-view-current-search-matches))))))
94dbe99c
TTN
1029
1030(defun doc-view-search-previous-match (arg)
1031 "Go to the ARGth previous matching page."
1032 (interactive "p")
937cb3fb 1033 (let* ((prev-pages (doc-view-remove-if
de171465 1034 (lambda (i) (>= (car i) (doc-view-current-page)))
937cb3fb 1035 doc-view-current-search-matches))
1ca678aa 1036 (page (car (nth (1- arg) (nreverse prev-pages)))))
94dbe99c 1037 (if page
1ca678aa 1038 (doc-view-goto-page page)
94dbe99c 1039 (when (and
1ca678aa
MC
1040 doc-view-current-search-matches
1041 (y-or-n-p "No more matches before current page. Wrap to last match? "))
1042 (doc-view-goto-page (caar (last doc-view-current-search-matches)))))))
94dbe99c 1043
640602f7 1044;;;; User interface commands and the mode
94dbe99c 1045
c17587fe
SM
1046;; (put 'doc-view-mode 'mode-class 'special)
1047
515357c2
TH
1048(defun doc-view-already-converted-p ()
1049 "Return non-nil if the current doc was already converted."
1050 (and (file-exists-p (doc-view-current-cache-dir))
1ecc9da7 1051 (> (length (directory-files (doc-view-current-cache-dir) nil "\\.png$")) 0)))
515357c2 1052
c17587fe
SM
1053(defun doc-view-initiate-display ()
1054 ;; Switch to image display if possible
322f4559 1055 (if (doc-view-mode-p doc-view-doc-type)
c17587fe
SM
1056 (progn
1057 (doc-view-buffer-message)
de171465 1058 (setf (doc-view-current-page) (or (doc-view-current-page) 1))
515357c2 1059 (if (doc-view-already-converted-p)
c17587fe
SM
1060 (progn
1061 (message "DocView: using cached files!")
cde4c3f1
TH
1062 ;; Load the saved resolution
1063 (let ((res-file (expand-file-name "resolution.el"
1064 (doc-view-current-cache-dir)))
1065 (res doc-view-resolution))
1066 (with-temp-buffer
1067 (when (file-exists-p res-file)
1068 (insert-file-contents res-file)
1069 (setq res (read (current-buffer)))))
1070 (when (numberp res)
1071 (set (make-local-variable 'doc-view-resolution) res)))
65073003 1072 (doc-view-display (current-buffer) 'force))
c17587fe
SM
1073 (doc-view-convert-current-doc))
1074 (message
1075 "%s"
1076 (substitute-command-keys
1077 (concat "Type \\[doc-view-toggle-display] to toggle between "
1078 "editing or viewing the document."))))
1079 (message
1080 "%s"
0855c2ca
CY
1081 (concat "No PNG support is available, or some conversion utility for "
1082 (file-name-extension doc-view-buffer-file-name)
1083 " files is missing."))
1084 (if (and (executable-find doc-view-pdftotext-program)
1085 (y-or-n-p
1086 "Unable to render file. View extracted text instead? "))
1087 (doc-view-open-text)
1088 (doc-view-toggle-display))))
94dbe99c 1089
e0385bf4 1090(defvar bookmark-make-record-function)
069b4ce3 1091
65073003
SM
1092(defun doc-view-clone-buffer-hook ()
1093 ;; FIXME: There are several potential problems linked with reconversion
1094 ;; and auto-revert when we have indirect buffers because they share their
1095 ;; /tmp cache directory. This sharing is good (you'd rather not reconvert
1096 ;; for each clone), but that means that clones need to collaborate a bit.
1097 ;; I guess it mostly means: detect when a reconversion process is already
1098 ;; running, and run the sentinel in all clones.
515357c2 1099 ;;
de171465 1100 ;; Maybe the clones should really have a separate /tmp directory
65073003
SM
1101 ;; so they could have a different resolution and you could use clones
1102 ;; for zooming.
de171465
SM
1103 (remove-overlays (point-min) (point-max) 'doc-view t)
1104 (if (consp image-mode-winprops-alist) (setq image-mode-winprops-alist nil)))
65073003 1105
eb79098b
SM
1106(defun doc-view-intersection (l1 l2)
1107 (let ((l ()))
1108 (dolist (x l1) (if (memq x l2) (push x l)))
1109 l))
1110
640602f7 1111;;;###autoload
937cb3fb 1112(defun doc-view-mode ()
640602f7 1113 "Major mode in DocView buffers.
06a21f70
TH
1114
1115DocView Mode is an Emacs document viewer. It displays PDF, PS
1116and DVI files (as PNG images) in Emacs buffers.
1117
640602f7 1118You can use \\<doc-view-mode-map>\\[doc-view-toggle-display] to
5c1f16b0
SM
1119toggle between displaying the document or editing it as text.
1120\\{doc-view-mode-map}"
937cb3fb 1121 (interactive)
f9adf05b 1122
96fe38a8 1123 (if (= (point-min) (point-max))
85699772 1124 ;; The doc is empty or doesn't exist at all, so fallback to
96fe38a8
SM
1125 ;; another mode. We used to also check file-exists-p, but this
1126 ;; returns nil for tar members.
85699772
TH
1127 (let ((auto-mode-alist (remq (rassq 'doc-view-mode auto-mode-alist)
1128 auto-mode-alist)))
1129 (normal-mode))
06a21f70
TH
1130
1131 (let* ((prev-major-mode (if (eq major-mode 'doc-view-mode)
1132 doc-view-previous-major-mode
1133 major-mode)))
1134 (kill-all-local-variables)
1135 (set (make-local-variable 'doc-view-previous-major-mode) prev-major-mode))
bc19637d 1136
06a21f70
TH
1137 ;; Figure out the document type.
1138 (let ((name-types
1139 (when buffer-file-name
1140 (cdr (assoc (file-name-extension buffer-file-name)
1141 '(("dvi" dvi)
1142 ("pdf" pdf)
1143 ("epdf" pdf)
1144 ("ps" ps)
1145 ("eps" ps))))))
1146 (content-types
1147 (save-excursion
1148 (goto-char (point-min))
1149 (cond
1150 ((looking-at "%!") '(ps))
1151 ((looking-at "%PDF") '(pdf))
1152 ((looking-at "\367\002") '(dvi))))))
1153 (set (make-local-variable 'doc-view-doc-type)
1154 (car (or (doc-view-intersection name-types content-types)
1155 (when (and name-types content-types)
1156 (error "Conflicting types: name says %s but content says %s"
1157 name-types content-types))
1158 name-types content-types
1159 (error "Cannot determine the document type")))))
bc19637d 1160
06a21f70
TH
1161 (doc-view-make-safe-dir doc-view-cache-directory)
1162 ;; Handle compressed files, remote files, files inside archives
1163 (set (make-local-variable 'doc-view-buffer-file-name)
1164 (cond
1165 (jka-compr-really-do-compress
1166 (expand-file-name
1167 (file-name-nondirectory
1168 (file-name-sans-extension buffer-file-name))
1169 doc-view-cache-directory))
1170 ;; Is the file readable by local processes?
1171 ;; We used to use `file-remote-p' but it's unclear what it's
1172 ;; supposed to return nil for things like local files accessed via
1173 ;; `su' or via file://...
1174 ((let ((file-name-handler-alist nil))
1175 (not (file-readable-p buffer-file-name)))
1176 (expand-file-name
1177 (file-name-nondirectory buffer-file-name)
1178 doc-view-cache-directory))
1179 (t buffer-file-name)))
1180 (when (not (string= doc-view-buffer-file-name buffer-file-name))
1181 (write-region nil nil doc-view-buffer-file-name))
bc19637d 1182
06a21f70
TH
1183 (add-hook 'change-major-mode-hook
1184 (lambda ()
1185 (doc-view-kill-proc)
1186 (remove-overlays (point-min) (point-max) 'doc-view t))
1187 nil t)
1188 (add-hook 'clone-indirect-buffer-hook 'doc-view-clone-buffer-hook nil t)
1189 (add-hook 'kill-buffer-hook 'doc-view-kill-proc nil t)
bc19637d 1190
06a21f70
TH
1191 (remove-overlays (point-min) (point-max) 'doc-view t) ;Just in case.
1192 ;; Keep track of display info ([vh]scroll, page number, overlay,
1193 ;; ...) for each window in which this document is shown.
1194 (add-hook 'image-mode-new-window-functions
1195 'doc-view-new-window-function nil t)
1196 (image-mode-setup-winprops)
bc19637d 1197
06a21f70
TH
1198 (set (make-local-variable 'mode-line-position)
1199 '(" P" (:eval (number-to-string (doc-view-current-page)))
1200 "/" (:eval (number-to-string (length doc-view-current-files)))))
1201 ;; Don't scroll unless the user specifically asked for it.
1202 (set (make-local-variable 'auto-hscroll-mode) nil)
1203 (set (make-local-variable 'cursor-type) nil)
1204 (use-local-map doc-view-mode-map)
1205 (set (make-local-variable 'after-revert-hook) 'doc-view-reconvert-doc)
1206 (set (make-local-variable 'bookmark-make-record-function)
1207 'doc-view-bookmark-make-record)
1208 (setq mode-name "DocView"
1209 buffer-read-only t
1210 major-mode 'doc-view-mode)
1211 (doc-view-initiate-display)
1212 (run-mode-hooks 'doc-view-mode-hook)))
937cb3fb
GM
1213
1214;;;###autoload
1215(define-minor-mode doc-view-minor-mode
1216 "Toggle Doc view minor mode.
1217With arg, turn Doc view minor mode on if arg is positive, off otherwise.
1218See the command `doc-view-mode' for more information on this mode."
1219 nil " DocView" doc-view-minor-mode-map
1220 :group 'doc-view
1221 (when doc-view-minor-mode
1222 (add-hook 'change-major-mode-hook (lambda () (doc-view-minor-mode -1)) nil t)
1223 (message
1224 "%s"
1225 (substitute-command-keys
1226 "Type \\[doc-view-toggle-display] to toggle between editing or viewing the document."))))
94dbe99c
TTN
1227
1228(defun doc-view-clear-cache ()
1229 "Delete the whole cache (`doc-view-cache-directory')."
1230 (interactive)
515357c2 1231 (dired-delete-file doc-view-cache-directory 'always))
94dbe99c
TTN
1232
1233(defun doc-view-dired-cache ()
1234 "Open `dired' in `doc-view-cache-directory'."
1235 (interactive)
1236 (dired doc-view-cache-directory))
1237
94dbe99c 1238
1666a6b3
TH
1239;;;; Bookmark integration
1240
c123f7fe
GM
1241(declare-function bookmark-make-record-default "bookmark"
1242 (&optional point-only))
a9f8b49b 1243(declare-function bookmark-prop-get "bookmark" (bookmark prop))
43f8b275 1244(declare-function bookmark-default-handler "bookmark" (bmk))
a9f8b49b 1245
32a091dd 1246(defun doc-view-bookmark-make-record ()
43f8b275
SM
1247 (nconc (bookmark-make-record-default)
1248 `((page . ,(doc-view-current-page))
1249 (handler . doc-view-bookmark-jump))))
1666a6b3 1250
069b4ce3 1251
1666a6b3
TH
1252;;;###autoload
1253(defun doc-view-bookmark-jump (bmk)
03e26a79 1254 ;; This implements the `handler' function interface for record type
e0385bf4 1255 ;; returned by `doc-view-bookmark-make-record', which see.
43f8b275
SM
1256 (prog1 (bookmark-default-handler bmk)
1257 (let ((page (bookmark-prop-get bmk 'page)))
1666a6b3 1258 (when (not (eq major-mode 'doc-view-mode))
43f8b275 1259 (doc-view-toggle-display))
a9f8b49b
SM
1260 (with-selected-window
1261 (or (get-buffer-window (current-buffer) 0)
1262 (selected-window))
43f8b275 1263 (doc-view-goto-page page)))))
1666a6b3 1264
069b4ce3
GM
1265
1266(provide 'doc-view)
1267
1268;; Local Variables:
1269;; mode: outline-minor
1270;; End:
1271
aab2236f 1272;; arch-tag: 5d6e5c5e-095f-489e-b4e4-1ca90a7d79be
94dbe99c 1273;;; doc-view.el ends here