Doc bug: date format used in scoring has four-digit year, not two digits.
[gnus] / lisp / gnus-util.el
1 ;;; gnus-util.el --- utility functions for Gnus
2 ;; Copyright (C) 1996, 1997, 1998, 1999, 2000
3 ;;        Free Software Foundation, Inc.
4
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;; Keywords: news
7
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 2, or (at your option)
13 ;; any later version.
14
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.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
22 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
24
25 ;;; Commentary:
26
27 ;; Nothing in this file depends on any other parts of Gnus -- all
28 ;; functions and macros in this file are utility functions that are
29 ;; used by Gnus and may be used by any other package without loading
30 ;; Gnus first.
31
32 ;;; Code:
33
34 (require 'custom)
35 (eval-when-compile (require 'cl))
36 (require 'nnheader)
37 (require 'message)
38 (require 'time-date)
39
40 (eval-and-compile
41   (autoload 'rmail-insert-rmail-file-header "rmail")
42   (autoload 'rmail-count-new-messages "rmail")
43   (autoload 'rmail-show-message "rmail"))
44
45 (defun gnus-boundp (variable)
46   "Return non-nil if VARIABLE is bound and non-nil."
47   (and (boundp variable)
48        (symbol-value variable)))
49
50 (defmacro gnus-eval-in-buffer-window (buffer &rest forms)
51   "Pop to BUFFER, evaluate FORMS, and then return to the original window."
52   (let ((tempvar (make-symbol "GnusStartBufferWindow"))
53         (w (make-symbol "w"))
54         (buf (make-symbol "buf")))
55     `(let* ((,tempvar (selected-window))
56             (,buf ,buffer)
57             (,w (get-buffer-window ,buf 'visible)))
58        (unwind-protect
59            (progn
60              (if ,w
61                  (progn
62                    (select-window ,w)
63                    (set-buffer (window-buffer ,w)))
64                (pop-to-buffer ,buf))
65              ,@forms)
66          (select-window ,tempvar)))))
67
68 (put 'gnus-eval-in-buffer-window 'lisp-indent-function 1)
69 (put 'gnus-eval-in-buffer-window 'edebug-form-spec '(form body))
70
71 (defmacro gnus-intern-safe (string hashtable)
72   "Set hash value.  Arguments are STRING, VALUE, and HASHTABLE."
73   `(let ((symbol (intern ,string ,hashtable)))
74      (or (boundp symbol)
75          (set symbol nil))
76      symbol))
77
78 ;; Added by Geoffrey T. Dairiki <dairiki@u.washington.edu>.  A safe way
79 ;; to limit the length of a string.  This function is necessary since
80 ;; `(substr "abc" 0 30)' pukes with "Args out of range".
81 (defsubst gnus-limit-string (str width)
82   (if (> (length str) width)
83       (substring str 0 width)
84     str))
85
86 (defsubst gnus-functionp (form)
87   "Return non-nil if FORM is funcallable."
88   (or (and (symbolp form) (fboundp form))
89       (and (listp form) (eq (car form) 'lambda))
90       (byte-code-function-p form)))
91
92 (defsubst gnus-goto-char (point)
93   (and point (goto-char point)))
94
95 (defmacro gnus-buffer-exists-p (buffer)
96   `(let ((buffer ,buffer))
97      (when buffer
98        (funcall (if (stringp buffer) 'get-buffer 'buffer-name)
99                 buffer))))
100
101 (defmacro gnus-kill-buffer (buffer)
102   `(let ((buf ,buffer))
103      (when (gnus-buffer-exists-p buf)
104        (kill-buffer buf))))
105
106 (defalias 'gnus-point-at-bol
107   (if (fboundp 'point-at-bol)
108       'point-at-bol
109     'line-beginning-position))
110
111 (defalias 'gnus-point-at-eol
112   (if (fboundp 'point-at-eol)
113       'point-at-eol
114     'line-end-position))
115
116 (defun gnus-delete-first (elt list)
117   "Delete by side effect the first occurrence of ELT as a member of LIST."
118   (if (equal (car list) elt)
119       (cdr list)
120     (let ((total list))
121       (while (and (cdr list)
122                   (not (equal (cadr list) elt)))
123         (setq list (cdr list)))
124       (when (cdr list)
125         (setcdr list (cddr list)))
126       total)))
127
128 ;; Delete the current line (and the next N lines).
129 (defmacro gnus-delete-line (&optional n)
130   `(delete-region (progn (beginning-of-line) (point))
131                   (progn (forward-line ,(or n 1)) (point))))
132
133 (defun gnus-byte-code (func)
134   "Return a form that can be `eval'ed based on FUNC."
135   (let ((fval (indirect-function func)))
136     (if (byte-code-function-p fval)
137         (let ((flist (append fval nil)))
138           (setcar flist 'byte-code)
139           flist)
140       (cons 'progn (cddr fval)))))
141
142 (defun gnus-extract-address-components (from)
143   (let (name address)
144     ;; First find the address - the thing with the @ in it.  This may
145     ;; not be accurate in mail addresses, but does the trick most of
146     ;; the time in news messages.
147     (when (string-match "\\b[^@ \t<>]+[!@][^@ \t<>]+\\b" from)
148       (setq address (substring from (match-beginning 0) (match-end 0))))
149     ;; Then we check whether the "name <address>" format is used.
150     (and address
151          ;; Linear white space is not required.
152          (string-match (concat "[ \t]*<" (regexp-quote address) ">") from)
153          (and (setq name (substring from 0 (match-beginning 0)))
154               ;; Strip any quotes from the name.
155               (string-match "\".*\"" name)
156               (setq name (substring name 1 (1- (match-end 0))))))
157     ;; If not, then "address (name)" is used.
158     (or name
159         (and (string-match "(.+)" from)
160              (setq name (substring from (1+ (match-beginning 0))
161                                    (1- (match-end 0)))))
162         (and (string-match "()" from)
163              (setq name address))
164         ;; XOVER might not support folded From headers.
165         (and (string-match "(.*" from)
166              (setq name (substring from (1+ (match-beginning 0))
167                                    (match-end 0)))))
168     (list (if (string= name "") nil name) (or address from))))
169
170
171 (defun gnus-fetch-field (field)
172   "Return the value of the header FIELD of current article."
173   (save-excursion
174     (save-restriction
175       (let ((case-fold-search t)
176             (inhibit-point-motion-hooks t))
177         (nnheader-narrow-to-headers)
178         (message-fetch-field field)))))
179
180 (defun gnus-goto-colon ()
181   (beginning-of-line)
182   (search-forward ":" (gnus-point-at-eol) t))
183
184 (defun gnus-remove-text-with-property (prop)
185   "Delete all text in the current buffer with text property PROP."
186   (save-excursion
187     (goto-char (point-min))
188     (while (not (eobp))
189       (while (get-text-property (point) prop)
190         (delete-char 1))
191       (goto-char (next-single-property-change (point) prop nil (point-max))))))
192
193 (defun gnus-newsgroup-directory-form (newsgroup)
194   "Make hierarchical directory name from NEWSGROUP name."
195   (let ((newsgroup (gnus-newsgroup-savable-name newsgroup))
196         (len (length newsgroup))
197         idx)
198     ;; If this is a foreign group, we don't want to translate the
199     ;; entire name.
200     (if (setq idx (string-match ":" newsgroup))
201         (aset newsgroup idx ?/)
202       (setq idx 0))
203     ;; Replace all occurrences of `.' with `/'.
204     (while (< idx len)
205       (when (= (aref newsgroup idx) ?.)
206         (aset newsgroup idx ?/))
207       (setq idx (1+ idx)))
208     newsgroup))
209
210 (defun gnus-newsgroup-savable-name (group)
211   ;; Replace any slashes in a group name (eg. an ange-ftp nndoc group)
212   ;; with dots.
213   (nnheader-replace-chars-in-string group ?/ ?.))
214
215 (defun gnus-string> (s1 s2)
216   (not (or (string< s1 s2)
217            (string= s1 s2))))
218
219 ;;; Time functions.
220
221 (defun gnus-file-newer-than (file date)
222   (let ((fdate (nth 5 (file-attributes file))))
223     (or (> (car fdate) (car date))
224         (and (= (car fdate) (car date))
225              (> (nth 1 fdate) (nth 1 date))))))
226
227 ;;; Keymap macros.
228
229 (defmacro gnus-local-set-keys (&rest plist)
230   "Set the keys in PLIST in the current keymap."
231   `(gnus-define-keys-1 (current-local-map) ',plist))
232
233 (defmacro gnus-define-keys (keymap &rest plist)
234   "Define all keys in PLIST in KEYMAP."
235   `(gnus-define-keys-1 (quote ,keymap) (quote ,plist)))
236
237 (defmacro gnus-define-keys-safe (keymap &rest plist)
238   "Define all keys in PLIST in KEYMAP without overwriting previous definitions."
239   `(gnus-define-keys-1 (quote ,keymap) (quote ,plist) t))
240
241 (put 'gnus-define-keys 'lisp-indent-function 1)
242 (put 'gnus-define-keys-safe 'lisp-indent-function 1)
243 (put 'gnus-local-set-keys 'lisp-indent-function 1)
244
245 (defmacro gnus-define-keymap (keymap &rest plist)
246   "Define all keys in PLIST in KEYMAP."
247   `(gnus-define-keys-1 ,keymap (quote ,plist)))
248
249 (put 'gnus-define-keymap 'lisp-indent-function 1)
250
251 (defun gnus-define-keys-1 (keymap plist &optional safe)
252   (when (null keymap)
253     (error "Can't set keys in a null keymap"))
254   (cond ((symbolp keymap)
255          (setq keymap (symbol-value keymap)))
256         ((keymapp keymap))
257         ((listp keymap)
258          (set (car keymap) nil)
259          (define-prefix-command (car keymap))
260          (define-key (symbol-value (caddr keymap)) (cadr keymap) (car keymap))
261          (setq keymap (symbol-value (car keymap)))))
262   (let (key)
263     (while plist
264       (when (symbolp (setq key (pop plist)))
265         (setq key (symbol-value key)))
266       (if (or (not safe)
267               (eq (lookup-key keymap key) 'undefined))
268           (define-key keymap key (pop plist))
269         (pop plist)))))
270
271 (defun gnus-completing-read (default prompt &rest args)
272   ;; Like `completing-read', except that DEFAULT is the default argument.
273   (let* ((prompt (if default
274                      (concat prompt " (default " default ") ")
275                    (concat prompt " ")))
276          (answer (apply 'completing-read prompt args)))
277     (if (or (null answer) (zerop (length answer)))
278         default
279       answer)))
280
281 ;; Two silly functions to ensure that all `y-or-n-p' questions clear
282 ;; the echo area.
283 (defun gnus-y-or-n-p (prompt)
284   (prog1
285       (y-or-n-p prompt)
286     (message "")))
287
288 (defun gnus-yes-or-no-p (prompt)
289   (prog1
290       (yes-or-no-p prompt)
291     (message "")))
292
293 (defun gnus-dd-mmm (messy-date)
294   "Return a string like DD-MMM from a big messy string."
295   (condition-case ()
296       (format-time-string "%d-%b" (safe-date-to-time messy-date))
297     (error "  -   ")))
298
299 (defmacro gnus-date-get-time (date)
300   "Convert DATE string to Emacs time.
301 Cache the result as a text property stored in DATE."
302   ;; Either return the cached value...
303   `(let ((d ,date))
304      (if (equal "" d)
305          '(0 0)
306        (or (get-text-property 0 'gnus-time d)
307            ;; or compute the value...
308            (let ((time (safe-date-to-time d)))
309              ;; and store it back in the string.
310              (put-text-property 0 1 'gnus-time time d)
311              time)))))
312
313 (defsubst gnus-time-iso8601 (time)
314   "Return a string of TIME in YYYYMMDDTHHMMSS format."
315   (format-time-string "%Y%m%dT%H%M%S" time))
316
317 (defun gnus-date-iso8601 (date)
318   "Convert the DATE to YYYYMMDDTHHMMSS."
319   (condition-case ()
320       (gnus-time-iso8601 (gnus-date-get-time date))
321     (error "")))
322
323 (defun gnus-mode-string-quote (string)
324   "Quote all \"%\"'s in STRING."
325   (save-excursion
326     (gnus-set-work-buffer)
327     (insert string)
328     (goto-char (point-min))
329     (while (search-forward "%" nil t)
330       (insert "%"))
331     (buffer-string)))
332
333 ;; Make a hash table (default and minimum size is 256).
334 ;; Optional argument HASHSIZE specifies the table size.
335 (defun gnus-make-hashtable (&optional hashsize)
336   (make-vector (if hashsize (max (gnus-create-hash-size hashsize) 256) 256) 0))
337
338 ;; Make a number that is suitable for hashing; bigger than MIN and
339 ;; equal to some 2^x.  Many machines (such as sparcs) do not have a
340 ;; hardware modulo operation, so they implement it in software.  On
341 ;; many sparcs over 50% of the time to intern is spent in the modulo.
342 ;; Yes, it's slower than actually computing the hash from the string!
343 ;; So we use powers of 2 so people can optimize the modulo to a mask.
344 (defun gnus-create-hash-size (min)
345   (let ((i 1))
346     (while (< i min)
347       (setq i (* 2 i)))
348     i))
349
350 (defcustom gnus-verbose 7
351   "*Integer that says how verbose Gnus should be.
352 The higher the number, the more messages Gnus will flash to say what
353 it's doing.  At zero, Gnus will be totally mute; at five, Gnus will
354 display most important messages; and at ten, Gnus will keep on
355 jabbering all the time."
356   :group 'gnus-start
357   :type 'integer)
358
359 ;; Show message if message has a lower level than `gnus-verbose'.
360 ;; Guideline for numbers:
361 ;; 1 - error messages, 3 - non-serious error messages, 5 - messages
362 ;; for things that take a long time, 7 - not very important messages
363 ;; on stuff, 9 - messages inside loops.
364 (defun gnus-message (level &rest args)
365   (if (<= level gnus-verbose)
366       (apply 'message args)
367     ;; We have to do this format thingy here even if the result isn't
368     ;; shown - the return value has to be the same as the return value
369     ;; from `message'.
370     (apply 'format args)))
371
372 (defun gnus-error (level &rest args)
373   "Beep an error if LEVEL is equal to or less than `gnus-verbose'."
374   (when (<= (floor level) gnus-verbose)
375     (apply 'message args)
376     (ding)
377     (let (duration)
378       (when (and (floatp level)
379                  (not (zerop (setq duration (* 10 (- level (floor level)))))))
380         (sit-for duration))))
381   nil)
382
383 (defun gnus-split-references (references)
384   "Return a list of Message-IDs in REFERENCES."
385   (let ((beg 0)
386         ids)
387     (while (string-match "<[^>]+>" references beg)
388       (push (substring references (match-beginning 0) (setq beg (match-end 0)))
389             ids))
390     (nreverse ids)))
391
392 (defsubst gnus-parent-id (references &optional n)
393   "Return the last Message-ID in REFERENCES.
394 If N, return the Nth ancestor instead."
395   (when references
396     (let ((ids (inline (gnus-split-references references))))
397       (while (nthcdr (or n 1) ids)
398         (setq ids (cdr ids)))
399       (car ids))))
400
401 (defsubst gnus-buffer-live-p (buffer)
402   "Say whether BUFFER is alive or not."
403   (and buffer
404        (get-buffer buffer)
405        (buffer-name (get-buffer buffer))))
406
407 (defun gnus-horizontal-recenter ()
408   "Recenter the current buffer horizontally."
409   (if (< (current-column) (/ (window-width) 2))
410       (set-window-hscroll (get-buffer-window (current-buffer) t) 0)
411     (let* ((orig (point))
412            (end (window-end (get-buffer-window (current-buffer) t)))
413            (max 0))
414       (when end
415         ;; Find the longest line currently displayed in the window.
416         (goto-char (window-start))
417         (while (and (not (eobp))
418                     (< (point) end))
419           (end-of-line)
420           (setq max (max max (current-column)))
421           (forward-line 1))
422         (goto-char orig)
423         ;; Scroll horizontally to center (sort of) the point.
424         (if (> max (window-width))
425             (set-window-hscroll
426              (get-buffer-window (current-buffer) t)
427              (min (- (current-column) (/ (window-width) 3))
428                   (+ 2 (- max (window-width)))))
429           (set-window-hscroll (get-buffer-window (current-buffer) t) 0))
430         max))))
431