utilities.el 69.5 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

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

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

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

David Byers's avatar
David Byers committed
66
67
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
(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)))

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

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

120
(defun filter-list (test list)
121
122
123
124
125
  (let ((result nil))
    (lyskom-traverse el list
      (when (funcall test el)
        (setq result (cons el result))))
    (nreverse result)))
126

127
128
129
130
131
132
133
;;;============================================================
;;;
;;; Utility functions.
;;;
;;; These should be shared in LysKOM
;;;

David Byers's avatar
David Byers committed
134
135
136
137
138
(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))))

139
(lyskom-provide-function copy-tree (l)
140
141
142
143
144
  "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
145
146
147
148
149
(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
150
   ((lyskom-compiled-function-p obj))
David Byers's avatar
David Byers committed
151
152
153
   ((consp obj)
    (if (eq (car obj) 'lambda) (listp (car (cdr obj)))))
   (t nil)))
154
155


156
157
158
159
(defun lyskom-ignore (&rest args)
  "Ignore all arguments"
  )

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


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


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

David Byers's avatar
David Byers committed
189
190
191
192
;; Set lyskom-maxint correctly

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

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

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

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


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

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

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

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

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

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

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

246
(defun lyskom-set-alist (alist item value)
Johan Sundström's avatar
Bugfix.    
Johan Sundström committed
247
248
  "Modifies (non-destructively) an alist ALIST to set item
ITEM to the value VALUE."
249
250
251
252
  (let ((pair (assq item alist)))
     (if pair
         (progn (setcdr pair value) alist)
       (cons (cons item value) alist))))
253

254
255
256
257
;;;
;;; LysKOM utility functions
;;;

258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
(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
283
284
285
286
287
288
289
290
291
;;;
;;; 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.
;;;
292
293
;;; Make sure your MULE Emacs doesnt fuck it up for you. It did for me.
;;;
David Byers's avatar
David Byers committed
294

295
(defvar lyskom-default-collate-table
David Byers's avatar
David Byers committed
296
  "\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"
297
298
299
300
301
  "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.")

302

David Byers's avatar
David Byers committed
303
304
305
306
307
308
(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)))
309
310
311
312
313
      (encode-coding-string s (or coding
                                  (and lyskom-language
                                       (lyskom-language-coding lyskom-language))
                                  'raw-text))
    s))
314

David Byers's avatar
David Byers committed
315
316
317
318
319
320
321
322
(defun lyskom-recode-string-for-title (s coding)
  "Encode S with CODING for use in frame titles.
Attempts to encode the string only in Emacs versions that do not require
MULE coding for frame titles"
  (if (> emacs-major-version 20)
      s
    (lyskom-maybe-recode-string s coding t)))

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


337
338
(defsubst lyskom-unicase-char (c)
  "Smash case and diacritical marks on c." 
339
  (if (< (char-to-int c) (length lyskom-collate-table))
David Byers's avatar
David Byers committed
340
      (aref lyskom-collate-table (char-to-int c))
341
342
343
344
    (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)))
345
346
347

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

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


376
377
378
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
(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
413
	  (let ((lst (cdr (car cls-to-strings))))
414
415
416
	    (if (> (length lst) 1)
		(while lst
		  (setq res (cons (cons (string-to-char (car lst))
Joel Rosdahl's avatar
Joel Rosdahl committed
417
					(cdr (car cls-to-strings)))
418
419
420
421
422
				  res))
		  (setq lst (cdr lst)))))
	  (setq cls-to-strings (cdr cls-to-strings)))
	res))))
    
David Byers's avatar
David Byers committed
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
;; 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
454
455
456
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

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


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

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

536
537
538
539
540
541
542
543
544
545
546
547
(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))

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

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

David Byers's avatar
David Byers committed
590

591
592
593
;;; ============================================================
;;; Prefix arguments

