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