utilities.el 29.7 KB
Newer Older
David Byers's avatar
David Byers committed
1
;;;;; -*-coding: iso-8859-1;-*-
2
;;;;;
3
4
5
6
7
8
9
;;;;; $Id$
;;;;; Copyright (C) 1996  Lysator Academic Computer Association.
;;;;;
;;;;; This file is part of the LysKOM server.
;;;;; 
;;;;; 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
64
65
66
67
(defun nfirst (n list)
  "Return a list of the N first elements of LIST."
  (if (or (<= n 0) (not list))
      nil
    (cons (car list) (nfirst (1- n) (cdr list)))))

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

95
96
97
98
99
100
101
102
103
(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)

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

122
123
124
125
126
127
(defun skip-first-zeros (list)
  (while (and list (zerop (car list)))
    (setq list (cdr list)))
  list)


128
129
130
131
132
133
(defun filter-list (test list)
  (cond ((null list) '())
	((apply test (car list) nil)
	 (cons (car list) (filter-list test (cdr list))))
	(t (filter-list test (cdr list)))))

134
135
136
137
138
139
140
;;;============================================================
;;;
;;; Utility functions.
;;;
;;; These should be shared in LysKOM
;;;

141
(lyskom-provide-function copy-tree (l)
142
143
144
145
146
  "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
147
148
149
150
151
(lyskom-provide-function functionp (obj)
  "Returns t if OBJ is a function, nil otherwise."
  (cond
   ((symbolp obj) (fboundp obj))
   ((subrp obj))
152
   ((byte-code-function-p obj))
David Byers's avatar
David Byers committed
153
154
155
   ((consp obj)
    (if (eq (car obj) 'lambda) (listp (car (cdr obj)))))
   (t nil)))
156
157


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

162
163
164
165
166
167
168
169
170
171
(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))


172
173
174
175
176
177
178
179
180
(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)))


181
(defun lyskom-maxint ()
David Byers's avatar
David Byers committed
182
183
184
185
  (let ((n 1) 
        (l nil)
        (i 31))
    (while (and (> n 0) (> i 0))
186
      (setq l (cons n l))
David Byers's avatar
David Byers committed
187
188
      (setq n (* 2 n))
      (setq i (1- i)))
189
190
    (apply '+ l)))

David Byers's avatar
David Byers committed
191
192
193
194
;; Set lyskom-maxint correctly

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

David Byers's avatar
David Byers committed
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213

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

214
215
216
217
218
(defun lyskom-emacs-version ()
  (cond ((string-match "^XEmacs" (emacs-version)) 'xemacs)
	(t 'emacs)))


David Byers's avatar
David Byers committed
219
220
(defvar lyskom-apo-timeout 0
  "Current millisecond timeout value for accept-process-output")
221

David Byers's avatar
David Byers committed
222
223
(defvar lyskom-apo-timeout-index 0
  "Index in lyskom-apo-timeout-vector-max where last timeout is")
224

David Byers's avatar
David Byers committed
225
226
227
(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")
228

David Byers's avatar
David Byers committed
229
230
(defconst lyskom-apo-timeout-vector-max (1- (length lyskom-apo-timeout-vector))
  "Maximum index in lyskom-apo-timeout-vector")
231

232
(defun lyskom-next-apo-timeout ()
David Byers's avatar
David Byers committed
233
234
235
236
237
  (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))))))
238

239
(defun lyskom-reset-apo-timeout ()
David Byers's avatar
David Byers committed
240
241
  (setq lyskom-apo-timeout-index -1)
  (setq lyskom-apo-timeout 0))
242

243
(defun lyskom-accept-process-output ()
David Byers's avatar
David Byers committed
244
245
246
  "Call accept-process-output with the correct timeout values."
  (lyskom-next-apo-timeout)
  (accept-process-output nil 0 lyskom-apo-timeout))
247

248
249
250
251
252
253
254
255
256
257
258
259
260
(defun lyskom-current-time (&optional secs)
  "Return the time in a format that LysKOM understands.
If optional argument SECS is set, it is used in place of the value
of \(current-time\)."
  (let ((time (decode-time (or secs (current-time)))))
    (setcar (cdr (cdr (cdr (cdr time))))
            (1- (car (cdr (cdr (cdr (cdr time)))))))
    (setcar (cdr (cdr (cdr (cdr (cdr time)))))
            (- (car (cdr (cdr (cdr (cdr (cdr time))))))
               1900))
    time))


261

262
263
264
265
;;;
;;; LysKOM utility functions
;;;

David Byers's avatar
David Byers committed
266
267
268
269
270
271
272
273
274
275
;;;
;;; 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.
;;;

276
(defvar lyskom-default-collate-table
David Byers's avatar
David Byers committed
277
  "\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[\\]~!AAAA[]ACEEEEIIIINOOOO\\OUUUYYAAAA[]ACEEEEIIIINOOOO\\OUUUYY"
David Byers's avatar
David Byers committed
278
  "String mapping lowercase to uppercase and equivalents to each others.")
279
280
281

(defsubst lyskom-unicase-char (c)
  "Smash case and diacritical marks on c." 
David Byers's avatar
David Byers committed
282
283
284
  (if (< (char-to-int c) (length lyskom-default-collate-table))
      (aref lyskom-collate-table (char-to-int c))
    c))
285
286
287

(defun lyskom-unicase (s)
  "Smash case and diacritical marks of all chars in s." 
288
  (lyskom-save-excursion
David Byers's avatar
X    
David Byers committed
289
   (set-buffer lyskom-buffer)
290
   (let ((l (length s))
David Byers's avatar
David Byers committed
291
	 (s2 (encode-coding-string s lyskom-server-coding-system)))
292
293
294
295
     (while (> l 0)
       (setq l (1- l))
       (aset s2 l (lyskom-unicase-char (aref s2 l))))
     s2)))
David Byers's avatar
David Byers committed
296

David Byers's avatar
David Byers committed
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
(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)))


David Byers's avatar
David Byers committed
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
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
366
367
368
369

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


370
371
372
373
374
375
(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)
376
       (string= (and s1 (if (multibyte-string-p s1)
377
378
		    s1
		  (decode-coding-string s1 (lyskom-language-coding
379
380
					    lyskom-language))))
		(and s2 (if (multibyte-string-p s2)
381
382
		    s2
		  (decode-coding-string s2 (lyskom-language-coding
383
					    lyskom-language)))))))))
