utilities.el 60.9 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
;;;
;;; Need Per Abrahamsens widget and custom packages There should be a
;;; better way of doing this, but I'll be darned if I know how. The
;;; various files need to be loaded in a very specific order.
;;;

47
;;; Define widget wrappers for all the functions in macros.el
48
49
50
51
52
53
54
55
56
57
58
59
60
61

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

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

(defun reverse-assoc (key cache)
  "Same as assoc, but searches on last element in a list"
  (reverse (assoc key (mapcar (function reverse) cache))))


62
63
(defun nfirst (n list)
  "Return a list of the N first elements of LIST."
David Byers's avatar
David Byers committed
64
65
66
67
68
69
  (let ((result nil))
    (while (and (> n 0) list)
      (setq result (cons (car list) result)
            list (cdr list)
            n (1- n)))
    (nreverse result)))
70

David Byers's avatar
David Byers committed
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
(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)))

98
99
100
101
102
103
104
105
106
(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)

107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
;;;
;;; +++ 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))))
124

125
126
127
128
129
130
(defun skip-first-zeros (list)
  (while (and list (zerop (car list)))
    (setq list (cdr list)))
  list)


131
(defun filter-list (test list)
132
133
134
135
136
  (let ((result nil))
    (lyskom-traverse el list
      (when (funcall test el)
        (setq result (cons el result))))
    (nreverse result)))
137

138
139
140
141
142
143
144
;;;============================================================
;;;
;;; Utility functions.
;;;
;;; These should be shared in LysKOM
;;;

David Byers's avatar
David Byers committed
145
146
147
148
149
(eval-and-compile
  (if (eval-when-compile (string-match "XEmacs" emacs-version))
      (defmacro lyskom-compiled-function-p (arg) `(compiled-function-p ,arg))
    (defmacro lyskom-compiled-function-p (arg) `(byte-code-function-p ,arg))))

150
(lyskom-provide-function copy-tree (l)
151
152
153
154
155
  "Recursively copy the list L"
  (cond ((atom l) l)
        (t (cons (copy-tree (car l))
                 (copy-tree (cdr l))))))

