utilities.el 105 KB
Newer Older
David Byers's avatar
David Byers committed
1
;;;;; -*-coding: iso-8859-1;-*-
2
;;;;;
3
;;;;; $Id$
4
;;;;; Copyright (C) 1991-2002  Lysator Academic Computer Association.
5
;;;;;
6
;;;;; This file is part of the LysKOM Emacs LISP client.
7
8
9
;;;;; 
;;;;; LysKOM is free software; you can redistribute it and/or modify it
;;;;; under the terms of the GNU General Public License as published by 
10
;;;;; the Free Software Foundation; either version 2, or (at your option) 
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
;;;;; any later version.
;;;;; 
;;;;; LysKOM is distributed in the hope that it will be useful, but WITHOUT
;;;;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
;;;;; FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
;;;;; for more details.
;;;;; 
;;;;; You should have received a copy of the GNU General Public License
;;;;; along with LysKOM; see the file COPYING.  If not, write to
;;;;; Lysator, c/o ISY, Linkoping University, S-581 83 Linkoping, SWEDEN,
;;;;; or the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, 
;;;;; MA 02139, USA.
;;;;;
;;;;; Please mail bug reports to bug-lyskom@lysator.liu.se. 
;;;;;
;;;; ================================================================
;;;; ================================================================
;;;;
29
;;;; File: utilities.el
30
31
32
33
34
35
36
37
38
39
40
;;;;
;;;; This file contains general lisp utility functions and
;;;; lyskom-specific utility functions (such as date formatting and
;;;; minibuffer reading)
;;;;


(setq lyskom-clientversion-long
      (concat lyskom-clientversion-long
	      "$Id$\n"))

David Byers's avatar
David Byers committed
41

