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