David Byers's avatar
David Byers committed
156
157
158
159
160
(lyskom-provide-function functionp (obj)
  "Returns t if OBJ is a function, nil otherwise."
  (cond
   ((symbolp obj) (fboundp obj))
   ((subrp obj))
David Byers's avatar
David Byers committed
161
   ((lyskom-compiled-function-p obj))
David Byers's avatar
David Byers committed
162
163
164
   ((consp obj)
    (if (eq (car obj) 'lambda) (listp (car (cdr obj)))))
   (t nil)))
165
166


167
168
169
170
(defun lyskom-ignore (&rest args)
  "Ignore all arguments"
  )

171
172
173
174
175
176
177
178
179
180
(defun regexpp (re)
  "Return non-nil if RE looks like a valid regexp."
  (let ((result t))
    (save-match-data
      (condition-case nil
          (string-match re "")
        (error (setq result nil))))
    result))


181
182
183
184
185
186
187
188
189
(defun mapcar2 (fn seq1 seq2)
  (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)))


190
(defun lyskom-maxint ()
David Byers's avatar
David Byers committed
191
192
193
194
  (let ((n 1) 
        (l nil)
        (i 31))
    (while (and (> n 0) (> i 0))
195
      (setq l (cons n l))
David Byers's avatar
David Byers committed
196
197
      (setq n (* 2 n))
      (setq i (1- i)))
198
199
    (apply '+ l)))

David Byers's avatar
David Byers committed
200
201
202
203
;; Set lyskom-maxint correctly

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

David Byers's avatar
David Byers committed
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222

(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))))
                               
      

223
224
225
226
227
(defun lyskom-emacs-version ()
  (cond ((string-match "^XEmacs" (emacs-version)) 'xemacs)
	(t 'emacs)))


David Byers's avatar
David Byers committed
228
229
(defvar lyskom-apo-timeout 0
  "Current millisecond timeout value for accept-process-output")
230

David Byers's avatar
David Byers committed
231
232
(defvar lyskom-apo-timeout-index 0
  "Index in lyskom-apo-timeout-vector-max where last timeout is")
233

David Byers's avatar
David Byers committed
234
235
236
(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")
237

David Byers's avatar
David Byers committed
238
239
(defconst lyskom-apo-timeout-vector-max (1- (length lyskom-apo-timeout-vector))
  "Maximum index in lyskom-apo-timeout-vector")
240

241
(defun lyskom-next-apo-timeout ()
David Byers's avatar
David Byers committed
242
243
244
245
246
  (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))))))
247

248
(defun lyskom-reset-apo-timeout ()
David Byers's avatar
David Byers committed
249
250
  (setq lyskom-apo-timeout-index -1)
  (setq lyskom-apo-timeout 0))
251

252
(defun lyskom-accept-process-output ()
David Byers's avatar
David Byers committed
253
254
255
  "Call accept-process-output with the correct timeout values."
  (lyskom-next-apo-timeout)
  (accept-process-output nil 0 lyskom-apo-timeout))
256

257
(defun lyskom-set-alist (alist item value)
Johan Sundström's avatar
Bugfix.    
Johan Sundström committed
258
259
  "Modifies (non-destructively) an alist ALIST to set item
ITEM to the value VALUE."
260
261
262
263
  (let ((pair (assq item alist)))
     (if pair
         (progn (setcdr pair value) alist)
       (cons (cons item value) alist))))
264

265
266
267
268
;;;
;;; LysKOM utility functions
;;;

269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
(lyskom-provide-function string-to-sequence (string type)
  "Convert STRING to a sequence of TYPE which contains characters in STRING.
TYPE should be `list' or `vector'."
  (let ((len (length string))
	(i 0)
	val)
    (cond ((eq type 'list)
	   (setq val (make-list len 0))
	   (let ((l val))
	     (while (< i len)
	       (setcar l (aref string i))
	       (setq l (cdr l) i (1+ i)))))
	  ((eq type 'vector)
	   (setq val (make-vector len 0))
	   (while (< i len)
	     (aset val i (aref string i))
	     (setq i (1+ i))))
	  (t
	   (error "Invalid type: %s" type)))
    val))

(lyskom-provide-subst string-to-vector (string)
  "Return a vector of characters in STRING."
  (string-to-sequence string 'vector))

David Byers's avatar
David Byers committed
294
295
296
297
298
299
300
301
302
;;;
;;; 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.
;;;
303
304
;;; Make sure your MULE Emacs doesnt fuck it up for you. It did for me.
;;;
David Byers's avatar
David Byers committed
305

306
(defvar lyskom-default-collate-table
David Byers's avatar
David Byers committed
307
  "\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"
308
309
310
311
312
  "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.")

313

David Byers's avatar
David Byers committed
314
315
316
317
318
319
(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."
  (if (and (multibyte-string-p s) (or force (not enable-multibyte-characters)))
320
321
322
323
324
      (encode-coding-string s (or coding
                                  (and lyskom-language
                                       (lyskom-language-coding lyskom-language))
                                  'raw-text))
    s))
325

David Byers's avatar
David Byers committed
326
327
328
329
330
331
(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
332
			(cons (lyskom-maybe-recode-string (car el) nil t)
333
334
			      (cdr el)))
                      table))
David Byers's avatar
David Byers committed
335
	(t (lyskom-traverse el table
David Byers's avatar
David Byers committed
336
		(setcar el (lyskom-maybe-recode-string (car el) nil t)))
David Byers's avatar
David Byers committed
337
338
339
	   table)))


340
341
(defsubst lyskom-unicase-char (c)
  "Smash case and diacritical marks on c." 
342
  (if (< (char-to-int c) (length lyskom-collate-table))
David Byers's avatar
David Byers committed
343
      (aref lyskom-collate-table (char-to-int c))
344
345
346
347
    (setq c (lyskom-encode-coding-char c lyskom-server-coding-system))
    (if (and c (< (char-to-int c) (length lyskom-collate-table)))
	(aref lyskom-collate-table (char-to-int c))
      c)))
348
349
350

(defun lyskom-unicase (s)
  "Smash case and diacritical marks of all chars in s." 
351
  (lyskom-save-excursion
352
   (and lyskom-buffer (set-buffer lyskom-buffer))
David Byers's avatar
David Byers committed
353
354
355
   (let* ((s2 (string-to-vector 
               (encode-coding-string s lyskom-server-coding-system)))
          (l (length s2)))
356
357
358
     (while (> l 0)
       (setq l (1- l))
       (aset s2 l (lyskom-unicase-char (aref s2 l))))
359
     (concat s2))))
David Byers's avatar
David Byers committed
360

David Byers's avatar
David Byers committed
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
(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)))


379
380
381
382
383
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
415
(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))
	       (str (decode-coding-string (concat (vector ix))
					  lyskom-server-coding-system))
	       (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
416
	  (let ((lst (cdr (car cls-to-strings))))
417
418
419
	    (if (> (length lst) 1)
		(while lst
		  (setq res (cons (cons (string-to-char (car lst))
Joel Rosdahl's avatar
Joel Rosdahl committed
420
					(cdr (car cls-to-strings)))
421
422
423
424
425
				  res))
		  (setq lst (cdr lst)))))
	  (setq cls-to-strings (cdr cls-to-strings)))
	res))))
    
David Byers's avatar
David Byers committed
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
;; 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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511

;; Stolen from Gnu Emacs

(defun lyskom-truncate-string-to-width (str end-column &optional start-column padding)
  "Truncate string STR to end at column END-COLUMN.
The optional 2nd arg START-COLUMN, if non-nil, specifies
the starting column; that means to return the characters occupying
columns START-COLUMN ... END-COLUMN of STR.

The optional 3rd arg PADDING, if non-nil, specifies a padding character
to add at the end of the result if STR doesn't reach column END-COLUMN,
or if END-COLUMN comes in the middle of a character in STR.
PADDING is also added at the beginning of the result
if column START-COLUMN appears in the middle of a character in STR.

If PADDING is nil, no padding is added in these cases, so
the resulting string may be narrower than END-COLUMN."
  (or start-column
      (setq start-column 0))
  (let ((len (length str))
	(idx 0)
	(column 0)
	(head-padding "") (tail-padding "")
	ch last-column last-idx from-idx)
    (condition-case nil
	(while (< column start-column)
	  (setq ch (aref str idx)
		column (+ column (char-width ch))
		idx (1+ idx)))
      (args-out-of-range (setq idx len)))
    (if (< column start-column)
	(if padding (make-string end-column padding) "")
      (if (and padding (> column start-column))
	  (setq head-padding (make-string (- column start-column) padding)))
      (setq from-idx idx)
      (if (< end-column column)
	  (setq idx from-idx)
	(condition-case nil
	    (while (< column end-column)
	      (setq last-column column
		    last-idx idx
		    ch (aref str idx)
		    column (+ column (char-width ch))
		    idx (1+ idx)))
	  (args-out-of-range (setq idx len)))
	(if (> column end-column)
	    (setq column last-column idx last-idx))
	(if (and padding (< column end-column))
	    (setq tail-padding (make-string (- end-column column) padding))))
      (setq str (substring str from-idx idx))
      (if padding
	  (concat head-padding str tail-padding)
	str))))