594
595
596
597
598
599
600
601
602
603
604
605
606
(defun lyskom-get-ancestors-of-text (text-no level)
  "Returns a list of all ancestors of TEXT-NO that are LEVEL
comment/foot-note levels up the comment tree. LEVEL is a
non-negative integer and 0 means the given text-no."
  (if (< level 1)
      (list text-no)
    (let* ((text-stat (blocking-do 'get-text-stat text-no))
	   (ancestors (and text-stat
			   (lyskom-text-stat-commented-texts text-stat)))
	   (level (1- level))
	   (result '()))
	(while ancestors
	  (setq result
David Byers's avatar
David Byers committed
607
608
		(lyskom-union
		 (lyskom-get-ancestors-of-text (car ancestors) level)
609
		 result
David Byers's avatar
David Byers committed
610
                 ))
611
612
613
614
615
616
617
618
619
	  (setq ancestors (cdr ancestors)))
	result)))

(defun lyskom-get-explicit-text (arg &optional prompt default constraint) arg)
(defun lyskom-get-command-specified-default-text (a p def &optional c) def)

(defun lyskom-get-last-read-text (&optional arg prompt default constraint)
  (lyskom-default-value 'lyskom-current-text))

Johan Sundström's avatar
Johan Sundström committed
620
621
622
(defun lyskom-get-previous-text (&optional arg prompt default constraint)
  lyskom-previous-text)

623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
(defun lyskom-get-text-at-point (&optional arg prompt default constraint)
  (or (lyskom-text-at-point)
       (lyskom-get-string 'no-text-at-point)))

(defun lyskom-get-text-at-point-ancestor (arg &optional p d c)
  (let* ((text (lyskom-text-at-point))
	 (cnos (and text (lyskom-get-ancestors-of-text text arg)))
	 (txts (length cnos)))
    (cond
     ((not text)
      (lyskom-get-string 'no-text-at-point))
     ((eq txts 0)
      (lyskom-get-string 'no-comment-to))
     ((eq txts 1)
      (car cnos))
     (t
      (lyskom-read-number (lyskom-get-string 'what-ancestor) (car cnos))))))

(defun lyskom-prompt-for-text-no (arg prompt default &optional constraint)
  (lyskom-read-number prompt default))

(defun lyskom-get-last-text-written-by-me (&optional a p d c)
  (lyskom-default-value 'lyskom-last-written))

(defun lyskom-get-last-written-or-read-by-me (&optional a p d c)
  (lyskom-default-value 'lyskom-last-seen-written))

(defun lyskom-get-text-above-point (arg &optional prompt default constraint)
  (save-excursion
    (let ((former-point (point)))
      (backward-text (+ 1 arg))
      (if (looking-at "\\([0-9]+\\)\\s-")
	  (string-to-int (match-string 1))
	(progn ;; we probably ended up above the first message in the buffer
	  (forward-text)
	  (if (and (< (point) former-point)
		   (looking-at "\\([0-9]+\\)\\s-"))
	      (string-to-int (match-string 1))
	    (lyskom-error (lyskom-get-string 'bad-text-no-prefix) arg)))))))

(defun lyskom-get-text-below-point (arg &optional prompt default constraint)
  (save-excursion
    (let ((former-point (point)))
      (forward-text arg)
      (if (looking-at "\\([0-9]+\\)\\s-")
	  (string-to-int (match-string 1))
	(progn ;; we probably ended up below the final message in the buffer
	  (backward-text)
	  (if (and (> (point) former-point)
		   (looking-at "\\([0-9]+\\)\\s-"))
	      (string-to-int (match-string 1))
	    (lyskom-error (lyskom-get-string 'bad-text-no-prefix) arg)))))))

676
677
678
679
680
(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))))

681
682
683
684
(defun lyskom-read-text-no-prefix-arg (prompt &optional always-prompt
				       default constraint)
  "Call in interactive list to read text-no for lyskom-commands using
configurable prefix argument heuristics. The strategy used for picking a
David Byers's avatar
David Byers committed
685
text-no is defined by the variable `kom-pick-text-no-strategy-alist'.
686
687
688
689
690
691
692

The PROMPT will be used to prompt for the number, either if invoked by the
strategy directly, or as a fallback when no strategy rule found a text-no,
or when that text-no did not meet the CONSTRAINT.

If the optional argument ALWAYS-PROMPT is non-nil and the user did not give
a prefix argument, she gets prompted for the text number regardless of the
David Byers's avatar
David Byers committed
693
`kom-pick-text-no-strategy-alist' settings. Another method of overriding
694
695
696
the prefix-less strategies for a command is via `kom-text-no-prompts'.

When DEFAULT is given, it will be the default text-no fall-back shown in the
David Byers's avatar
David Byers committed
697
prompt, when `kom-pick-text-no-strategy-alist' did not specify a working
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
default. The requirements that must be met are given by CONSTRAINT, when
specified. DEFAULT is either a text-no, a function for returning one or one
of the symbols 'last-seen-written and 'last-written, which are compatibility
aliases for lyskom-get-last-written-or-read-by-me and
lyskom-get-last-text-written-by-me respectively.

If the optional CONSTRAINT function or list is provided, it is called for
the text chosen by the strategy alist functions to validate that the text
really applies to the command. Returning nil means that it does, and
otherwise a helpful lyskom format string should be returned, which explains
to the user why that text did not apply to the command. This string may
refer to the text-no as %#1. The message is then presented to the user and
she gets prompted for a better text number. Failing a second time will
invoke the command anyway (probably to fail miserably, reporting a less
helpful error message).

When CONSTRAINT is a list, its first item is called with the text number as
its first argument and remaining list items appended to the argument list."
;  (lyskom-insert (format "Prefix arg: %s\n" current-prefix-arg))
  (let ((default (cond ((eq default 'last-written)
			(lyskom-get-last-text-written-by-me))
		       ((eq default 'last-seen-written)
			(lyskom-get-last-written-or-read-by-me))
		       ((functionp default) (funcall default))
		       (t default)))
	(constraint-func constraint)
	(constraint-args '())
	(text-no nil))
David Byers's avatar
David Byers committed
726
727
728
    (when (listp constraint)
      (setq constraint-func (car constraint))
      (setq constraint-args (cdr constraint)))
David Byers's avatar
David Byers committed
729
    (let* ((strategies kom-pick-text-no-strategy-alist)
David Byers's avatar
David Byers committed
730
731
732
733
734
           (how (append (cdr (assq lyskom-current-command strategies))
                        (cdr (assq t strategies)))))
      (while (and how (null text-no))
        (let* ((strategy-pred nil) ;; when a predicate to test the prefix
               (compare-value nil) ;; when a value to compare the prefix to
735
736
               (applies-p (car (car how))) ;; either one of the above
               (what-text (cdr (car how)))
David Byers's avatar
David Byers committed
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
               (constraint-not-met nil))
          (if (or (eq applies-p '-) (not (functionp applies-p)))
              (setq compare-value applies-p)
            (setq strategy-pred applies-p))

          (cond
           ((eq compare-value t) ;; provided a default value for the prompt
            (let ((new-default (lyskom-evaluate-text-no-strategy
                                what-text prompt default constraint)))
              (when (and (lyskom-plusp new-default))
                (setq default (or default new-default)))))

           ((or (eq compare-value current-prefix-arg) ;; a text-no strategy
                (and (functionp strategy-pred)
                     (funcall strategy-pred current-prefix-arg)))
            (setq text-no (lyskom-evaluate-text-no-strategy
                           what-text prompt default constraint))
Johan Sundström's avatar
Johan Sundström committed
754
755
;	    (lyskom-insert (format "cmp: %s\npred: %s\ntext-no: %s\n\n"
;				   compare-value strategy-pred text-no))
David Byers's avatar
David Byers committed
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
            (when (and (not (stringp text-no)) text-no constraint)
              (setq constraint-not-met
                    (apply constraint-func text-no constraint-args))
              (when constraint-not-met
                (lyskom-format-insert constraint-not-met text-no)
                (lyskom-format-insert
                 (lyskom-get-string 'prefix-arg-try-again))
                (setq text-no (lyskom-read-number prompt default))))))
          (setq how (cdr how)))))
    (cond
     ((stringp text-no) ;; a strategy failure error message
      (lyskom-error text-no))
     ((and (null current-prefix-arg)
           (or always-prompt
               (lyskom-read-text-no-prompt-p lyskom-current-command)))
      (lyskom-read-number prompt 
                          (if (lyskom-plusp text-no) 
                              text-no
                            (lyskom-default-value 'lyskom-current-text))))
     ((and (lyskom-plusp text-no)) ;; a proper text-no
      text-no)
     ((null current-prefix-arg) ;; a fall-back when no strategy had kicked in
      (lyskom-read-number prompt default))
     (t
      (lyskom-error (lyskom-get-string 'bad-text-no-prefix)
                    current-prefix-arg)))))
782
783
784
785
786

(defun lyskom-evaluate-text-no-strategy (strategy prompt default constraint)
  (let ((prefix current-prefix-arg)
	(strategy-func nil)
	(strategy-args '()))
787
    (cond
788
     ((listp strategy)
789
790
791
      (setq strategy-func (car strategy))
      (setq prefix (funcall (car (cdr strategy)) prefix))
      (setq strategy-args (cdr (cdr strategy)))
792
793
794
795
      (apply strategy-func prefix prompt default constraint
	     strategy-args))
     ((functionp strategy)
      (funcall strategy prefix prompt default constraint)))))
796

797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
;;; ============================================================
;;; 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))))

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

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

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

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

853
854
855
856
857
858
859
860
861
862
;;; ======================================================================
;;; Display device management
;;;


;;; Definition of some useful functions from XEmacs

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

863
864
865
866
(lyskom-external-function display-color-p)
(lyskom-external-function display-grayscale-p)

(eval-and-compile
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
  (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))))))
887
888
889
890
891
892
893
894
895
896
897
898

(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
899
900
901
902
903
904
905
;;; ======================================================================
;;; 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."
906
907
908
  (lyskom-save-excursion (set-buffer (or (and (boundp 'lyskom-buffer)
                                              lyskom-buffer)
                                         (current-buffer)))
David Byers's avatar
X    
David Byers committed
909
                  (apply 'run-hook-with-args hook args)))
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958


;;;(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
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981

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

985
986
(defun lyskom-princ (object &optional stream)
  "Output the printed representation of OBJECT, any Lisp OBJECT.
987
988
989
990
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
991
992
993
994
995
996
997
998
999
1000
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))
For faster browsing, not all history is shown. View entire blame