开发者

Download a File with Emacs Lisp

Does elisp have a function that takes a url and a destination and downloads that开发者_如何学运维 url off the internet?

I've discovered url-retrieve and url-retrieve-synchronously but url-retrieve takes a callback and url-retrieve-synchronously puts everything into a buffer. Is there anything simpler?


Try url-copy-file. Its description reads,

url-copy-file is an autoloaded Lisp function in `url-handlers.el'.

(url-copy-file url newname &optional ok-if-already-exists keep-time)

Copy url to newname. Both args must be strings. Signals a `file-already-exists' error if file newname already exists, unless a third argument ok-if-already-exists is supplied and non-nil. A number as third arg means request confirmation if newname already exists. This is what happens in interactive use with M-x. Fourth arg keep-time non-nil means give the new file the same last-modified time as the old one. (This works on only some systems.) A prefix arg makes keep-time non-nil.


Obviously url-copy-file is the best option, but to the more adventurous Emacs hackers I'd suggest something like this:

(require 'url)

(defun download-file (&optional url download-dir download-name)
  (interactive)
  (let ((url (or url
                 (read-string "Enter download URL: "))))
    (let ((download-buffer (url-retrieve-synchronously url)))
      (save-excursion
        (set-buffer download-buffer)
        ;; we may have to trim the http response
        (goto-char (point-min))
        (re-search-forward "^$" nil 'move)
        (forward-char)
        (delete-region (point-min) (point))
        (write-file (concat (or download-dir
                                "~/downloads/")
                            (or download-name
                                (car (last (split-string url "/" t))))))))))


(w3m-download "http://www.gnu.org/index.html")


http://steloflute.tistory.com/entry/Emacs-Lisp-urlretrieve

; synchronously    
(defun get-url (url)
  (with-current-buffer (url-retrieve-synchronously url) (buffer-string)))

(print (get-url "http://www.gnu.org"))

; asynchronously    
(defun print-url (url)
  (url-retrieve url (lambda (a) (print a))))

(print-url "http://www.gnu.org")

Retrieving URLs | http://www.gnu.org/software/emacs/manual/html_node/url/Retrieving-URLs.html

Current Buffer | http://www.gnu.org/software/emacs/manual/html_node/elisp/Current-Buffer.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