42
43
44
45
46
47
48
49
50
51
52
53
54
55
(defvar coding-category-list)
(defun lyskom-check-configuration ()
  ;; Excuse my paranoia. This code is hardly tested at all, so I
  ;; really want it wrapped to prevent errors from breaking the
  ;; client. Plus it lets me check how to do stuff in Gnu Emacs 21
  ;; without worrying about compatibility with other versions.
  (when kom-check-configuration-on-startup
    (condition-case nil
        (progn
          ;; Check that we have MULE
          (when (and (>= emacs-major-version 20)
                     (boundp 'enable-multibyte-characters)
                     (not enable-multibyte-characters))
            (lyskom-format-insert 'no-mule-warning
56
                                  `(face ,kom-warning-face)
57
58
59
60
61
                                  ))

          ;; Check coding system
          (when (and enable-multibyte-characters
                     (not (memq lyskom-server-coding-system
62
                                (lyskom-coding-system-get
63
64
65
66
67
                                 (symbol-value (car coding-category-list))
                                 'alias-coding-systems))))
            (lyskom-format-insert 'coding-system-mismatch-warning
                                  (symbol-value (car coding-category-list))
                                  lyskom-server-coding-system
68
                                  `(face ,kom-warning-face)
69
70
71
72
                                  ))
          )
      (error nil)
      )))
73
74
75
76
77
78
79
80
81

;;;
;;; Lisp utility functions
;;;

(defsubst listify-vector (vector)
  "Turn VECTOR into a list"
  (append vector nil))

82
83
(defun nfirst (n list)
  "Return a list of the N first elements of LIST."
David Byers's avatar
David Byers committed
84
85
86
87
88
89
  (let ((result nil))
    (while (and (> n 0) list)
      (setq result (cons (car list) result)
            list (cdr list)
            n (1- n)))
    (nreverse result)))
90

David Byers's avatar
David Byers committed
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
(defun lyskom-rotate-list (list el)
  "Destructively rotate LIST so EL becomes the first element.
If EL occurs more than one, the first occurrence is used."
  (let ((tail (memq el list)))
    (if (or (null tail) (eq el (car list)))
        list
      (setcdr (nthcdr (- (length list) (length tail) 1) list) nil)
      (setcdr (nthcdr (1- (length tail)) tail) list)
      tail)))

(defun lyskom-preceding-cons (list el)
  "Return the cons cell of LIST preceding the first cons cell whose car is EL.
Return nil if TAIL is the same as LIST or not a member of LIST."
  (unless (or (eq (car list) el)
              (not (memq el list)))
    (nthcdr (- (length list) (length (memq el list)) 1) list)))

(defun lyskom-insert-in-list (el list before)
  "Destructively insert EL in LIST before element BEFORE.
If BEFORE is not in the list, then insert EL at the end of the list."
  (cond ((eq before (car list))
         (cons el list))
        (t (setcdr (nthcdr (- (length list)
                              (length (memq before list)) 1) list)
                   (cons el (memq before list)))
           list)))

118
119
120
121
122
123
124
125
126
(defun lyskom-move-in-list (el list pos)
  "Destructively move EL within LIST so it appears at position POS."
  (when (memq el list)
    (setq list (delq el list))
    (cond ((eq 0 pos) (setq list (cons el list)))
          (t (setcdr (nthcdr (1- pos) list)
                     (cons el (nthcdr pos list))))))
  list)

127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
;;;
;;; +++ FIXME: If cl.el can be guaranteed, this is pointless.
;;;

(defun lyskom-butlast (x &optional n)
  "Returns a copy of LIST with the last N elements removed."
  (if (and n (<= n 0)) x
    (lyskom-nbutlast (copy-sequence x) n)))

(defun lyskom-nbutlast (x &optional n)
  "Modifies LIST to remove the last N elements."
  (let ((m (length x)))
    (or n (setq n 1))
    (and (< n m)
	 (progn
	   (if (> n 0) (setcdr (nthcdr (- (1- m) n) x) nil))
	   x))))
144

145
(defun filter-list (test list)
146
147
148
149
150
  (let ((result nil))
    (lyskom-traverse el list
      (when (funcall test el)
        (setq result (cons el result))))
    (nreverse result)))
151

152
153
154
155
156
157
158
;;;============================================================
;;;
;;; Utility functions.
;;;
;;; These should be shared in LysKOM
;;;

159
160
161
162
(defun lyskom-ignore (&rest args)
  "Ignore all arguments"
  )

163
(defun lyskom-mapcar2 (fn seq1 seq2)
164
165
166
167
168
169
170
  (let (result)
    (while (and seq1 seq2)
      (setq result (cons (funcall fn (car seq1) (car seq2)) result))
      (setq seq1 (cdr seq1)
            seq2 (cdr seq2)))
    (nreverse result)))

171
(defun lyskom-maxint ()
David Byers's avatar
David Byers committed
172
173
174
175
  (let ((n 1) 
        (l nil)
        (i 31))
    (while (and (> n 0) (> i 0))
176
      (setq l (cons n l))
David Byers's avatar
David Byers committed
177
178
      (setq n (* 2 n))
      (setq i (1- i)))
179
180
    (apply '+ l)))

David Byers's avatar
David Byers committed
181
182
183
184
;; Set lyskom-maxint correctly

(setq lyskom-max-int (lyskom-maxint))

David Byers's avatar
David Byers committed
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200

(defun lyskom-try-require (feature &optional message &rest args)
  "Load the feature FEATURE using require. 
If optional MESSAGE is non-nil, use it as a LysKOM format string 
taking one string argument to print an error message. Remaining
arguments are used as arguments for the format string.

Returns t if the feature is loaded or can be loaded, and nil otherwise."
  (or (featurep 'feature)
      (condition-case nil
          (progn (require feature)
                 t)
        (error 
         (when message
           (apply 'lyskom-format-insert-before-prompt message (symbol-name feature) args))
         nil))))
201
202


David Byers's avatar
David Byers committed
203
204
(defvar lyskom-apo-timeout 0
  "Current millisecond timeout value for accept-process-output")
205

David Byers's avatar
David Byers committed
206
207
(defvar lyskom-apo-timeout-index 0
  "Index in lyskom-apo-timeout-vector-max where last timeout is")
208

David Byers's avatar
David Byers committed
209
210
211
(defconst lyskom-apo-timeout-vector
  [0 1000 1000 2000 3000 5000 8000 13000 21000 34000 55000 89000 144000 233000 377000 610000]
  "Vector of timeout values (usecs) for accept-process-output")
212

David Byers's avatar
David Byers committed
213
214
(defconst lyskom-apo-timeout-vector-max (1- (length lyskom-apo-timeout-vector))
  "Maximum index in lyskom-apo-timeout-vector")
215

216
(defun lyskom-next-apo-timeout ()
David Byers's avatar
David Byers committed
217
218
219
220
221
  (if (< lyskom-apo-timeout-index lyskom-apo-timeout-vector-max)
      (setq lyskom-apo-timeout
            (aref lyskom-apo-timeout-vector
                  (setq lyskom-apo-timeout-index
                        (1+ lyskom-apo-timeout-index))))))
222

223
(defun lyskom-reset-apo-timeout ()
David Byers's avatar
David Byers committed
224
225
  (setq lyskom-apo-timeout-index -1)
  (setq lyskom-apo-timeout 0))
226

227
(defun lyskom-accept-process-output ()
David Byers's avatar
David Byers committed
228
229
230
  "Call accept-process-output with the correct timeout values."
  (lyskom-next-apo-timeout)
  (accept-process-output nil 0 lyskom-apo-timeout))
231

232
(defun lyskom-set-alist (alist item value)
Johan Sundström's avatar
Bugfix.    
Johan Sundström committed
233
234
  "Modifies (non-destructively) an alist ALIST to set item
ITEM to the value VALUE."
235
236
237
238
  (let ((pair (assq item alist)))
     (if pair
         (progn (setcdr pair value) alist)
       (cons (cons item value) alist))))
239

240

David Byers's avatar
David Byers committed
241
242
243
244
245
246
247
248
249
;;;
;;; WARNING!
;;;
;;; The following variable is *important* if you fuck it up in any
;;; way, the functions used to read conference names won't work. So if
;;; you change it, try to work one character at a time, and when
;;; you're done, run through the mappings of all 256 characters to
;;; make sure they look OK.
;;;
250
251
;;; Make sure your MULE Emacs doesnt fuck it up for you. It did for me.
;;;
David Byers's avatar
David Byers committed
252

253
(defvar lyskom-default-collate-table
David Byers's avatar
David Byers committed
254
  "\000\001\002\003\004\005\006\007\010 \012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037 !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]~\200\201\202\203\204\205\206\207\210\211\212\213\214\215\216\217\220\221\222\223\224\225\226\227\230\231\232\233\234\235\236\237!AAAA[]ACEEEEIIIINOOOO\\OUUUYYAAAA[]ACEEEEIIIINOOOO\\OUUUYY"
255
256
257
258
259
  "String mapping characters to their collate class.

Lowercase, uppercase and other equivalents are mapped to the same class.
The class number defines a proper sorting order.")

260

David Byers's avatar
David Byers committed
261
262
263
264
265
(defsubst lyskom-maybe-recode-string (s &optional coding force)
  "Change the encoding of S for when multibyte characters are not supported.
Optional second argument CODING is the coding system to use. If optional
third argument FORCE is non-nil, always encode multibyte strings, otherwise
only encode when multibyte strings are not supported."
266
267
268
269
270
271
  (if (and (lyskom-multibyte-string-p s)
           (or force (not enable-multibyte-characters)))
      (lyskom-encode-coding-string s (or coding
                                         (and lyskom-language
                                              (lyskom-language-coding lyskom-language))
                                         'raw-text))
272
    s))
273

David Byers's avatar
David Byers committed
274
275
276
277
(defun lyskom-recode-string-for-title (s coding)
  "Encode S with CODING for use in frame titles.
Attempts to encode the string only in Emacs versions that do not require
MULE coding for frame titles"
David Byers's avatar
David Byers committed
278
279
280
281
282
  (cond
   ((memq window-system '(win32 mswindows w32))
    (lyskom-maybe-recode-string s coding t))
   ((> emacs-major-version 20) s)
   (t (lyskom-maybe-recode-string s coding t))))
David Byers's avatar
David Byers committed
283

David Byers's avatar
David Byers committed
284
285
286
287
288
289
(defun lyskom-maybe-frob-completion-table (table &optional copy)
  "Recode the cars of alist TABLE to default coding system unless multibyte
characters are enabled. This function is destructive unless optional copy
is non-nil."
  (cond (enable-multibyte-characters table)
	(copy (mapcar (lambda (el)
David Byers's avatar
David Byers committed
290
			(cons (lyskom-maybe-recode-string (car el) nil t)
291
292
			      (cdr el)))
                      table))
David Byers's avatar
David Byers committed
293
	(t (lyskom-traverse el table
David Byers's avatar
David Byers committed
294
		(setcar el (lyskom-maybe-recode-string (car el) nil t)))
David Byers's avatar
David Byers committed
295
296
297
	   table)))


298
299
(defsubst lyskom-unicase-char (c)
  "Smash case and diacritical marks on c." 
300
301
  (if (< (lyskom-char-to-int c) (length lyskom-collate-table))
      (aref lyskom-collate-table (lyskom-char-to-int c))
302
    (setq c (lyskom-encode-coding-char c lyskom-server-coding-system))
303
304
    (if (and c (< (lyskom-char-to-int c) (length lyskom-collate-table)))
	(aref lyskom-collate-table (lyskom-char-to-int c))
305
      c)))
306
307
308

(defun lyskom-unicase (s)
  "Smash case and diacritical marks of all chars in s." 
309
  (lyskom-save-excursion
310
   (and lyskom-buffer (set-buffer lyskom-buffer))
David Byers's avatar
David Byers committed
311
   (let* ((s2 (string-to-vector 
312
               (lyskom-encode-coding-string s lyskom-server-coding-system)))
David Byers's avatar
David Byers committed
313
          (l (length s2)))
314
315
316
     (while (> l 0)
       (setq l (1- l))
       (aset s2 l (lyskom-unicase-char (aref s2 l))))
317
     (concat s2))))
David Byers's avatar
David Byers committed
318

David Byers's avatar
David Byers committed
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
(defun lyskom-looking-at (s)
  "Version of looking-at that will work in Gnu Emacs 20.3"
  (save-excursion
    (let ((start (point)))
      (and (re-search-forward s nil t)
	   (eq (match-beginning 0) start)))))

;; Don't slow things down with our own looking-at unless we have to

(eval-and-compile
 (condition-case nil
     (if (and (eq emacs-major-version 20)
	      (eq emacs-minor-version 3))
	 nil
       (fset 'lyskom-looking-at (symbol-function 'looking-at)))
   (error nil)))


337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
(defun lyskom-compute-char-classes (map)
  "Find out which characters that are equivalent according to MAP.

MAP should be a collate table.

The return value is an assoc list, which characters as keys, and a
list of single-character strings as values.  Only characters that are
equivalent to at least one more character is returned in the assoc
list.

Example: if this function returns

	((97 \"A\" \"a\")
         (65 \"A\" \"a\")
	 (48 \"O\" \"o\" \"0\")
	 (111 \"O\" \"o\" \"0\")
	 (79 \"O\" \"o\" \"0\"))

it means that a and A are equivalent, and o, O and 0 are equivalent.
All other characters are unique."

  (lyskom-save-excursion
    (and lyskom-buffer (set-buffer lyskom-buffer))
    (let ((ix (length map))
	  (cls-to-strings nil)) ;assoc-list from equivalence class to
				;list of chars
      (while (> ix 0)
	(setq ix (1- ix))
	(let* ((cls (aref map ix))
366
367
	       (str (lyskom-decode-coding-string (concat (vector ix))
                                                 lyskom-server-coding-system))
368
369
370
371
372
373
	       (elem (assoc cls cls-to-strings)))
	  (if elem
	      (rplacd elem (cons str (cdr elem)))
	    (setq cls-to-strings (cons (list cls str) cls-to-strings)))))
      (let ((res nil))
	(while cls-to-strings
Joel Rosdahl's avatar
Joel Rosdahl committed
374
	  (let ((lst (cdr (car cls-to-strings))))
375
376
377
	    (if (> (length lst) 1)
		(while lst
		  (setq res (cons (cons (string-to-char (car lst))
Joel Rosdahl's avatar
Joel Rosdahl committed
378
					(cdr (car cls-to-strings)))
379
380
381
382
383
				  res))
		  (setq lst (cdr lst)))))
	  (setq cls-to-strings (cdr cls-to-strings)))
	res))))
    
David Byers's avatar
David Byers committed
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
;; Stolen from thingatpt.el
;; FIXME: We may not really need this function. Check the callers.

(defun lyskom-thing-at-point-looking-at (regexp)
  "Return non-nil if point is in or just after a match for REGEXP.
Set the match data from the earliest such match ending at or after
point."
  (save-excursion
    (let ((old-point (point)) match)
      (and (looking-at regexp)
	   (>= (match-end 0) old-point)
	   (setq match (point)))
      ;; Search back repeatedly from end of next match.
      ;; This may fail if next match ends before this match does.
      (re-search-forward regexp nil 'limit)
      (while (and (re-search-backward regexp nil t)
		  (or (> (match-beginning 0) old-point)
		      (and (looking-at regexp) ; Extend match-end past search start
			   (>= (match-end 0) old-point)
			   (setq match (point))))))
      (if (not match) nil
	(goto-char match)
	;; Back up a char at a time in case search skipped
	;; intermediate match straddling search start pos.
	(while (and (not (bobp))
		    (progn (backward-char 1) (looking-at regexp))
		    (>= (match-end 0) old-point)
		    (setq match (point))))
	(goto-char match)
	(looking-at regexp)))))

David Byers's avatar
David Byers committed
415
416
417

;; Stolen from Gnu Emacs

David Byers's avatar
David Byers committed
418
(defun lyskom-truncate-string-to-width (str end-column &optional trailer)
David Byers's avatar
David Byers committed
419
  "Truncate string STR to end at column END-COLUMN.
David Byers's avatar
David Byers committed
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448

If optional TRAILER is non-nil, it is a string to append if STR is
truncated. The total width will still be at most END-COLUMN."
  (when (and trailer (>= (lyskom-string-width trailer) end-column))
    (setq trailer nil))

  (cond ((< (lyskom-string-width str) end-column) str)
        (t (when trailer 
             (setq end-column (- end-column (lyskom-string-width trailer))))
           (let ((idx 0)
                 (column 0)
                 (len (length str))
                 ch last-column last-idx)

             (condition-case nil
                 (while (< column end-column)
                   (setq last-column column
                         last-idx idx
                         ch (aref str idx)
                         column (+ column (lyskom-char-width ch))
                         idx (1+ idx)))
               (args-out-of-range (setq idx len)))
             (if (> column end-column)
                 (setq column last-column idx last-idx))
             (setq str (substring str 0 idx))
             (when trailer
               (setq str (concat str trailer)))
             str))))

David Byers's avatar
David Byers committed
449
450


451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
(defun lyskom-buffer-display-message (string &optional buffer)
  (let* ((inhibit-read-only t)
         (buffer (or buffer (current-buffer)))
         (window (cdr 
                  (assoc (selected-frame)
                         (mapcar (lambda (x) (cons (window-frame x) x))
                                 (get-buffer-window-list buffer))))))
    (erase-buffer)
    (unless window (setq window (display-buffer buffer)))
    (select-window window)
    (delete-other-windows window)
    (insert (make-string (/ (window-height window) 3) ?\n))
    (insert string)
    (center-region (point-min) (point-max))
    (goto-char (point-min))
    (fundamental-mode)
    (toggle-read-only t)))


470
471
472
473
474
475
(eval-and-compile
  (lyskom-xemacs-or-gnu
   (fset 'lyskom-string= (symbol-function 'string=))
   (if (< emacs-major-version 20)
       (fset 'lyskom-string= (symbol-function 'string=))
     (defun lyskom-string= (s1 s2)
476
       (string= (and s1 (if (lyskom-multibyte-string-p s1)
477
		    s1
478
		  (lyskom-decode-coding-string s1 (lyskom-language-coding
479
					    lyskom-language))))
480
		(and s2 (if (lyskom-multibyte-string-p s2)
481
		    s2
482
		  (lyskom-decode-coding-string s2 (lyskom-language-coding
483
					    lyskom-language)))))))))
484

David Byers's avatar
X    
David Byers committed
485
486
487
(defun lyskom-string-assoc (key list)
  "Return non-nil if KEY is the same string as the car of an element of LIST.
The value is actually the element of LIST whose car equals KEY."
David Byers's avatar
David Byers committed
488
  (let ((s (and key (downcase key)))
David Byers's avatar
X    
David Byers committed
489
490
        (result nil))
    (while list
491
      (when (lyskom-string= s (downcase (car (car list))))
David Byers's avatar
X    
David Byers committed
492
493
494
495
        (setq result (car list))
        (setq list nil))
      (setq list (cdr list)))
    result))
David Byers's avatar
David Byers committed
496

497
498
499
500
501
502
503
504
505
506
507
508
(defun lyskom-string-member (key list)
  "Return non-nil if KEY is the same string as the car of an element of LIST.
The value is actually the element of LIST whose car equals KEY."
  (let ((s (and key (downcase key)))
        (result nil))
    (while list
      (when (lyskom-string= s (downcase (car list)))
        (setq result (car list))
        (setq list nil))
      (setq list (cdr list)))
    result))

509
510
511
(defun lyskom-string-rassoc (key list)
  "Return non-nil if KEY is the same string as the cdr of an element of LIST.
The value is actually the element of LIST whose car equals KEY."
David Byers's avatar
David Byers committed
512
  (let ((s (and key (downcase key)))
513
514
515
516
517
518
519
520
        (result nil))
    (while list
      (when (lyskom-string= s (downcase (cdr (car list))))
        (setq result (car list))
        (setq list nil))
      (setq list (cdr list)))
    result))

David Byers's avatar
X    
David Byers committed
521
522
(defun lyskom-set-default (sym val)
  "Set the value of SYM in the LysKOM buffer to VAL."
David Byers's avatar
David Byers committed
523
  (save-excursion
David Byers's avatar
X    
David Byers committed
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
    (set-buffer (or (and (boundp 'lyskom-buffer)
                         (bufferp lyskom-buffer)
                         (buffer-live-p lyskom-buffer)
                         lyskom-buffer)
                    (current-buffer)))
    (set sym val)))

(defun lyskom-default-value (sym)
  "Get the value of SYM in the LysKOM buffer"
  (save-excursion
    (set-buffer (or (and (boundp 'lyskom-buffer)
                         (bufferp lyskom-buffer)
                         (buffer-live-p lyskom-buffer)
                         lyskom-buffer)
                    (current-buffer)))
David Byers's avatar
David Byers committed
539
540
    (symbol-value sym)))

David Byers's avatar
X    
David Byers committed
541
542
(defun lyskom-default-value-safe (sym)
  "Get the value of SYM in the LysKOM buffer"
David Byers's avatar
David Byers committed
543
  (save-excursion
David Byers's avatar
X    
David Byers committed
544
545
546
547
548
549
    (set-buffer (or (and (boundp 'lyskom-buffer)
                         (bufferp lyskom-buffer)
                         (buffer-live-p lyskom-buffer)
                         lyskom-buffer)
                    (current-buffer)))
    (and (boundp sym) (symbol-value sym))))
550

David Byers's avatar
David Byers committed
551

552
553
554
;;; ============================================================
;;; Prefix arguments

555
556
557
558
559
560
561
562
563
564
565
566
567
(defun lyskom-get-ancestors-of-text (text-no level)
  "Returns a list of all ancestors of TEXT-NO that are LEVEL
comment/foot-note levels up the comment tree. LEVEL is a
non-negative integer and 0 means the given text-no."
  (if (< level 1)
      (list text-no)
    (let* ((text-stat (blocking-do 'get-text-stat text-no))
	   (ancestors (and text-stat
			   (lyskom-text-stat-commented-texts text-stat)))
	   (level (1- level))
	   (result '()))
	(while ancestors
	  (setq result
David Byers's avatar
David Byers committed
568
569
		(lyskom-union
		 (lyskom-get-ancestors-of-text (car ancestors) level)
570
		 result
David Byers's avatar
David Byers committed
571
                 ))
572
573
574
	  (setq ancestors (cdr ancestors)))
	result)))

575
(defun lyskom-maybe-get-commented-text ()
576
577
578
579
580
581
  (let* ((text-no (lyskom-text-at-point))
         (text-stat (and text-no (blocking-do 'get-text-stat text-no))))
    (when text-no
      (if (lyskom-misc-infos-from-list 
           'COMM-IN (text-stat->misc-info-list text-stat))
          text-no
582
        (lyskom-get-text-at-point-ancestor 1)))))
583

584
(defun lyskom-maybe-get-footnoted-text ()
585
586
587
588
589
590
  (let* ((text-no (lyskom-text-at-point))
         (text-stat (and text-no (blocking-do 'get-text-stat text-no))))
    (when text-no
      (if (lyskom-misc-infos-from-list 
           'FOOTN-IN (text-stat->misc-info-list text-stat))
          text-no
591
        (lyskom-get-text-at-point-ancestor 1)))))
592

593
(defun lyskom-get-last-read-text ()
594
595
  (lyskom-default-value 'lyskom-current-text))

596
597
(defun lyskom-get-previous-text ()
  (lyskom-default-value 'lyskom-previous-text))
Johan Sundström's avatar
Johan Sundström committed
598

599
600
(defun lyskom-get-text-at-point ()
  (lyskom-text-at-point))
601

602
(defun lyskom-get-text-at-point-ancestor (arg)
603
604
605
606
607
  (let* ((text (lyskom-text-at-point))
	 (cnos (and text (lyskom-get-ancestors-of-text text arg)))
	 (txts (length cnos)))
    (cond
     ((not text)
608
      (lyskom-error (lyskom-get-string 'no-text-at-point)))
609
     ((eq txts 0)
610
      (lyskom-error (lyskom-get-string 'no-comment-to)))
611
612
613
     ((eq txts 1)
      (car cnos))
     (t
David Byers's avatar
David Byers committed
614
615
616
617
618
      (lyskom-read-number (lyskom-get-string 'what-ancestor) 
                          (car cnos)
                          nil
                          nil
                          cnos)))))
619

620
(defun lyskom-get-last-text-written-by-me ()
621
622
  (lyskom-default-value 'lyskom-last-written))

623
(defun lyskom-get-last-written-or-read-by-me ()
624
625
  (lyskom-default-value 'lyskom-last-seen-written))

626
(defun lyskom-get-text-above-point (arg)
627
628
629
630
631
632
633
634
635
636
637
638
  (save-excursion
    (let ((former-point (point)))
      (backward-text (+ 1 arg))
      (if (looking-at "\\([0-9]+\\)\\s-")
	  (string-to-int (match-string 1))
	(progn ;; we probably ended up above the first message in the buffer
	  (forward-text)
	  (if (and (< (point) former-point)
		   (looking-at "\\([0-9]+\\)\\s-"))
	      (string-to-int (match-string 1))
	    (lyskom-error (lyskom-get-string 'bad-text-no-prefix) arg)))))))

639
640
641
642
643
644
645
646
647
648
649
650
651
652
(defun lyskom-get-text-below-point (arg)
  (if (and (numberp arg) (> arg 20))
      arg
    (save-excursion
      (let ((former-point (point)))
        (forward-text arg)
        (if (looking-at "\\([0-9]+\\)\\s-")
            (string-to-int (match-string 1))
          (progn ;; we probably ended up below the final message in the buffer
            (backward-text)
            (if (and (> (point) former-point)
                     (looking-at "\\([0-9]+\\)\\s-"))
                (string-to-int (match-string 1))
              (lyskom-error (lyskom-get-string 'bad-text-no-prefix) arg))))))))
653

654
655
656
657
658
(defun lyskom-read-text-no-prompt-p (command)
  "Return non-nil if the COMMAND should prompt for a text number."
  (let ((check (assq command kom-text-no-prompts)))
    (if check (cdr check) (memq command lyskom-text-no-prompts-defaults))))

659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
;;; ------------------------------------------------------------
;;; Constraints

(defun lyskom-text-written-by-me-p (text-no)
  (let ((text-stat (blocking-do 'get-text-stat text-no)))
    (and text-stat
         (lyskom-is-supervisor (text-stat->author text-stat)
                               lyskom-pers-no))))



;;; ------------------------------------------------------------
;;; Functions used in predicates and strategies

(defun lyskom-eq-dash (e) (eq e '-))

(defun lyskom-tnpa-prompt (text-nos)
  (lyskom-tnpa-add-property text-nos 'prompt))

(defun lyskom-tnpa-valid (text-nos)
  (lyskom-tnpa-add-property text-nos 'valid))

(defun lyskom-tnpa-add-property (text-nos what)
  (cond ((numberp text-nos) (vector text-nos (list what)))
        ((vectorp text-nos)
         (aset text-nos 1 (cons what (aref text-nos 1)))
         text-nos)
        ((and text-nos (listp text-nos))
         (mapcar (lambda (el)
                   (cond ((vectorp el) (aset el 1 (cons what (aref el 1))))
                         (t (vector el (list what)))))
                 text-nos))))

(defsubst lyskom-tnpa-text-no (el)
  (if (vectorp el) (aref el 0) el))

(defsubst lyskom-tnpa-text-property (el prop)
  (and (vectorp el) (memq prop (aref el 1))))



;;; ------------------------------------------------------------
;;; The main function

(defun lyskom-tnpa-apply-strategy (strategies filter-spec constraint-spec)
704
705
  (let ((filter-locl (car (cdr (memq :filter strategies))))
        (constraint-locl (car (cdr (memq :constraint strategies)))))
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
    (lyskom-traverse strategy strategies
      (if (memq strategy '(:filter :constraint :save))
          (lyskom-traverse-break)
        (let ((tmp (cond ((functionp strategy) (funcall strategy))
                         ((and (symbolp strategy) (boundp strategy)) (symbol-value strategy))
                         (t nil))))
          (unless (listp tmp) (setq tmp (list tmp)))
          (when filter-locl (setq tmp (mapcar filter-locl tmp)))
          (when filter-spec (setq tmp (mapcar filter-spec tmp)))
          (when (or constraint-spec constraint-locl)
            (setq tmp 
                  (delq nil (mapcar (lambda (el)
                                      (when (or (lyskom-tnpa-text-property el 'valid)
                                                (and (or (null constraint-locl)
                                                         (funcall constraint-locl (lyskom-tnpa-text-no el)))
                                                     (or (null constraint-spec)
                                                         (funcall constraint-spec (lyskom-tnpa-text-no el)))))
                                        el))
                                    tmp))))
          (when tmp (lyskom-traverse-break (car tmp))))))))



(defun lyskom-read-text-no-prefix-arg (prompt &optional command)
  (when (listp prompt) (setq prompt (car prompt)))
  (let* ((command (or command lyskom-current-command this-command))
         (command-spec (cdr (assq command kom-pick-text-no-strategy-alist)))
733
         (refer-spec (car (cdr (memq :refer command-spec))))
734
         (default-spec (cdr (assq t kom-pick-text-no-strategy-alist)))
735
736
737
738
         (filter-spec (car (cdr (or (memq :filter command-spec)
                                    (memq :filter default-spec)))))
         (constraint-spec (car (cdr (or (memq :constraint command-spec)
                                        (memq :constraint default-spec)))))
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
         (text nil))

    (if refer-spec
        (lyskom-read-text-no-prefix-arg prompt refer-spec)

      ;; Traverse all strategy lists, in the appropriate order.
      ;; Identical predicates are only called once. We traverse
      ;; command-spec and default-spec until we find an applicable
      ;; element (one that matches the prefix argument). When we find
      ;; that element, we call its strategies until we find one that
      ;; generates a result that passes the filter and the constraint.
      ;;
      ;; If we never find an element, we use the t predicates in the
      ;; specification. These are fallbacks and only applied if no
      ;; strategy provides a text number.
      ;;
      ;; The exit from this block should give us a text (perhaps with
      ;; properties) that we can either use or prompt for.
      ;;
      ;; Using catch and throw significantly simplifies this code.

      (setq text
            (catch 'lyskom-tnpa-text
              (let ((handled nil))
                (lyskom-traverse spec-list (list command-spec default-spec)
                  (lyskom-traverse el spec-list
                    (if (not (listp el))
                        (lyskom-traverse-break) ; We hit :filter or something like that
                      (cond
                       ((memq (car el) handled)) ; Already handled once
                       ((eq (car el) t)) ; Defaults are handled after this loop
                       ((or (eq (car el) current-prefix-arg)
                            (condition-case nil (funcall (car el) current-prefix-arg) (error nil)))

                        ;; The predicate matches the perfix argument, so now we can
                        ;; evaluate the strategies.

                        (let ((tmp (lyskom-tnpa-apply-strategy (cdr el) filter-spec constraint-spec)))
                          (when tmp (throw 'lyskom-tnpa-text tmp)))))
                      (setq handled (cons (car el) handled))))))

              ;; The strategies failed to yield anything useful Apply
              ;; the default strategies, both from the command and from
              ;; the default strategy list..

              (throw 'lyskom-tnpa-text
                     (or (lyskom-tnpa-apply-strategy (cdr (assq t command-spec)) filter-spec constraint-spec)
                         (lyskom-tnpa-apply-strategy (cdr (assq t default-spec)) filter-spec constraint-spec)))
              ))

      ;; We now have a text that fits the constraint. Really, the only
      ;; thing to do at this point is prompt for the text, if that is
      ;; requested.

      (if (or (not (lyskom-tnpa-text-no text))
              (lyskom-tnpa-text-property text 'prompt)
              (lyskom-read-text-no-prompt-p lyskom-current-command))
          (lyskom-read-number prompt (or (lyskom-tnpa-text-no text)
                                         (lyskom-default-value 'lyskom-current-text)))
        (lyskom-tnpa-text-no text)))))
799

800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
;;; ============================================================
;;; Set functions

(defun lyskom-subset-p (a b)
  "Return non-nil if A is a subset of B"
  (let ((result t))
    (while a
      (if (memq (car a) b)
          (setq a (cdr a))
        (setq result nil a nil)))
    result))

(defun lyskom-intersection (a b)
  "Returns as a list the intersection of list A and list B.
The order of the list a is kept."
  (if (or a b)
      (let ((list nil))
        (while a
          (if (memq (car a) b)
              (setq list (cons (car a) list)))
          (setq a (cdr a)))
        (nreverse list))))

823
824
(defun lyskom-union (a b)
  "Returns a list containing the union of list A and list B.
David Byers's avatar
David Byers committed
825
826
827
Specifically, concatenate all elements of B that are not in A
to the end of A. This operation is destructive and modifies the
list pointed to by A."
828
  (let ((result nil))
David Byers's avatar
David Byers committed
829
830
831
    (lyskom-traverse x b
      (unless (memq x a) (setq result (cons x result))))
    (nconc a (nreverse result))))
832

David Byers's avatar
David Byers committed
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
(defun lyskom-delete-duplicates (list &optional key)
  "Removes all but one instance of each element in LIST.
If optional argument KEY is non-nil, apply KEY to each element before
comparison. Comparison is done with eq."
  (let ((clist (mapcar (lambda (el)
                         (if key
                             (cons (funcall key el) el)
                           (cons el el)))
                       list))
        (result nil))
    (lyskom-traverse el clist
      (unless (assq (car el) result)
        (setq result (cons el result))))
    (nreverse (mapcar 'cdr result))))

848
849
850
851
852
853
(defun lyskom-plusp (int)
  "Returns t for integers greater than 0, nil otherwise."
  (and (integerp int) (> int 0)))

(defun lyskom-minusp (int)
  "Returns t for integers smaller than 0, nil otherwise."
Johan Sundström's avatar
Johan Sundström committed
854
  (and (integerp int) (< int 0)))
855

856
857


David Byers's avatar
X    
David Byers committed
858
859
860
861
862
863
864
;;; ======================================================================
;;; LysKOM Hooks
;;;

(defun lyskom-run-hook-with-args (hook &rest args)
  "Run HOOK with the specified arguments ARGS in the LysKOM buffer.
See run-hook-with-args for detailed information."
865
866
867
  (lyskom-save-excursion (set-buffer (or (and (boundp 'lyskom-buffer)
                                              lyskom-buffer)
                                         (current-buffer)))
David Byers's avatar
X    
David Byers committed
868
                  (apply 'run-hook-with-args hook args)))
869
870


David Byers's avatar
X    
David Byers committed
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893

(defun lyskom-add-hook (hook function &optional append)
  "Add to the value of HOOK the function FUNCTION in the LysKOM buffer.
If optional APPEND is non-nil, add at the end of HOOK."
  (save-excursion (set-buffer (or (and (boundp 'lyskom-buffer)
                                       lyskom-buffer)
                                  (current-buffer)))
                  (add-hook hook function append t)))

(defun lyskom-remove-hook (hook function)
  "From the value of HOOK remove the function FUNCTION in the LysKOM buffer."
  (save-excursion (set-buffer (or (and (boundp 'lyskom-buffer)
                                       lyskom-buffer)
                                  (current-buffer)))
                  (remove-hook hook function t)))




;;; ======================================================================
;;; Printing
;;;
;;; XEmacs princ does not insert text properties. This function is based
894
;;; on the C code for princ. 
David Byers's avatar
X    
David Byers committed
895
896
;;;

897
898
(defun lyskom-princ (object &optional stream)
  "Output the printed representation of OBJECT, any Lisp OBJECT.
899
900
901
902
No quoting characters are used; no delimiters are printed around
the contents of strings. Text properties are retained.

Output stream is STREAM, or value of standard-output, and must be a
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
buffer or a marker. Function or minibuffer streams are not supported
for strings."
  (if (not (stringp object))
      (princ object stream)
    (let ((old-point nil)
          (start-point nil)
          (old-buffer (current-buffer)))
      (unwind-protect
          (progn
            (cond ((bufferp stream) (set-buffer stream))
                  ((markerp stream) 
                   (setq old-point (point))
                   (set-buffer (marker-buffer stream))
                   (goto-char stream)
                   (setq start-point (point)))
                  ((null stream)
                   (cond ((bufferp standard-output) (set-buffer standard-output))
                         ((markerp standard-output) 
                          (setq old-point (point))
                          (set-buffer (marker-buffer standard-output))
                          (goto-char standard-output)
                          (setq start-point (point))))))

            (insert object))
        (cond ((markerp stream) 
               (set-marker stream (point))
               (if (>= old-point start-point)
                   (goto-char (+ old-point (- (point) start-point)))
                 (goto-char old-point))))
        (set-buffer old-buffer)))))
David Byers's avatar
X    
David Byers committed
933
934


935
936
937
938
;;; ======================================================================
;;; Faces
;;;

939
940
941
(make-face 'lyskom-weak-highlight-face)
(make-face 'lyskom-strong-highlight-face)

942
943
944
945
946
(defun lyskom-copy-face (old new)
  (lyskom-xemacs-or-gnu (copy-face old new nil nil nil 'remove-all)
                        (copy-face old new)))


947

David Byers's avatar
David Byers committed
948
949
950
;;; ============================================================
;;; Date and time utilities

951
952
(defun lyskom-current-client-time ()
  "Return time representing current client time."
953
954
955
956
  (let ((now (decode-time)))
    (lyskom-create-time (elt now 0)     ;sec
                        (elt now 1)     ;min
                        (elt now 2)     ;hour
957
                        (elt now 3)     ;mday
958
                        (elt now 4)     ;mon
959
                        (elt now 5)     ;year
960
961
                        (elt now 6)     ;wday
                        0               ;yday
962
963
964
                        (if (elt now 7) ;isdst
                            1
                          0)
965
966
                        )))

967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
(defun lyskom-current-server-time ()
  "Return time representing current server time."
  (blocking-do 'get-time))

(defun lyskom-format-time (format &optional time)
  "Return TIME as a string formatted as FORMAT.

FORMAT may be a string or a symbol.  If it is a symbol, it is
interpreted as follows:

    'date-and-time  Include date and time. [1][2]
    'date           Include just date. [1]
    'time           Include just time. [2]

    [1] If kom-print-seconds-in-time-strings is nil, only hours and
    minutes will be included in the time; if it is non-nil, seconds
    will also be included.
    [2] If kom-print-relative-dates is non-nil and the date is today's
    or yesterday's, the string \"today\" or \"yesterday\" (respectively)
    is used instead of the standard date format.

If FORMAT is a symbol but not one of the symbols listed above, the
Joel Rosdahl's avatar
Joel Rosdahl committed
989
format string will be looked up with lyskom-get-string.  The
990
991
992
timeformat-* strings are tailored to be used as formats for this
function.

Joel Rosdahl's avatar
Joel Rosdahl committed
993
The arguments to the format string are (in order): year, month number
994
\(starting with one for January), day-of-month number, hour, minute,
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
second, full name of the day of the week, abbreviated name of the day
of the week.

TIME defaults to the current client time."
  (let* ((time (or time (lyskom-current-client-time)))
         (fmt (cond
               ((stringp format)
                format)
               ((memq format '(date-and-time date time))
                (lyskom-format (cond ((eq format 'date-and-time)
                                      'format-time-date-and-time)
                                     ((eq format 'date)
                                      'format-time-just-date)
                                     ((eq format 'time)
                                      'format-time-just-time))
                               (lyskom-get-string
                                (or (and kom-print-relative-dates
                                         (lyskom-calculate-day-diff time))
                                    'timeformat-yyyy-mm-dd))
                               (lyskom-get-string
                                (if kom-print-seconds-in-time-strings
                                    'timeformat-hh-mm-ss
                                  'timeformat-hh-mm))))
               ((symbolp format)
                (lyskom-get-string format))
               (t (error "Invalid argument")))))
    (lyskom-format fmt
                   (time->year time)
                   (time->mon  time)
                   (time->mday time)
                   (time->hour time)
                   (time->min  time)
                   (time->sec  time)
                   (elt (lyskom-get-string 'weekdays)
                        (time->wday time))
                   (elt (lyskom-get-string 'weekdays-short)
                        (time->wday time)))))


1034
1035
1036
1037
;;; ============================================================
;;; Keymap utilities

(defun lyskom-lookup-key (keymap event &optional accept-default)
1038
1039
  (if (not (arrayp event))
      (setq event (vector event)))
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
  (if (null keymap)
      (and accept-default 
           (lookup-key global-map event))
    (or (lookup-key keymap event)
        (lyskom-lookup-key (keymap-parent keymap) event accept-default))))

(defun lyskom-keymap-body (keymap)
  (setq keymap (cdr keymap))
  (cond ((arrayp (car keymap)) (car keymap))
        (t keymap)))

(defun lyskom-keymap-realbinding (binding)
  (while (stringp (car-safe binding))
    (setq binding (cdr binding)))
  binding)

(defun lyskom-overlay-keymap (basemap overlay keymap &optional prefix)
  (let ((keys (make-vector (1+ (length prefix)) nil))
        (index (length prefix))
        (body nil)
        (r 0))

    (while (< r (length prefix))
      (aset keys r (aref prefix r))
      (setq r (1+ r)))

    (cond ((not (keymapp keymap)))
          ((not (keymapp overlay)))
          ((not (keymapp basemap)))

          ((setq body (lyskom-keymap-body overlay))
           (mapcar
            (function
             (lambda (element)
               (cond ((arrayp element)
                      (let ((len (length element)))
                        (setq r 0)
                        (while (< r len)
                          (aset keys index r)
                          (lyskom-overlay-keys keys (aref element r)
                                               basemap overlay keymap)
                          (setq r (1+ r)))))

                     ((consp element)
                      (when (not (eq t (car element)))
                        (aset keys index (car element))
                        (lyskom-overlay-keys keys
                                             (lyskom-keymap-realbinding
                                              (cdr element))
                                             basemap overlay keymap)))

                     (t nil))))
            body)))))


(defun lyskom-overlay-keys (keys binding basemap overlay keymap)
  (let ((base-binding (lyskom-lookup-key basemap keys nil)))

   ;; If the binding is a keymap or prefix and
   ;; the binding in the base is a keymap or prefix 
   ;; then recurse

   (cond ((and (keymapp binding)
               (keymapp base-binding))
          (lyskom-overlay-keymap basemap binding keymap keys))

   ;; If the binding is a keymap or prefix and
   ;; we are bound in the base
   ;; then don't recurse

         ((and (keymapp binding)
               base-binding) nil)

   ;; If we are not bound in the base
   ;; copy the binding

         ((and binding
               (null base-binding)) (define-key keymap keys binding)))))

1119
1120
1121
1122
1123
1124
(defun lyskom-traverse-keymap (fn keymap)
  "Like lyskom-map-keymap, but traverses parent links too."
  (let ((parent (keymap-parent keymap)))
    (lyskom-map-keymap fn keymap)
    (when (keymapp parent) (lyskom-traverse-keymap fn parent))))

1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137

;;;
;;; Stuff
;;;

(defun lyskom-return-membership-type (mt)
  "Return a text description of membership type mt"
  (let ((tmp
         (mapconcat 
          'identity
          (delete nil
                  (list (if (membership-type->invitation mt) (lyskom-get-string 'invitation-mt-type) nil)
                        (if (membership-type->passive mt) (lyskom-get-string 'passive-mt-type) nil)
David Byers's avatar
David Byers committed
1138
1139
1140
1141
1142
1143
                        (if (membership-type->secret mt) (lyskom-get-string 'secret-mt-type) nil)
                        (if (eq (membership-type->message-flag mt)
                                (membership-type->passive mt))
                            (lyskom-get-string (if (membership-type->message-flag mt)
                                                   'message-flag-on-mt-type
                                                 'message-flag-off-mt-type)))))
1144
1145
1146
1147
          ", ")))
    (if (string= tmp "") 
        tmp
      (concat "[" tmp "]"))))
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159

(defun lyskom-find-unread (conf-no)
  "Return the number of unread texts in CONF-NO.
If this function is unable to calculate the number of unread texts it will
return nil."
  (save-excursion
   (set-buffer lyskom-buffer)
   (let ((rlist (read-list->all-entries lyskom-to-do-list))
         (found nil))
     (while (and (not found) rlist)
       (when (eq conf-no (conf-stat->conf-no
                          (read-info->conf-stat (car rlist))))
David Byers's avatar
David Byers committed
1160
         (setq found (text-list->length (read-info->text-list (car rlist)))))
1161
1162
       (setq rlist (cdr rlist)))
     found)))
1163

David Byers's avatar
David Byers committed
1164
(defun lyskom-prev-area (num prop &optional goto-point-min)
1165
1166
  (while (> num 0)
    (let ((where (previous-single-property-change (point) prop)))
David Byers's avatar
David Byers committed
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
      (cond (where
             (if (not (get-text-property where prop))
                 (setq where (previous-single-property-change 
                              where prop)))
             (if where
                 (goto-char where)
               (goto-char (point-min))
               (setq num 1)))
            (goto-point-min (goto-char (point-min))
                            (setq num 1))))
1177
1178
    (setq num (1- num))))

David Byers's avatar
David Byers committed
1179
(defun lyskom-next-area (num prop &optional goto-point-max)
1180
1181
1182
1183
  "Move the cursor to the next prompt in the LysKOM buffer"
  (interactive "p")
  (while (> num 0)
    (let ((where (next-single-property-change (point) prop)))
David Byers's avatar
David Byers committed
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
      (cond (where
             (if (not (get-text-property where prop))
                 (setq where (next-single-property-change where prop)))
             (if where
                 (goto-char where)
               (goto-char (point-max))
               (setq num 1)))
            (goto-point-max (goto-char (point-max))
                            (setq num 1))))
      (setq num (1- num))))
David Byers's avatar
David Byers committed
1194
1195
1196
1197

;;; ============================================================
;;; Database stuff

1198
1199
1200
1201
1202
1203
(defun lyskom-get-send-comments-to (conf-no &optional want-type)
  "Get the send-comments-to value for conference CONF-NO.
Returns nil if there is no send-comments-to set.

f WANT-TYPE is set, return as a conf (RECPT . TYPE), wher RECPT
is the conference to use and TYPE is the type of recipient (numeric)."
1204
1205
1206
  (let* ((conf-stat (if (numberp conf-no)
                        (blocking-do 'get-conf-stat conf-no)
                      conf-no))
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
         (send-comments-to
          (and conf-stat 
               (car (lyskom-get-aux-item (conf-stat->aux-items conf-stat) 33))))
         (result (when send-comments-to
                   (cond ((string-match "^\\([0-9]+\\)\\s-+\\([0-9]+\\)" (aux-item->data send-comments-to))
                          (cons (string-to-number
                                 (match-string 1 (aux-item->data send-comments-to)))
                                (string-to-number
                                 (match-string 2 (aux-item->data send-comments-to)))))
                         ((string-match "^\\([0-9]+\\)"
                                        (aux-item->data send-comments-to))
                          (cons (string-to-number
                                 (match-string 1 (aux-item->data send-comments-to)))
                                0))
                         (t nil)))))
    (if want-type result (car result))))
    
1224
1225
1226
1227
1228
1229
1230
1231
(defun lyskom-get-all-conferences (&optional feep)
  "Return a list of all conferences.
If FEEP is non-nil, show progress messages"
  (and feep (lyskom-message (lyskom-get-string 'getting-all-confs)))
  (prog1 (mapcar 'conf-z-info->conf-no
                 (conf-z-info-list->conf-z-infos
                  (blocking-do 'lookup-z-name "" nil t)))
    (and feep (lyskom-message (lyskom-get-string 'getting-all-confs-done)))))
1232

David Byers's avatar
David Byers committed
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
(defun lyskom-is-supervisor (conf-no viewer-no)
  "Return non-nil if the supervisor of CONF-NO is VIEWER-NO."
  (or (eq viewer-no conf-no)
      (lyskom-is-strictly-supervisor conf-no viewer-no)))

(defun lyskom-is-strictly-supervisor (conf-no viewer-no)
  "Return non-nil if VIEWER-NO is strictly a supervisor of CONF-NO

Cannot be called from a callback."
  (let ((collector (make-collector))
        (conf-stat nil))
    (initiate-get-conf-stat 'background 'collector-push conf-no collector)
    (lyskom-wait-queue 'background)
    (setq conf-stat (car (collector->value collector)))

    (cond ((null viewer-no) nil)
          ((eq viewer-no 0) nil)
          ((null conf-stat) nil)
          ((eq viewer-no (conf-stat->supervisor conf-stat)) t)
          ((lyskom-is-member (conf-stat->supervisor conf-stat) viewer-no) t)
          (t nil))))

1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
(defun lyskom-i-am-supervisor (conf-stat &optional may-block)
  "Returns non-nil if lyskom-pers-no is the supervisor of CONF-STAT.

If MAY-BLOCK is non-nil, this function never makes server calls, so if
the information required to answer accurately is not cached, this
function will return an incorrect result (nil instead of t)."
  (let ((marshal nil))
    (when conf-stat
      (let ((conf (conf-stat->supervisor conf-stat))
            (result nil))
        (while (and (not (memq conf marshal)) conf (not result))
          (setq marshal (cons conf marshal))
          (if (lyskom-try-get-membership conf t)
              (setq result t)
            (if may-block
                (setq conf (conf-stat->supervisor 
                            (blocking-do 'get-conf-stat conf)))
              (setq conf (conf-stat->supervisor (cache-get-conf-stat conf))))))
        result))))

1275

David Byers's avatar
David Byers committed
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
(defun lyskom-is-member (conf-no pers-no &optional queue)
  "Return the membership in CONF-NO of PERS-NO
Optional argument QUEUE is the queue to send the queries on.

Cannot be called from a callback."
  (or (and (eq pers-no lyskom-pers-no)
           (lyskom-try-get-membership conf-no t))
      (let ((collector (make-collector)))
        (initiate-query-read-texts (or queue 'background)
                                   'collector-push
                                   pers-no
                                   conf-no
1288
                                   nil 0
David Byers's avatar
David Byers committed
1289
1290
1291
                                   collector)
        (lyskom-wait-queue (or queue 'background))
        (car (collector->value collector)))))
1292
1293
1294
1295
1296
1297
1298

(defun lyskom-text-recipients (text-stat &optional want-types)
  "Return the list of recipients for TEXT-STAT.
If WANT-TYPES is non-nil then the result is an assoc list where the 
car of each element is the recipient number and the cdr is the type."
  (let ((result nil))
    (lyskom-traverse misc (text-stat->misc-info-list text-stat)
1299
      (when (memq (misc-info->type misc) lyskom-recpt-types-list)
1300
1301
1302
1303
1304
1305
1306
        (if want-types
            (setq result (cons (cons (misc-info->recipient-no misc)
                                     (misc-info->type misc))
                               result))
          (setq result (cons (misc-info->recipient-no misc)
                             result)))))
    (nreverse result)))
1307

David Byers's avatar
David Byers committed
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
(defun lyskom-text-comments (text-stat)
  "Return the list of comments to TEXT-STAT"
  (let ((result nil))
    (lyskom-traverse misc (text-stat->misc-info-list text-stat)
      (cond ((eq (misc-info->type misc) 'FOOTN-IN)
             (setq result (cons (misc-info->footn-in misc) result)))
            ((eq (misc-info->type misc) 'COMM-IN)
             (setq result (cons (misc-info->comm-in misc) result)))))
    (nreverse result)))

1318

1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
(defun lyskom-find-conf-by-date (target-date)
  "Search all conferences for a conference created on or about TARGET-DATE.
Returns the conf-stat of the conference."
  (blocking-do-multiple ((lowest (find-next-conf-no 0))
                         (highest (first-unused-conf-no)))

    (let* ((index (+ lowest (/ (- highest lowest) 2)))
           (last-index (1- index))
           (result nil))
      (while (/= last-index index)

        ;; Get the first conf-stat after index

        (let ((conf-stat nil)
              (conf-no index))
          (while (and (null conf-stat)
                      (<= conf-no highest))
            (setq conf-stat (blocking-do 'get-conf-stat conf-no))
            (unless conf-stat
              (setq conf-no (blocking-do 'find-next-conf-no conf-no))))

          ;; If we were unable to find a conf-stat, then set highest
          ;; equal to index -- there are no conf-stats in that area,
          ;; so we might as well start looking below index

          (cond ((null conf-stat) (setq highest index))
                ((lyskom-time-greater (conf-stat->creation-time conf-stat)
                                      target-date)
                 (setq highest (1+ conf-no)))
                (t (setq lowest conf-no)))
          (setq last-index index result conf-stat)
          (setq index (+ lowest (/ (- highest lowest) 2)))))
      result)))


1354
1355
1356
1357
1358
(defun lyskom-find-text-by-date (conf-stat target-date)
  "Search texts in CONF-STAT for a text added on or about TARGET-DATE.
Returns a cons of (LOCAL . GLOBAL)"
  (let* ((lowest (conf-stat->first-local-no conf-stat))
         (highest (+ lowest (conf-stat->no-of-texts conf-stat)))
David Byers's avatar
David Byers committed
1359
         (conf-no (conf-stat->conf-no conf-stat))
1360
1361
         (result nil)
         (index (+ lowest (/ (- highest lowest) 2)))
Joel Rosdahl's avatar
Joel Rosdahl committed
1362
         (last-index (1- index)))
1363
1364
    (while (/= last-index index)
      (let* ((map (blocking-do 'local-to-global 
David Byers's avatar
David Byers committed
1365
                               conf-no
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
                               index
                               1)))
        (cond ((null map) (setq lowest highest))
              ((null (text-mapping->global-numbers map))
               (setq highest index))
              (t 
               (let* ((text-no (car (text-mapping->global-numbers map)))
                      (text-stat (blocking-do 'get-text-stat text-no))
                      (local-no (text-mapping->global-to-local map text-no))
                      (date (and text-stat
                                 (lyskom-traverse misc
                                     (text-stat->misc-info-list text-stat)
1378
                                   (when (and (memq (misc-info->type misc) lyskom-recpt-types-list)
David Byers's avatar
David Byers committed
1379
					      (eq (misc-info->recipient-no misc) conf-no))
1380
1381
1382
1383
1384
1385
1386
                                     (lyskom-traverse-break 
                                      (if (misc-info->sent-at misc)
                                          (misc-info->sent-at misc)
                                        (text-stat->creation-time text-stat))))))))
                 (when text-stat
                   (setq index local-no)
                   (if (lyskom-time-greater
1387
			date
1388
1389
1390
1391
1392
1393
                        target-date)
                       (setq highest index)
                     (setq lowest index))
                   (setq result text-stat))))))
      (setq last-index index)
      (setq index (+ lowest (/ (- highest lowest) 2))))
David Byers's avatar
David Byers committed
1394
1395
1396
1397
1398
1399
    (cons last-index (text-stat->text-no result))))

(put 'lyskom-parse-date-invalid 'error-conditions
     '(error lyskom-error))
(put 'lyskom-parse-date-invalid 'error-message
     "Error parsing date")
1400
1401
1402
1403
1404
1405

(defvar lyskom-year-window-start 80
  "Windowing threshold for YY year specifications.
Years below this are considered in the 21st century. Years above this
in the 20th century")

1406
1407
1408
1409
1410
1411
1412
1413
1414
(defun lyskom-all-prefixes (s)
  "Return part of a regular expression matching all prefixes of S.
The value returned does not include the parens before at either ends of the expression."
  (let ((result nil)
        (i 1))
    (while (<= i (length s))
      (setq result (cons (substring s 0 i) result) i (1+ i)))
    (mapconcat 'regexp-quote result "\\|")))

1415
(defun lyskom-read-date (prompt &optional empty)
David Byers's avatar
David Byers committed
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
  "Read a date from the minibuffer. 
Returns a list (YEAR MONTH DATE) corresponding to the user's input."
  (let ((result nil)
        (date nil))
    (while (null result)
      (setq date (lyskom-verified-read-from-minibuffer 
                  prompt 
                  date
                  (lambda (data)
                    (condition-case nil
1426
1427
                        (cond ((and empty (string-equal data "")) nil)
                              (t (lyskom-parse-date data) nil))
David Byers's avatar
David Byers committed
1428
1429
                      (lyskom-error (lyskom-get-string 'invalid-date-entry))))))
      (condition-case nil
1430
1431
          (cond ((and empty (string-equal date "")) (setq result t))
                (t (setq result (lyskom-parse-date date))))
David Byers's avatar
David Byers committed
1432
        (lyskom-error nil)))
1433
    (and (listp result) result)))
David Byers's avatar
David Byers committed
1434

1435
(defun lyskom-parse-date (arg)
David Byers's avatar
David Byers committed
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
  "Parse ARG (a string) as a date.
Returns a list (YEAR MONTH DAY) corresponding to the date in ARG."
  (let* ((month-regexp (concat "\\("
                               (mapconcat (lambda (el)
                                            (regexp-quote (car el)))
                                          lyskom-month-names
                                          "\\|")
                               "\\)"))
         (y-regexp (concat "\\("
                             (mapconcat (lambda (el)
1446
                                          (lyskom-all-prefixes (lyskom-get-string el)))
David Byers's avatar
David Byers committed
1447
1448
1449
1450
1451
                                        '(years year)
                                        "\\|")
                             "\\)"))
         (m-regexp (concat "\\("
                             (mapconcat (lambda (el)
1452
                                          (lyskom-all-prefixes (lyskom-get-string el)))
David Byers's avatar
David Byers committed
1453
1454
1455
1456
1457
                                        '(months month)
                                        "\\|")
                             "\\)"))
         (d-regexp (concat "\\("
                             (mapconcat (lambda (el)
1458
                                          (lyskom-all-prefixes (lyskom-get-string el)))
David Byers's avatar
David Byers committed
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
                                        '(days day)
                                        "\\|")
                             "\\)"))
         (test-date (format-time-string "%x" '(20 0)))
         (now (decode-time))
         (current-day (elt now 3))
         (current-month (elt now 4))
         (current-year (elt now 5))
         (case-fold-search t)
         year month day di mi yi)

    ;; Look at test-date to see where dates in ambiguous cases should go
1471
1472
1473
1474
1475
1476
1477
    (cond ((string-match "01.*16.*70" test-date) (setq di 2 mi 1 yi 3))
          ((string-match "01.*70.*16" test-date) (setq di 3 mi 1 yi 2))
          ((string-match "16.*01.*70" test-date) (setq di 1 mi 2 yi 3))
          ((string-match "16.*70.*01" test-date) (setq di 1 mi 3 yi 2))
          ((string-match "70.*01.*16" test-date) (setq di 3 mi 2 yi 1))
          ((string-match "70.*16.*01" test-date) (setq di 2 mi 3 yi 1)))

David Byers's avatar
David Byers committed
1478
    ;; Match various variants
1479
    (cond ((string-match "^\\s-*\\([0-9][0-9][0-9][0-9]?\\)\\s-*[ -./]\\s-*\\([0-9][0-9]?\\)\\s-*[ -./]\\s-*\\([0-9][0-9]?\\)\\s-*$" arg)
1480
1481
1482
           ;; YYYY-MM-DD
           (setq year (string-to-int (match-string 1 arg))
                 month (string-to-int (match-string (if (> mi di) 3 2) arg))
David Byers's avatar
David Byers committed
1483
                 day (string-to-int (match-string (if (> mi di) 2 3) arg)))
1484
1485
           (when (> month 12) (setq month day day month))
           )