(url-insert-file-contents): Set buffer-file-coding-system
[emacs.git] / lisp / url / url-handlers.el
blobe42f552c416492a4d6afd0a05d810f9c3617ef89
1 ;;; url-handlers.el --- file-name-handler stuff for URL loading
3 ;; Copyright (C) 1996-1999, 2004-2015 Free Software Foundation, Inc.
5 ;; Keywords: comm, data, processes, hypermedia
7 ;; This file is part of GNU Emacs.
8 ;;
9 ;; GNU Emacs is free software: you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation, either version 3 of the License, or
12 ;; (at your option) any later version.
14 ;; GNU Emacs is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 ;; GNU General Public License for more details.
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
22 ;;; Commentary:
24 ;;; Code:
26 ;; (require 'url)
27 (require 'url-parse)
28 ;; (require 'url-util)
29 (eval-when-compile (require 'mm-decode))
30 ;; (require 'mailcap)
31 ;; The following are autoloaded instead of `require'd to avoid eagerly
32 ;; loading all of URL when turning on url-handler-mode in the .emacs.
33 (autoload 'url-expand-file-name "url-expand" "Convert url to a fully specified url, and canonicalize it.")
34 (autoload 'mm-dissect-buffer "mm-decode" "Dissect the current buffer and return a list of MIME handles.")
35 (autoload 'url-scheme-get-property "url-methods" "Get property of a URL SCHEME.")
37 ;; Always used after mm-dissect-buffer and defined in the same file.
38 (declare-function mm-save-part-to-file "mm-decode" (handle file))
39 (declare-function mm-destroy-parts "mm-decode" (handles))
40 ;; mm-decode loads mm-bodies.
41 (declare-function mm-decode-string "mm-bodies" (string charset))
42 ;; mm-decode loads mail-parse.
43 (declare-function mail-content-type-get "mail-parse" (ct attribute))
45 ;; Implementation status
46 ;; ---------------------
47 ;; Function Status
48 ;; ------------------------------------------------------------
49 ;; add-name-to-file Needs DAV Bindings
50 ;; copy-file Broken (assumes 1st item is URL)
51 ;; delete-directory Finished (DAV)
52 ;; delete-file Finished (DAV)
53 ;; diff-latest-backup-file
54 ;; directory-file-name unnecessary (what about VMS)?
55 ;; directory-files Finished (DAV)
56 ;; dired-call-process
57 ;; dired-compress-file
58 ;; dired-uncache
59 ;; expand-file-name Finished
60 ;; file-accessible-directory-p
61 ;; file-attributes Finished, better with DAV
62 ;; file-directory-p Needs DAV, finished
63 ;; file-executable-p Finished
64 ;; file-exists-p Finished
65 ;; file-local-copy
66 ;; file-modes
67 ;; file-name-all-completions Finished (DAV)
68 ;; file-name-as-directory
69 ;; file-name-completion Finished (DAV)
70 ;; file-name-directory
71 ;; file-name-nondirectory
72 ;; file-name-sans-versions why?
73 ;; file-newer-than-file-p
74 ;; file-ownership-preserved-p No way to know
75 ;; file-readable-p Finished
76 ;; file-regular-p !directory_p
77 ;; file-remote-p Finished
78 ;; file-symlink-p Needs DAV bindings
79 ;; file-truename Needs DAV bindings
80 ;; file-writable-p Check for LOCK?
81 ;; find-backup-file-name why?
82 ;; get-file-buffer why?
83 ;; insert-directory Use DAV
84 ;; insert-file-contents Finished
85 ;; load
86 ;; make-directory Finished (DAV)
87 ;; make-symbolic-link Needs DAV bindings
88 ;; rename-file Finished (DAV)
89 ;; set-file-modes Use mod_dav specific executable flag?
90 ;; set-visited-file-modtime Impossible?
91 ;; shell-command Impossible?
92 ;; unhandled-file-name-directory
93 ;; vc-registered Finished (DAV)
94 ;; verify-visited-file-modtime
95 ;; write-region
97 (defvar url-handler-regexp) ; defined below to avoid recursive load (revno:108572)
99 ;;;###autoload
100 (define-minor-mode url-handler-mode
101 "Toggle using `url' library for URL filenames (URL Handler mode).
102 With a prefix argument ARG, enable URL Handler mode if ARG is
103 positive, and disable it otherwise. If called from Lisp, enable
104 the mode if ARG is omitted or nil."
105 :global t :group 'url
106 ;; Remove old entry, if any.
107 (setq file-name-handler-alist
108 (delq (rassq 'url-file-handler file-name-handler-alist)
109 file-name-handler-alist))
110 (if url-handler-mode
111 (push (cons url-handler-regexp 'url-file-handler)
112 file-name-handler-alist)))
114 (defcustom url-handler-regexp "\\`\\(https?\\|ftp\\|file\\|nfs\\)://"
115 "Regular expression for URLs handled by `url-handler-mode'.
116 When URL Handler mode is enabled, this regular expression is
117 added to `file-name-handler-alist'.
119 Some valid URL protocols just do not make sense to visit
120 interactively \(about, data, info, irc, mailto, etc\). This
121 regular expression avoids conflicts with local files that look
122 like URLs \(Gnus is particularly bad at this\)."
123 :group 'url
124 :type 'regexp
125 :set (lambda (symbol value)
126 (let ((enable url-handler-mode))
127 (url-handler-mode 0)
128 (set-default symbol value)
129 (if enable
130 (url-handler-mode)))))
132 (defun url-run-real-handler (operation args)
133 (let ((inhibit-file-name-handlers (cons 'url-file-handler
134 (if (eq operation inhibit-file-name-operation)
135 inhibit-file-name-handlers)))
136 (inhibit-file-name-operation operation))
137 (apply operation args)))
139 (defvar url-file-handler-load-in-progress nil
140 "Check for recursive load.")
142 ;;;###autoload
143 (defun url-file-handler (operation &rest args)
144 "Function called from the `file-name-handler-alist' routines.
145 OPERATION is what needs to be done (`file-exists-p', etc). ARGS are
146 the arguments that would have been passed to OPERATION."
147 ;; Avoid recursive load.
148 (if (and load-in-progress url-file-handler-load-in-progress)
149 (url-run-real-handler operation args)
150 (let ((url-file-handler-load-in-progress load-in-progress)
151 (fn (get operation 'url-file-handlers))
152 (val nil)
153 (hooked nil))
154 (if (and (not fn) (intern-soft (format "url-%s" operation))
155 (fboundp (intern-soft (format "url-%s" operation))))
156 (error "Missing URL handler mapping for %s" operation))
157 (if fn
158 (setq hooked t
159 val (save-match-data (apply fn args)))
160 (setq hooked nil
161 val (url-run-real-handler operation args)))
162 (url-debug 'handlers "%s %S%S => %S" (if hooked "Hooked" "Real")
163 operation args val)
164 val)))
166 (defun url-file-handler-identity (&rest args)
167 ;; Identity function
168 (car args))
170 ;; These are operations that we can fully support
171 (put 'file-readable-p 'url-file-handlers 'url-file-exists-p)
172 (put 'substitute-in-file-name 'url-file-handlers 'url-file-handler-identity)
173 (put 'file-name-absolute-p 'url-file-handlers (lambda (&rest ignored) t))
174 (put 'expand-file-name 'url-file-handlers 'url-handler-expand-file-name)
175 (put 'directory-file-name 'url-file-handlers 'url-handler-directory-file-name)
176 (put 'unhandled-file-name-directory 'url-file-handlers 'url-handler-unhandled-file-name-directory)
177 (put 'file-remote-p 'url-file-handlers 'url-handler-file-remote-p)
178 ;; (put 'file-name-as-directory 'url-file-handlers 'url-handler-file-name-as-directory)
180 ;; These are operations that we do not support yet (DAV!!!)
181 (put 'file-writable-p 'url-file-handlers 'ignore)
182 (put 'file-symlink-p 'url-file-handlers 'ignore)
183 ;; Just like for ange-ftp: let's not waste time trying to look for RCS/foo,v
184 ;; files and such since we can't do anything clever with them anyway.
185 (put 'vc-registered 'url-file-handlers 'ignore)
187 (defun url-handler-expand-file-name (file &optional base)
188 ;; When we see "/foo/bar" in a file whose working dir is "http://bla/bla",
189 ;; there are two interpretations possible: either it's a local "/foo/bar"
190 ;; or it's "http:/bla/foo/bar". When working with URLs, the second
191 ;; interpretation is the right one, but when working with Emacs file
192 ;; names, the first is preferred.
193 (if (file-name-absolute-p file)
194 (expand-file-name file "/")
195 (url-expand-file-name file base)))
197 ;; directory-file-name and file-name-as-directory are kind of hard to
198 ;; implement really right for URLs since URLs can have repeated / chars.
199 ;; We'd want the following behavior:
200 ;; idempotence: (d-f-n (d-f-n X) == (d-f-n X)
201 ;; idempotence: (f-n-a-d (f-n-a-d X) == (f-n-a-d X)
202 ;; reversible: (d-f-n (f-n-a-d (d-f-n X))) == (d-f-n X)
203 ;; reversible: (f-n-a-d (d-f-n (f-n-a-d X))) == (f-n-a-d X)
204 (defun url-handler-directory-file-name (dir)
205 ;; When there's more than a single /, just don't touch the slashes at all.
206 (if (string-match "//\\'" dir) dir
207 (url-run-real-handler 'directory-file-name (list dir))))
209 (defun url-handler-unhandled-file-name-directory (filename)
210 (let ((url (url-generic-parse-url filename)))
211 (if (equal (url-type url) "file")
212 ;; `file' URLs are actually local. The filename part may be ""
213 ;; which really stands for "/".
214 ;; FIXME: maybe we should check that the host part is "" or "localhost"
215 ;; or some name that represents the local host?
216 (or (file-name-directory (url-filename url)) "/")
217 ;; All other URLs are not expected to be directly accessible from
218 ;; a local process.
219 nil)))
221 (defun url-handler-file-remote-p (filename &optional identification connected)
222 (let ((url (url-generic-parse-url filename)))
223 (if (and (url-type url) (not (equal (url-type url) "file")))
224 ;; Maybe we can find a suitable check for CONNECTED. For now,
225 ;; we ignore it.
226 (cond
227 ((eq identification 'method) (url-type url))
228 ((eq identification 'user) (url-user url))
229 ((eq identification 'host) (url-host url))
230 ((eq identification 'localname) (url-filename url))
231 (t (url-recreate-url
232 (url-parse-make-urlobj (url-type url) (url-user url) nil
233 (url-host url) (url-port url)))))
234 ;; If there is no URL type, or it is a "file://" URL, the
235 ;; filename is expected to be non remote. A more subtle check
236 ;; for "file://" URLs could be applied, as said in
237 ;; `url-handler-unhandled-file-name-directory'.
238 nil)))
240 ;; The actual implementation
241 ;;;###autoload
242 (defun url-copy-file (url newname &optional ok-if-already-exists
243 keep-time preserve-uid-gid)
244 "Copy URL to NEWNAME. Both args must be strings.
245 Signals a `file-already-exists' error if file NEWNAME already exists,
246 unless a third argument OK-IF-ALREADY-EXISTS is supplied and non-nil.
247 A number as third arg means request confirmation if NEWNAME already exists.
248 This is what happens in interactive use with M-x.
249 Fourth arg KEEP-TIME non-nil means give the new file the same
250 last-modified time as the old one. (This works on only some systems.)
251 Fifth arg PRESERVE-UID-GID is ignored.
252 A prefix arg makes KEEP-TIME non-nil."
253 (if (and (file-exists-p newname)
254 (not ok-if-already-exists))
255 (error "Opening output file: File already exists, %s" newname))
256 (let ((buffer (url-retrieve-synchronously url))
257 (handle nil))
258 (if (not buffer)
259 (error "Opening input file: No such file or directory, %s" url))
260 (with-current-buffer buffer
261 (setq handle (mm-dissect-buffer t)))
262 (mm-save-part-to-file handle newname)
263 (kill-buffer buffer)
264 (mm-destroy-parts handle)))
265 (put 'copy-file 'url-file-handlers 'url-copy-file)
267 ;;;###autoload
268 (defun url-file-local-copy (url &rest ignored)
269 "Copy URL into a temporary file on this machine.
270 Returns the name of the local copy, or nil, if FILE is directly
271 accessible."
272 (let ((filename (make-temp-file "url")))
273 (url-copy-file url filename 'ok-if-already-exists)
274 filename))
275 (put 'file-local-copy 'url-file-handlers 'url-file-local-copy)
277 (defun url-insert (buffer &optional beg end)
278 "Insert the body of a URL object.
279 BUFFER should be a complete URL buffer as returned by `url-retrieve'.
280 If the headers specify a coding-system, it is applied to the body before it is inserted.
281 Returns a list of the form (SIZE CHARSET), where SIZE is the size in bytes
282 of the inserted text and CHARSET is the charset that was specified in the header,
283 or nil if none was found.
284 BEG and END can be used to only insert a subpart of the body.
285 They count bytes from the beginning of the body."
286 (let* ((handle (with-current-buffer buffer (mm-dissect-buffer t)))
287 (data (with-current-buffer (mm-handle-buffer handle)
288 (if beg
289 (buffer-substring (+ (point-min) beg)
290 (if end (+ (point-min) end) (point-max)))
291 (buffer-string))))
292 (charset (mail-content-type-get (mm-handle-type handle)
293 'charset)))
294 (mm-destroy-parts handle)
295 (if charset
296 (insert (mm-decode-string data (mm-charset-to-coding-system charset)))
297 (insert data))
298 (list (length data) charset)))
300 (defvar url-http-codes)
302 ;;;###autoload
303 (defun url-insert-file-contents (url &optional visit beg end replace)
304 (let ((buffer (url-retrieve-synchronously url)))
305 (unless buffer (signal 'file-error (list url "No Data")))
306 (with-current-buffer buffer
307 ;; XXX: This is HTTP/S specific and should be moved to url-http
308 ;; instead. See http://debbugs.gnu.org/17549.
309 (when (bound-and-true-p url-http-response-status)
310 (unless (and (>= url-http-response-status 200)
311 (< url-http-response-status 300))
312 (let ((desc (nth 2 (assq url-http-response-status url-http-codes))))
313 (kill-buffer buffer)
314 ;; Signal file-error per http://debbugs.gnu.org/16733.
315 (signal 'file-error (list url desc))))))
316 (if visit (setq buffer-file-name url))
317 (save-excursion
318 (let* ((start (point))
319 (size-and-charset (url-insert buffer beg end)))
320 (kill-buffer buffer)
321 (when replace
322 (delete-region (point-min) start)
323 (delete-region (point) (point-max)))
324 (unless (cadr size-and-charset)
325 ;; If the headers don't specify any particular charset, use the
326 ;; usual heuristic/rules that we apply to files.
327 (decode-coding-inserted-region start (point) url
328 visit beg end replace))
329 (let ((inserted (car size-and-charset)))
330 (when (fboundp 'after-insert-file-set-coding)
331 (let ((insval (after-insert-file-set-coding inserted visit)))
332 (if insval (setq inserted insval))))
333 (list url inserted))))))
335 (put 'insert-file-contents 'url-file-handlers 'url-insert-file-contents)
337 (defun url-file-name-completion (url directory &optional predicate)
338 ;; Even if it's not implemented, it's not an error to ask for completion,
339 ;; in case it's available (bug#14806).
340 ;; (error "Unimplemented")
341 url)
342 (put 'file-name-completion 'url-file-handlers 'url-file-name-completion)
344 (defun url-file-name-all-completions (file directory)
345 ;; Even if it's not implemented, it's not an error to ask for completion,
346 ;; in case it's available (bug#14806).
347 ;; (error "Unimplemented")
348 nil)
349 (put 'file-name-all-completions
350 'url-file-handlers 'url-file-name-all-completions)
352 ;; All other handlers map onto their respective backends.
353 (defmacro url-handlers-create-wrapper (method args)
354 `(progn
355 (defun ,(intern (format "url-%s" method)) ,args
356 ,(format "URL file-name-handler wrapper for `%s' call.\n---\n%s" method
357 (or (documentation method t) "No original documentation."))
358 (setq url (url-generic-parse-url url))
359 (when (url-type url)
360 (funcall (url-scheme-get-property (url-type url) (quote ,method))
361 ,@(remove '&rest (remove '&optional args)))))
362 (unless (get ',method 'url-file-handlers)
363 (put ',method 'url-file-handlers ',(intern (format "url-%s" method))))))
365 (url-handlers-create-wrapper file-exists-p (url))
366 (url-handlers-create-wrapper file-attributes (url &optional id-format))
367 (url-handlers-create-wrapper file-symlink-p (url))
368 (url-handlers-create-wrapper file-writable-p (url))
369 (url-handlers-create-wrapper file-directory-p (url))
370 (url-handlers-create-wrapper file-executable-p (url))
371 (url-handlers-create-wrapper directory-files (url &optional full match nosort))
372 (url-handlers-create-wrapper file-truename (url &optional counter prev-dirs))
374 (add-hook 'find-file-hook 'url-handlers-set-buffer-mode)
376 (defun url-handlers-set-buffer-mode ()
377 "Set correct modes for the current buffer if visiting a remote file."
378 (and (stringp buffer-file-name)
379 (string-match url-handler-regexp buffer-file-name)
380 (auto-save-mode 0)))
382 (provide 'url-handlers)
384 ;;; url-handlers.el ends here