*** 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 (defmacro gnus-eval-in-buffer-window (buffer &rest forms)
40   "Pop to BUFFER, evaluate FORMS, and then return to the original window."
41   (let ((tempvar (make-symbol "GnusStartBufferWindow"))
42         (w (make-symbol "w"))
43         (buf (make-symbol "buf")))
44     `(let* ((,tempvar (selected-window))
45             (,buf ,buffer)
46             (,w (get-buffer-window ,buf 'visible)))
47        (unwind-protect
48            (progn
49              (if ,w
50                  (select-window ,w)
51                (pop-to-buffer ,buf))
52              ,@forms)
53          (select-window ,tempvar)))))
54
55 (put 'gnus-eval-in-buffer-window 'lisp-indent-function 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      (when buffer
90        (funcall (if (stringp buffer) 'get-buffer 'buffer-name)
91                 buffer))))
92
93 (defmacro gnus-kill-buffer (buffer)
94   `(let ((buf ,buffer))
95      (when (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     (when (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       (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-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-safe 'lisp-indent-function 1)
279 (put 'gnus-local-set-keys 'lisp-indent-function 1)
280
281 (defmacro gnus-define-keymap (keymap &rest plist)
282   "Define all keys in PLIST in KEYMAP."
283   `(gnus-define-keys-1 ,keymap (quote ,plist)))
284
285 (put 'gnus-define-keymap 'lisp-indent-function 1)
286
287 (defun gnus-define-keys-1 (keymap plist &optional safe)
288   (when (null keymap)
289     (error "Can't set keys in a null keymap"))
290   (cond ((symbolp keymap)
291          (setq keymap (symbol-value keymap)))
292         ((keymapp keymap))
293         ((listp keymap)
294          (set (car keymap) nil)
295          (define-prefix-command (car keymap))
296          (define-key (symbol-value (caddr keymap)) (cadr keymap) (car keymap))
297          (setq keymap (symbol-value (car keymap)))))
298   (let (key)
299     (while plist
300       (when (symbolp (setq key (pop plist)))
301         (setq key (symbol-value key)))
302       (if (or (not safe)
303               (eq (lookup-key keymap key) 'undefined))
304           (define-key keymap key (pop plist))
305         (pop plist)))))
306
307 (defun gnus-completing-read (default prompt &rest args)
308   ;; Like `completing-read', except that DEFAULT is the default argument.
309   (let* ((prompt (if default 
310                      (concat prompt " (default " default ") ")
311                    (concat prompt " ")))
312          (answer (apply 'completing-read prompt args)))
313     (if (or (null answer) (zerop (length answer)))
314         default
315       answer)))
316
317 ;; Two silly functions to ensure that all `y-or-n-p' questions clear
318 ;; the echo area.
319 (defun gnus-y-or-n-p (prompt)
320   (prog1
321       (y-or-n-p prompt)
322     (message "")))
323
324 (defun gnus-yes-or-no-p (prompt)
325   (prog1
326       (yes-or-no-p prompt)
327     (message "")))
328
329 ;; I suspect there's a better way, but I haven't taken the time to do
330 ;; it yet.  -erik selberg@cs.washington.edu
331 (defun gnus-dd-mmm (messy-date)
332   "Return a string like DD-MMM from a big messy string"
333   (let ((datevec (ignore-errors (timezone-parse-date messy-date))))
334     (if (not datevec)
335         "??-???"
336       (format "%2s-%s"
337               (condition-case ()
338                   ;; Make sure leading zeroes are stripped.
339                   (number-to-string (string-to-number (aref datevec 2)))
340                 (error "??"))
341               (capitalize
342                (or (car
343                     (nth (1- (string-to-number (aref datevec 1)))
344                          timezone-months-assoc))
345                    "???"))))))
346
347 (defmacro gnus-date-get-time (date)
348   "Convert DATE string to Emacs time.
349 Cache the result as a text property stored in DATE."
350   ;; Either return the cached value...
351   `(let ((d ,date))
352      (if (equal "" d)
353          '(0 0)
354        (or (get-text-property 0 'gnus-time d)
355            ;; or compute the value...
356            (let ((time (nnmail-date-to-time d)))
357              ;; and store it back in the string.
358              (put-text-property 0 1 'gnus-time time d)
359              time)))))
360
361 (defsubst gnus-time-iso8601 (time)
362   "Return a string of TIME in YYMMDDTHHMMSS format."
363   (format-time-string "%Y%m%dT%H%M%S" time))
364   
365 (defun gnus-date-iso8601 (header)
366   "Convert the date field in HEADER to YYMMDDTHHMMSS"
367   (condition-case ()
368       (gnus-time-iso8601 (gnus-date-get-time (mail-header-date header)))
369     (error "")))
370
371 (defun gnus-mode-string-quote (string)
372   "Quote all \"%\"'s in STRING."
373   (save-excursion
374     (gnus-set-work-buffer)
375     (insert string)
376     (goto-char (point-min))
377     (while (search-forward "%" nil t)
378       (insert "%"))
379     (buffer-string)))
380
381 ;; Make a hash table (default and minimum size is 255).
382 ;; Optional argument HASHSIZE specifies the table size.
383 (defun gnus-make-hashtable (&optional hashsize)
384   (make-vector (if hashsize (max (gnus-create-hash-size hashsize) 255) 255) 0))
385
386 ;; Make a number that is suitable for hashing; bigger than MIN and one
387 ;; less than 2^x.
388 (defun gnus-create-hash-size (min)
389   (let ((i 1))
390     (while (< i min)
391       (setq i (* 2 i)))
392     (1- i)))
393
394 (defcustom gnus-verbose 7
395   "*Integer that says how verbose Gnus should be.
396 The higher the number, the more messages Gnus will flash to say what
397 it's doing.  At zero, Gnus will be totally mute; at five, Gnus will
398 display most important messages; and at ten, Gnus will keep on
399 jabbering all the time."
400   :group 'gnus-start
401   :type 'integer)
402
403 ;; Show message if message has a lower level than `gnus-verbose'.
404 ;; Guideline for numbers:
405 ;; 1 - error messages, 3 - non-serious error messages, 5 - messages
406 ;; for things that take a long time, 7 - not very important messages
407 ;; on stuff, 9 - messages inside loops.
408 (defun gnus-message (level &rest args)
409   (if (<= level gnus-verbose)
410       (apply 'message args)
411     ;; We have to do this format thingy here even if the result isn't
412     ;; shown - the return value has to be the same as the return value
413     ;; from `message'.
414     (apply 'format args)))
415
416 (defun gnus-error (level &rest args)
417   "Beep an error if LEVEL is equal to or less than `gnus-verbose'."
418   (when (<= (floor level) gnus-verbose)
419     (apply 'message args)
420     (ding)
421     (let (duration)
422       (when (and (floatp level)
423                  (not (zerop (setq duration (* 10 (- level (floor level)))))))
424         (sit-for duration))))
425   nil)
426
427 (defun gnus-parent-id (references &optional n)
428   "Return the last Message-ID in REFERENCES.
429 If N, return the Nth ancestor instead."
430   (when references
431     (let ((ids (gnus-split-references references)))
432       (car (last ids (or n 1))))))
433
434 (defun gnus-split-references (references)
435   "Return a list of Message-IDs in REFERENCES."
436   (let ((beg 0)
437         ids)
438     (while (string-match "<[^>]+>" references beg)
439       (push (substring references (match-beginning 0) (setq beg (match-end 0)))
440             ids))
441     (nreverse ids)))
442
443 (defun gnus-buffer-live-p (buffer)
444   "Say whether BUFFER is alive or not."
445   (and buffer
446        (get-buffer buffer)
447        (buffer-name (get-buffer buffer))))
448
449 (defun gnus-horizontal-recenter ()
450   "Recenter the current buffer horizontally."
451   (if (< (current-column) (/ (window-width) 2))
452       (set-window-hscroll (get-buffer-window (current-buffer) t) 0)
453     (let* ((orig (point))
454            (end (window-end (get-buffer-window (current-buffer) t)))
455            (max 0))
456       ;; Find the longest line currently displayed in the window.
457       (goto-char (window-start))
458       (while (and (not (eobp))
459                   (< (point) end))
460         (end-of-line)
461         (setq max (max max (current-column)))
462         (forward-line 1))
463       (goto-char orig)
464       ;; Scroll horizontally to center (sort of) the point.
465       (if (> max (window-width))
466           (set-window-hscroll 
467            (get-buffer-window (current-buffer) t)
468            (min (- (current-column) (/ (window-width) 3))
469                 (+ 2 (- max (window-width)))))
470         (set-window-hscroll (get-buffer-window (current-buffer) t) 0))
471       max)))
472
473 (defun gnus-read-event-char ()
474   "Get the next event."
475   (let ((event (read-event)))
476     (cons (and (numberp event) event) event)))
477
478 (defun gnus-sortable-date (date)
479   "Make sortable string by string-lessp from DATE.
480 Timezone package is used."
481   (condition-case ()
482       (progn
483         (setq date (inline (timezone-fix-time 
484                             date nil 
485                             (aref (inline (timezone-parse-date date)) 4))))
486         (inline
487           (timezone-make-sortable-date
488            (aref date 0) (aref date 1) (aref date 2)
489            (inline
490              (timezone-make-time-string
491               (aref date 3) (aref date 4) (aref date 5))))))
492     (error "")))
493   
494 (defun gnus-copy-file (file &optional to)
495   "Copy FILE to TO."
496   (interactive
497    (list (read-file-name "Copy file: " default-directory)
498          (read-file-name "Copy file to: " default-directory)))
499   (unless to
500     (setq to (read-file-name "Copy file to: " default-directory)))
501   (when (file-directory-p to)
502     (setq to (concat (file-name-as-directory to)
503                      (file-name-nondirectory file))))
504   (copy-file file to))
505
506 (defun gnus-kill-all-overlays ()
507   "Delete all overlays in the current buffer."
508   (when (fboundp 'overlay-lists)
509     (let* ((overlayss (overlay-lists))
510            (buffer-read-only nil)
511            (overlays (nconc (car overlayss) (cdr overlayss))))
512       (while overlays
513         (delete-overlay (pop overlays))))))
514
515 (defvar gnus-work-buffer " *gnus work*")
516
517 (defun gnus-set-work-buffer ()
518   "Put point in the empty Gnus work buffer."
519   (if (get-buffer gnus-work-buffer)
520       (progn
521         (set-buffer gnus-work-buffer)
522         (erase-buffer))
523     (set-buffer (get-buffer-create gnus-work-buffer))
524     (kill-all-local-variables)
525     (buffer-disable-undo (current-buffer))))
526
527 (defmacro gnus-group-real-name (group)
528   "Find the real name of a foreign newsgroup."
529   `(let ((gname ,group))
530      (if (string-match "^[^:]+:" gname)
531          (substring gname (match-end 0))
532        gname)))
533
534 (defun gnus-make-sort-function (funs)
535   "Return a composite sort condition based on the functions in FUNC."
536   (cond 
537    ((not (listp funs)) funs)
538    ((null funs) funs)
539    ((cdr funs)
540     `(lambda (t1 t2)
541        ,(gnus-make-sort-function-1 (reverse funs))))
542    (t
543     (car funs))))
544
545 (defun gnus-make-sort-function-1 (funs)
546   "Return a composite sort condition based on the functions in FUNC."
547   (if (cdr funs)
548       `(or (,(car funs) t1 t2)
549            (and (not (,(car funs) t2 t1))
550                 ,(gnus-make-sort-function-1 (cdr funs))))
551     `(,(car funs) t1 t2)))
552
553 (defun gnus-turn-off-edit-menu (type)
554   "Turn off edit meny in `gnus-TYPE-mode-map'."
555   (define-key (symbol-value (intern (format "gnus-%s-mode-map" type)))
556     [menu-bar edit] 'undefined))
557
558 (defun gnus-prin1 (form)
559   "Use `prin1' on FORM in the current buffer.
560 Bind `print-quoted' to t while printing."
561   (let ((print-quoted t))
562     (prin1 form (current-buffer))))
563
564 (defun gnus-prin1-to-string (form)
565   "The same as `prin1', but but `print-quoted' to t."
566   (prin1-to-string form))
567
568 (defun gnus-make-directory (directory)
569   "Make DIRECTORY (and all its parents) if it doesn't exist."
570   (when (not (file-exists-p directory))
571     (make-directory directory t))
572   t)
573
574 (defun gnus-write-buffer (file)
575   "Write the current buffer's contents to FILE."
576   ;; Make sure the directory exists.
577   (gnus-make-directory (file-name-directory file))
578   ;; Write the buffer.
579   (write-region (point-min) (point-max) file nil 'quietly))
580
581 (defmacro gnus-delete-assq (key list)
582   `(let ((listval (eval ,list)))
583      (setq ,list (delq (assq ,key listval) listval))))
584
585 (defmacro gnus-delete-assoc (key list)
586   `(let ((listval ,list))
587      (setq ,list (delq (assoc ,key listval) listval))))
588
589 (defun gnus-delete-file (file)
590   "Delete FILE if it exists."
591   (when (file-exists-p file)
592     (delete-file file)))
593
594 (provide 'gnus-util)
595
596 ;;; gnus-util.el ends here