*** empty log message ***
[gnus] / lisp / gnus-util.el
1 ;;; gnus-util.el --- utility functions for Gnus
2 ;; Copyright (C) 1996 Free Software Foundation, Inc.
3
4 ;; Author: Lars Magne Ingebrigtsen <larsi@ifi.uio.no>
5 ;; Keywords: news
6
7 ;; This file is part of GNU Emacs.
8
9 ;; GNU Emacs is free software; you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation; either version 2, or (at your option)
12 ;; any later version.
13
14 ;; GNU Emacs is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 ;; GNU General Public License for more details.
18
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
21 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
22 ;; Boston, MA 02111-1307, USA.
23
24 ;;; Commentary:
25
26 ;; Nothing in this file depends on any other parts of Gnus -- all
27 ;; functions and macros in this file are utility functions that are
28 ;; used by Gnus and may be used by any other package without loading
29 ;; Gnus first.
30
31 ;;; Code:
32
33 (require 'custom)
34 (require 'cl)
35 (require 'nnheader)
36 (require 'timezone)
37 (require 'message)
38
39 (defun gnus-boundp (variable)
40   "Return non-nil if VARIABLE is bound and non-nil."
41   (and (boundp variable)
42        (symbol-value variable)))
43
44 (defmacro gnus-eval-in-buffer-window (buffer &rest forms)
45   "Pop to BUFFER, evaluate FORMS, and then return to the original window."
46   (let ((tempvar (make-symbol "GnusStartBufferWindow"))
47         (w (make-symbol "w"))
48         (buf (make-symbol "buf")))
49     `(let* ((,tempvar (selected-window))
50             (,buf ,buffer)
51             (,w (get-buffer-window ,buf 'visible)))
52        (unwind-protect
53            (progn
54              (if ,w
55                  (select-window ,w)
56                (pop-to-buffer ,buf))
57              ,@forms)
58          (select-window ,tempvar)))))
59
60 (put 'gnus-eval-in-buffer-window 'lisp-indent-function 1)
61 (put 'gnus-eval-in-buffer-window 'edebug-form-spec '(form body))
62
63 (defmacro gnus-intern-safe (string hashtable)
64   "Set hash value.  Arguments are STRING, VALUE, and HASHTABLE."
65   `(let ((symbol (intern ,string ,hashtable)))
66      (or (boundp symbol)
67          (set symbol nil))
68      symbol))
69
70 ;; modified by MORIOKA Tomohiko <morioka@jaist.ac.jp>
71 ;;   function `substring' might cut on a middle of multi-octet
72 ;;   character.
73 (defun gnus-truncate-string (str width)
74   (substring str 0 width))
75
76 ;; Added by Geoffrey T. Dairiki <dairiki@u.washington.edu>.  A safe way
77 ;; to limit the length of a string.  This function is necessary since
78 ;; `(substr "abc" 0 30)' pukes with "Args out of range".
79 (defsubst gnus-limit-string (str width)
80   (if (> (length str) width)
81       (substring str 0 width)
82     str))
83
84 (defsubst gnus-functionp (form)
85   "Return non-nil if FORM is funcallable."
86   (or (and (symbolp form) (fboundp form))
87       (and (listp form) (eq (car form) 'lambda))))
88
89 (defsubst gnus-goto-char (point)
90   (and point (goto-char point)))
91
92 (defmacro gnus-buffer-exists-p (buffer)
93   `(let ((buffer ,buffer))
94      (when buffer
95        (funcall (if (stringp buffer) 'get-buffer 'buffer-name)
96                 buffer))))
97
98 (defmacro gnus-kill-buffer (buffer)
99   `(let ((buf ,buffer))
100      (when (gnus-buffer-exists-p buf)
101        (kill-buffer buf))))
102
103 (defsubst gnus-point-at-bol ()
104   "Return point at the beginning of the line."
105   (let ((p (point)))
106     (beginning-of-line)
107     (prog1
108         (point)
109       (goto-char p))))
110
111 (defsubst gnus-point-at-eol ()
112   "Return point at the end of the line."
113   (let ((p (point)))
114     (end-of-line)
115     (prog1
116         (point)
117       (goto-char p))))
118
119 (defun gnus-delete-first (elt list)
120   "Delete by side effect the first occurrence of ELT as a member of LIST."
121   (if (equal (car list) elt)
122       (cdr list)
123     (let ((total list))
124       (while (and (cdr list)
125                   (not (equal (cadr list) elt)))
126         (setq list (cdr list)))
127       (when (cdr list)
128         (setcdr list (cddr list)))
129       total)))
130
131 ;; Delete the current line (and the next N lines).
132 (defmacro gnus-delete-line (&optional n)
133   `(delete-region (progn (beginning-of-line) (point))
134                   (progn (forward-line ,(or n 1)) (point))))
135
136 (defun gnus-byte-code (func)
137   "Return a form that can be `eval'ed based on FUNC."
138   (let ((fval (symbol-function func)))
139     (if (byte-code-function-p fval)
140         (let ((flist (append fval nil)))
141           (setcar flist 'byte-code)
142           flist)
143       (cons 'progn (cddr fval)))))
144
145 (defun gnus-extract-address-components (from)
146   (let (name address)
147     ;; First find the address - the thing with the @ in it.  This may
148     ;; not be accurate in mail addresses, but does the trick most of
149     ;; the time in news messages.
150     (when (string-match "\\b[^@ \t<>]+[!@][^@ \t<>]+\\b" from)
151       (setq address (substring from (match-beginning 0) (match-end 0))))
152     ;; Then we check whether the "name <address>" format is used.
153     (and address
154          ;; Fix by MORIOKA Tomohiko <morioka@jaist.ac.jp>
155          ;; Linear white space is not required.
156          (string-match (concat "[ \t]*<" (regexp-quote address) ">") from)
157          (and (setq name (substring from 0 (match-beginning 0)))
158               ;; Strip any quotes from the name.
159               (string-match "\".*\"" name)
160               (setq name (substring name 1 (1- (match-end 0))))))
161     ;; If not, then "address (name)" is used.
162     (or name
163         (and (string-match "(.+)" from)
164              (setq name (substring from (1+ (match-beginning 0))
165                                    (1- (match-end 0)))))
166         (and (string-match "()" from)
167              (setq name address))
168         ;; Fix by MORIOKA Tomohiko <morioka@jaist.ac.jp>.
169         ;; XOVER might not support folded From headers.
170         (and (string-match "(.*" from)
171              (setq name (substring from (1+ (match-beginning 0))
172                                    (match-end 0)))))
173     ;; Fix by Hallvard B Furuseth <h.b.furuseth@usit.uio.no>.
174     (list (or name from) (or address from))))
175
176 (defun gnus-fetch-field (field)
177   "Return the value of the header FIELD of current article."
178   (save-excursion
179     (save-restriction
180       (let ((case-fold-search t)
181             (inhibit-point-motion-hooks t))
182         (nnheader-narrow-to-headers)
183         (message-fetch-field field)))))
184
185 (defun gnus-goto-colon ()
186   (beginning-of-line)
187   (search-forward ":" (gnus-point-at-eol) t))
188
189 (defun gnus-remove-text-with-property (prop)
190   "Delete all text in the current buffer with text property PROP."
191   (save-excursion
192     (goto-char (point-min))
193     (while (not (eobp))
194       (while (get-text-property (point) prop)
195         (delete-char 1))
196       (goto-char (next-single-property-change (point) prop nil (point-max))))))
197
198 (defun gnus-newsgroup-directory-form (newsgroup)
199   "Make hierarchical directory name from NEWSGROUP name."
200   (let ((newsgroup (gnus-newsgroup-savable-name newsgroup))
201         (len (length newsgroup))
202         idx)
203     ;; If this is a foreign group, we don't want to translate the
204     ;; entire name.
205     (if (setq idx (string-match ":" newsgroup))
206         (aset newsgroup idx ?/)
207       (setq idx 0))
208     ;; Replace all occurrences of `.' with `/'.
209     (while (< idx len)
210       (when (= (aref newsgroup idx) ?.)
211         (aset newsgroup idx ?/))
212       (setq idx (1+ idx)))
213     newsgroup))
214
215 (defun gnus-newsgroup-savable-name (group)
216   ;; Replace any slashes in a group name (eg. an ange-ftp nndoc group)
217   ;; with dots.
218   (nnheader-replace-chars-in-string group ?/ ?.))
219
220 (defun gnus-string> (s1 s2)
221   (not (or (string< s1 s2)
222            (string= s1 s2))))
223
224 ;;; Time functions.
225
226 (defun gnus-days-between (date1 date2)
227   ;; Return the number of days between date1 and date2.
228   (- (gnus-day-number date1) (gnus-day-number date2)))
229
230 (defun gnus-day-number (date)
231   (let ((dat (mapcar (lambda (s) (and s (string-to-int s)) )
232                      (timezone-parse-date date))))
233     (timezone-absolute-from-gregorian
234      (nth 1 dat) (nth 2 dat) (car dat))))
235
236 (defun gnus-time-to-day (time)
237   "Convert TIME to day number."
238   (let ((tim (decode-time time)))
239     (timezone-absolute-from-gregorian
240      (nth 4 tim) (nth 3 tim) (nth 5 tim))))
241
242 (defun gnus-encode-date (date)
243   "Convert DATE to internal time."
244   (let* ((parse (timezone-parse-date date))
245          (date (mapcar (lambda (d) (and d (string-to-int d))) parse))
246          (time (mapcar 'string-to-int (timezone-parse-time (aref parse 3)))))
247     (encode-time (caddr time) (cadr time) (car time)
248                  (caddr date) (cadr date) (car date) (nth 4 date))))
249
250 (defun gnus-time-minus (t1 t2)
251   "Subtract two internal times."
252   (let ((borrow (< (cadr t1) (cadr t2))))
253     (list (- (car t1) (car t2) (if borrow 1 0))
254           (- (+ (if borrow 65536 0) (cadr t1)) (cadr t2)))))
255
256 (defun gnus-time-less (t1 t2)
257   "Say whether time T1 is less than time T2."
258   (or (< (car t1) (car t2))
259       (and (= (car t1) (car t2))
260            (< (nth 1 t1) (nth 1 t2)))))
261
262 (defun gnus-file-newer-than (file date)
263   (let ((fdate (nth 5 (file-attributes file))))
264     (or (> (car fdate) (car date))
265         (and (= (car fdate) (car date))
266              (> (nth 1 fdate) (nth 1 date))))))
267
268 ;;; Keymap macros.
269
270 (defmacro gnus-local-set-keys (&rest plist)
271   "Set the keys in PLIST in the current keymap."
272   `(gnus-define-keys-1 (current-local-map) ',plist))
273
274 (defmacro gnus-define-keys (keymap &rest plist)
275   "Define all keys in PLIST in KEYMAP."
276   `(gnus-define-keys-1 (quote ,keymap) (quote ,plist)))
277
278 (defmacro gnus-define-keys-safe (keymap &rest plist)
279   "Define all keys in PLIST in KEYMAP without overwriting previous definitions."
280   `(gnus-define-keys-1 (quote ,keymap) (quote ,plist) t))
281
282 (put 'gnus-define-keys 'lisp-indent-function 1)
283 (put 'gnus-define-keys-safe 'lisp-indent-function 1)
284 (put 'gnus-local-set-keys 'lisp-indent-function 1)
285
286 (defmacro gnus-define-keymap (keymap &rest plist)
287   "Define all keys in PLIST in KEYMAP."
288   `(gnus-define-keys-1 ,keymap (quote ,plist)))
289
290 (put 'gnus-define-keymap 'lisp-indent-function 1)
291
292 (defun gnus-define-keys-1 (keymap plist &optional safe)
293   (when (null keymap)
294     (error "Can't set keys in a null keymap"))
295   (cond ((symbolp keymap)
296          (setq keymap (symbol-value keymap)))
297         ((keymapp keymap))
298         ((listp keymap)
299          (set (car keymap) nil)
300          (define-prefix-command (car keymap))
301          (define-key (symbol-value (caddr keymap)) (cadr keymap) (car keymap))
302          (setq keymap (symbol-value (car keymap)))))
303   (let (key)
304     (while plist
305       (when (symbolp (setq key (pop plist)))
306         (setq key (symbol-value key)))
307       (if (or (not safe)
308               (eq (lookup-key keymap key) 'undefined))
309           (define-key keymap key (pop plist))
310         (pop plist)))))
311
312 (defun gnus-completing-read (default prompt &rest args)
313   ;; Like `completing-read', except that DEFAULT is the default argument.
314   (let* ((prompt (if default 
315                      (concat prompt " (default " default ") ")
316                    (concat prompt " ")))
317          (answer (apply 'completing-read prompt args)))
318     (if (or (null answer) (zerop (length answer)))
319         default
320       answer)))
321
322 ;; Two silly functions to ensure that all `y-or-n-p' questions clear
323 ;; the echo area.
324 (defun gnus-y-or-n-p (prompt)
325   (prog1
326       (y-or-n-p prompt)
327     (message "")))
328
329 (defun gnus-yes-or-no-p (prompt)
330   (prog1
331       (yes-or-no-p prompt)
332     (message "")))
333
334 ;; I suspect there's a better way, but I haven't taken the time to do
335 ;; it yet.  -erik selberg@cs.washington.edu
336 (defun gnus-dd-mmm (messy-date)
337   "Return a string like DD-MMM from a big messy string"
338   (let ((datevec (ignore-errors (timezone-parse-date messy-date))))
339     (if (not datevec)
340         "??-???"
341       (format "%2s-%s"
342               (condition-case ()
343                   ;; Make sure leading zeroes are stripped.
344                   (number-to-string (string-to-number (aref datevec 2)))
345                 (error "??"))
346               (capitalize
347                (or (car
348                     (nth (1- (string-to-number (aref datevec 1)))
349                          timezone-months-assoc))
350                    "???"))))))
351
352 (defmacro gnus-date-get-time (date)
353   "Convert DATE string to Emacs time.
354 Cache the result as a text property stored in DATE."
355   ;; Either return the cached value...
356   `(let ((d ,date))
357      (if (equal "" d)
358          '(0 0)
359        (or (get-text-property 0 'gnus-time d)
360            ;; or compute the value...
361            (let ((time (nnmail-date-to-time d)))
362              ;; and store it back in the string.
363              (put-text-property 0 1 'gnus-time time d)
364              time)))))
365
366 (defsubst gnus-time-iso8601 (time)
367   "Return a string of TIME in YYMMDDTHHMMSS format."
368   (format-time-string "%Y%m%dT%H%M%S" time))
369   
370 (defun gnus-date-iso8601 (header)
371   "Convert the date field in HEADER to YYMMDDTHHMMSS"
372   (condition-case ()
373       (gnus-time-iso8601 (gnus-date-get-time (mail-header-date header)))
374     (error "")))
375
376 (defun gnus-mode-string-quote (string)
377   "Quote all \"%\"'s in STRING."
378   (save-excursion
379     (gnus-set-work-buffer)
380     (insert string)
381     (goto-char (point-min))
382     (while (search-forward "%" nil t)
383       (insert "%"))
384     (buffer-string)))
385
386 ;; Make a hash table (default and minimum size is 255).
387 ;; Optional argument HASHSIZE specifies the table size.
388 (defun gnus-make-hashtable (&optional hashsize)
389   (make-vector (if hashsize (max (gnus-create-hash-size hashsize) 255) 255) 0))
390
391 ;; Make a number that is suitable for hashing; bigger than MIN and one
392 ;; less than 2^x.
393 (defun gnus-create-hash-size (min)
394   (let ((i 1))
395     (while (< i min)
396       (setq i (* 2 i)))
397     (1- i)))
398
399 (defcustom gnus-verbose 7
400   "*Integer that says how verbose Gnus should be.
401 The higher the number, the more messages Gnus will flash to say what
402 it's doing.  At zero, Gnus will be totally mute; at five, Gnus will
403 display most important messages; and at ten, Gnus will keep on
404 jabbering all the time."
405   :group 'gnus-start
406   :type 'integer)
407
408 ;; Show message if message has a lower level than `gnus-verbose'.
409 ;; Guideline for numbers:
410 ;; 1 - error messages, 3 - non-serious error messages, 5 - messages
411 ;; for things that take a long time, 7 - not very important messages
412 ;; on stuff, 9 - messages inside loops.
413 (defun gnus-message (level &rest args)
414   (if (<= level gnus-verbose)
415       (apply 'message args)
416     ;; We have to do this format thingy here even if the result isn't
417     ;; shown - the return value has to be the same as the return value
418     ;; from `message'.
419     (apply 'format args)))
420
421 (defun gnus-error (level &rest args)
422   "Beep an error if LEVEL is equal to or less than `gnus-verbose'."
423   (when (<= (floor level) gnus-verbose)
424     (apply 'message args)
425     (ding)
426     (let (duration)
427       (when (and (floatp level)
428                  (not (zerop (setq duration (* 10 (- level (floor level)))))))
429         (sit-for duration))))
430   nil)
431
432 (defun gnus-parent-id (references &optional n)
433   "Return the last Message-ID in REFERENCES.
434 If N, return the Nth ancestor instead."
435   (when references
436     (let ((ids (gnus-split-references references)))
437       (car (last ids (or n 1))))))
438
439 (defun gnus-split-references (references)
440   "Return a list of Message-IDs in REFERENCES."
441   (let ((beg 0)
442         ids)
443     (while (string-match "<[^>]+>" references beg)
444       (push (substring references (match-beginning 0) (setq beg (match-end 0)))
445             ids))
446     (nreverse ids)))
447
448 (defun gnus-buffer-live-p (buffer)
449   "Say whether BUFFER is alive or not."
450   (and buffer
451        (get-buffer buffer)
452        (buffer-name (get-buffer buffer))))
453
454 (defun gnus-horizontal-recenter ()
455   "Recenter the current buffer horizontally."
456   (if (< (current-column) (/ (window-width) 2))
457       (set-window-hscroll (get-buffer-window (current-buffer) t) 0)
458     (let* ((orig (point))
459            (end (window-end (get-buffer-window (current-buffer) t)))
460            (max 0))
461       ;; Find the longest line currently displayed in the window.
462       (goto-char (window-start))
463       (while (and (not (eobp))
464                   (< (point) end))
465         (end-of-line)
466         (setq max (max max (current-column)))
467         (forward-line 1))
468       (goto-char orig)
469       ;; Scroll horizontally to center (sort of) the point.
470       (if (> max (window-width))
471           (set-window-hscroll 
472            (get-buffer-window (current-buffer) t)
473            (min (- (current-column) (/ (window-width) 3))
474                 (+ 2 (- max (window-width)))))
475         (set-window-hscroll (get-buffer-window (current-buffer) t) 0))
476       max)))
477
478 (defun gnus-read-event-char ()
479   "Get the next event."
480   (let ((event (read-event)))
481     (cons (and (numberp event) event) event)))
482
483 (defun gnus-sortable-date (date)
484   "Make sortable string by string-lessp from DATE.
485 Timezone package is used."
486   (condition-case ()
487       (progn
488         (setq date (inline (timezone-fix-time 
489                             date nil 
490                             (aref (inline (timezone-parse-date date)) 4))))
491         (inline
492           (timezone-make-sortable-date
493            (aref date 0) (aref date 1) (aref date 2)
494            (inline
495              (timezone-make-time-string
496               (aref date 3) (aref date 4) (aref date 5))))))
497     (error "")))
498   
499 (defun gnus-copy-file (file &optional to)
500   "Copy FILE to TO."
501   (interactive
502    (list (read-file-name "Copy file: " default-directory)
503          (read-file-name "Copy file to: " default-directory)))
504   (unless to
505     (setq to (read-file-name "Copy file to: " default-directory)))
506   (when (file-directory-p to)
507     (setq to (concat (file-name-as-directory to)
508                      (file-name-nondirectory file))))
509   (copy-file file to))
510
511 (defun gnus-kill-all-overlays ()
512   "Delete all overlays in the current buffer."
513   (when (fboundp 'overlay-lists)
514     (let* ((overlayss (overlay-lists))
515            (buffer-read-only nil)
516            (overlays (nconc (car overlayss) (cdr overlayss))))
517       (while overlays
518         (delete-overlay (pop overlays))))))
519
520 (defvar gnus-work-buffer " *gnus work*")
521
522 (defun gnus-set-work-buffer ()
523   "Put point in the empty Gnus work buffer."
524   (if (get-buffer gnus-work-buffer)
525       (progn
526         (set-buffer gnus-work-buffer)
527         (erase-buffer))
528     (set-buffer (get-buffer-create gnus-work-buffer))
529     (kill-all-local-variables)
530     (buffer-disable-undo (current-buffer))))
531
532 (defmacro gnus-group-real-name (group)
533   "Find the real name of a foreign newsgroup."
534   `(let ((gname ,group))
535      (if (string-match "^[^:]+:" gname)
536          (substring gname (match-end 0))
537        gname)))
538
539 (defun gnus-make-sort-function (funs)
540   "Return a composite sort condition based on the functions in FUNC."
541   (cond 
542    ((not (listp funs)) funs)
543    ((null funs) funs)
544    ((cdr funs)
545     `(lambda (t1 t2)
546        ,(gnus-make-sort-function-1 (reverse funs))))
547    (t
548     (car funs))))
549
550 (defun gnus-make-sort-function-1 (funs)
551   "Return a composite sort condition based on the functions in FUNC."
552   (if (cdr funs)
553       `(or (,(car funs) t1 t2)
554            (and (not (,(car funs) t2 t1))
555                 ,(gnus-make-sort-function-1 (cdr funs))))
556     `(,(car funs) t1 t2)))
557
558 (defun gnus-turn-off-edit-menu (type)
559   "Turn off edit meny in `gnus-TYPE-mode-map'."
560   (define-key (symbol-value (intern (format "gnus-%s-mode-map" type)))
561     [menu-bar edit] 'undefined))
562
563 (defun gnus-prin1 (form)
564   "Use `prin1' on FORM in the current buffer.
565 Bind `print-quoted' to t while printing."
566   (let ((print-quoted t))
567     (prin1 form (current-buffer))))
568
569 (defun gnus-prin1-to-string (form)
570   "The same as `prin1', but but `print-quoted' to t."
571   (prin1-to-string form))
572
573 (defun gnus-make-directory (directory)
574   "Make DIRECTORY (and all its parents) if it doesn't exist."
575   (when (and directory
576              (not (file-exists-p directory)))
577     (make-directory directory t))
578   t)
579
580 (defun gnus-write-buffer (file)
581   "Write the current buffer's contents to FILE."
582   ;; Make sure the directory exists.
583   (gnus-make-directory (file-name-directory file))
584   ;; Write the buffer.
585   (write-region (point-min) (point-max) file nil 'quietly))
586
587 (defmacro gnus-delete-assq (key list)
588   `(let ((listval (eval ,list)))
589      (setq ,list (delq (assq ,key listval) listval))))
590
591 (defmacro gnus-delete-assoc (key list)
592   `(let ((listval ,list))
593      (setq ,list (delq (assoc ,key listval) listval))))
594
595 (defun gnus-delete-file (file)
596   "Delete FILE if it exists."
597   (when (file-exists-p file)
598     (delete-file file)))
599
600 (provide 'gnus-util)
601
602 ;;; gnus-util.el ends here