Remove non-free old and crusty clearcase pkg
[packages] / xemacs-packages / gnus / lisp / gnus-util.el
1 ;;; gnus-util.el --- utility functions for Gnus
2
3 ;; Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
4 ;;   2005, 2006, 2007, 2008 Free Software Foundation, Inc.
5
6 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
7 ;; Keywords: news
8
9 ;; This file is part of GNU Emacs.
10
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)
14 ;; any later version.
15
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.
20
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.
25
26 ;;; Commentary:
27
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
31 ;; Gnus first.
32
33 ;; [Unfortunately, it does depend on other parts of Gnus, e.g. the
34 ;; autoloads below...]
35
36 ;;; Code:
37
38 (require 'custom)
39 (eval-when-compile
40   (require 'cl)
41   ;; Fixme: this should be a gnus variable, not nnmail-.
42   (defvar nnmail-pathname-coding-system)
43   (defvar nnmail-active-file-coding-system)
44
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)
49   )
50 (require 'time-date)
51 (require 'netrc)
52
53 (eval-and-compile
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"))
61
62 (eval-and-compile
63   (cond
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
66    ;; on empty matches:
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.
74
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))
79    (t
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.
84
85 This is a compatibility function for different Emacsen."
86       (let ((start 0) tail)
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))))
91       string))))
92
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)
97
98 (defun gnus-boundp (variable)
99   "Return non-nil if VARIABLE is bound and non-nil."
100   (and (boundp variable)
101        (symbol-value variable)))
102
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))
109             (,buf ,buffer)
110             (,w (gnus-get-buffer-window ,buf 'visible)))
111        (unwind-protect
112            (progn
113              (if ,w
114                  (progn
115                    (select-window ,w)
116                    (set-buffer (window-buffer ,w)))
117                (pop-to-buffer ,buf))
118              ,@forms)
119          (select-window ,tempvar)))))
120
121 (put 'gnus-eval-in-buffer-window 'lisp-indent-function 1)
122 (put 'gnus-eval-in-buffer-window 'edebug-form-spec '(form body))
123
124 (defmacro gnus-intern-safe (string hashtable)
125   "Get hash value.  Arguments are STRING and HASHTABLE."
126   `(let ((symbol (intern ,string ,hashtable)))
127      (or (boundp symbol)
128          (set symbol nil))
129      symbol))
130
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)
138     str))
139
140 (defsubst gnus-goto-char (point)
141   (and point (goto-char point)))
142
143 (defmacro gnus-buffer-exists-p (buffer)
144   `(let ((buffer ,buffer))
145      (when buffer
146        (funcall (if (stringp buffer) 'get-buffer 'buffer-name)
147                 buffer))))
148
149 (defalias 'gnus-point-at-bol
150   (if (fboundp 'point-at-bol)
151       'point-at-bol
152     'line-beginning-position))
153
154 (defalias 'gnus-point-at-eol
155   (if (fboundp 'point-at-eol)
156       'point-at-eol
157     'line-end-position))
158
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)
166       'ignore                           ; Emacs
167     'make-local-hook))                  ; XEmacs
168
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)
172       (cdr list)
173     (let ((total list))
174       (while (and (cdr list)
175                   (not (equal (cadr list) elt)))
176         (setq list (cdr list)))
177       (when (cdr list)
178         (setcdr list (cddr list)))
179       total)))
180
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))))
185
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)
192           flist)
193       (cons 'progn (cddr fval)))))
194
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
200 is slower."
201   (let (name address)
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)
207            ;; correctly.
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.
213     (and address
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.
221     (or name
222         (and (string-match "(.+)" from)
223              (setq name (substring from (1+ (match-beginning 0))
224                                    (1- (match-end 0)))))
225         (and (string-match "()" from)
226              (setq name address))
227         ;; XOVER might not support folded From headers.
228         (and (string-match "(.*" from)
229              (setq name (substring from (1+ (match-beginning 0))
230                                    (match-end 0)))))
231     (list (if (string= name "") nil name) (or address from))))
232
233
234 (defun gnus-fetch-field (field)
235   "Return the value of the header FIELD of current article."
236   (save-excursion
237     (save-restriction
238       (let ((case-fold-search t)
239             (inhibit-point-motion-hooks t))
240         (nnheader-narrow-to-headers)
241         (message-fetch-field field)))))
242
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)))
247
248
249 (defun gnus-goto-colon ()
250   (beginning-of-line)
251   (let ((eol (gnus-point-at-eol)))
252     (goto-char (or (text-property-any (point) eol 'gnus-position t)
253                    (search-forward ":" eol t)
254                    (point)))))
255
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
260                                                 method group)))
261                (message-tokenize-header newsgroups)
262                ",")))
263
264 (defun gnus-remove-text-with-property (prop)
265   "Delete all text in the current buffer with text property PROP."
266   (save-excursion
267     (goto-char (point-min))
268     (while (not (eobp))
269       (while (get-text-property (point) prop)
270         (delete-char 1))
271       (goto-char (next-single-property-change (point) prop nil (point-max))))))
272
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)))
277     (concat
278      (if idx (substring newsgroup 0 idx))
279      (if idx "/")
280      (nnheader-replace-chars-in-string
281       (if idx (substring newsgroup (1+ idx)) newsgroup)
282       ?. ?/))))
283
284 (defun gnus-newsgroup-savable-name (group)
285   ;; Replace any slashes in a group name (eg. an ange-ftp nndoc group)
286   ;; with dots.
287   (nnheader-replace-chars-in-string group ?/ ?.))
288
289 (defun gnus-string> (s1 s2)
290   (not (or (string< s1 s2)
291            (string= s1 s2))))
292
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."
297   (if case-fold-search
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)))
301
302 ;;; Time functions.
303
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))))))
309
310 ;;; Keymap macros.
311
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))
315
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)))
319
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))
323
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)
327
328 (defmacro gnus-define-keymap (keymap &rest plist)
329   "Define all keys in PLIST in KEYMAP."
330   `(gnus-define-keys-1 ,keymap (quote ,plist)))
331
332 (put 'gnus-define-keymap 'lisp-indent-function 1)
333
334 (defun gnus-define-keys-1 (keymap plist &optional safe)
335   (when (null keymap)
336     (error "Can't set keys in a null keymap"))
337   (cond ((symbolp keymap)
338          (setq keymap (symbol-value keymap)))
339         ((keymapp keymap))
340         ((listp 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)))))
345   (let (key)
346     (while plist
347       (when (symbolp (setq key (pop plist)))
348         (setq key (symbol-value key)))
349       (if (or (not safe)
350               (eq (lookup-key keymap key) 'undefined))
351           (define-key keymap key (pop plist))
352         (pop plist)))))
353
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)))
361         default
362       answer)))
363
364 ;; Two silly functions to ensure that all `y-or-n-p' questions clear
365 ;; the echo area.
366 (defun gnus-y-or-n-p (prompt)
367   (prog1
368       (y-or-n-p prompt)
369     (message "")))
370
371 (defun gnus-yes-or-no-p (prompt)
372   (prog1
373       (yes-or-no-p prompt)
374     (message "")))
375
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)
380
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))))
385
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))))
391
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))))
398
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
405                                             ;;other does match
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.
413
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.
417
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,
421 respectively.")
422
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\"."
427   (condition-case ()
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))
436             (progn
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)))
442     (error "  ?   ")))
443
444 (defun gnus-dd-mmm (messy-date)
445   "Return a string like DD-MMM from a big messy string."
446   (condition-case ()
447       (format-time-string "%d-%b" (safe-date-to-time messy-date))
448     (error "  -   ")))
449
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...
454   `(let ((d ,date))
455      (if (equal "" d)
456          '(0 0)
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)
462              time)))))
463
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))
467
468 (defun gnus-date-iso8601 (date)
469   "Convert the DATE to YYYYMMDDTHHMMSS."
470   (condition-case ()
471       (gnus-time-iso8601 (gnus-date-get-time date))
472     (error "")))
473
474 (defun gnus-mode-string-quote (string)
475   "Quote all \"%\"'s in STRING."
476   (gnus-replace-in-string string "%" "%%"))
477
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))
482
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)
490   (let ((i 1))
491     (while (< i min)
492       (setq i (* 2 i)))
493     i))
494
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."
501   :group 'gnus-start
502   :type 'integer)
503
504 (defun gnus-message (level &rest args)
505   "If LEVEL is lower than `gnus-verbose' print ARGS using `message'.
506
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
510 inside loops."
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
515     ;; from `message'.
516     (apply 'format args)))
517
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)
523     (ding)
524     (let (duration)
525       (when (and (floatp level)
526                  (not (zerop (setq duration (* 10 (- level (floor level)))))))
527         (sit-for duration))))
528   nil)
529
530 (defun gnus-split-references (references)
531   "Return a list of Message-IDs in REFERENCES."
532   (let ((beg 0)
533         ids)
534     (while (string-match "<[^<]+[^< \t]" references beg)
535       (push (substring references (match-beginning 0) (setq beg (match-end 0)))
536             ids))
537     (nreverse ids)))
538
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))))
544     (if n
545         (let ((ids (inline (gnus-split-references references))))
546           (while (nthcdr n ids)
547             (setq ids (cdr ids)))
548           (car ids))
549       (when (string-match "\\(<[^<]+>\\)[ \t]*\\'" references)
550         (match-string 1 references)))))
551
552 (defun gnus-buffer-live-p (buffer)
553   "Say whether BUFFER is alive or not."
554   (and buffer
555        (get-buffer buffer)
556        (buffer-name (get-buffer buffer))))
557
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)))
564            (max 0))
565       (when end
566         ;; Find the longest line currently displayed in the window.
567         (goto-char (window-start))
568         (while (and (not (eobp))
569         &nb