384

David Byers's avatar
X    
David Byers committed
385
386
387
388
389
390
(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."
  (let ((s (downcase key))
        (result nil))
    (while list
391
      (when (lyskom-string= s (downcase (car (car list))))
David Byers's avatar
X    
David Byers committed
392
393
394
395
        (setq result (car list))
        (setq list nil))
      (setq list (cdr list)))
    result))
David Byers's avatar
David Byers committed
396

David Byers's avatar
X    
David Byers committed
397
398
(defun lyskom-set-default (sym val)
  "Set the value of SYM in the LysKOM buffer to VAL."
David Byers's avatar
David Byers committed
399
  (save-excursion
David Byers's avatar
X    
David Byers committed
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
    (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
415
416
    (symbol-value sym)))

David Byers's avatar
X    
David Byers committed
417
418
(defun lyskom-default-value-safe (sym)
  "Get the value of SYM in the LysKOM buffer"
David Byers's avatar
David Byers committed
419
  (save-excursion
David Byers's avatar
X    
David Byers committed
420
421
422
423
424
425
    (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))))
426

David Byers's avatar
David Byers committed
427

428
429
430
;;; ============================================================
;;; Prefix arguments

431
432
433
434
(defun lyskom-read-text-no-prefix-arg (prompt &optional always-read)
  "Call in interactive list to read text-no.
If optional argument ALWAYS-READ is non-nil the user is prompted if
an explicit prefix argument was not given."
435
  (cond
436
437
438
439
   ((null current-prefix-arg) 
    (if always-read 
        (lyskom-read-number prompt lyskom-current-text)
      lyskom-current-text))
440
441
442
443
444
445
   ((integerp current-prefix-arg) current-prefix-arg)
   ((listp current-prefix-arg) 
    (lyskom-read-number prompt (lyskom-text-at-point)))
   (t (lyskom-error (lyskom-get-string 'bad-text-no-prefix)
                    current-prefix-arg))))

446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
;;; ============================================================
;;; 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))))

469
470


471
472
473
474
475
476
477
478
479
480
481
;;; ======================================================================
;;; Display device management
;;;


;;; Definition of some useful functions from XEmacs

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

