doc-view.el 61 KB

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