Update.
[elisp/wanderlust.git] / wl / wl-util.el
1 ;;; wl-util.el --- Utility modules for Wanderlust.
2
3 ;; Copyright (C) 1998,1999,2000 Yuuichi Teranishi <teranisi@gohome.org>
4 ;; Copyright (C) 2000 A. SAGATA <sagata@nttvdt.hil.ntt.co.jp>
5 ;; Copyright (C) 2000 Katsumi Yamaoka <yamaoka@jpl.org>
6
7 ;; Author: Yuuichi Teranishi <teranisi@gohome.org>
8 ;;      A. SAGATA <sagata@nttvdt.hil.ntt.co.jp>
9 ;;      Katsumi Yamaoka <yamaoka@jpl.org>
10 ;; Keywords: mail, net news
11
12 ;; This file is part of Wanderlust (Yet Another Message Interface on Emacsen).
13
14 ;; This program is free software; you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation; either version 2, or (at your option)
17 ;; any later version.
18 ;;
19 ;; This program is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22 ;; GNU General Public License for more details.
23 ;;
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
26 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
27 ;; Boston, MA 02111-1307, USA.
28 ;;
29
30 ;;; Commentary:
31 ;;
32
33 ;;; Code:
34 ;;
35 (require 'bytecomp)
36 (eval-when-compile
37   (require 'elmo-util))
38
39 (condition-case nil (require 'pp) (error nil))
40
41 (eval-when-compile
42   (require 'time-stamp)
43   (defalias-maybe 'next-command-event 'ignore)
44   (defalias-maybe 'event-to-character 'ignore)
45   (defalias-maybe 'key-press-event-p 'ignore)
46   (defalias-maybe 'button-press-event-p 'ignore)
47   (defalias-maybe 'set-process-kanji-code 'ignore)
48   (defalias-maybe 'set-process-coding-system 'ignore)
49   (defalias-maybe 'dispatch-event 'ignore))
50
51 (defalias 'wl-set-work-buf 'elmo-set-work-buf)
52 (make-obsolete 'wl-set-work-buf 'elmo-set-work-buf)
53
54 (defmacro wl-append (val func)
55   (list 'if val
56       (list 'nconc val func)
57     (list 'setq val func)))
58
59 (defalias 'wl-parse 'elmo-parse)
60 (make-obsolete 'wl-parse 'elmo-parse)
61
62 (defun wl-delete-duplicates (list &optional all hack-addresses)
63   "Delete duplicate equivalent strings from the LIST.
64 If ALL is t, then if there is more than one occurrence of a string in the LIST,
65  then all occurrences of it are removed instead of just the subsequent ones.
66 If HACK-ADDRESSES is t, then the strings are considered to be mail addresses,
67  and only the address part is compared (so that \"Name <foo>\" and \"foo\"
68  would be considered to be equivalent.)"
69   (let ((hashtable (make-vector 29 0))
70         (new-list nil)
71         sym-string sym)
72     (fillarray hashtable 0)
73     (while list
74       (setq sym-string
75             (if hack-addresses
76                 (wl-address-header-extract-address (car list))
77               (car list))
78             sym-string (or sym-string "-unparseable-garbage-")
79             sym (intern sym-string hashtable))
80       (if (boundp sym)
81           (and all (setcar (symbol-value sym) nil))
82         (setq new-list (cons (car list) new-list))
83         (set sym new-list))
84       (setq list (cdr list)))
85     (delq nil (nreverse new-list))))
86
87 ;; string utils.
88 (defalias 'wl-string-member 'elmo-string-member)
89 (defalias 'wl-string-match-member 'elmo-string-match-member)
90 (defalias 'wl-string-delete-match 'elmo-string-delete-match)
91 (defalias 'wl-string-match-assoc 'elmo-string-match-assoc)
92 (defalias 'wl-string-assoc 'elmo-string-assoc)
93 (defalias 'wl-string-rassoc 'elmo-string-rassoc)
94
95 (defun wl-parse-addresses (string)
96   (if (null string)
97       ()
98     (elmo-set-work-buf
99      ;;(unwind-protect
100      (let (list start s char)
101        (insert string)
102        (goto-char (point-min))
103        (skip-chars-forward "\t\f\n\r ")
104        (setq start (point))
105        (while (not (eobp))
106          (skip-chars-forward "^\"\\,(")
107          (setq char (following-char))
108          (cond ((= char ?\\)
109                 (forward-char 1)
110                 (if (not (eobp))
111                     (forward-char 1)))
112                ((= char ?,)
113                 (setq s (buffer-substring start (point)))
114                 (if (or (null (string-match "^[\t\f\n\r ]+$" s))
115                         (not (string= s "")))
116                     (setq list (cons s list)))
117                 (skip-chars-forward ",\t\f\n\r ")
118                 (setq start (point)))
119                ((= char ?\")
120                 (re-search-forward "[^\\]\"" nil 0))
121                ((= char ?\()
122                 (let ((parens 1))
123                   (forward-char 1)
124                   (while (and (not (eobp)) (not (zerop parens)))
125                     (re-search-forward "[()]" nil 0)
126                     (cond ((or (eobp)
127                                (= (char-after (- (point) 2)) ?\\)))
128                           ((= (preceding-char) ?\()
129                            (setq parens (1+ parens)))
130                           (t
131                            (setq parens (1- parens)))))))))
132        (setq s (buffer-substring start (point)))
133        (if (and (null (string-match "^[\t\f\n\r ]+$" s))
134                 (not (string= s "")))
135            (setq list (cons s list)))
136        (nreverse list)) ; jwz: fixed order
137      )))
138
139 (defun wl-append-element (list element)
140   (if element
141       (append list (list element))
142     list))
143
144 (defmacro wl-push (v l)
145   "Insert V at the head of the list stored in L."
146   (list 'setq l (list 'cons v l)))
147
148 (defmacro wl-pop (l)
149   "Remove the head of the list stored in L."
150   (list 'car (list 'prog1 l (list 'setq l (list 'cdr l)))))
151
152 (defun wl-ask-folder (func mes-string)
153   (let* (key keve
154              (cmd (if (featurep 'xemacs)
155                       (event-to-character last-command-event)
156                     (string-to-char (format "%s" (this-command-keys))))))
157     (message "%s" mes-string)
158     (setq key (car (setq keve (wl-read-event-char))))
159     (if (or (equal key ?\ )
160             (and cmd
161                  (equal key cmd)))
162         (progn
163           (message "")
164           (funcall func))
165       (wl-push (cdr keve) unread-command-events))))
166
167 (defun wl-require-update-all-folder-p (name)
168   "Return non-nil if NAME is draft or queue folder."
169   (or (string= name wl-draft-folder)
170       (string= name wl-queue-folder)))
171
172 ;(defalias 'wl-make-hash 'elmo-make-hash)
173 ;;(make-obsolete 'wl-make-hash 'elmo-make-hash)
174
175 ;;(defalias 'wl-get-hash-val 'elmo-get-hash-val)
176 ;;(make-obsolete 'wl-get-hash-val 'elmo-get-hash-val)
177
178 ;;(defalias 'wl-set-hash-val 'elmo-set-hash-val)
179 ;;(make-obsolete 'wl-set-hash-val 'elmo-set-hash-val)
180
181 (defsubst wl-set-string-width (width string &optional padding ignore-invalid)
182   "Make a new string which have specified WIDTH and content of STRING.
183 `wl-invalid-character-message' is used when invalid character is contained.
184 If WIDTH is negative number, padding chars are added to the head and
185 otherwise, padding chars are added to the tail of the string.
186 The optional 3rd arg PADDING, if non-nil, specifies a padding character
187 to add the result instead of white space.
188 If optional 4th argument is non-nil, don't use `wl-invalid-character-message'
189 even when invalid character is contained."
190   (static-cond
191    ((and (fboundp 'string-width) (fboundp 'truncate-string-to-width)
192          (not (featurep 'xemacs)))
193     (if (> (string-width string) (abs width))
194         (setq string (truncate-string-to-width string (abs width))))
195     (if (= (string-width string) (abs width))
196         string
197       (when (and (not ignore-invalid)
198                  (< (abs width) (string-width string)))
199         (setq string
200               (truncate-string-to-width wl-invalid-character-message
201                                         (abs width))))
202       (let ((paddings (make-string
203                        (max 0 (- (abs width) (string-width string)))
204                        (or padding ?\ ))))
205         (if (< width 0)
206             (concat paddings string)
207           (concat string paddings)))))
208    (t
209     (elmo-set-work-buf
210      (elmo-set-buffer-multibyte default-enable-multibyte-characters)
211      (insert string)
212      (when (> (current-column) (abs width))
213        (when (> (move-to-column (abs width)) (abs width))
214          (condition-case nil ; ignore error
215              (backward-char 1)
216            (error)))
217        (setq string (buffer-substring (point-min) (point))))
218      (if (= (current-column) (abs width))
219          string
220        (let ((paddings (make-string (- (abs width) (current-column))
221                                     (or padding ?\ ))))
222          (if (< width 0)
223              (concat paddings string)
224            (concat string paddings))))))))
225
226 (defun wl-mode-line-buffer-identification (&optional id)
227   (let ((priorities '(biff plug title)))
228     (let ((items (reverse wl-mode-line-display-priority-list))
229           item)
230       (while items
231         (setq item (car items)
232               items (cdr items))
233         (unless (memq item '(biff plug))
234           (setq item 'title))
235         (setq priorities (cons item (delq item priorities)))))
236     (let (priority result)
237       (while priorities
238         (setq priority (car priorities)
239               priorities (cdr priorities))
240         (cond
241          ((eq 'biff priority)
242           (when wl-biff-check-folder-list
243             (setq result (append result '((wl-modeline-biff-status
244                                            wl-modeline-biff-state-on
245                                            wl-modeline-biff-state-off))))))
246          ((eq 'plug priority)
247           (when wl-show-plug-status-on-modeline
248             (setq result (append result '((wl-modeline-plug-status
249                                            wl-modeline-plug-state-on
250                                            wl-modeline-plug-state-off))))))
251          (t
252           (setq result (append result (or id '("Wanderlust: %12b")))))))
253       (prog1
254           (setq mode-line-buffer-identification (if (stringp (car result))
255                                                     result
256                                                   (cons "" result)))
257         (force-mode-line-update t)))))
258
259 (defalias 'wl-display-error 'elmo-display-error)
260 (make-obsolete 'wl-display-error 'elmo-display-error)
261
262 (defun wl-get-assoc-list-value (assoc-list folder &optional match)
263   (catch 'found
264     (let ((alist assoc-list)
265           value pair)
266       (while alist
267         (setq pair (car alist))
268         (if (and (eq match 'function)
269                  (functionp (car pair)))
270             (when (funcall (car pair) folder)
271               (throw 'found (cdr pair)))
272           (if (string-match (car pair) folder)
273               (cond ((eq match 'all)
274                      (setq value (append value (list (cdr pair)))))
275                     ((eq match 'all-list)
276                      (setq value (append value (cdr pair))))
277                     ((or (not match) (eq match 'function))
278                      (throw 'found (cdr pair))))))
279         (setq alist (cdr alist)))
280       value)))
281
282 (defmacro wl-match-string (pos string)
283   "Substring POSth matched STRING."
284   (` (substring (, string) (match-beginning (, pos)) (match-end (, pos)))))
285
286 (defmacro wl-match-buffer (pos)
287   "Substring POSth matched from the current buffer."
288   (` (buffer-substring-no-properties
289       (match-beginning (, pos)) (match-end (, pos)))))
290
291 (put 'wl-as-coding-system 'lisp-indent-function 1)
292 (put 'wl-as-mime-charset 'lisp-indent-function 1)
293
294 (eval-and-compile
295   (cond
296    (wl-on-mule3
297     (defmacro wl-as-coding-system (coding-system &rest body)
298       (` (let ((coding-system-for-read (, coding-system))
299                (coding-system-for-write (, coding-system)))
300            (,@ body)))))
301    (wl-on-mule
302     (defmacro wl-as-coding-system (coding-system &rest body)
303       (` (let ((file-coding-system-for-read (, coding-system))
304                (file-coding-system (, coding-system)))
305            (,@ body)))))
306    (t
307     (defmacro wl-as-coding-system (coding-system &rest body)
308       (` (progn (,@ body)))))))
309
310 (defmacro wl-as-mime-charset (mime-charset &rest body)
311   (` (wl-as-coding-system (mime-charset-to-coding-system (, mime-charset))
312        (,@ body))))
313
314 (defalias 'wl-string 'elmo-string)
315 (make-obsolete 'wl-string 'elmo-string)
316
317 ;; Check if active region exists or not.
318 (if (boundp 'mark-active)
319     (defmacro wl-region-exists-p ()
320       'mark-active)
321   (if (fboundp 'region-exists-p)
322       (defmacro wl-region-exists-p ()
323         (list 'region-exists-p))))
324
325 (if (not (fboundp 'overlays-in))
326     (defun overlays-in (beg end)
327       "Return a list of the overlays that overlap the region BEG ... END.
328 Overlap means that at least one character is contained within the overlay
329 and also contained within the specified region.
330 Empty overlays are included in the result if they are located at BEG
331 or between BEG and END."
332       (let ((ovls (overlay-lists))
333             tmp retval)
334         (if (< end beg)
335             (setq tmp end
336                   end beg
337                   beg tmp))
338         (setq ovls (nconc (car ovls) (cdr ovls)))
339         (while ovls
340           (setq tmp (car ovls)
341                 ovls (cdr ovls))
342           (if (or (and (<= (overlay-start tmp) end)
343                        (>= (overlay-start tmp) beg))
344                   (and (<= (overlay-end tmp) end)
345                        (>= (overlay-end tmp) beg)))
346               (setq retval (cons tmp retval))))
347         retval)))
348
349 (defsubst wl-repeat-string (str times)
350   (let ((loop times)
351         ret-val)
352     (while (> loop 0)
353       (setq ret-val (concat ret-val str))
354       (setq loop (- loop 1)))
355     ret-val))
356
357 (defun wl-list-diff (list1 list2)
358   "Return a list of elements of LIST1 that do not appear in LIST2."
359   (let ((list1 (copy-sequence list1)))
360     (while list2
361       (setq list1 (delq (car list2) list1))
362       (setq list2 (cdr list2)))
363     list1))
364
365 (defun wl-append-assoc-list (item value alist)
366   "make assoc list '((item1 value1-1 value1-2 ...)) (item2 value2-1 ...)))"
367   (let ((entry (assoc item alist)))
368     (if entry
369         (progn
370           (when (not (member value (cdr entry)))
371             (nconc entry (list value)))
372           alist)
373       (append alist
374               (list (list item value))))))
375
376 (defun wl-delete-alist (key alist)
377   "Delete by side effect any entries specified with KEY from ALIST.
378 Return the modified ALIST.  Key comparison is done with `assq'.
379 Write `(setq foo (wl-delete-alist key foo))' to be sure of changing
380 the value of `foo'."
381   (let (entry)
382     (while (setq entry (assq key alist))
383       (setq alist (delq entry alist)))
384     alist))
385
386 (defun wl-delete-associations (keys alist)
387   "Delete by side effect any entries specified with KEYS from ALIST.
388 Return the modified ALIST.  KEYS must be a list of keys for ALIST.
389 Deletion is done with `wl-delete-alist'.
390 Write `(setq foo (wl-delete-associations keys foo))' to be sure of
391 changing the value of `foo'."
392   (while keys
393     (setq alist (wl-delete-alist (car keys) alist))
394     (setq keys (cdr keys)))
395   alist)
396
397 (defun wl-inverse-alist (keys alist)
398   "Inverse ALIST, copying.
399 Return an association list represents the inverse mapping of ALIST,
400 from objects to KEYS.
401 The objects mapped (cdrs of elements of the ALIST) are shared."
402   (let (x y tmp result)
403     (while keys
404       (setq x (car keys))
405       (setq y (cdr (assq x alist)))
406       (if y
407           (if (setq tmp (assoc y result))
408               (setq result (cons (append tmp (list x))
409                                  (delete tmp result)))
410             (setq result (cons (list y x) result))))
411       (setq keys (cdr keys)))
412     result))
413
414 (eval-when-compile
415   (require 'static))
416 (static-unless (fboundp 'pp)
417   (defvar pp-escape-newlines t)
418   (defun pp (object &optional stream)
419     "Output the pretty-printed representation of OBJECT, any Lisp object.
420 Quoting characters are printed when needed to make output that `read'
421 can handle, whenever this is possible.
422 Output stream is STREAM, or value of `standard-output' (which see)."
423     (princ (pp-to-string object) (or stream standard-output)))
424
425   (defun pp-to-string (object)
426     "Return a string containing the pretty-printed representation of OBJECT,
427 any Lisp object.  Quoting characters are used when needed to make output
428 that `read' can handle, whenever this is possible."
429     (save-excursion
430       (set-buffer (generate-new-buffer " pp-to-string"))
431       (unwind-protect
432           (progn
433             (lisp-mode-variables t)
434             (let ((print-escape-newlines pp-escape-newlines))
435               (prin1 object (current-buffer)))
436             (goto-char (point-min))
437             (while (not (eobp))
438               (cond
439                ((looking-at "\\s(\\|#\\s(")
440                 (while (looking-at "\\s(\\|#\\s(")
441                   (forward-char 1)))
442                ((and (looking-at "\\(quote[ \t]+\\)\\([^.)]\\)")
443                      (> (match-beginning 1) 1)
444                      (= ?\( (char-after (1- (match-beginning 1))))
445                      ;; Make sure this is a two-element list.
446                      (save-excursion
447                        (goto-char (match-beginning 2))
448                        (forward-sexp)
449                        ;; Avoid mucking with match-data; does this test work?
450                        (char-equal ?\) (char-after (point)))))
451                 ;; -1 gets the paren preceding the quote as well.
452                 (delete-region (1- (match-beginning 1)) (match-end 1))
453                 (insert "'")
454                 (forward-sexp 1)
455                 (if (looking-at "[ \t]*\)")
456                     (delete-region (match-beginning 0) (match-end 0))
457                   (error "Malformed quote"))
458                 (backward-sexp 1))
459                ((condition-case err-var
460                     (prog1 t (down-list 1))
461                   (error nil))
462                 (backward-char 1)
463                 (skip-chars-backward " \t")
464                 (delete-region
465                  (point)
466                  (progn (skip-chars-forward " \t") (point)))
467                 (if (not (char-equal ?' (char-after (1- (point)))))
468                     (insert ?\n)))
469                ((condition-case err-var
470                     (prog1 t (up-list 1))
471                   (error nil))
472                 (while (looking-at "\\s)")
473                   (forward-char 1))
474                 (skip-chars-backward " \t")
475                 (delete-region
476                  (point)
477                  (progn (skip-chars-forward " \t") (point)))
478                 (if (not (char-equal ?' (char-after (1- (point)))))
479                     (insert ?\n)))
480                (t (goto-char (point-max)))))
481             (goto-char (point-min))
482             (indent-sexp)
483             (buffer-string))
484         (kill-buffer (current-buffer))))))
485
486 (defsubst wl-get-date-iso8601 (date)
487   (or (get-text-property 0 'wl-date date)
488       (let* ((d1 (timezone-fix-time date nil nil))
489              (time (format "%04d%02d%02dT%02d%02d%02d"
490                            (aref d1 0) (aref d1 1) (aref d1 2)
491                            (aref d1 3) (aref d1 4) (aref d1 5))))
492         (put-text-property 0 1 'wl-date time date)
493         time)))
494
495 (defun wl-make-date-string ()
496   (let ((s (current-time-string)))
497     (string-match "\\`\\([A-Z][a-z][a-z]\\) +[A-Z][a-z][a-z] +[0-9][0-9]? *[0-9][0-9]?:[0-9][0-9]:[0-9][0-9] *[0-9]?[0-9]?[0-9][0-9]"
498                   s)
499     (concat (wl-match-string 1 s) ", "
500             (timezone-make-date-arpa-standard s (current-time-zone)))))
501
502 (defun wl-date-iso8601 (date)
503   "Convert the DATE to YYMMDDTHHMMSS."
504   (condition-case ()
505       (wl-get-date-iso8601 date)
506     (error "")))
507
508 (defun wl-day-number (date)
509   (let ((dat (mapcar '(lambda (s) (and s (string-to-int s)) )
510                      (timezone-parse-date date))))
511     (timezone-absolute-from-gregorian
512      (nth 1 dat) (nth 2 dat) (car dat))))
513
514 (defun wl-url-news (url &rest args)
515   (interactive "sURL: ")
516   (if (string-match "^news:\\(.*\\)$" url)
517       (wl-summary-goto-folder-subr
518        (concat "-" (elmo-match-string 1 url)) nil nil nil t)
519     (message "Not a news: url.")))
520
521 (defun wl-url-nntp (url &rest args)
522   (interactive "sURL: ")
523   (let (folder fld-name server port msg)
524     (if (string-match
525          "^nntp://\\([^:/]*\\):?\\([0-9]*\\)/\\([^/]*\\)/\\([0-9]*\\).*$" url)
526         (progn
527           (if (eq (length (setq fld-name
528                                 (elmo-match-string 3 url))) 0)
529               (setq fld-name nil))
530           (if (eq (length (setq port
531                                 (elmo-match-string 2 url))) 0)
532               (setq port (int-to-string elmo-nntp-default-port)))
533           (if (eq (length (setq server
534                                 (elmo-match-string 1 url))) 0)
535               (setq server elmo-nntp-default-server))
536           (setq folder (concat "-" fld-name "@" server ":" port))
537           (if (eq (length (setq msg
538                                 (elmo-match-string 4 url))) 0)
539               (wl-summary-goto-folder-subr
540                folder nil nil nil t)
541             (wl-summary-goto-folder-subr
542              folder 'update nil nil t)
543             (goto-char (point-min))
544             (re-search-forward (concat "^ *" msg) nil t)
545             (wl-summary-redisplay)))
546       (message "Not a nntp: url."))))
547
548 (defmacro wl-concat-list (list separator)
549   (` (mapconcat 'identity (delete "" (delq nil (, list))) (, separator))))
550
551 (defun wl-current-message-buffer ()
552   (when (buffer-live-p wl-current-summary-buffer)
553     (with-current-buffer wl-current-summary-buffer
554       (car (wl-message-buffer-display wl-summary-buffer-elmo-folder
555                                       (wl-summary-message-number)
556                                       'mime)))))
557
558 (defmacro wl-kill-buffers (regexp)
559   (` (mapcar (function
560               (lambda (x)
561                 (if (and (buffer-name x)
562                          (string-match (, regexp) (buffer-name x)))
563                     (and (get-buffer x)
564                          (kill-buffer x)))))
565              (buffer-list))))
566
567 (defun wl-collect-summary ()
568   (let (result)
569     (mapcar
570      (function (lambda (x)
571                  (if (and (string-match "^Summary"
572                                         (buffer-name x))
573                           (save-excursion
574                             (set-buffer x)
575                             (equal major-mode 'wl-summary-mode)))
576                      (setq result (nconc result (list x))))))
577      (buffer-list))
578     result))
579
580 (defun wl-collect-draft ()
581   (let ((draft-regexp (concat
582                        "^" (regexp-quote wl-draft-folder)))
583         result buf)
584     (mapcar
585      (function (lambda (x)
586                  (if (with-current-buffer x
587                        (and (eq major-mode 'wl-draft-mode)
588                             (buffer-name)
589                             (string-match draft-regexp (buffer-name))))
590                      (setq result (nconc result (list x))))))
591      (buffer-list))
592     result))
593
594 (static-if (fboundp 'read-directory-name)
595     (defun wl-read-directory-name (prompt dir)
596       (read-directory-name prompt dir dir))
597   (defun wl-read-directory-name (prompt dir)
598     (let ((dir (read-file-name prompt dir)))
599       (unless (file-directory-p dir)
600         (error "%s is not directory" dir))
601       dir)))
602
603 ;; local variable check.
604 (static-if (fboundp 'local-variable-p)
605     (defalias 'wl-local-variable-p 'local-variable-p)
606   (defmacro wl-local-variable-p (symbol &optional buffer)
607     (` (if (assq (, symbol) (buffer-local-variables (, buffer)))
608            t))))
609
610 (defun wl-number-base36 (num len)
611   (if (if (< len 0)
612           (<= num 0)
613         (= len 0))
614       ""
615     (concat (wl-number-base36 (/ num 36) (1- len))
616             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
617                                   (% num 36))))))
618
619 (defvar wl-unique-id-char nil)
620
621 (defun wl-unique-id ()
622   ;; Don't use microseconds from (current-time), they may be unsupported.
623   ;; Instead we use this randomly inited counter.
624   (setq wl-unique-id-char
625         (% (1+ (or wl-unique-id-char (logand (random t) (1- (lsh 1 20)))))
626            ;; (current-time) returns 16-bit ints,
627            ;; and 2^16*25 just fits into 4 digits i base 36.
628            (* 25 25)))
629   (let ((tm (static-if (fboundp 'current-time)
630                 (current-time)
631               (let* ((cts (split-string (current-time-string) "[ :]"))
632                      (m (cdr (assoc (nth 1 cts)
633                                     '(("Jan" . "01") ("Feb" . "02")
634                                       ("Mar" . "03") ("Apr" . "04")
635                                       ("May" . "05") ("Jun" . "06")
636                                       ("Jul" . "07") ("Aug" . "08")
637                                       ("Sep" . "09") ("Oct" . "10")
638                                       ("Nov" . "11") ("Dec" . "12"))))))
639                 (list (string-to-int (concat (nth 6 cts) m
640                                              (substring (nth 2 cts) 0 1)))
641                       (string-to-int (concat (substring (nth 2 cts) 1)
642                                              (nth 4 cts) (nth 5 cts)
643                                              (nth 6 cts))))))))
644     (concat
645      (if (memq system-type '(ms-dos emx vax-vms))
646          (let ((user (downcase (user-login-name))))
647            (while (string-match "[^a-z0-9_]" user)
648              (aset user (match-beginning 0) ?_))
649            user)
650        (wl-number-base36 (user-uid) -1))
651      (wl-number-base36 (+ (car   tm)
652                           (lsh (% wl-unique-id-char 25) 16)) 4)
653      (wl-number-base36 (+ (nth 1 tm)
654                           (lsh (/ wl-unique-id-char 25) 16)) 4)
655      ;; Append the name of the message interface, because while the
656      ;; generated ID is unique to this newsreader, other newsreaders
657      ;; might otherwise generate the same ID via another algorithm.
658      wl-unique-id-suffix)))
659
660 (defvar wl-message-id-function 'wl-draft-make-message-id-string)
661 (defun wl-draft-make-message-id-string ()
662   "Return Message-ID field value."
663   (concat "<" (wl-unique-id)
664           (let (from user domain)
665             (if (and wl-message-id-use-wl-from
666                      (progn
667                        (setq from (wl-address-header-extract-address wl-from))
668                        (and (string-match "^\\(.*\\)@\\(.*\\)$" from)
669                             (setq user   (match-string 1 from))
670                             (setq domain (match-string 2 from)))))
671                 (format "%%%s@%s>" user domain)
672               (format "@%s>"
673                       (or wl-message-id-domain
674                           (if wl-local-domain
675                               (concat (system-name) "." wl-local-domain)
676                             (system-name))))))))
677
678 ;;; Profile loading.
679 (defvar wl-load-profile-function 'wl-local-load-profile)
680 (defun wl-local-load-profile ()
681   "Load `wl-init-file'."
682   (message "Initializing...")
683   (load wl-init-file 'noerror 'nomessage))
684
685 (defun wl-load-profile ()
686   "Call `wl-load-profile-function' function."
687   (funcall wl-load-profile-function))
688
689 ;;;
690
691 (defmacro wl-count-lines ()
692   (` (save-excursion
693        (beginning-of-line)
694        (count-lines 1 (point)))))
695
696 (defun wl-horizontal-recenter ()
697   "Recenter the current buffer horizontally."
698   (beginning-of-line)
699   (re-search-forward "[[<]" (point-at-eol) t)
700   (if (< (current-column) (/ (window-width) 2))
701       (set-window-hscroll (get-buffer-window (current-buffer) t) 0)
702     (let* ((orig (point))
703            (end (window-end (get-buffer-window (current-buffer) t)))
704            (max 0))
705       (when end
706         ;; Find the longest line currently displayed in the window.
707         (goto-char (window-start))
708         (while (and (not (eobp))
709                     (< (point) end))
710           (end-of-line)
711           (setq max (max max (current-column)))
712           (forward-line 1))
713         (goto-char orig)
714         ;; Scroll horizontally to center (sort of) the point.
715         (if (> max (window-width))
716             (set-window-hscroll
717              (get-buffer-window (current-buffer) t)
718              (min (- (current-column) (/ (window-width) 3))
719                   (+ 2 (- max (window-width)))))
720           (set-window-hscroll (get-buffer-window (current-buffer) t) 0))
721         max))))
722
723 ;; Biff
724 (static-cond
725  (wl-on-xemacs
726   (defvar wl-biff-timer-name "wl-biff")
727
728   (defun wl-biff-stop ()
729     (when (get-itimer wl-biff-timer-name)
730       (delete-itimer wl-biff-timer-name)))
731
732   (defun wl-biff-start ()
733     (wl-biff-stop)
734     (when wl-biff-check-folder-list
735       (wl-biff-check-folders)
736       (start-itimer wl-biff-timer-name 'wl-biff-check-folders
737                     wl-biff-check-interval wl-biff-check-interval))))
738
739  ((and (condition-case nil (require 'timer) (error nil));; FSFmacs 19+
740        (fboundp 'timer-activate))
741
742   (defun wl-biff-stop ()
743     (when (get 'wl-biff 'timer)
744       (cancel-timer (get 'wl-biff 'timer))))
745
746   (defun wl-biff-start ()
747     (require 'timer)
748     (when wl-biff-check-folder-list
749       (wl-biff-check-folders)
750       (if (get 'wl-biff 'timer)
751           (timer-activate (get 'wl-biff 'timer))
752         (put 'wl-biff 'timer (run-at-time
753                               (timer-next-integral-multiple-of-time
754                                (current-time) wl-biff-check-interval)
755                               wl-biff-check-interval
756                               'wl-biff-event-handler)))))
757
758   (defun-maybe timer-next-integral-multiple-of-time (time secs)
759     "Yield the next value after TIME that is an integral multiple of SECS.
760 More precisely, the next value, after TIME, that is an integral multiple
761 of SECS seconds since the epoch.  SECS may be a fraction.
762 This function is imported from Emacs 20.7."
763     (let ((time-base (ash 1 16)))
764       (if (fboundp 'atan)
765           ;; Use floating point, taking care to not lose precision.
766           (let* ((float-time-base (float time-base))
767                  (million 1000000.0)
768                  (time-usec (+ (* million
769                                   (+ (* float-time-base (nth 0 time))
770                                      (nth 1 time)))
771                                (nth 2 time)))
772                  (secs-usec (* million secs))
773                  (mod-usec (mod time-usec secs-usec))
774                  (next-usec (+ (- time-usec mod-usec) secs-usec))
775                  (time-base-million (* float-time-base million)))
776             (list (floor next-usec time-base-million)
777                   (floor (mod next-usec time-base-million) million)
778                   (floor (mod next-usec million))))
779         ;; Floating point is not supported.
780         ;; Use integer arithmetic, avoiding overflow if possible.
781         (let* ((mod-sec (mod (+ (* (mod time-base secs)
782                                    (mod (nth 0 time) secs))
783                                 (nth 1 time))
784                              secs))
785                (next-1-sec (+ (- (nth 1 time) mod-sec) secs)))
786           (list (+ (nth 0 time) (floor next-1-sec time-base))
787                 (mod next-1-sec time-base)
788                 0)))))
789
790   (defun wl-biff-event-handler ()
791     ;; PAKURing from FSF:time.el
792     (wl-biff-check-folders)
793     ;; Do redisplay right now, if no input pending.
794     (sit-for 0)
795     (let* ((current (current-time))
796            (timer (get 'wl-biff 'timer))
797            ;; Compute the time when this timer will run again, next.
798            (next-time (timer-relative-time
799                        (list (aref timer 1) (aref timer 2) (aref timer 3))
800                        (* 5 (aref timer 4)) 0)))
801       ;; If the activation time is far in the past,
802       ;; skip executions until we reach a time in the future.
803       ;; This avoids a long pause if Emacs has been suspended for hours.
804       (or (> (nth 0 next-time) (nth 0 current))
805           (and (= (nth 0 next-time) (nth 0 current))
806                (> (nth 1 next-time) (nth 1 current)))
807           (and (= (nth 0 next-time) (nth 0 current))
808                (= (nth 1 next-time) (nth 1 current))
809                (> (nth 2 next-time) (nth 2 current)))
810           (progn
811             (timer-set-time timer (timer-next-integral-multiple-of-time
812                                    current wl-biff-check-interval)
813                             wl-biff-check-interval)
814             (timer-activate timer))))))
815  (t
816   (fset 'wl-biff-stop 'ignore)
817   (fset 'wl-biff-start 'ignore)))
818
819 (defsubst wl-biff-notify (new-mails notify-minibuf)
820   (when (and (not wl-modeline-biff-status) (> new-mails 0))
821     (run-hooks 'wl-biff-notify-hook))
822   (when (and wl-modeline-biff-status (eq new-mails 0))
823     (run-hooks 'wl-biff-unnotify-hook))
824   (setq wl-modeline-biff-status (> new-mails 0))
825   (force-mode-line-update t)
826   (when notify-minibuf
827     (cond ((zerop new-mails) (message "No mail."))
828           ((= 1 new-mails) (message "You have a new mail."))
829           (t (message "You have %d new mails." new-mails)))))
830
831 ;; Internal variable.
832 (defvar wl-biff-check-folders-running nil)
833
834 (defun wl-biff-check-folders ()
835   (interactive)
836   (if wl-biff-check-folders-running
837       (when (interactive-p)
838         (message "Biff process is running."))
839     (setq wl-biff-check-folders-running t)
840     (when (interactive-p)
841       (message "Checking new mails..."))
842     (let ((new-mails 0)
843           (flist (or wl-biff-check-folder-list (list wl-default-folder)))
844           folder)
845       (if (eq (length flist) 1)
846           (wl-biff-check-folder-async (wl-folder-get-elmo-folder
847                                        (car flist) 'biff) (interactive-p))
848         (unwind-protect
849             (while flist
850               (setq folder (wl-folder-get-elmo-folder (car flist))
851                     flist (cdr flist))
852               (when (elmo-folder-plugged-p folder)
853                 (setq new-mails
854                       (+ new-mails
855                          (nth 0 (wl-biff-check-folder folder))))))
856           (setq wl-biff-check-folders-running nil)
857           (wl-biff-notify new-mails (interactive-p)))))))
858
859 (defun wl-biff-check-folder (folder)
860   (if (eq (elmo-folder-type-internal folder) 'pop3)
861       (unless (elmo-pop3-get-session folder 'any-exists)
862         (wl-folder-check-one-entity (elmo-folder-name-internal folder)
863                                     'biff))
864     (wl-folder-check-one-entity (elmo-folder-name-internal folder)
865                                 'biff)))
866
867 (defun wl-biff-check-folder-async-callback (diff data)
868   (if (nth 1 data)
869       (with-current-buffer (nth 1 data)
870         (wl-folder-entity-hashtb-set wl-folder-entity-hashtb
871                                      (nth 0 data)
872                                      (list (nth 0 diff)
873                                            (- (nth 1 diff) (nth 0 diff))
874                                            (nth 2 diff))
875                                      (current-buffer))))
876   (setq wl-folder-info-alist-modified t)
877   (setq wl-biff-check-folders-running nil)
878   (sit-for 0)
879   (wl-biff-notify (car diff) (nth 2 data)))
880
881 (defun wl-biff-check-folder-async (folder notify-minibuf)
882   (when (elmo-folder-plugged-p folder)
883     (elmo-folder-set-biff-internal folder t)
884     (if (and (eq (elmo-folder-type-internal folder) 'imap4)
885              (elmo-folder-use-flag-p folder))
886         ;; Check asynchronously only when IMAP4 and use server diff.
887         (progn
888           (setq elmo-folder-diff-async-callback
889                 'wl-biff-check-folder-async-callback)
890           (setq elmo-folder-diff-async-callback-data
891                 (list (elmo-folder-name-internal folder)
892                       (get-buffer wl-folder-buffer-name)
893                       notify-minibuf))
894           (elmo-folder-diff-async folder))
895       (unwind-protect
896           (wl-biff-notify (car (wl-biff-check-folder folder))
897                           notify-minibuf)
898         (setq wl-biff-check-folders-running nil)))))
899
900 (if (and (fboundp 'regexp-opt)
901          (not (featurep 'xemacs)))
902     (defalias 'wl-regexp-opt 'regexp-opt)
903   (defun wl-regexp-opt (strings &optional paren)
904     "Return a regexp to match a string in STRINGS.
905 Each string should be unique in STRINGS and should not contain any regexps,
906 quoted or not.  If optional PAREN is non-nil, ensure that the returned regexp
907 is enclosed by at least one regexp grouping construct."
908     (let ((open-paren (if paren "\\(" "")) (close-paren (if paren "\\)" "")))
909       (concat open-paren (mapconcat 'regexp-quote strings "\\|")
910               close-paren))))
911
912 (defalias 'wl-expand-newtext 'elmo-expand-newtext)
913 (defalias 'wl-regexp-opt 'elmo-regexp-opt)
914
915 (defun wl-region-exists-p ()
916   "Return non-nil if a region exists on current buffer."
917   (static-if (featurep 'xemacs)
918       (and zmacs-regions zmacs-region-active-p)
919     (and transient-mark-mode mark-active)))
920
921 (defvar wl-line-string)
922 (defun wl-line-parse-format (format spec-alist)
923   "Make a formatter from FORMAT and SPEC-ALIST."
924   (let (f spec specs stack)
925     (setq f
926           (with-temp-buffer
927             (insert format)
928             (goto-char (point-min))
929             (while (search-forward "%" nil t)
930               (cond
931                ((looking-at "%")
932                 (goto-char (match-end 0)))
933                ((looking-at "\\(-?\\(0?\\)[0-9]*\\)\\([^0-9]\\)")
934                 (cond
935                  ((string= (match-string 3) "(")
936                   (if (zerop (length (match-string 1)))
937                       (error "No number specification for %%( line format"))
938                   (push (list
939                          (match-beginning 0) ; start
940                          (match-end 0)       ; start-content
941                          (string-to-number
942                           (match-string 1))  ; width
943                          specs) ; specs
944                         stack)
945                   (setq specs nil))
946                  ((string= (match-string 3) ")")
947                   (let ((entry (pop stack))
948                         form)
949                     (unless entry
950                       (error
951                        "No matching %%( parenthesis in summary line format"))
952                     (goto-char (car entry)) ; start
953                     (setq form (buffer-substring (nth 1 entry) ; start-content
954                                                  (- (match-beginning 0) 1)))
955                     (delete-region (car entry) (match-end 0))
956                     (insert "s")
957                     (setq specs
958                           (append
959                            (nth 3 entry)
960                            (list (list 'wl-set-string-width (nth 2 entry)
961                                        (append
962                                         (list 'format form)
963                                         specs)))))))
964                  (t
965                   (setq spec
966                         (if (setq spec (assq (string-to-char (match-string 3))
967                                              spec-alist))
968                             (nth 1 spec)
969                           (match-string 3)))
970                   (unless (string= "" (match-string 1))
971                     (setq spec (list 'wl-set-string-width
972                                      (string-to-number (match-string 1))
973                                      spec
974                                      (unless (string= "" (match-string 2))
975                                        (string-to-char (match-string 2))))))
976                   (replace-match "s" 'fixed)
977                   (setq specs (append specs
978                                       (list
979                                        (list
980                                         'setq 'wl-line-string
981                                         spec)))))))))
982             (buffer-string)))
983     (append (list 'format f) specs)))
984
985 (defmacro wl-line-formatter-setup (formatter format alist)
986   (` (let (byte-compile-warnings)
987        (setq (, formatter)
988              (byte-compile
989               (list 'lambda ()
990                     (wl-line-parse-format (, format) (, alist)))))
991        (when (get-buffer "*Compile-Log*")
992          (bury-buffer "*Compile-Log*"))
993        (when (get-buffer "*Compile-Log-Show*")
994          (bury-buffer "*Compile-Log-Show*")))))
995
996 (defsubst wl-copy-local-variables (src dst local-variables)
997   "Copy value of LOCAL-VARIABLES from SRC buffer to DST buffer."
998   (with-current-buffer dst
999     (dolist (variable local-variables)
1000       (set (make-local-variable variable)
1001            (with-current-buffer src
1002              (symbol-value variable))))))
1003
1004 (require 'product)
1005 (product-provide (provide 'wl-util) (require 'wl-version))
1006
1007 ;;; wl-util.el ends here