(lyskom-provide-function device-class (&optional device)
David Kågedal's avatar
David Kågedal committed
482
483
484
485
486
487
488
  (condition-case nil
      (if (x-display-grayscale-p)
	  (if (x-display-color-p)
	      'color
	    'grayscale)
	'mono)
    (error 'mono)))
489
490
491
492
493
494
495
496
497
498
499
500
501


(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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
;;; ======================================================================
;;; 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."
  (save-excursion (set-buffer (or (and (boundp 'lyskom-buffer)
                                       lyskom-buffer)
                                  (current-buffer)))
                  (apply 'run-hook-with-args hook args)))
                              

(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
;;; on the C code for princ. It only works on strings
;;;

(defun lyskom-princ (string &optional stream)
  "Similar to princ but will only print a string. Does not lose text properties
under XEmacs."
  (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))))

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


564
565
566
567
568
569
570
571
572
573
574
575
576
577
;;; ======================================================================
;;; Faces
;;;

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

578
579
580
581
582
(defun lyskom-copy-face (old new)
  (lyskom-xemacs-or-gnu (copy-face old new nil nil nil 'remove-all)
                        (copy-face old new)))


583

David Kågedal's avatar
David Kågedal committed
584
(defun lyskom-set-face-scheme (scheme)
585
586
587
  "Set the LysKOM color and face scheme to SCHEME. Valid schemes are listed
in lyskom-face-schemes."
  (let ((tmp (assoc scheme lyskom-face-schemes)))
588
589
590
591
592
593
594
    (when (and tmp
               (fboundp 'copy-face)
               (fboundp 'lyskom-set-face-foreground)
               (fboundp 'lyskom-set-face-background))
      (mapcar 
       (function
        (lambda (spec)
595
          (lyskom-copy-face (or (elt spec 1) 'default) (elt spec 0))
596
597
598
599
600
          (if (elt spec 2)
              (lyskom-set-face-foreground (elt spec 0) (elt spec 2)))
          (if (elt spec 3)
              (lyskom-set-face-background (elt spec 0) (elt spec 3)))))
       (cdr tmp)))))
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622


(defun lyskom-face-resource (face-name attr type)
  (if (eq (lyskom-emacs-version) 'xemacs)
      ;; XEmac style
      (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
623
(defun lyskom-modify-face (what face)
David Byers's avatar
David Byers committed
624
  (condition-case nil
David Byers's avatar
X    
David Byers committed
625
626
627
628
      (funcall (intern (concat "make-face-" (symbol-name what)))
               face)
    (error nil)))

629
630
631
632
633
634
635
(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
David Kågedal's avatar
David Kågedal committed
636
	      (cond ((eq (device-class) 'mono) 'monochrome)
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
		    ((eq (lyskom-background-mode) 'dark)
		     'inverse)
		    (t 'default))
	    (error 'default))))  
  (lyskom-set-face-scheme kom-default-face-scheme)
  (if (eq (console-type) 'x)
      (mapcar
       (function
	(lambda (face)
	  (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))
David Byers's avatar
X    
David Byers committed
654
655
656
657
	    (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))
658
659
	    (if ul (set-face-underline-p face (eq ul 'on))))))
       lyskom-faces)))
660
661


David Byers's avatar
David Byers committed
662
663
664
665
666
667
668
669
670
671
672
673
;;; ============================================================
;;; Date and time utilities

(defun lyskom-client-date-string (&optional fmt)
  "Format the current client time as a string.
The optional format string FMT specifies the format. If no format string
is supplied time-yyyy-mm-dd-hh-mm is used. The arguments to the format
string are the following: the year, the month, the day, the hour, the 
minutes, the seconds, the full name of the day of week, the abbreviated
name of the day of week."
  (let ((now (decode-time)))
    (lyskom-format (or fmt 'time-yyyy-mm-dd-hh-mm)
David Byers's avatar
David Byers committed
674
                   (elt now 5)
David Byers's avatar
David Byers committed
675
676
677
678
679
680
681
682
683
684
                   (elt now 4)
                   (elt now 3)
                   (elt now 2)
                   (elt now 1)
                   (elt now 0)
                   (elt (lyskom-get-string 'weekdays)
                        (elt now 6))
                   (elt (lyskom-get-string 'weekdays-short)
                        (elt now 6)))))

685
686
687
688
689
690
691
692
693
694
695
(defun lyskom-client-date ()
  "Format the current client time as a string.
The optional format string FMT specifies the format. If no format string
is supplied time-yyyy-mm-dd-hh-mm is used. The arguments to the format
string are the following: the year, the month, the day, the hour, the 
minutes, the seconds, the full name of the day of week, the abbreviated
name of the day of week."
  (let ((now (decode-time)))
    (lyskom-create-time (elt now 0)     ;sec
                        (elt now 1)     ;min
                        (elt now 2)     ;hour
David Byers's avatar
David Byers committed
696
                        (1- (elt now 3))     ;mday
697
698
699
700
701
702
703
                        (elt now 4)     ;mon
                        (- (elt now 5) 1900) ;year
                        (elt now 6)     ;wday
                        0               ;yday
                        (elt now 7)
                        )))

704
705
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
733
734
735
736
737
738
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
;;; ============================================================
;;; Keymap utilities

(defun lyskom-lookup-key (keymap event &optional accept-default)
  (if (null keymap)
      (and accept-default 
           (lookup-key global-map event))
    (if (not (arrayp event))
	(setq event (vector 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)))))

789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806

;;;
;;; 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 "]"))))
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821

(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)))
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848

(defun lyskom-prev-area (num prop)
  (while (> num 0)
    (let ((where (previous-single-property-change (point) prop)))
      (when 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))))
    (setq num (1- num))))

(defun lyskom-next-area (num prop)
  "Move the cursor to the next prompt in the LysKOM buffer"
  (interactive "p")
  (while (> num 0)
    (let ((where (next-single-property-change (point) prop)))
      (when 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))))
    (setq num (1- num))))
David Byers's avatar
David Byers committed
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902

;;; ============================================================
;;; 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)))))