512
513
514
515
516
517
(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)
518
       (string= (and s1 (if (multibyte-string-p s1)
519
520
		    s1
		  (decode-coding-string s1 (lyskom-language-coding
521
522
					    lyskom-language))))
		(and s2 (if (multibyte-string-p s2)
523
524
		    s2
		  (decode-coding-string s2 (lyskom-language-coding
525
					    lyskom-language)))))))))
526

David Byers's avatar
X    
David Byers committed
527
528
529
(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
530
  (let ((s (and key (downcase key)))
David Byers's avatar
X    
David Byers committed
531
532
        (result nil))
    (while list
533
      (when (lyskom-string= s (downcase (car (car list))))
David Byers's avatar
X    
David Byers committed
534
535
536
537
        (setq result (car list))
        (setq list nil))
      (setq list (cdr list)))
    result))
David Byers's avatar
David Byers committed
538

539
540
541
542
543
544
545
546
547
548
549
550
(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))

551
552
553
(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
554
  (let ((s (and key (downcase key)))
555
556
557
558
559
560
561
562
        (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
563
564
(defun lyskom-set-default (sym val)
  "Set the value of SYM in the LysKOM buffer to VAL."
David Byers's avatar
David Byers committed
565
  (save-excursion
David Byers's avatar
X    
David Byers committed
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
    (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
581
582
    (symbol-value sym)))

David Byers's avatar
X    
David Byers committed
583
584
(defun lyskom-default-value-safe (sym)
  "Get the value of SYM in the LysKOM buffer"
David Byers's avatar
David Byers committed
585
  (save-excursion
David Byers's avatar
X    
David Byers committed
586
587
588
589
590
591
    (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))))
592

David Byers's avatar
David Byers committed
593

594
595
596
;;; ============================================================
;;; Prefix arguments

597
598
599
600
601
(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))))

602
(defun lyskom-read-text-no-prefix-arg (prompt &optional always-read default)
603
  "Call in interactive list to read text-no.
604
605
606
607
608
609
610
If optional argument ALWAYS-READ is non-nil the user is prompted if an
explicit prefix argument was not given. The prefix argument zero
refers to the text under point. A positive prefix argument is
interpreted as a text-no, whereas a negative prefix argument will try
to find the text-no of the text `arg' messages above point from the
current kom buffer. DEFAULT specifies the default text to use. If it
is nil, the most recently read text is the default. The symbol
611
last-written means use the text most recently written. The symbol
612
613
614
last-seen-written means use the text in lyskom-last-seen-written. A
number means use that text as the default."
  (let ((default (cond ((or (null default)
David Byers's avatar
David Byers committed
615
                            (eq 0 default))
616
617
                        (lyskom-default-value 'lyskom-current-text))
                       ((numberp default) default)
618
619
620
621
622
                       ((eq default 'last-written)
                        (or (lyskom-default-value 'lyskom-last-seen-written)
                            (lyskom-default-value 'lyskom-current-text)))
                       ((eq default 'last-seen-written)
                        (or (lyskom-default-value 'lyskom-last-seen-written)
623
624
625
                            (lyskom-default-value 'lyskom-current-text))))))
    ;; If the default is *still* zero, then we really can't figure
    ;; one out, so set it to nil.
David Byers's avatar
David Byers committed
626
    (when (eq 0 default) (setq default nil))
627
628
    (cond
     ((null current-prefix-arg)
629
      (if (or always-read
630
              (lyskom-read-text-no-prompt-p lyskom-current-command)
631
              (null default))
632
633
634
635
636
637
          (lyskom-read-number prompt default)
        default))
     ((or (integerp current-prefix-arg)
          (eq '- current-prefix-arg))
      (let ((current-prefix-arg
             (if (eq '- current-prefix-arg) -1 current-prefix-arg)))
638
639
        (cond
	 ((> current-prefix-arg 0) current-prefix-arg)
640
	 ((zerop current-prefix-arg) (lyskom-text-at-point))
641
	 (t
642
643
644
645
646
          (save-excursion
            (backward-text (- 1 current-prefix-arg))
            (if (looking-at "\\([0-9]+\\)\\s-")
                (string-to-int (match-string 1))
              (lyskom-error (lyskom-get-string 'bad-text-no-prefix)
647
                            current-prefix-arg)))))))
648
     ((listp current-prefix-arg)
649
      (lyskom-read-number prompt default))
650
651
     (t (lyskom-error (lyskom-get-string 'bad-text-no-prefix)
                      current-prefix-arg)))))
652

653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
;;; ============================================================
;;; 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))))

676
677
678
679
680
681
682
683
684
(defun lyskom-union (a b)
  "Returns a list containing the union of list A and list B.
The list may contain list A or list B as its tail. This means that
destructive operations on the result may affect either operand."
  (let ((result nil))
    (lyskom-traverse x a
      (unless (memq x b) (setq result (cons x result))))
    (nconc (nreverse result) b)))

685
686


687
688
689
690
691
692
693
694
695
696
;;; ======================================================================
;;; Display device management
;;;


;;; Definition of some useful functions from XEmacs

(lyskom-provide-function console-type (&optional console)
  (or window-system 'tty))

697
698
699
700
(lyskom-external-function display-color-p)
(lyskom-external-function display-grayscale-p)

(eval-and-compile
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
  (cond ((fboundp 'device-class)	; XEmacsism
	 (defalias 'lyskom-device-class 'device-class))
	((and (fboundp 'display-color-p) (fboundp 'display-grayscale-p))
	 ;; Emacs 21 can use color even when not running under
	 ;; X-windows.  Note that display-grayscale-p can be false when
	 ;; using a color display!  This happens when running on a
	 ;; classic Linux tty console.
	 (defun lyskom-device-class (&optional device)
	   (cond ((display-color-p device) 'color)
		 ((display-grayscale-p device) 'grayscale)
		 (t 'mono))))
	(t ;; This works in Emacs 20 and earlier.
	 (defun lyskom-device-class (&optional device)
	   (condition-case nil
	       (if (x-display-grayscale-p device)
		   (if (x-display-color-p device)
		       'color
		       'grayscale)
		   'mono)
	     (error 'mono))))))
721
722
723
724
725
726
727
728
729
730
731
732

(lyskom-provide-function frame-property (frame property &optional default)
  (or (cdr (assq property (frame-parameters frame)))
      default))


;;; XEmacs doesn't seem to have a background-mode frame property

(defun lyskom-background-mode ()
  (frame-property (selected-frame) 'background-mode 'light))


David Byers's avatar
X    
David Byers committed
733
734
735
736
737
738
739
;;; ======================================================================
;;; 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."
740
741
742
  (lyskom-save-excursion (set-buffer (or (and (boundp 'lyskom-buffer)
                                              lyskom-buffer)
                                         (current-buffer)))
David Byers's avatar
X    
David Byers committed
743
                  (apply 'run-hook-with-args hook args)))
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


;;;(defun lyskom-set-variable-hook-wrapper (hook-function args)
;;;  "Wrapper for running HOOK-FUNCTION with ARGS.
;;;If HOOK returns an alist ((S1 . V1) ...), set value of symbol S1 to V1
;;;and similarly for each element.
;;;
;;;The hook may set hook-function-args to change the arguments to subsequent
;;;hook functions.
;;;
;;;Hook functions that rely on this are totally dependent on the current 
;;;implementation of all callers. If you think you want to use this feature,
;;;think again. You probably don't."
;;;  (lyskom-traverse el (apply hook args)
;;;    (set (car el) (cdr el))))
;;;
;;;
;;;(defun lyskom-run-hook-with-wrapper (hook wrapper &rest args)
;;;  "Run HOOK by calling WRAPPER for each function in the LysKOM buffer.
;;;The wrapper will be called with arguments FUNCTION and ARGS. It
;;;calls the actual hook function by applying FUNCTION to ARGS.
;;;
;;;This function emulates the built-in run-hook-with-args function.
;;;It is modeled on the XEmacs 21.2 implementation, so there may be
;;;slight discrepancies with other Emacs versions.
;;;
;;;The variable hook-function-args holds the arguments to the hook 
;;;function (the ARGS parameter for the wrapper)."
;;;  (save-excursion
;;;    (set-buffer (or (and (boundp 'lyskom-buffer) lyskom-buffer)
;;;                    (current-buffer)))
;;;    (let ((hook-function-args args))
;;;      (when (and hook (boundp hook))
;;;        (let ((val (symbol-value hook)))
;;;          (if (and (consp val) (eq (car val 'lambda)))
;;;              (funcall wrapper val args)
;;;            (while (and val (consp val))
;;;              (if (eq (car val) t)
;;;                  (let ((globals (default-value hook)))
;;;                    (if (and (consp globals) (eq (car globals 'lambda)))
;;;                        (funcall wrapper hook args)
;;;                      (while (and globals (consp globals))
;;;                        (unless (eq (car globals t))
;;;                          (funcall wrapper (car globals) args))
;;;                        (setq globals (cdr globals)))))
;;;                (funcall wrapper (car val) args)
;;;                (setq val (cdr val))))))))))

                                                     
David Byers's avatar
X    
David Byers committed
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815

(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
816
;;; on the C code for princ. 
David Byers's avatar
X    
David Byers committed
817
818
;;;

819
820
(defun lyskom-princ (object &optional stream)
  "Output the printed representation of OBJECT, any Lisp OBJECT.
821
822
823
824
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
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
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
855
856


857
858
859
860
;;; ======================================================================
;;; Faces
;;;

861
862
863
(make-face 'lyskom-weak-highlight-face)
(make-face 'lyskom-strong-highlight-face)

864
865
866
867
868
869
870
871
872
873
(defun lyskom-set-face-foreground (face color)
  (condition-case nil
      (set-face-foreground face color)
    (error nil)))

(defun lyskom-set-face-background (face color)
  (condition-case nil
      (set-face-background face color)
    (error nil)))

874
875
876
877
878
(defun lyskom-copy-face (old new)
  (lyskom-xemacs-or-gnu (copy-face old new nil nil nil 'remove-all)
                        (copy-face old new)))


879

David Kågedal's avatar
David Kågedal committed
880
(defun lyskom-set-face-scheme (scheme)
881
882
  "Set the LysKOM color and face scheme to SCHEME. Valid schemes are listed
in lyskom-face-schemes."
883
884
885
886
  (let ((tmp (assoc scheme lyskom-face-schemes))
        (properties nil)
        (background (or (face-background 'default)
                        (frame-property (selected-frame) 'background-color))))
887
888
889
890
    (when (and tmp
               (fboundp 'copy-face)
               (fboundp 'lyskom-set-face-foreground)
               (fboundp 'lyskom-set-face-background))
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918


      ;; If we have a background color, then compute the highlight colors

      (when background
        (lyskom-set-face-background 'lyskom-strong-highlight-face
                                    (lyskom-get-color-highlight (lyskom-color-values background) 0.05))
        (lyskom-set-face-background 'lyskom-weak-highlight-face
                                    (lyskom-get-color-highlight (lyskom-color-values background) 0.025)))

      ;; Traverse face specifications in the face scheme

      (lyskom-traverse spec (cdr tmp)
        (if (eq 'property (car spec))
            (setq properties (cons (cons (elt spec 1) (elt spec 2)) properties))
          (if (elt spec 1) (lyskom-copy-face (elt spec 1) (elt spec 0)) (make-face (elt spec 0)))
          (when (elt spec 2) (lyskom-set-face-foreground (elt spec 0) (elt spec 2)))
          (when (elt spec 3) (lyskom-set-face-background (elt spec 0) (elt spec 3)))))

      ;; Check that the background color of the default face is what
      ;; the face scheme expects. If not, copy the computed highlight
      ;; faces to the real highlight faces.

      (when (and background (assq 'expected-background properties))
        (unless (equal (lyskom-color-values (cdr (assq 'expected-background properties)))
                       (lyskom-color-values background))
          (copy-face 'lyskom-strong-highlight-face 'kom-dashed-lines-face)
          (copy-face 'lyskom-weak-highlight-face 'kom-text-body-face))))))
919
920
921
922


(defun lyskom-face-resource (face-name attr type)
  (if (eq (lyskom-emacs-version) 'xemacs)
923
      ;; XEmacs style
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
      (let ((val (x-get-resource (concat face-name ".attribute" attr)
				 (concat "Face.Attribute" attr)
				 type)))
	(cond ((eq type 'string) val)
	      ((and (eq type 'boolean) val) (if (car val) 'on 'off))
	      (t val)))
    ;; Emacs style
    (let ((val (x-get-resource (concat face-name ".attribute" attr)
			       (concat "Face.Attribute" attr))))
      (cond ((eq type 'string) val)
	    ((and val
		  (eq type 'boolean)
		  (member (downcase val) '("on" "true"))) 'on)
	    ((and val (eq type 'boolean)) 'off)
	    (t val)))))


David Byers's avatar
X    
David Byers committed
941
(defun lyskom-modify-face (what face)
David Byers's avatar
David Byers committed
942
  (condition-case nil
David Byers's avatar
X    
David Byers committed
943
944
945
946
      (funcall (intern (concat "make-face-" (symbol-name what)))
               face)
    (error nil)))

947
948
949
950
951
952
953
(defun lyskom-setup-faces ()
  "Initalize the faces in the LysKOM client.
This sets the face scheme according to `kom-default-face-scheme', and
also reads the proper X resources."
  (unless kom-default-face-scheme
    (setq kom-default-face-scheme
	  (condition-case nil
954
	      (cond ((eq (lyskom-device-class) 'mono) 'monochrome)
955
956
957
958
959
960
		    ((eq (lyskom-background-mode) 'dark)
		     'inverse)
		    (t 'default))
	    (error 'default))))  
  (lyskom-set-face-scheme kom-default-face-scheme)
  (if (eq (console-type) 'x)
961
962
963
964
965
966
967
968
969
970
971
972
973
974
      (lyskom-traverse face lyskom-faces
        (let* ((face-name (symbol-name face))
               (fg (lyskom-face-resource face-name "Foreground" 'string))
               (bg (lyskom-face-resource face-name "Background" 'string))
               (bl (lyskom-face-resource face-name "Bold" 'boolean))
               (it (lyskom-face-resource face-name "Italic" 'boolean))
               (ul (lyskom-face-resource face-name "Underline" 'boolean)))
          (if fg (set-face-foreground face fg))
          (if bg (set-face-background face bg))
          (if (eq bl 'on) (lyskom-modify-face 'bold face))
          (if (eq bl 'off) (lyskom-modify-face 'unbold face))
          (if (eq it 'on) (lyskom-modify-face 'italic face))
          (if (eq it 'off) (lyskom-modify-face 'unitalic face))
          (if ul (set-face-underline-p face (eq ul 'on)))))))
975
976


David Byers's avatar
David Byers committed
977
978
979
;;; ============================================================
;;; Date and time utilities

980
981
(defun lyskom-current-client-time ()
  "Return time representing current client time."
982
983
984
985
  (let ((now (decode-time)))
    (lyskom-create-time (elt now 0)     ;sec
                        (elt now 1)     ;min
                        (elt now 2)     ;hour
986
                        (elt now 3)     ;mday
987
                        (elt now 4)     ;mon
988
                        (elt now 5)     ;year
989
990
                        (elt now 6)     ;wday
                        0               ;yday
991
992
993
                        (if (elt now 7) ;isdst
                            1
                          0)
994
995
                        )))

996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
(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
1018
format string will be looked up with lyskom-get-string.  The
1019
1020
1021
timeformat-* strings are tailored to be used as formats for this
function.

Joel Rosdahl's avatar
Joel Rosdahl committed
1022
The arguments to the format string are (in order): year, month number
1023
\(starting with one for January), day-of-month number, hour, minute,
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
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)))))


1063
1064
1065
1066
;;; ============================================================
;;; Keymap utilities

(defun lyskom-lookup-key (keymap event &optional accept-default)
1067
1068
  (if (not (arrayp event))
      (setq event (vector event)))
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
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
  (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)))))

1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165

;;;
;;; 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)
                        (if (membership-type->secret mt) (lyskom-get-string 'secret-mt-type) nil)))
          ", ")))
    (if (string= tmp "") 
        tmp
      (concat "[" tmp "]"))))
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180

(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))))
         (setq found (length (cdr (read-info->text-list (car rlist))))))
       (setq rlist (cdr rlist)))
     found)))
1181

David Byers's avatar
David Byers committed
1182
(defun lyskom-prev-area (num prop &optional goto-point-min)
1183
1184
  (while (> num 0)
    (let ((where (previous-single-property-change (point) prop)))
David Byers's avatar
David Byers committed
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
      (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))))
1195
1196
    (setq num (1- num))))

David Byers's avatar
David Byers committed
1197
(defun lyskom-next-area (num prop &optional goto-point-max)
1198
1199
1200
1201
  "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
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
      (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
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265

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

;; Extracted from edit-text.el
;;(defun lyskom-is-supervisor (conf-stat &optional memo)
;;  "Return non-nil if lyskom-pers-no is a supervisor of CONF-STAT."
;;  (cond ((null conf-stat) nil)
;;        ((memq (conf-stat->conf-no conf-stat) memo) nil)
;;        ((eq lyskom-pers-no (conf-stat->conf-no conf-stat)) t)
;;        ((eq lyskom-pers-no (conf-stat->supervisor conf-stat)) t)
;;        ((eq 0 (conf-stat->supervisor conf-stat)) nil)
;;        ((lyskom-get-membership (conf-stat->conf-no conf-stat) t) t)
;;        ((lyskom-is-supervisor
;;          (blocking-do 'get-conf-stat (conf-stat->supervisor conf-stat))
;;          (cons (conf-stat->conf-no conf-stat) memo)))))

(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))))

(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
                                   collector)
        (lyskom-wait-queue (or queue 'background))
        (car (collector->value collector)))))
1266
1267
1268
1269
1270
1271
1272

(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)
1273
      (when (memq (misc-info->type misc) lyskom-recpt-types-list)
1274
1275
1276
1277
1278
1279
1280
        (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)))
1281

David Byers's avatar
David Byers committed
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
(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)))

1292
1293
1294
1295
1296
1297
1298
1299

(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)))
         (result nil)
         (index (+ lowest (/ (- highest lowest) 2)))
Joel Rosdahl's avatar
Joel Rosdahl committed
1300
         (last-index (1- index)))
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
    (while (/= last-index index)
      (let* ((map (blocking-do 'local-to-global 
                               (conf-stat->conf-no conf-stat)
                               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)
1316
1317
                                   (when (and (memq (misc-info->type misc) lyskom-recpt-types-list)
					      (eq (misc-info->recipient-no misc) text-no))
1318
1319
1320
1321
1322
1323
1324
                                     (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
1325
			date
1326
1327
1328
1329
1330
1331
1332
                        target-date)
                       (setq highest index)
                     (setq lowest index))
                   (setq result text-stat))))))
      (setq last-index index)
      (setq index (+ lowest (/ (- highest lowest) 2))))
    (cons last-index result)))
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426

