More CL cleanups and reduction of use of cl.el.
[emacs.git] / lisp / url / url-util.el
blob2faca26f2dd22eb64f350ee058b7ee4b79a1431f
1 ;;; url-util.el --- Miscellaneous helper routines for URL library
3 ;; Copyright (C) 1996-1999, 2001, 2004-2012 Free Software Foundation, Inc.
5 ;; Author: Bill Perry <wmperry@gnu.org>
6 ;; Keywords: comm, data, processes
8 ;; This file is part of GNU Emacs.
9 ;;
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
23 ;;; Commentary:
25 ;;; Code:
27 (require 'url-parse)
28 (require 'url-vars)
29 (autoload 'timezone-parse-date "timezone")
30 (autoload 'timezone-make-date-arpa-standard "timezone")
31 (autoload 'mail-header-extract "mailheader")
33 (defvar url-parse-args-syntax-table
34 (copy-syntax-table emacs-lisp-mode-syntax-table)
35 "A syntax table for parsing sgml attributes.")
37 (modify-syntax-entry ?' "\"" url-parse-args-syntax-table)
38 (modify-syntax-entry ?` "\"" url-parse-args-syntax-table)
39 (modify-syntax-entry ?{ "(" url-parse-args-syntax-table)
40 (modify-syntax-entry ?} ")" url-parse-args-syntax-table)
42 ;;;###autoload
43 (defcustom url-debug nil
44 "What types of debug messages from the URL library to show.
45 Debug messages are logged to the *URL-DEBUG* buffer.
47 If t, all messages will be logged.
48 If a number, all messages will be logged, as well shown via `message'.
49 If a list, it is a list of the types of messages to be logged."
50 :type '(choice (const :tag "none" nil)
51 (const :tag "all" t)
52 (checklist :tag "custom"
53 (const :tag "HTTP" :value http)
54 (const :tag "DAV" :value dav)
55 (const :tag "General" :value retrieval)
56 (const :tag "Filename handlers" :value handlers)
57 (symbol :tag "Other")))
58 :group 'url-hairy)
60 ;;;###autoload
61 (defun url-debug (tag &rest args)
62 (if quit-flag
63 (error "Interrupted!"))
64 (if (or (eq url-debug t)
65 (numberp url-debug)
66 (and (listp url-debug) (memq tag url-debug)))
67 (with-current-buffer (get-buffer-create "*URL-DEBUG*")
68 (goto-char (point-max))
69 (insert (symbol-name tag) " -> " (apply 'format args) "\n")
70 (if (numberp url-debug)
71 (apply 'message args)))))
73 ;;;###autoload
74 (defun url-parse-args (str &optional nodowncase)
75 ;; Return an assoc list of attribute/value pairs from an RFC822-type string
76 (let (
77 name ; From name=
78 value ; its value
79 results ; Assoc list of results
80 name-pos ; Start of XXXX= position
81 val-pos ; Start of value position
85 (save-excursion
86 (save-restriction
87 (set-buffer (get-buffer-create " *urlparse-temp*"))
88 (set-syntax-table url-parse-args-syntax-table)
89 (erase-buffer)
90 (insert str)
91 (setq st (point-min)
92 nd (point-max))
93 (set-syntax-table url-parse-args-syntax-table)
94 (narrow-to-region st nd)
95 (goto-char (point-min))
96 (while (not (eobp))
97 (skip-chars-forward "; \n\t")
98 (setq name-pos (point))
99 (skip-chars-forward "^ \n\t=;")
100 (if (not nodowncase)
101 (downcase-region name-pos (point)))
102 (setq name (buffer-substring name-pos (point)))
103 (skip-chars-forward " \t\n")
104 (if (/= (or (char-after (point)) 0) ?=) ; There is no value
105 (setq value nil)
106 (skip-chars-forward " \t\n=")
107 (setq val-pos (point)
108 value
109 (cond
110 ((or (= (or (char-after val-pos) 0) ?\")
111 (= (or (char-after val-pos) 0) ?'))
112 (buffer-substring (1+ val-pos)
113 (condition-case ()
114 (prog2
115 (forward-sexp 1)
116 (1- (point))
117 (skip-chars-forward "\""))
118 (error
119 (skip-chars-forward "^ \t\n")
120 (point)))))
122 (buffer-substring val-pos
123 (progn
124 (skip-chars-forward "^;")
125 (skip-chars-backward " \t")
126 (point)))))))
127 (setq results (cons (cons name value) results))
128 (skip-chars-forward "; \n\t"))
129 results))))
131 ;;;###autoload
132 (defun url-insert-entities-in-string (string)
133 "Convert HTML markup-start characters to entity references in STRING.
134 Also replaces the \" character, so that the result may be safely used as
135 an attribute value in a tag. Returns a new string with the result of the
136 conversion. Replaces these characters as follows:
137 & ==> &amp;
138 < ==> &lt;
139 > ==> &gt;
140 \" ==> &quot;"
141 (if (string-match "[&<>\"]" string)
142 (with-current-buffer (get-buffer-create " *entity*")
143 (erase-buffer)
144 (buffer-disable-undo (current-buffer))
145 (insert string)
146 (goto-char (point-min))
147 (while (progn
148 (skip-chars-forward "^&<>\"")
149 (not (eobp)))
150 (insert (cdr (assq (char-after (point))
151 '((?\" . "&quot;")
152 (?& . "&amp;")
153 (?< . "&lt;")
154 (?> . "&gt;")))))
155 (delete-char 1))
156 (buffer-string))
157 string))
159 ;;;###autoload
160 (defun url-normalize-url (url)
161 "Return a 'normalized' version of URL.
162 Strips out default port numbers, etc."
163 (let (type data retval)
164 (setq data (url-generic-parse-url url)
165 type (url-type data))
166 (if (member type '("www" "about" "mailto" "info"))
167 (setq retval url)
168 ;; FIXME all this does, and all this function seems to do in
169 ;; most cases, is remove any trailing "#anchor" part of a url.
170 (setf (url-target data) nil)
171 (setq retval (url-recreate-url data)))
172 retval))
174 ;;;###autoload
175 (defun url-lazy-message (&rest args)
176 "Just like `message', but is a no-op if called more than once a second.
177 Will not do anything if `url-show-status' is nil."
178 (if (or (and url-current-object
179 (url-silent url-current-object))
180 (null url-show-status)
181 (active-minibuffer-window)
182 (= url-lazy-message-time
183 (setq url-lazy-message-time (nth 1 (current-time)))))
185 (apply 'message args)))
187 ;;;###autoload
188 (defun url-get-normalized-date (&optional specified-time)
189 "Return a 'real' date string that most HTTP servers can understand."
190 (let ((system-time-locale "C"))
191 (format-time-string "%a, %d %b %Y %T GMT"
192 (or specified-time (current-time)) t)))
194 ;;;###autoload
195 (defun url-eat-trailing-space (x)
196 "Remove spaces/tabs at the end of a string."
197 (let ((y (1- (length x)))
198 (skip-chars (list ? ?\t ?\n)))
199 (while (and (>= y 0) (memq (aref x y) skip-chars))
200 (setq y (1- y)))
201 (substring x 0 (1+ y))))
203 ;;;###autoload
204 (defun url-strip-leading-spaces (x)
205 "Remove spaces at the front of a string."
206 (let ((y (1- (length x)))
207 (z 0)
208 (skip-chars (list ? ?\t ?\n)))
209 (while (and (<= z y) (memq (aref x z) skip-chars))
210 (setq z (1+ z)))
211 (substring x z nil)))
213 ;;;###autoload
214 (defun url-pretty-length (n)
215 (cond
216 ((< n 1024)
217 (format "%d bytes" n))
218 ((< n (* 1024 1024))
219 (format "%dk" (/ n 1024.0)))
221 (format "%2.2fM" (/ n (* 1024 1024.0))))))
223 ;;;###autoload
224 (defun url-display-percentage (fmt perc &rest args)
225 (when (and url-show-status
226 (or (null url-current-object)
227 (not (url-silent url-current-object))))
228 (if (null fmt)
229 (if (fboundp 'clear-progress-display)
230 (clear-progress-display))
231 (if (and (fboundp 'progress-display) perc)
232 (apply 'progress-display fmt perc args)
233 (apply 'message fmt args)))))
235 ;;;###autoload
236 (defun url-percentage (x y)
237 (if (fboundp 'float)
238 (round (* 100 (/ x (float y))))
239 (/ (* x 100) y)))
241 ;;;###autoload
242 (defalias 'url-basepath 'url-file-directory)
244 ;;;###autoload
245 (defun url-file-directory (file)
246 "Return the directory part of FILE, for a URL."
247 (cond
248 ((null file) "")
249 ((string-match "\\?" file)
250 (file-name-directory (substring file 0 (match-beginning 0))))
251 (t (file-name-directory file))))
253 ;;;###autoload
254 (defun url-file-nondirectory (file)
255 "Return the nondirectory part of FILE, for a URL."
256 (cond
257 ((null file) "")
258 ((string-match "\\?" file)
259 (file-name-nondirectory (substring file 0 (match-beginning 0))))
260 (t (file-name-nondirectory file))))
262 ;;;###autoload
263 (defun url-parse-query-string (query &optional downcase allow-newlines)
264 (let (retval pairs cur key val)
265 (setq pairs (split-string query "[;&]"))
266 (while pairs
267 (setq cur (car pairs)
268 pairs (cdr pairs))
269 (unless (string-match "=" cur)
270 (setq cur (concat cur "=")))
272 (when (string-match "=" cur)
273 (setq key (url-unhex-string (substring cur 0 (match-beginning 0))
274 allow-newlines))
275 (setq val (url-unhex-string (substring cur (match-end 0) nil)
276 allow-newlines))
277 (if downcase
278 (setq key (downcase key)))
279 (setq cur (assoc key retval))
280 (if cur
281 (setcdr cur (cons val (cdr cur)))
282 (setq retval (cons (list key val) retval)))))
283 retval))
285 ;;;###autoload
286 (defun url-build-query-string (query &optional semicolons keep-empty)
287 "Build a query-string.
289 Given a QUERY in the form:
290 '((key1 val1)
291 (key2 val2)
292 (key3 val1 val2)
293 (key4)
294 (key5 ""))
296 \(This is the same format as produced by `url-parse-query-string')
298 This will return a string
299 \"key1=val1&key2=val2&key3=val1&key3=val2&key4&key5\". Keys may
300 be strings or symbols; if they are symbols, the symbol name will
301 be used.
303 When SEMICOLONS is given, the separator will be \";\".
305 When KEEP-EMPTY is given, empty values will show as \"key=\"
306 instead of just \"key\" as in the example above."
307 (mapconcat
308 (lambda (key-vals)
309 (let ((escaped
310 (mapcar (lambda (sym)
311 (url-hexify-string (format "%s" sym))) key-vals)))
312 (mapconcat (lambda (val)
313 (let ((vprint (format "%s" val))
314 (eprint (format "%s" (car escaped))))
315 (concat eprint
316 (if (or keep-empty
317 (and val (not (zerop (length vprint)))))
320 vprint)))
321 (or (cdr escaped) '("")) (if semicolons ";" "&"))))
322 query (if semicolons ";" "&")))
324 (defun url-unhex (x)
325 (if (> x ?9)
326 (if (>= x ?a)
327 (+ 10 (- x ?a))
328 (+ 10 (- x ?A)))
329 (- x ?0)))
331 ;; Fixme: Is this definition better, and does it ever matter?
333 ;; (defun url-unhex-string (str &optional allow-newlines)
334 ;; "Remove %XX, embedded spaces, etc in a url.
335 ;; If optional second argument ALLOW-NEWLINES is non-nil, then allow the
336 ;; decoding of carriage returns and line feeds in the string, which is normally
337 ;; forbidden in URL encoding."
338 ;; (setq str (or str ""))
339 ;; (setq str (replace-regexp-in-string "%[[:xdigit:]]\\{2\\}"
340 ;; (lambda (match)
341 ;; (string (string-to-number
342 ;; (substring match 1) 16)))
343 ;; str t t))
344 ;; (if allow-newlines
345 ;; (replace-regexp-in-string "[\n\r]" (lambda (match)
346 ;; (format "%%%.2X" (aref match 0)))
347 ;; str t t)
348 ;; str))
350 ;;;###autoload
351 (defun url-unhex-string (str &optional allow-newlines)
352 "Remove %XX embedded spaces, etc in a URL.
353 If optional second argument ALLOW-NEWLINES is non-nil, then allow the
354 decoding of carriage returns and line feeds in the string, which is normally
355 forbidden in URL encoding."
356 (setq str (or str ""))
357 (let ((tmp "")
358 (case-fold-search t))
359 (while (string-match "%[0-9a-f][0-9a-f]" str)
360 (let* ((start (match-beginning 0))
361 (ch1 (url-unhex (elt str (+ start 1))))
362 (code (+ (* 16 ch1)
363 (url-unhex (elt str (+ start 2))))))
364 (setq tmp (concat
365 tmp (substring str 0 start)
366 (cond
367 (allow-newlines
368 (byte-to-string code))
369 ((or (= code ?\n) (= code ?\r))
370 " ")
371 (t (byte-to-string code))))
372 str (substring str (match-end 0)))))
373 (concat tmp str)))
375 (defconst url-unreserved-chars
376 '(?a ?b ?c ?d ?e ?f ?g ?h ?i ?j ?k ?l ?m ?n ?o ?p ?q ?r ?s ?t ?u ?v ?w ?x ?y ?z
377 ?A ?B ?C ?D ?E ?F ?G ?H ?I ?J ?K ?L ?M ?N ?O ?P ?Q ?R ?S ?T ?U ?V ?W ?X ?Y ?Z
378 ?0 ?1 ?2 ?3 ?4 ?5 ?6 ?7 ?8 ?9
379 ?- ?_ ?. ?~)
380 "List of characters that are unreserved in the URL spec.
381 This is taken from RFC 3986 (section 2.3).")
383 (defconst url-encoding-table
384 (let ((vec (make-vector 256 nil)))
385 (dotimes (byte 256)
386 ;; RFC 3986 (Section 2.1): For consistency, URI producers and
387 ;; normalizers should use uppercase hexadecimal digits for all
388 ;; percent-encodings.
389 (aset vec byte (format "%%%02X" byte)))
390 vec)
391 "Vector translating bytes to URI-encoded %-sequences.")
393 (defun url--allowed-chars (char-list)
394 "Return an \"allowed character\" mask (a 256-slot vector).
395 The Nth element is non-nil if character N is in CHAR-LIST. The
396 result can be passed as the second arg to `url-hexify-string'."
397 (let ((vec (make-vector 256 nil)))
398 (dolist (byte char-list)
399 (ignore-errors (aset vec byte t)))
400 vec))
402 ;;;###autoload
403 (defun url-hexify-string (string &optional allowed-chars)
404 "URI-encode STRING and return the result.
405 If STRING is multibyte, it is first converted to a utf-8 byte
406 string. Each byte corresponding to an allowed character is left
407 as-is, while all other bytes are converted to a three-character
408 string: \"%\" followed by two upper-case hex digits.
410 The allowed characters are specified by ALLOWED-CHARS. If this
411 argument is nil, the list `url-unreserved-chars' determines the
412 allowed characters. Otherwise, ALLOWED-CHARS should be a vector
413 whose Nth element is non-nil if character N is allowed."
414 (unless allowed-chars
415 (setq allowed-chars (url--allowed-chars url-unreserved-chars)))
416 (mapconcat (lambda (byte)
417 (if (aref allowed-chars byte)
418 (char-to-string byte)
419 (aref url-encoding-table byte)))
420 (if (multibyte-string-p string)
421 (encode-coding-string string 'utf-8)
422 string)
423 ""))
425 (defconst url-host-allowed-chars
426 ;; Allow % to avoid re-encoding %-encoded sequences.
427 (url--allowed-chars (append '(?% ?! ?$ ?& ?' ?\( ?\) ?* ?+ ?, ?\; ?=)
428 url-unreserved-chars))
429 "Allowed-character byte mask for the host segment of a URI.
430 These characters are specified in RFC 3986, Appendix A.")
432 (defconst url-path-allowed-chars
433 (let ((vec (copy-sequence url-host-allowed-chars)))
434 (aset vec ?/ t)
435 (aset vec ?: t)
436 (aset vec ?@ t)
437 vec)
438 "Allowed-character byte mask for the path segment of a URI.
439 These characters are specified in RFC 3986, Appendix A.")
441 (defconst url-query-allowed-chars
442 (let ((vec (copy-sequence url-path-allowed-chars)))
443 (aset vec ?? t)
444 vec)
445 "Allowed-character byte mask for the query segment of a URI.
446 These characters are specified in RFC 3986, Appendix A.")
448 ;;;###autoload
449 (defun url-encode-url (url)
450 "Return a properly URI-encoded version of URL.
451 This function also performs URI normalization, e.g. converting
452 the scheme to lowercase if it is uppercase. Apart from
453 normalization, if URL is already URI-encoded, this function
454 should return it unchanged."
455 (if (multibyte-string-p url)
456 (setq url (encode-coding-string url 'utf-8)))
457 (let* ((obj (url-generic-parse-url url))
458 (user (url-user obj))
459 (pass (url-password obj))
460 (host (url-host obj))
461 (path-and-query (url-path-and-query obj))
462 (path (car path-and-query))
463 (query (cdr path-and-query))
464 (frag (url-target obj)))
465 (if user
466 (setf (url-user obj) (url-hexify-string user)))
467 (if pass
468 (setf (url-password obj) (url-hexify-string pass)))
469 ;; No special encoding for IPv6 literals.
470 (and host
471 (not (string-match "\\`\\[.*\\]\\'" host))
472 (setf (url-host obj)
473 (url-hexify-string host url-host-allowed-chars)))
475 (if path
476 (setq path (url-hexify-string path url-path-allowed-chars)))
477 (if query
478 (setq query (url-hexify-string query url-query-allowed-chars)))
479 (setf (url-filename obj) (if query (concat path "?" query) path))
481 (if frag
482 (setf (url-target obj)
483 (url-hexify-string frag url-query-allowed-chars)))
484 (url-recreate-url obj)))
486 ;;;###autoload
487 (defun url-file-extension (fname &optional x)
488 "Return the filename extension of FNAME.
489 If optional argument X is t, then return the basename
490 of the file with the extension stripped off."
491 (if (and fname
492 (setq fname (url-file-nondirectory fname))
493 (string-match "\\.[^./]+$" fname))
494 (if x (substring fname 0 (match-beginning 0))
495 (substring fname (match-beginning 0) nil))
497 ;; If fname has no extension, and x then return fname itself instead of
498 ;; nothing. When caching it allows the correct .hdr file to be produced
499 ;; for filenames without extension.
501 (if x
502 fname
503 "")))
505 ;;;###autoload
506 (defun url-truncate-url-for-viewing (url &optional width)
507 "Return a shortened version of URL that is WIDTH characters wide or less.
508 WIDTH defaults to the current frame width."
509 (let* ((fr-width (or width (frame-width)))
510 (str-width (length url))
511 (fname nil)
512 (modified 0)
513 (urlobj nil))
514 ;; The first thing that can go are the search strings
515 (if (and (>= str-width fr-width)
516 (string-match "?" url))
517 (setq url (concat (substring url 0 (match-beginning 0)) "?...")
518 str-width (length url)))
519 (if (< str-width fr-width)
520 nil ; Hey, we are done!
521 (setq urlobj (url-generic-parse-url url)
522 fname (url-filename urlobj)
523 fr-width (- fr-width 4))
524 (while (and (>= str-width fr-width)
525 (string-match "/" fname))
526 (setq fname (substring fname (match-end 0) nil)
527 modified (1+ modified))
528 (setf (url-filename urlobj) fname)
529 (setq url (url-recreate-url urlobj)
530 str-width (length url)))
531 (if (> modified 1)
532 (setq fname (concat "/.../" fname))
533 (setq fname (concat "/" fname)))
534 (setf (url-filename urlobj) fname)
535 (setq url (url-recreate-url urlobj)))
536 url))
538 ;;;###autoload
539 (defun url-view-url (&optional no-show)
540 "View the current document's URL.
541 Optional argument NO-SHOW means just return the URL, don't show it in
542 the minibuffer.
544 This uses `url-current-object', set locally to the buffer."
545 (interactive)
546 (if (not url-current-object)
548 (if no-show
549 (url-recreate-url url-current-object)
550 (message "%s" (url-recreate-url url-current-object)))))
552 (defvar url-get-url-filename-chars "-%.?@a-zA-Z0-9()_/:~=&"
553 "Valid characters in a URL.")
555 (defun url-get-url-at-point (&optional pt)
556 "Get the URL closest to point, but don't change position.
557 Has a preference for looking backward when not directly on a symbol."
558 ;; Not at all perfect - point must be right in the name.
559 (save-excursion
560 (if pt (goto-char pt))
561 (let (start url)
562 (save-excursion
563 ;; first see if you're just past a filename
564 (if (not (eobp))
565 (if (looking-at "[] \t\n[{}()]") ; whitespace or some parens
566 (progn
567 (skip-chars-backward " \n\t\r({[]})")
568 (if (not (bobp))
569 (backward-char 1)))))
570 (if (and (char-after (point))
571 (string-match (concat "[" url-get-url-filename-chars "]")
572 (char-to-string (char-after (point)))))
573 (progn
574 (skip-chars-backward url-get-url-filename-chars)
575 (setq start (point))
576 (skip-chars-forward url-get-url-filename-chars))
577 (setq start (point)))
578 (setq url (buffer-substring-no-properties start (point))))
579 (if (and url (string-match "^(.*)\\.?$" url))
580 (setq url (match-string 1 url)))
581 (if (and url (string-match "^URL:" url))
582 (setq url (substring url 4 nil)))
583 (if (and url (string-match "\\.$" url))
584 (setq url (substring url 0 -1)))
585 (if (and url (string-match "^www\\." url))
586 (setq url (concat "http://" url)))
587 (if (and url (not (string-match url-nonrelative-link url)))
588 (setq url nil))
589 url)))
591 (defun url-generate-unique-filename (&optional fmt)
592 "Generate a unique filename in `url-temporary-directory'."
593 ;; This variable is obsolete, but so is this function.
594 (let ((tempdir (with-no-warnings url-temporary-directory)))
595 (if (not fmt)
596 (let ((base (format "url-tmp.%d" (user-real-uid)))
597 (fname "")
598 (x 0))
599 (setq fname (format "%s%d" base x))
600 (while (file-exists-p
601 (expand-file-name fname tempdir))
602 (setq x (1+ x)
603 fname (concat base (int-to-string x))))
604 (expand-file-name fname tempdir))
605 (let ((base (concat "url" (int-to-string (user-real-uid))))
606 (fname "")
607 (x 0))
608 (setq fname (format fmt (concat base (int-to-string x))))
609 (while (file-exists-p
610 (expand-file-name fname tempdir))
611 (setq x (1+ x)
612 fname (format fmt (concat base (int-to-string x)))))
613 (expand-file-name fname tempdir)))))
614 (make-obsolete 'url-generate-unique-filename 'make-temp-file "23.1")
616 (defun url-extract-mime-headers ()
617 "Set `url-current-mime-headers' in current buffer."
618 (save-excursion
619 (goto-char (point-min))
620 (unless url-current-mime-headers
621 (set (make-local-variable 'url-current-mime-headers)
622 (mail-header-extract)))))
624 (defun url-make-private-file (file)
625 "Make FILE only readable and writable by the current user.
626 Creates FILE and its parent directories if they do not exist."
627 (let ((dir (file-name-directory file)))
628 (when dir
629 ;; For historical reasons.
630 (make-directory dir t)))
631 ;; Based on doc-view-make-safe-dir.
632 (condition-case nil
633 (let ((umask (default-file-modes)))
634 (unwind-protect
635 (progn
636 (set-default-file-modes #o0600)
637 (with-temp-buffer
638 (write-region (point-min) (point-max)
639 file nil 'silent nil 'excl)))
640 (set-default-file-modes umask)))
641 (file-already-exists
642 (if (file-symlink-p file)
643 (error "Danger: `%s' is a symbolic link" file))
644 (set-file-modes file #o0600))))
646 (provide 'url-util)
648 ;;; url-util.el ends here