1 ;;; gnus-util.el --- utility functions for Gnus
3 ;; Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
4 ;; 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
6 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software; you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation; either version 3, or (at your option)
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs; see the file COPYING. If not, write to the
23 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
24 ;; Boston, MA 02110-1301, USA.
28 ;; Nothing in this file depends on any other parts of Gnus -- all
29 ;; functions and macros in this file are utility functions that are
30 ;; used by Gnus and may be used by any other package without loading
33 ;; [Unfortunately, it does depend on other parts of Gnus, e.g. the
34 ;; autoloads below...]
41 ;; Fixme: this should be a gnus variable, not nnmail-.
42 (defvar nnmail-pathname-coding-system)
43 (defvar nnmail-active-file-coding-system)
45 ;; Inappropriate references to other parts of Gnus.
46 (defvar gnus-emphasize-whitespace-regexp)
47 (defvar gnus-original-article-buffer)
48 (defvar gnus-user-agent)
54 (autoload 'message-fetch-field "message")
55 (autoload 'gnus-get-buffer-window "gnus-win")
56 (autoload 'rmail-insert-rmail-file-header "rmail")
57 (autoload 'rmail-count-new-messages "rmail")
58 (autoload 'rmail-show-message "rmail")
59 (autoload 'nnheader-narrow-to-headers "nnheader")
60 (autoload 'nnheader-replace-chars-in-string "nnheader"))
64 ;; Prefer `replace-regexp-in-string' (present in Emacs, XEmacs 21.5,
65 ;; SXEmacs 22.1.4) over `replace-in-string'. The later leads to inf-loops
67 ;; (replace-in-string "foo" "/*$" "/")
68 ;; (replace-in-string "xe" "\\(x\\)?" "")
69 ((fboundp 'replace-regexp-in-string)
70 (defun gnus-replace-in-string (string regexp newtext &optional literal)
71 "Replace all matches for REGEXP with NEWTEXT in STRING.
72 If LITERAL is non-nil, insert NEWTEXT literally. Return a new
73 string containing the replacements.
75 This is a compatibility function for different Emacsen."
76 (replace-regexp-in-string regexp newtext string nil literal)))
77 ((fboundp 'replace-in-string)
78 (defalias 'gnus-replace-in-string 'replace-in-string))
80 (defun gnus-replace-in-string (string regexp newtext &optional literal)
81 "Replace all matches for REGEXP with NEWTEXT in STRING.
82 If LITERAL is non-nil, insert NEWTEXT literally. Return a new
83 string containing the replacements.
85 This is a compatibility function for different Emacsen."
87 (while (string-match regexp string start)
88 (setq tail (- (length string) (match-end 0)))
89 (setq string (replace-match newtext nil literal string))
90 (setq start (- (length string) tail))))
93 ;;; bring in the netrc functions as aliases
94 (defalias 'gnus-netrc-get 'netrc-get)
95 (defalias 'gnus-netrc-machine 'netrc-machine)
96 (defalias 'gnus-parse-netrc 'netrc-parse)
98 (defun gnus-boundp (variable)
99 "Return non-nil if VARIABLE is bound and non-nil."
100 (and (boundp variable)
101 (symbol-value variable)))
103 (defmacro gnus-eval-in-buffer-window (buffer &rest forms)
104 "Pop to BUFFER, evaluate FORMS, and then return to the original window."
105 (let ((tempvar (make-symbol "GnusStartBufferWindow"))
106 (w (make-symbol "w"))
107 (buf (make-symbol "buf")))
108 `(let* ((,tempvar (selected-window))
110 (,w (gnus-get-buffer-window ,buf 'visible)))
116 (set-buffer (window-buffer ,w)))
117 (pop-to-buffer ,buf))
119 (select-window ,tempvar)))))
121 (put 'gnus-eval-in-buffer-window 'lisp-indent-function 1)
122 (put 'gnus-eval-in-buffer-window 'edebug-form-spec '(form body))
124 (defmacro gnus-intern-safe (string hashtable)
125 "Get hash value. Arguments are STRING and HASHTABLE."
126 `(let ((symbol (intern ,string ,hashtable)))
131 ;; Added by Geoffrey T. Dairiki <dairiki@u.washington.edu>. A safe way
132 ;; to limit the length of a string. This function is necessary since
133 ;; `(substr "abc" 0 30)' pukes with "Args out of range".
134 ;; Fixme: Why not `truncate-string-to-width'?
135 (defsubst gnus-limit-string (str width)
136 (if (> (length str) width)
137 (substring str 0 width)
140 (defsubst gnus-goto-char (point)
141 (and point (goto-char point)))
143 (defmacro gnus-buffer-exists-p (buffer)
144 `(let ((buffer ,buffer))
146 (funcall (if (stringp buffer) 'get-buffer 'buffer-name)
149 (defalias 'gnus-point-at-bol
150 (if (fboundp 'point-at-bol)
152 'line-beginning-position))
154 (defalias 'gnus-point-at-eol
155 (if (fboundp 'point-at-eol)
159 ;; The LOCAL arg to `add-hook' is interpreted differently in Emacs and
160 ;; XEmacs. In Emacs we don't need to call `make-local-hook' first.
161 ;; It's harmless, though, so the main purpose of this alias is to shut
162 ;; up the byte compiler.
163 (defalias 'gnus-make-local-hook
164 (if (eq (get 'make-local-hook 'byte-compile)
165 'byte-compile-obsolete)
167 'make-local-hook)) ; XEmacs
169 (defun gnus-delete-first (elt list)
170 "Delete by side effect the first occurrence of ELT as a member of LIST."
171 (if (equal (car list) elt)
174 (while (and (cdr list)
175 (not (equal (cadr list) elt)))
176 (setq list (cdr list)))
178 (setcdr list (cddr list)))
181 ;; Delete the current line (and the next N lines).
182 (defmacro gnus-delete-line (&optional n)
183 `(delete-region (gnus-point-at-bol)
184 (progn (forward-line ,(or n 1)) (point))))
186 (defun gnus-byte-code (func)
187 "Return a form that can be `eval'ed based on FUNC."
188 (let ((fval (indirect-function func)))
189 (if (byte-code-function-p fval)
190 (let ((flist (append fval nil)))
191 (setcar flist 'byte-code)
193 (cons 'progn (cddr fval)))))
195 (defun gnus-extract-address-components (from)
196 "Extract address components from a From header.
197 Given an RFC-822 address FROM, extract full name and canonical address.
198 Returns a list of the form (FULL-NAME CANONICAL-ADDRESS). Much more simple
199 solution than `mail-extract-address-components', which works much better, but
202 ;; First find the address - the thing with the @ in it. This may
203 ;; not be accurate in mail addresses, but does the trick most of
204 ;; the time in news messages.
205 (cond (;; Check ``<foo@bar>'' first in order to handle the quite common
206 ;; form ``"abc@xyz" <foo@bar>'' (i.e. ``@'' as part of a comment)
208 (string-match "<\\([^@ \t<>]+[!@][^@ \t<>]+\\)>" from)
209 (setq address (substring from (match-beginning 1) (match-end 1))))
210 ((string-match "\\b[^@ \t<>]+[!@][^@ \t<>]+\\b" from)
211 (setq address (substring from (match-beginning 0) (match-end 0)))))
212 ;; Then we check whether the "name <address>" format is used.
214 ;; Linear white space is not required.
215 (string-match (concat "[ \t]*<" (regexp-quote address) ">") from)
216 (and (setq name (substring from 0 (match-beginning 0)))
217 ;; Strip any quotes from the name.
218 (string-match "^\".*\"$" name)
219 (setq name (substring name 1 (1- (match-end 0))))))
220 ;; If not, then "address (name)" is used.
222 (and (string-match "(.+)" from)
223 (setq name (substring from (1+ (match-beginning 0))
224 (1- (match-end 0)))))
225 (and (string-match "()" from)
227 ;; XOVER might not support folded From headers.
228 (and (string-match "(.*" from)
229 (setq name (substring from (1+ (match-beginning 0))
231 (list (if (string= name "") nil name) (or address from))))
234 (defun gnus-fetch-field (field)
235 "Return the value of the header FIELD of current article."
238 (let ((case-fold-search t)
239 (inhibit-point-motion-hooks t))
240 (nnheader-narrow-to-headers)
241 (message-fetch-field field)))))
243 (defun gnus-fetch-original-field (field)
244 "Fetch FIELD from the original version of the current article."
245 (with-current-buffer gnus-original-article-buffer
246 (gnus-fetch-field field)))
249 (defun gnus-goto-colon ()
251 (let ((eol (gnus-point-at-eol)))
252 (goto-char (or (text-property-any (point) eol 'gnus-position t)
253 (search-forward ":" eol t)
256 (defun gnus-decode-newsgroups (newsgroups group &optional method)
257 (let ((method (or method (gnus-find-method-for-group group))))
258 (mapconcat (lambda (group)
259 (gnus-group-name-decode group (gnus-group-name-charset
261 (message-tokenize-header newsgroups)
264 (defun gnus-remove-text-with-property (prop)
265 "Delete all text in the current buffer with text property PROP."
267 (goto-char (point-min))
269 (while (get-text-property (point) prop)
271 (goto-char (next-single-property-change (point) prop nil (point-max))))))
273 (defun gnus-newsgroup-directory-form (newsgroup)
274 "Make hierarchical directory name from NEWSGROUP name."
275 (let* ((newsgroup (gnus-newsgroup-savable-name newsgroup))
276 (idx (string-match ":" newsgroup)))
278 (if idx (substring newsgroup 0 idx))
280 (nnheader-replace-chars-in-string
281 (if idx (substring newsgroup (1+ idx)) newsgroup)
284 (defun gnus-newsgroup-savable-name (group)
285 ;; Replace any slashes in a group name (eg. an ange-ftp nndoc group)
287 (nnheader-replace-chars-in-string group ?/ ?.))
289 (defun gnus-string> (s1 s2)
290 (not (or (string< s1 s2)
293 (defun gnus-string< (s1 s2)
294 "Return t if first arg string is less than second in lexicographic order.
295 Case is significant if and only if `case-fold-search' is nil.
296 Symbols are also allowed; their print names are used instead."
298 (string-lessp (downcase (if (symbolp s1) (symbol-name s1) s1))
299 (downcase (if (symbolp s2) (symbol-name s2) s2)))
300 (string-lessp s1 s2)))
304 (defun gnus-file-newer-than (file date)
305 (let ((fdate (nth 5 (file-attributes file))))
306 (or (> (car fdate) (car date))
307 (and (= (car fdate) (car date))
308 (> (nth 1 fdate) (nth 1 date))))))
312 (defmacro gnus-local-set-keys (&rest plist)
313 "Set the keys in PLIST in the current keymap."
314 `(gnus-define-keys-1 (current-local-map) ',plist))
316 (defmacro gnus-define-keys (keymap &rest plist)
317 "Define all keys in PLIST in KEYMAP."
318 `(gnus-define-keys-1 (quote ,keymap) (quote ,plist)))
320 (defmacro gnus-define-keys-safe (keymap &rest plist)
321 "Define all keys in PLIST in KEYMAP without overwriting previous definitions."
322 `(gnus-define-keys-1 (quote ,keymap) (quote ,plist) t))
324 (put 'gnus-define-keys 'lisp-indent-function 1)
325 (put 'gnus-define-keys-safe 'lisp-indent-function 1)
326 (put 'gnus-local-set-keys 'lisp-indent-function 1)
328 (defmacro gnus-define-keymap (keymap &rest plist)
329 "Define all keys in PLIST in KEYMAP."
330 `(gnus-define-keys-1 ,keymap (quote ,plist)))
332 (put 'gnus-define-keymap 'lisp-indent-function 1)
334 (defun gnus-define-keys-1 (keymap plist &optional safe)
336 (error "Can't set keys in a null keymap"))
337 (cond ((symbolp keymap)
338 (setq keymap (symbol-value keymap)))
341 (set (car keymap) nil)
342 (define-prefix-command (car keymap))
343 (define-key (symbol-value (caddr keymap)) (cadr keymap) (car keymap))
344 (setq keymap (symbol-value (car keymap)))))
347 (when (symbolp (setq key (pop plist)))
348 (setq key (symbol-value key)))
350 (eq (lookup-key keymap key) 'undefined))
351 (define-key keymap key (pop plist))
354 (defun gnus-completing-read-with-default (default prompt &rest args)
355 ;; Like `completing-read', except that DEFAULT is the default argument.
356 (let* ((prompt (if default
357 (concat prompt " (default " default "): ")
358 (concat prompt ": ")))
359 (answer (apply 'completing-read prompt args)))
360 (if (or (null answer) (zerop (length answer)))
364 ;; Two silly functions to ensure that all `y-or-n-p' questions clear
366 (defun gnus-y-or-n-p (prompt)
371 (defun gnus-yes-or-no-p (prompt)
376 ;; By Frank Schmitt <ich@Frank-Schmitt.net>. Allows to have
377 ;; age-depending date representations. (e.g. just the time if it's
378 ;; from today, the day of the week if it's within the last 7 days and
379 ;; the full date if it's older)
381 (defun gnus-seconds-today ()
382 "Return the number of seconds passed today."
383 (let ((now (decode-time (current-time))))
384 (+ (car now) (* (car (cdr now)) 60) (* (car (nthcdr 2 now)) 3600))))
386 (defun gnus-seconds-month ()
387 "Return the number of seconds passed this month."
388 (let ((now (decode-time (current-time))))
389 (+ (car now) (* (car (cdr now)) 60) (* (car (nthcdr 2 now)) 3600)
390 (* (- (car (nthcdr 3 now)) 1) 3600 24))))
392 (defun gnus-seconds-year ()
393 "Return the number of seconds passed this year."
394 (let ((now (decode-time (current-time)))
395 (days (format-time-string "%j" (current-time))))
396 (+ (car now) (* (car (cdr now)) 60) (* (car (nthcdr 2 now)) 3600)
397 (* (- (string-to-number days) 1) 3600 24))))
399 (defvar gnus-user-date-format-alist
400 '(((gnus-seconds-today) . "%k:%M")
401 (604800 . "%a %k:%M") ;;that's one week
402 ((gnus-seconds-month) . "%a %d")
403 ((gnus-seconds-year) . "%b %d")
404 (t . "%b %d '%y")) ;;this one is used when no
406 "Specifies date format depending on age of article.
407 This is an alist of items (AGE . FORMAT). AGE can be a number (of
408 seconds) or a Lisp expression evaluating to a number. When the age of
409 the article is less than this number, then use `format-time-string'
410 with the corresponding FORMAT for displaying the date of the article.
411 If AGE is not a number or a Lisp expression evaluating to a
412 non-number, then the corresponding FORMAT is used as a default value.
414 Note that the list is processed from the beginning, so it should be
415 sorted by ascending AGE. Also note that items following the first
416 non-number AGE will be ignored.
418 You can use the functions `gnus-seconds-today', `gnus-seconds-month'
419 and `gnus-seconds-year' in the AGE spec. They return the number of
420 seconds passed since the start of today, of this month, of this year,
423 (defun gnus-user-date (messy-date)
424 "Format the messy-date according to gnus-user-date-format-alist.
425 Returns \" ? \" if there's bad input or if an other error occurs.
426 Input should look like this: \"Sun, 14 Oct 2001 13:34:39 +0200\"."
428 (let* ((messy-date (time-to-seconds (safe-date-to-time messy-date)))
429 (now (time-to-seconds (current-time)))
430 ;;If we don't find something suitable we'll use this one
431 (my-format "%b %d '%y"))
432 (let* ((difference (- now messy-date))
433 (templist gnus-user-date-format-alist)
434 (top (eval (caar templist))))
435 (while (if (numberp top) (< top difference) (not top))
437 (setq templist (cdr templist))
438 (setq top (eval (caar templist)))))
439 (if (stringp (cdr (car templist)))
440 (setq my-format (cdr (car templist)))))
441 (format-time-string (eval my-format) (seconds-to-time messy-date)))
444 (defun gnus-dd-mmm (messy-date)
445 "Return a string like DD-MMM from a big messy string."
447 (format-time-string "%d-%b" (safe-date-to-time messy-date))
450 (defmacro gnus-date-get-time (date)
451 "Convert DATE string to Emacs time.
452 Cache the result as a text property stored in DATE."
453 ;; Either return the cached value...
457 (or (get-text-property 0 'gnus-time d)
458 ;; or compute the value...
459 (let ((time (safe-date-to-time d)))
460 ;; and store it back in the string.
461 (put-text-property 0 1 'gnus-time time d)
464 (defsubst gnus-time-iso8601 (time)
465 "Return a string of TIME in YYYYMMDDTHHMMSS format."
466 (format-time-string "%Y%m%dT%H%M%S" time))
468 (defun gnus-date-iso8601 (date)
469 "Convert the DATE to YYYYMMDDTHHMMSS."
471 (gnus-time-iso8601 (gnus-date-get-time date))
474 (defun gnus-mode-string-quote (string)
475 "Quote all \"%\"'s in STRING."
476 (gnus-replace-in-string string "%" "%%"))
478 ;; Make a hash table (default and minimum size is 256).
479 ;; Optional argument HASHSIZE specifies the table size.
480 (defun gnus-make-hashtable (&optional hashsize)
481 (make-vector (if hashsize (max (gnus-create-hash-size hashsize) 256) 256) 0))
483 ;; Make a number that is suitable for hashing; bigger than MIN and
484 ;; equal to some 2^x. Many machines (such as sparcs) do not have a
485 ;; hardware modulo operation, so they implement it in software. On
486 ;; many sparcs over 50% of the time to intern is spent in the modulo.
487 ;; Yes, it's slower than actually computing the hash from the string!
488 ;; So we use powers of 2 so people can optimize the modulo to a mask.
489 (defun gnus-create-hash-size (min)
495 (defcustom gnus-verbose 7
496 "*Integer that says how verbose Gnus should be.
497 The higher the number, the more messages Gnus will flash to say what
498 it's doing. At zero, Gnus will be totally mute; at five, Gnus will
499 display most important messages; and at ten, Gnus will keep on
500 jabbering all the time."
504 (defun gnus-message (level &rest args)
505 "If LEVEL is lower than `gnus-verbose' print ARGS using `message'.
507 Guideline for numbers:
508 1 - error messages, 3 - non-serious error messages, 5 - messages for things
509 that take a long time, 7 - not very important messages on stuff, 9 - messages
511 (if (<= level gnus-verbose)
512 (apply 'message args)
513 ;; We have to do this format thingy here even if the result isn't
514 ;; shown - the return value has to be the same as the return value
516 (apply 'format args)))
518 (defun gnus-error (level &rest args)
519 "Beep an error if LEVEL is equal to or less than `gnus-verbose'.
520 ARGS are passed to `message'."
521 (when (<= (floor level) gnus-verbose)
522 (apply 'message args)
525 (when (and (floatp level)
526 (not (zerop (setq duration (* 10 (- level (floor level)))))))
527 (sit-for duration))))
530 (defun gnus-split-references (references)
531 "Return a list of Message-IDs in REFERENCES."
534 (while (string-match "<[^<]+[^< \t]" references beg)
535 (push (substring references (match-beginning 0) (setq beg (match-end 0)))
539 (defsubst gnus-parent-id (references &optional n)
540 "Return the last Message-ID in REFERENCES.
541 If N, return the Nth ancestor instead."
542 (when (and references
543 (not (zerop (length references))))
545 (let ((ids (inline (gnus-split-references references))))
546 (while (nthcdr n ids)
547 (setq ids (cdr ids)))
549 (when (string-match "\\(<[^<]+>\\)[ \t]*\\'" references)
550 (match-string 1 references)))))
552 (defun gnus-buffer-live-p (buffer)
553 "Say whether BUFFER is alive or not."
556 (buffer-name (get-buffer buffer))))
558 (defun gnus-horizontal-recenter ()
559 "Recenter the current buffer horizontally."
560 (if (< (current-column) (/ (window-width) 2))
561 (set-window-hscroll (gnus-get-buffer-window (current-buffer) t) 0)
562 (let* ((orig (point))
563 (end (window-end (gnus-get-buffer-window (current-buffer) t)))
566 ;; Find the longest line currently displayed in the window.
567 (goto-char (window-start))
568 (while (and (not (eobp))