* wl-dnd.el (wl-dnd-drop-func): Fix.
[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 (if (not (fboundp 'overlays-in))
318     (defun overlays-in (beg end)
319       "Return a list of the overlays that overlap the region BEG ... END.
320 Overlap means that at least one character is contained within the overlay
321 and also contained within the specified region.
322 Empty overlays are included in the result if they are located at BEG
323 or between BEG and END."
324       (let ((ovls (overlay-lists))
325             tmp retval)
326         (if (< end beg)
327             (setq tmp end
328                   end beg
329                   beg tmp))
330         (setq ovls (nconc (car ovls) (cdr ovls)))
331         (while ovls
332           (setq tmp (car ovls)
333                 ovls (cdr ovls))
334           (if (or (and (<= (overlay-start tmp) end)
335                        (>= (overlay-start tmp) beg))
336                   (and (<= (overlay-end tmp) end)
337                        (>= (overlay-end tmp) beg)))
338               (setq retval (cons tmp retval))))
339         retval)))
340
341 (defsubst wl-repeat-string (str times)
342   (let ((loop times)
343         ret-val)
344     (while (> loop 0)
345       (setq ret-val (concat ret-val str))
346       (setq loop (- loop 1)))
347     ret-val))
348
349 (defun wl-list-diff (list1 list2)
350   "Return a list of elements of LIST1 that do not appear in LIST2."
351   (let ((list1 (copy-sequence list1)))
352     (while list2
353       (setq list1 (delq (car list2) list1))
354       (setq list2 (cdr list2)))
355     list1))
356
357 (defun wl-append-assoc-list (item value alist)
358   "make assoc list '((item1 value1-1 value1-2 ...)) (item2 value2-1 ...)))"
359   (let ((entry (assoc item alist)))
360     (if entry
361         (progn
362           (when (not (member value (cdr entry)))
363             (nconc entry (list value)))
364           alist)
365       (append alist
366               (list (list item value))))))
367
368 (defun wl-delete-alist (key alist)
369   "Delete by side effect any entries specified with KEY from ALIST.
370 Return the modified ALIST.  Key comparison is done with `assq'.
371 Write `(setq foo (wl-delete-alist key foo))' to be sure of changing
372 the value of `foo'."
373   (let (entry)
374     (while (setq entry (assq key alist))
375       (setq alist (delq entry alist)))
376     alist))
377
378 (defun wl-delete-associations (keys alist)
379   "Delete by side effect any entries specified with KEYS from ALIST.
380 Return the modified ALIST.  KEYS must be a list of keys for ALIST.
381 Deletion is done with `wl-delete-alist'.
382 Write `(setq foo (wl-delete-associations keys foo))' to be sure of
383 changing the value of `foo'."
384   (while keys
385     (setq alist (wl-delete-alist (car keys) alist))
386     (setq keys (cdr keys)))
387   alist)
388
389 (defun wl-inverse-alist (keys alist)
390   "Inverse ALIST, copying.
391 Return an association list represents the inverse mapping of ALIST,
392 from objects to KEYS.
393 The objects mapped (cdrs of elements of the ALIST) are shared."
394   (let (x y tmp result)
395     (while keys
396       (setq x (car keys))
397       (setq y (cdr (assq x alist)))
398       (if y
399           (if (setq tmp (assoc y result))
400               (setq result (cons (append tmp (list x))
401                                  (delete tmp result)))
402             (setq result (cons (list y x) result))))
403       (setq keys (cdr keys)))
404     result))
405
406 (eval-when-compile
407   (require 'static))
408 (static-unless (fboundp 'pp)
409   (defvar pp-escape-newlines t)
410   (defun pp (object &optional stream)
411     "Output the pretty-printed representation of OBJECT, any Lisp object.
412 Quoting characters are printed when needed to make output that `read'
413 can handle, whenever this is possible.
414 Output stream is STREAM, or value of `standard-output' (which see)."
415     (princ (pp-to-string object) (or stream standard-output)))
416
417   (defun pp-to-string (object)
418     "Return a string containing the pretty-printed representation of OBJECT,
419 any Lisp object.  Quoting characters are used when needed to make output
420 that `read' can handle, whenever this is possible."
421     (save-excursion
422       (set-buffer (generate-new-buffer " pp-to-string"))
423       (unwind-protect
424           (progn
425             (lisp-mode-variables t)
426             (let ((print-escape-newlines pp-escape-newlines))
427               (prin1 object (current-buffer)))
428             (goto-char (point-min))
429             (while (not (eobp))
430               (cond
431                ((looking-at "\\s(\\|#\\s(")
432                 (while (looking-at "\\s(\\|#\\s(")
433                   (forward-char 1)))
434                ((and (looking-at "\\(quote[ \t]+\\)\\([^.)]\\)")
435                      (> (match-beginning 1) 1)
436                      (= ?\( (char-after (1- (match-beginning 1))))
437                      ;; Make sure this is a two-element list.
438                      (save-excursion
439                        (goto-char (match-beginning 2))
440                        (forward-sexp)
441                        ;; Avoid mucking with match-data; does this test work?
442                        (char-equal ?\) (char-after (point)))))
443                 ;; -1 gets the paren preceding the quote as well.
444                 (delete-region (1- (match-beginning 1)) (match-end 1))
445                 (insert "'")
446                 (forward-sexp 1)
447                 (if (looking-at "[ \t]*\)")
448                     (delete-region (match-beginning 0) (match-end 0))
449                   (error "Malformed quote"))
450                 (backward-sexp 1))
451                ((condition-case err-var
452                     (prog1 t (down-list 1))
453                   (error nil))
454                 (backward-char 1)
455                 (skip-chars-backward " \t")
456                 (delete-region
457                  (point)
458                  (progn (skip-chars-forward " \t") (point)))
459                 (if (not (char-equal ?' (char-after (1- (point)))))
460                     (insert ?\n)))
461                ((condition-case err-var
462                     (prog1 t (up-list 1))
463                   (error nil))
464                 (while (looking-at "\\s)")
465                   (forward-char 1))
466                 (skip-chars-backward " \t")
467                 (delete-region
468                  (point)
469                  (progn (skip-chars-forward " \t") (point)))
470                 (if (not (char-equal ?' (char-after (1- (point)))))
471                     (insert ?\n)))
472                (t (goto-char (point-max)))))
473             (goto-char (point-min))
474             (indent-sexp)
475             (buffer-string))
476         (kill-buffer (current-buffer))))))
477
478 (defsubst wl-get-date-iso8601 (date)
479   (or (get-text-property 0 'wl-date date)
480       (let* ((d1 (timezone-fix-time date nil nil))
481              (time (format "%04d%02d%02dT%02d%02d%02d"
482                            (aref d1 0) (aref d1 1) (aref d1 2)
483                            (aref d1 3) (aref d1 4) (aref d1 5))))
484         (put-text-property 0 1 'wl-date time date)
485         time)))
486
487 (defun wl-make-date-string ()
488   (let ((s (current-time-string)))
489     (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]"
490                   s)
491     (concat (wl-match-string 1 s) ", "
492             (timezone-make-date-arpa-standard s (current-time-zone)))))
493
494 (defun wl-date-iso8601 (date)
495   "Convert the DATE to YYMMDDTHHMMSS."
496   (condition-case ()
497       (wl-get-date-iso8601 date)
498     (error "")))
499
500 (defun wl-day-number (date)
501   (let ((dat (mapcar '(lambda (s) (and s (string-to-int s)) )
502                      (timezone-parse-date date))))
503     (timezone-absolute-from-gregorian
504      (nth 1 dat) (nth 2 dat) (car dat))))
505
506 (defun wl-url-news (url &rest args)
507   (interactive "sURL: ")
508   (if (string-match "^news:\\(.*\\)$" url)
509       (wl-summary-goto-folder-subr
510        (concat "-" (elmo-match-string 1 url)) nil nil nil t)
511     (message "Not a news: url.")))
512
513 (defun wl-url-nntp (url &rest args)
514   (interactive "sURL: ")
515   (let (folder fld-name server port msg)
516     (if (string-match
517          "^nntp://\\([^:/]*\\):?\\([0-9]*\\)/\\([^/]*\\)/\\([0-9]*\\).*$" url)
518         (progn
519           (if (eq (length (setq fld-name
520                                 (elmo-match-string 3 url))) 0)
521               (setq fld-name nil))
522           (if (eq (length (setq port
523                                 (elmo-match-string 2 url))) 0)
524               (setq port (int-to-string elmo-nntp-default-port)))
525           (if (eq (length (setq server
526                                 (elmo-match-string 1 url))) 0)
527               (setq server elmo-nntp-default-server))
528           (setq folder (concat "-" fld-name "@" server ":" port))
529           (if (eq (length (setq msg
530                                 (elmo-match-string 4 url))) 0)
531               (wl-summary-goto-folder-subr
532                folder nil nil nil t)
533             (wl-summary-goto-folder-subr
534              folder 'update nil nil t)
535             (wl-summary-jump-to-msg (string-to-number msg))
536             (wl-summary-redisplay)))
537       (message "Not a nntp: url."))))
538
539 (defmacro wl-concat-list (list separator)
540   (` (mapconcat 'identity (delete "" (delq nil (, list))) (, separator))))
541
542 (defun wl-current-message-buffer ()
543   (when (buffer-live-p wl-current-summary-buffer)
544     (with-current-buffer wl-current-summary-buffer
545       (or wl-message-buffer
546           (and (wl-summary-message-number)
547                (car (wl-message-buffer-display wl-summary-buffer-elmo-folder
548                                                (wl-summary-message-number)
549                                                'mime)))))))
550
551 (defmacro wl-kill-buffers (regexp)
552   (` (mapcar (function
553               (lambda (x)
554                 (if (and (buffer-name x)
555                          (string-match (, regexp) (buffer-name x)))
556                     (and (get-buffer x)
557                          (kill-buffer x)))))
558              (buffer-list))))
559
560 (defun wl-collect-summary ()
561   (let (result)
562     (mapcar
563      (function (lambda (x)
564                  (if (and (string-match "^Summary"
565                                         (buffer-name x))
566                           (save-excursion
567                             (set-buffer x)
568                             (equal major-mode 'wl-summary-mode)))
569                      (setq result (nconc result (list x))))))
570      (buffer-list))
571     result))
572
573 (defun wl-collect-draft ()
574   (let ((draft-regexp (concat
575                        "^" (regexp-quote wl-draft-folder)))
576         result buf)
577     (mapcar
578      (function (lambda (x)
579                  (if (with-current-buffer x
580                        (and (eq major-mode 'wl-draft-mode)
581                             (buffer-name)
582                             (string-match draft-regexp (buffer-name))))
583                      (setq result (nconc result (list x))))))
584      (buffer-list))
585     result))
586
587 (static-if (fboundp 'read-directory-name)
588     (defun wl-read-directory-name (prompt dir)
589       (read-directory-name prompt dir dir))
590   (defun wl-read-directory-name (prompt dir)
591     (let ((dir (read-file-name prompt dir)))
592       (unless (file-directory-p dir)
593         (error "%s is not directory" dir))
594       dir)))
595
596 ;; local variable check.
597 (static-if (fboundp 'local-variable-p)
598     (defalias 'wl-local-variable-p 'local-variable-p)
599   (defmacro wl-local-variable-p (symbol &optional buffer)
600     (` (if (assq (, symbol) (buffer-local-variables (, buffer)))
601            t))))
602
603 (defun wl-number-base36 (num len)
604   (if (if (< len 0)
605           (<= num 0)
606         (= len 0))
607       ""
608     (concat (wl-number-base36 (/ num 36) (1- len))
609             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
610                                   (% num 36))))))
611
612 (defvar wl-unique-id-char nil)
613
614 (defun wl-unique-id ()
615   ;; Don't use microseconds from (current-time), they may be unsupported.
616   ;; Instead we use this randomly inited counter.
617   (setq wl-unique-id-char
618         (% (1+ (or wl-unique-id-char (logand (random t) (1- (lsh 1 20)))))
619            ;; (current-time) returns 16-bit ints,
620            ;; and 2^16*25 just fits into 4 digits i base 36.
621            (* 25 25)))
622   (let ((tm (static-if (fboundp 'current-time)
623                 (current-time)
624               (let* ((cts (split-string (current-time-string) "[ :]"))
625                      (m (cdr (assoc (nth 1 cts)
626                                     '(("Jan" . "01") ("Feb" . "02")
627                                       ("Mar" . "03") ("Apr" . "04")
628                                       ("May" . "05") ("Jun" . "06")
629                                       ("Jul" . "07") ("Aug" . "08")
630                                       ("Sep" . "09") ("Oct" . "10")
631                                       ("Nov" . "11") ("Dec" . "12"))))))
632                 (list (string-to-int (concat (nth 6 cts) m
633                                              (substring (nth 2 cts) 0 1)))
634                       (string-to-int (concat (substring (nth 2 cts) 1)
635                                              (nth 4 cts) (nth 5 cts)
636                                              (nth 6 cts))))))))
637     (concat
638      (if (memq system-type '(ms-dos emx vax-vms))
639          (let ((user (downcase (user-login-name))))
640            (while (string-match "[^a-z0-9_]" user)
641              (aset user (match-beginning 0) ?_))
642            user)
643        (wl-number-base36 (user-uid) -1))
644      (wl-number-base36 (+ (car   tm)
645                           (lsh (% wl-unique-id-char 25) 16)) 4)
646      (wl-number-base36 (+ (nth 1 tm)
647                           (lsh (/ wl-unique-id-char 25) 16)) 4)
648      ;; Append the name of the message interface, because while the
649      ;; generated ID is unique to this newsreader, other newsreaders
650      ;; might otherwise generate the same ID via another algorithm.
651      wl-unique-id-suffix)))
652
653 (defvar wl-message-id-function 'wl-draft-make-message-id-string)
654 (defun wl-draft-make-message-id-string ()
655   "Return Message-ID field value."
656   (concat "<" (wl-unique-id)
657           (let (from user domain)
658             (if (and wl-message-id-use-wl-from
659                      (progn
660                        (setq from (wl-address-header-extract-address wl-from))
661                        (and (string-match "^\\(.*\\)@\\(.*\\)$" from)
662                             (setq user   (match-string 1 from))
663                             (setq domain (match-string 2 from)))))
664                 (format "%%%s@%s>" user domain)
665               (format "@%s>"
666                       (or wl-message-id-domain
667                           (if wl-local-domain
668                               (concat (system-name) "." wl-local-domain)
669                             (system-name))))))))
670
671 ;;; Profile loading.
672 (defvar wl-load-profile-function 'wl-local-load-profile)
673 (defun wl-local-load-profile ()
674   "Load `wl-init-file'."
675   (message "Initializing...")
676   (load wl-init-file 'noerror 'nomessage))
677
678 (defun wl-load-profile ()
679   "Call `wl-load-profile-function' function."
680   (funcall wl-load-profile-function))
681
682 ;;;
683
684 (defmacro wl-count-lines ()
685   (` (save-excursion
686        (beginning-of-line)
687        (count-lines 1 (point)))))
688
689 (defun wl-horizontal-recenter ()
690   "Recenter the current buffer horizontally."
691   (beginning-of-line)
692   (re-search-forward "[[<]" (point-at-eol) t)
693   (if (< (current-column) (/ (window-width) 2))
694       (set-window-hscroll (get-buffer-window (current-buffer) t) 0)
695     (let* ((orig (point))
696            (end (window-end (get-buffer-window (current-buffer) t)))
697            (max 0))
698       (when end
699         ;; Find the longest line currently displayed in the window.
700         (goto-char (window-start))
701         (while (and (not (eobp))
702                     (< (point) end))
703           (end-of-line)
704           (setq max (max max (current-column)))
705           (forward-line 1))
706         (goto-char orig)
707         ;; Scroll horizontally to center (sort of) the point.
708         (if (> max (window-width))
709             (set-window-hscroll
710              (get-buffer-window (current-buffer) t)
711              (min (- (current-column) (/ (window-width) 3))
712                   (+ 2 (- max (window-width)))))
713           (set-window-hscroll (get-buffer-window (current-buffer) t) 0))
714         max))))
715
716 ;; Biff
717 (static-cond
718  (wl-on-xemacs
719   (defvar wl-biff-timer-name "wl-biff")
720
721   (defun wl-biff-stop ()
722     (when (get-itimer wl-biff-timer-name)
723       (delete-itimer wl-biff-timer-name)))
724
725   (defun wl-biff-start ()
726     (wl-biff-stop)
727     (when wl-biff-check-folder-list
728       (wl-biff-check-folders)
729       (start-itimer wl-biff-timer-name 'wl-biff-check-folders
730                     wl-biff-check-interval wl-biff-check-interval))))
731
732  ((and (condition-case nil (require 'timer) (error nil));; FSFmacs 19+
733        (fboundp 'timer-activate))
734
735   (defun wl-biff-stop ()
736     (when (get 'wl-biff 'timer)
737       (cancel-timer (get 'wl-biff 'timer))))
738
739   (defun wl-biff-start ()
740     (require 'timer)
741     (when wl-biff-check-folder-list
742       (wl-biff-check-folders)
743       (if (get 'wl-biff 'timer)
744           (timer-activate (get 'wl-biff 'timer))
745         (put 'wl-biff 'timer (run-at-time
746                               (timer-next-integral-multiple-of-time
747                                (current-time) wl-biff-check-interval)
748                               wl-biff-check-interval
749                               'wl-biff-event-handler)))))
750
751   (defun-maybe timer-next-integral-multiple-of-time (time secs)
752     "Yield the next value after TIME that is an integral multiple of SECS.
753 More precisely, the next value, after TIME, that is an integral multiple
754 of SECS seconds since the epoch.  SECS may be a fraction.
755 This function is imported from Emacs 20.7."
756     (let ((time-base (ash 1 16)))
757       (if (fboundp 'atan)
758           ;; Use floating point, taking care to not lose precision.
759           (let* ((float-time-base (float time-base))
760                  (million 1000000.0)
761                  (time-usec (+ (* million
762                                   (+ (* float-time-base (nth 0 time))
763                                      (nth 1 time)))
764                                (nth 2 time)))
765                  (secs-usec (* million secs))
766                  (mod-usec (mod time-usec secs-usec))
767                  (next-usec (+ (- time-usec mod-usec) secs-usec))
768                  (time-base-million (* float-time-base million)))
769             (list (floor next-usec time-base-million)
770                   (floor (mod next-usec time-base-million) million)
771                   (floor (mod next-usec million))))
772         ;; Floating point is not supported.
773         ;; Use integer arithmetic, avoiding overflow if possible.
774         (let* ((mod-sec (mod (+ (* (mod time-base secs)
775                                    (mod (nth 0 time) secs))
776                                 (nth 1 time))
777                              secs))
778                (next-1-sec (+ (- (nth 1 time) mod-sec) secs)))
779           (list (+ (nth 0 time) (floor next-1-sec time-base))
780                 (mod next-1-sec time-base)
781                 0)))))
782
783   (defun wl-biff-event-handler ()
784     ;; PAKURing from FSF:time.el
785     (wl-biff-check-folders)
786     ;; Do redisplay right now, if no input pending.
787     (sit-for 0)
788     (let* ((current (current-time))
789            (timer (get 'wl-biff 'timer))
790            ;; Compute the time when this timer will run again, next.
791            (next-time (timer-relative-time
792                        (list (aref timer 1) (aref timer 2) (aref timer 3))
793                        (* 5 (aref timer 4)) 0)))
794       ;; If the activation time is far in the past,
795       ;; skip executions until we reach a time in the future.
796       ;; This avoids a long pause if Emacs has been suspended for hours.
797       (or (> (nth 0 next-time) (nth 0 current))
798           (and (= (nth 0 next-time) (nth 0 current))
799                (> (nth 1 next-time) (nth 1 current)))
800           (and (= (nth 0 next-time) (nth 0 current))
801                (= (nth 1 next-time) (nth 1 current))
802                (> (nth 2 next-time) (nth 2 current)))
803           (progn
804             (timer-set-time timer (timer-next-integral-multiple-of-time
805                                    current wl-biff-check-interval)
806                             wl-biff-check-interval)
807             (timer-activate timer))))))
808  (t
809   (fset 'wl-biff-stop 'ignore)
810   (fset 'wl-biff-start 'ignore)))
811
812 (defsubst wl-biff-notify (new-mails notify-minibuf)
813   (when (and (not wl-modeline-biff-status) (> new-mails 0))
814     (run-hooks 'wl-biff-notify-hook))
815   (when (and wl-modeline-biff-status (eq new-mails 0))
816     (run-hooks 'wl-biff-unnotify-hook))
817   (setq wl-modeline-biff-status (> new-mails 0))
818   (force-mode-line-update t)
819   (when notify-minibuf
820     (cond ((zerop new-mails) (message "No mail."))
821           ((= 1 new-mails) (message "You have a new mail."))
822           (t (message "You have %d new mails." new-mails)))))
823
824 ;; Internal variable.
825 (defvar wl-biff-check-folders-running nil)
826
827 (defun wl-biff-check-folders ()
828   (interactive)
829   (if wl-biff-check-folders-running
830       (when (interactive-p)
831         (message "Biff process is running."))
832     (setq wl-biff-check-folders-running t)
833     (when (interactive-p)
834       (message "Checking new mails..."))
835     (let ((new-mails 0)
836           (flist (or wl-biff-check-folder-list (list wl-default-folder)))
837           folder)
838       (if (eq (length flist) 1)
839           (wl-biff-check-folder-async (wl-folder-get-elmo-folder
840                                        (car flist) 'biff) (interactive-p))
841         (unwind-protect
842             (while flist
843               (setq folder (wl-folder-get-elmo-folder (car flist))
844                     flist (cdr flist))
845               (when (elmo-folder-plugged-p folder)
846                 (setq new-mails
847                       (+ new-mails
848                          (nth 0 (wl-biff-check-folder folder))))))
849           (setq wl-biff-check-folders-running nil)
850           (wl-biff-notify new-mails (interactive-p)))))))
851
852 (defun wl-biff-check-folder (folder)
853   (if (eq (elmo-folder-type-internal folder) 'pop3)
854       (unless (elmo-pop3-get-session folder 'any-exists)
855         (wl-folder-check-one-entity (elmo-folder-name-internal folder)
856                                     'biff))
857     (wl-folder-check-one-entity (elmo-folder-name-internal folder)
858                                 'biff)))
859
860 (defun wl-biff-check-folder-async-callback (diff data)
861   (if (nth 1 data)
862       (with-current-buffer (nth 1 data)
863         (wl-folder-entity-hashtb-set wl-folder-entity-hashtb
864                                      (nth 0 data)
865                                      (list (nth 0 diff)
866                                            (- (nth 1 diff) (nth 0 diff))
867                                            (nth 2 diff))
868                                      (current-buffer))))
869   (setq wl-folder-info-alist-modified t)
870   (setq wl-biff-check-folders-running nil)
871   (sit-for 0)
872   (wl-biff-notify (car diff) (nth 2 data)))
873
874 (defun wl-biff-check-folder-async (folder notify-minibuf)
875   (when (elmo-folder-plugged-p folder)
876     (elmo-folder-set-biff-internal folder t)
877     (if (and (eq (elmo-folder-type-internal folder) 'imap4)
878              (elmo-folder-use-flag-p folder))
879         ;; Check asynchronously only when IMAP4 and use server diff.
880         (progn
881           (setq elmo-folder-diff-async-callback
882                 'wl-biff-check-folder-async-callback)
883           (setq elmo-folder-diff-async-callback-data
884                 (list (elmo-folder-name-internal folder)
885                       (get-buffer wl-folder-buffer-name)
886                       notify-minibuf))
887           (elmo-folder-diff-async folder))
888       (unwind-protect
889           (wl-biff-notify (car (wl-biff-check-folder folder))
890                           notify-minibuf)
891         (setq wl-biff-check-folders-running nil)))))
892
893 (if (and (fboundp 'regexp-opt)
894          (not (featurep 'xemacs)))
895     (defalias 'wl-regexp-opt 'regexp-opt)
896   (defun wl-regexp-opt (strings &optional paren)
897     "Return a regexp to match a string in STRINGS.
898 Each string should be unique in STRINGS and should not contain any regexps,
899 quoted or not.  If optional PAREN is non-nil, ensure that the returned regexp
900 is enclosed by at least one regexp grouping construct."
901     (let ((open-paren (if paren "\\(" "")) (close-paren (if paren "\\)" "")))
902       (concat open-paren (mapconcat 'regexp-quote strings "\\|")
903               close-paren))))
904
905 (defalias 'wl-expand-newtext 'elmo-expand-newtext)
906 (defalias 'wl-regexp-opt 'elmo-regexp-opt)
907
908 (defun wl-region-exists-p ()
909   "Return non-nil if a region exists on current buffer."
910   (static-if (featurep 'xemacs)
911       (region-active-p)
912     (and transient-mark-mode mark-active)))
913
914 (defun wl-deactivate-region ()
915   "Deactivate region on current buffer"
916   (static-if (not (featurep 'xemacs))
917       (setq mark-active nil)))
918
919 (defvar wl-line-string)
920 (defun wl-line-parse-format (format spec-alist)
921   "Make a formatter from FORMAT and SPEC-ALIST."
922   (let (f spec specs stack)
923     (setq f
924           (with-temp-buffer
925             (insert format)
926             (goto-char (point-min))
927             (while (search-forward "%" nil t)
928               (cond
929                ((looking-at "%")
930                 (goto-char (match-end 0)))
931                ((looking-at "\\(-?\\(0?\\)[0-9]*\\)\\([^0-9]\\)")
932                 (cond
933                  ((string= (match-string 3) "(")
934                   (if (zerop (length (match-string 1)))
935                       (error "No number specification for %%( line format"))
936                   (push (list
937                          (match-beginning 0) ; start
938                          (match-end 0)       ; start-content
939                          (string-to-number
940                           (match-string 1))  ; width
941                          specs) ; specs
942                         stack)
943                   (setq specs nil))
944                  ((string= (match-string 3) ")")
945                   (let ((entry (pop stack))
946                         form)
947                     (unless entry
948                       (error
949                        "No matching %%( parenthesis in summary line format"))
950                     (goto-char (car entry)) ; start
951                     (setq form (buffer-substring (nth 1 entry) ; start-content
952                                                  (- (match-beginning 0) 1)))
953                     (delete-region (car entry) (match-end 0))
954                     (insert "s")
955                     (setq specs
956                           (append
957                            (nth 3 entry)
958                            (list (list 'wl-set-string-width (nth 2 entry)
959                                        (append
960                                         (list 'format form)
961                                         specs)))))))
962                  (t
963                   (setq spec
964                         (if (setq spec (assq (string-to-char (match-string 3))
965                                              spec-alist))
966                             (nth 1 spec)
967                           (match-string 3)))
968                   (unless (string= "" (match-string 1))
969                     (setq spec (list 'wl-set-string-width
970                                      (string-to-number (match-string 1))
971                                      spec
972                                      (unless (string= "" (match-string 2))
973                                        (string-to-char (match-string 2))))))
974                   (replace-match "s" 'fixed)
975                   (setq specs (append specs
976                                       (list
977                                        (list
978                                         'setq 'wl-line-string
979                                         spec)))))))))
980             (buffer-string)))
981     (append (list 'format f) specs)))
982
983 (defmacro wl-line-formatter-setup (formatter format alist)
984   (` (let (byte-compile-warnings)
985        (setq (, formatter)
986              (byte-compile
987               (list 'lambda ()
988                     (wl-line-parse-format (, format) (, alist)))))
989        (when (get-buffer "*Compile-Log*")
990          (bury-buffer "*Compile-Log*"))
991        (when (get-buffer "*Compile-Log-Show*")
992          (bury-buffer "*Compile-Log-Show*")))))
993
994 (defsubst wl-copy-local-variables (src dst local-variables)
995   "Copy value of LOCAL-VARIABLES from SRC buffer to DST buffer."
996   (with-current-buffer dst
997     (dolist (variable local-variables)
998       (set (make-local-variable variable)
999            (with-current-buffer src
1000              (symbol-value variable))))))
1001
1002 (require 'product)
1003 (product-provide (provide 'wl-util) (require 'wl-version))
1004
1005 ;;; wl-util.el ends here