(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")

(defun lyskom-parse-date (arg)
  "Parse ARG as a date."
  (let ((month-regexp (concat "\\("
                              (mapconcat (lambda (el)
                                           (regexp-quote (car el)))
                                         lyskom-month-names
                                         "\\|")
                              "\\)"))
        (dmy-regexp (concat "\\("
                            (mapconcat (lambda (el)
                                         (regexp-quote (lyskom-get-string el)))
                                       '(years year months month days day)
                                       "\\|")
                            "\\)"))
        (test-date (format-time-string "%x" '(20 0)))
        year month day di mi yi)

  ;; Look at test-date to see where dates in ambiguous cases should go

    (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)))

     (cond ((string-match "\\([0-9][0-9][0-9][0-9]\\)[-./]\\([0-9][0-9]?\\)[-./]\\([0-9][0-9]?\\)" arg)
           ;; YYYY-MM-DD
           (setq year (string-to-int (match-string 1 arg))
                 month (string-to-int (match-string (if (> mi di) 3 2) arg))
                 day (string-to-int (match-string (if (> di mi) 2 3) arg)))
           (when (> month 12) (setq month day day month))
           )
          ((string-match "\\([0-9][0-9]?\\)[-./]\\([0-9][0-9]?\\)[-./]\\([0-9][0-9][0-9][0-9]?\\)" arg)
           ;; YYYY-MM-DD
           (setq year (string-to-int (match-string 3 arg))
                 month (string-to-int (match-string (if (> mi di) 2 1) arg))
                 day (string-to-int (match-string (if (> di mi) 1 2) arg)))
           (when (> month 12) (setq month day day month))
           )
          ((string-match "\\([0-9][0-9]\\)[-./]\\([0-9][0-9]?\\)[-./]\\([0-9][0-9]?\\)" arg)
           (setq year (string-to-int (match-string yi arg))
                 month (string-to-int (match-string mi arg))
                 day (string-to-int (match-string di arg)))
           (when (> month 12) (setq month day day month))
           )
          ((string-match "\\([0-9][0-9]\\)/\\([0-9][0-9]\\)" arg)
           ;; Ambiguous:
           ;; MM/DD       Euro
           ;; DD/MM       US
           (let ((a (string-to-int (match-string 1 arg)))
                 (b (string-to-int (match-string 2 arg))))
             (cond ((> a 12) (setq month b day a))
                   ((> b 12) (setq month a day b))
                   ((> di mi) (setq month b day a))
                   (t (setq month a day b))))
           )
          ((string-match (format "%s \\([0-9][0-9]?\\)" month-regexp) arg)
           ;; Ambiguous:
           ;; Month DD
           )
          ((string-match (format "%s,? \\([0-9][0-9][0-9][0-9]\\)" month-regexp) arg)
           ;; Ambiguous:
           ;; Month YYYY
           )
          ((string-match (format "\\([0-9][0-9]?\\) %s" month-regexp) arg)
           ;; DD Month
           )
          ((string-match (format "\\([0-9][0-9]?\\) %s \\([0-9][0-9][0-9][0-9]\\)" month-regexp) arg)
           ;; DD Month YYYY
           )
          ((string-match (format "%s \\([0-9][0-9]?\\), \\([0-9][0-9][0-9]?[0-9]?\\)" month-regexp) arg)
           ;; Month DD, YYYY
           )
          ((string-match (format "\\([0-9][0-9]?\\) %s, \\([0-9][0-9][0-9]?[0-9]?\\)" month-regexp) arg)
           ;; DD Month, YYYY
           )
          ((string-match (format "-\\([0-9]+\\) %s" dmy-regexp) arg)
           ;; -NN days, months, years
           )
          )

    (if (< year lyskom-year-window-start)
        (setq year (+ 2000 year))
      (setq year (+ 1900 year)))

    (list year month day)
    ))
David Byers's avatar
David Byers committed
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444


;;; ================================================================
;;; Read membership types

(defun lyskom-read-membership-type ()
  "Interactively read a membership type"
  (let ((invitation (lyskom-j-or-n-p 'mship-type-invitation-q))
        (passive (lyskom-j-or-n-p 'mship-type-passive-q))
        (secret (lyskom-j-or-n-p 'mship-type-secret-q)))
    (lyskom-create-membership-type invitation
                                   passive
                                   secret
                                   nil
                                   nil
                                   nil
                                   nil
                                   nil)))
David Byers's avatar
David Byers committed
1445

1446

1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
;;; ================================================================
;;; String truncation
;;;

(defun lyskom-truncate-to-lines (string threshold show-lines &optional width)
  "If STRING is more than THRESHOLD lines on screen, truncate it to  SHOW-LINES.
Optional argument WIDTH is thw window width to use instead of window-width.

This function takes the setting of truncate-lines into account, so
the resulting string may not have SHOW-LINES newline characters.

Result is eq to STRING when no truncation is required.

The result is approximate when truncate-lines is non-nil since different
Emacsen use a different number of characters for the continuation marks
at the end of broken lines. We assume one character continuation marks."
  (let ((line-length (if truncate-lines lyskom-max-int (- (or width (window-width)) 1)))
        (count 0)
        (end nil)
        (pos 0))
    (while (and (< pos (length string)) (< count threshold))
      (setq count (1+ count))
      (let ((next (string-match "\\(\n\\|\\'\\)" string pos)))
        (if (> (- next pos) line-length)
            (setq pos (+ pos line-length))
          (setq pos (match-end 0))))
        (when (= count show-lines)
          (setq end pos)))

    (if (>= count threshold)
        (substring string 0 end)
      string)))

1480
1481
1482
1483
1484
1485
1486
1487
1488

;;; ================================================================
;;; Color model manipulations
;;;
;;; (Of COURSE you need this in a KOM client!)
;;;

(defun lyskom-get-color-highlight (color distance)
  "Create a highlight color for COLOR that is DISTANCE away.
1489
1490
1491
1492
COLOR is a list of R G and B components from 0 to 65535.
DISTANCE is a non-negative integer no larger than 1.0, that in some
way specifies how far away from the original color the new color
should be."
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
  (when color
    (let* ((hls (lyskom-rgb-to-hls (mapcar (lambda (x) (/ x 65535.0)) color)))
           (l (elt hls 1)))
      (if (> l 0.6)
          (setq l (- l distance))
        (setq l (+ l distance)))
      (cond ((> l 1.0) (setq l 1.0))
            ((< l 0.0) (setq l 0.0)))
      (aset hls 1 l)

      (apply 'format "#%02x%02x%02x"
             (mapcar (lambda (c) (round (* 255 c)))
                     (lyskom-hls-to-rgb hls))))))
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613


(defun lyskom-string-to-rgb (color)
  "Convert the name of a color to RGB values."
  (mapcar (lambda (x) (/ x 65535.0)) (lyskom-color-values color)))

(defun lyskom-rgb-to-hls (rgb)
  "Convert a point in RGB color space to a point in HLS color space.

Input value is a vector [R G B], where R, G and B represent red, green
and blue components, respectively. Each value is a non-negative
floating-point value no larger than 1.0.

Output is a vector [H L S], where H, L and S represend hue, lightness
and saturation, respectively. H is in the range 0..360, L and S are
non-negative floating-point numbers no higher than 1.0. If the input
color is a shade of gray (all components are equal), then H in the
output is nil.

Algorithm adapted from Foley, \"Computer Graphics\"."
  (let* ((r (elt rgb 0))
         (g (elt rgb 1))
         (b (elt rgb 2))
         (rgbmin (min r g b))
         (rgbmax (max r g b))
         (h nil)
         (l (/ (+ rgbmax rgbmin) 2.0))
         (s nil)
         (delta (- rgbmax rgbmin)))
    (if (zerop delta)
        (setq s 0.0)
      (if (<= l 0.5)
          (setq s (/ delta (+ rgbmax rgbmin)))
        (setq s (/ delta (- 2.0 rgbmax rgbmin))))
      (cond ((= r rgbmax)
             (setq h (/ (- g b) delta)))
            ((= g rgbmax)
             (setq h (+ 2.0 (/ (- b r) delta))))
            ((= b rgbmax)
             (setq h (+ 4.0 (/ (- r g) delta)))))
      (setq h (* h 60.0))
      (if (< h 0)
          (setq h (+ 360.0 h))))
    (vector h l s)))

(defun lyskom-hls-to-rgb-value (n1 n2 h)
  "Helper function for lyskom-hls-to-rgb"
  (cond ((> h 360) (setq h (- h 360.0)))
        ((< h 0) (setq h (+ h 360.0))))

  (cond ((< h 60)  (+ n1 (* (- n2 n1) (/ h 60.0))))
        ((< h 180) n2)
        ((< h 240) (+ n1 (* (- n2 n1) (/ (- 240.0 h) 60.0))))
        (t n1)))

(defun lyskom-hls-to-rgb (hls)
  "Convert a point in HLS color space to a point in RGB color space.

Input HLS is a vector [H L S], where H, L and S represend hue,
lightness and saturation, respectively. H is in the range 0..360, L
and S are non-negative floating-point numbers no higher than 1.0. If
the input color is a shade of gray (all components are equal), then S
in the input is ignored and may be anything.

Output value is a vector [R G B], where R, G and B represent red,
green and blue components, respectively. Each value is in the range
1..1.0.

This algorithm is adapted from Foley, \"Computer Graphics\" (and
has the bug in that algorithm fixed)."
  (let* ((h (elt hls 0))
         (l (elt hls 1))
         (s (elt hls 2))
         (m2 (if (<= l 0.5)
                 (* l (+ 1.0 s))
               (+ l (* s (- 1 l)))))
         (m1 (- (* 2 l) m2)))
    (if (zerop s)
        (vector l l l)
      (vector (lyskom-hls-to-rgb-value m1 m2 (+ h 120))
              (lyskom-hls-to-rgb-value m1 m2 h)
              (lyskom-hls-to-rgb-value m1 m2 (- h 120))))))


;;; ================================================================
;;; Automatically test that RGB->X and X->RGB color model conversions
;;; really are the inverse of each other.
;;; 
;;; (defun lyskom-test-color-model ()
;;;   (let ((r 0.0)
;;;         (g 0.0)
;;;         (b 0.0)
;;;         (step 0.05))
;;;     (while (<= r 1.0)
;;;       (setq g 0.0)
;;;       (while (<= g 1.0)
;;;         (setq b 0.0)
;;;         (while (<= b 1.0)
;;;           (let ((tmp (lyskom-hls-to-rgb
;;;                       (lyskom-rgb-to-hls (vector r g b)))))
;;;             (unless (and (< (- r (elt tmp 0)) 0.000000001)
;;;                          (< (- g (elt tmp 1)) 0.000000001)
;;;                          (< (- b (elt tmp 2)) 0.000000001))
;;;               (message "Mismatch %1.2f,%1.2f,%1.2f gave %S/%S" r g b (lyskom-rgb-to-hls (vector r g b)) tmp)))
;;;           (setq b (+ b step)))
;;;         (setq g (+ g step)))
;;;       (setq r (+ r step)))))

1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
;;;(defun lyskom-test-auto-colors ()
;;;  (make-face 'test-1)
;;;  (make-face 'test-2)
;;;  (make-face 'test-default)
;;;  (while t
;;;    (let ((foreground (read-from-minibuffer "Foreground: "))
;;;          (background (read-from-minibuffer "Background: ")))
;;;      (pop-to-buffer (get-buffer-create "*kom*-test"))
;;;      (erase-buffer)
;;;      (set-face-foreground 'test-default foreground)
;;;      (set-face-background 'test-default background)
;;;      (set-face-background 'test-1 (lyskom-get-color-highlight (x-color-values background) 0.05))
;;;      (set-face-background 'test-2 (lyskom-get-color-highlight (x-color-values background) 0.025))
;;;      (let ((lyskom-buffer (current-buffer)))
;;;        (lyskom-format-insert "\
;;;%#3@Lsa nsta fotnot...
;;;8408827 idag 00:40 /1 rad/ Lunkwill/CH ( Auf das Universum! )
;;;Fotnot till text 8408825 av Lunkwill/CH ( Auf das Universum! )
;;;Mottagare: Ntverk, Internet, LysNET, Sunet... <30873>
;;;Mottagare: SUBnet (Stngstadens och LiU:s) studentbostadsnt <12152>
;;;Mottagare: Lunkwill/CH ( Auf das Universum! ) <2092>
;;;rende: Vrmtet
;;;%[%#1$------------------------------------------------------------
;;;%]%[%#2$Och tack s mycket fr frklaringarna! =)
;;;%]%[%#1$(8408827) /Lunkwill/CH ( Auf das Universum! )/------
;;;%]G till nsta mte...
;;;SUN erfarenhetsutbyte - 1 olst
;;;Lsa nsta text...
;;;8408823 idag 00:39 /4 rader/ Erik Persson, Lysato(r)
;;;Kommentar till text 8407161 av Dejan (ngot desperat)
;;;Mottagare: SUN erfarenhetsutbyte <23622>
;;;rende: Skapa partitionstabell
;;;%[%#1$------------------------------------------------------------
;;;%]%[%#2$Om du nu vill spela Fibre Channel med IDE-RAID s gr du ver n efter
;;;vatten. Det finns redan IDE-RAID med FC-interface.  Dock har jag inte
;;;sett ngon som stdjer ngot annat n FC-AL vilket r lite
;;;begrnsande.
;;;%]%[%#1$(8408823) ------------------------------------------
;;;%]G till nsta mte...
;;;
;;;
;;;
;;;"
;;;                              '(face test-1)
;;;                              '(face test-2)
;;;                              '(face test-default))))))
1660
;;;