Rearranged; see ChangeLog for detail.
[elisp/apel.git] / poe.el
1 ;;; poe.el --- Portable Outfit for Emacsen
2
3 ;; Copyright (C) 1995,1996,1997,1998,1999 Free Software Foundation, Inc.
4
5 ;; Author: MORIOKA Tomohiko <tomo@m17n.org>
6 ;;      Shuhei KOBAYASHI <shuhei@aqua.ocn.ne.jp>
7 ;; Keywords: emulation, compatibility, Nemacs, MULE, Emacs/mule, XEmacs
8
9 ;; This file is part of APEL (A Portable Emacs Library).
10
11 ;; This program is free software; you can redistribute it and/or
12 ;; modify it under the terms of the GNU General Public License as
13 ;; published by the Free Software Foundation; either version 2, or (at
14 ;; your option) any later version.
15
16 ;; This program is distributed in the hope that it will be useful, but
17 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19 ;; General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
23 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
24 ;; Boston, MA 02111-1307, USA.
25
26 ;;; Commentary:
27
28 ;;; Code:
29
30 (provide 'poe)                          ; beware of circular dependency.
31                                         ; localhook.el depends on poe.el.
32 (require 'pym)                          ; `static-*' and `def*-maybe'.
33
34
35 ;;; @ Version information.
36 ;;;
37
38 (defconst-maybe emacs-major-version
39   (progn (string-match "^[0-9]+" emacs-version)
40          (string-to-int (substring emacs-version
41                                    (match-beginning 0)(match-end 0))))
42   "Major version number of this version of Emacs.")
43
44 (defconst-maybe emacs-minor-version
45   (progn (string-match "^[0-9]+\\.\\([0-9]+\\)" emacs-version)
46          (string-to-int (substring emacs-version
47                                    (match-beginning 1)(match-end 1))))
48   "Minor version number of this version of Emacs.")
49
50 (static-when (= emacs-major-version 18)
51   (require 'poe-18))
52
53 ;; Some ancient version of XEmacs did not provide 'xemacs.
54 (static-when (string-match "XEmacs" emacs-version)
55   (provide 'xemacs))
56
57 ;; `file-coding' was appeared in the spring of 1998, just before XEmacs
58 ;; 21.0. Therefore it is not provided in XEmacs with MULE versions 20.4
59 ;; or earlier.
60 (static-when (featurep 'xemacs)
61   ;; must be load-time check to share .elc between w/ MULE and w/o MULE.
62   (when (featurep 'mule)
63     (provide 'file-coding)))
64
65 (static-when (featurep 'xemacs)
66   (require 'poe-xemacs))
67 \f
68
69 ;;; @ C primitives emulation.
70 ;;;
71
72 ;; (require FEATURE &optional FILENAME NOERROR)
73 ;; Emacs 20.4 and later takes optional 3rd arg NOERROR.
74 (static-condition-case nil
75     ;; compile-time check.
76     (progn
77       (require 'nofeature "nofile" 'noerror)
78       (if (get 'require 'defun-maybe)
79           (error "")))                  ; already redefined.
80   (error
81    ;; load-time check.
82    (or (fboundp 'si:require)
83        (progn
84          (fset 'si:require (symbol-function 'require))
85          (put 'require 'defun-maybe t)
86          (defun require (feature &optional filename noerror)
87            "\
88 If feature FEATURE is not loaded, load it from FILENAME.
89 If FEATURE is not a member of the list `features', then the feature
90 is not loaded; so load the file FILENAME.
91 If FILENAME is omitted, the printname of FEATURE is used as the file name,
92 but in this case `load' insists on adding the suffix `.el' or `.elc'.
93 If the optional third argument NOERROR is non-nil,
94 then return nil if the file is not found.
95 Normally the return value is FEATURE."
96            (if noerror
97                (condition-case nil
98                    (si:require feature filename)
99                  (error))
100              (si:require feature filename)))))))
101
102 ;; Emacs 19.29 and later: (plist-get PLIST PROP)
103 ;; (defun-maybe plist-get (plist prop)
104 ;;   (while (and plist
105 ;;               (not (eq (car plist) prop)))
106 ;;     (setq plist (cdr (cdr plist))))
107 ;;   (car (cdr plist)))
108 (static-unless (and (fboundp 'plist-get)
109                     (not (get 'plist-get 'defun-maybe)))
110   (or (fboundp 'plist-get)
111       (progn
112         (defvar plist-get-internal-symbol)
113         (defun plist-get (plist prop)
114           "\
115 Extract a value from a property list.
116 PLIST is a property list, which is a list of the form
117 \(PROP1 VALUE1 PROP2 VALUE2...\).  This function returns the value
118 corresponding to the given PROP, or nil if PROP is not
119 one of the properties on the list."
120           (setplist 'plist-get-internal-symbol plist)
121           (get 'plist-get-internal-symbol prop))
122         (setq current-load-list (cons 'plist-get current-load-list))
123         (put 'plist-get 'defun-maybe t))))
124
125 ;; Emacs 19.29 and later: (plist-put PLIST PROP VAL)
126 ;; (defun-maybe plist-put (plist prop val)
127 ;;   (catch 'found
128 ;;     (let ((tail plist)
129 ;;           (prev nil))
130 ;;       (while (and tail (cdr tail))
131 ;;         (if (eq (car tail) prop)
132 ;;             (progn
133 ;;               (setcar (cdr tail) val)
134 ;;               (throw 'found plist))
135 ;;           (setq prev tail
136 ;;                 tail (cdr (cdr tail)))))
137 ;;       (if prev
138 ;;           (progn
139 ;;             (setcdr (cdr prev) (list prop val))
140 ;;             plist)
141 ;;         (list prop val)))))
142 (static-unless (and (fboundp 'plist-put)
143                     (not (get 'plist-put 'defun-maybe)))
144   (or (fboundp 'plist-put)
145       (progn
146         (defvar plist-put-internal-symbol)
147         (defun plist-put (plist prop val)
148           "\
149 Change value in PLIST of PROP to VAL.
150 PLIST is a property list, which is a list of the form
151 \(PROP1 VALUE1 PROP2 VALUE2 ...\).  PROP is a symbol and VAL is any object.
152 If PROP is already a property on the list, its value is set to VAL,
153 otherwise the new PROP VAL pair is added.  The new plist is returned;
154 use `\(setq x \(plist-put x prop val\)\)' to be sure to use the new value.
155 The PLIST is modified by side effects."
156           (setplist 'plist-put-internal-symbol plist)
157           (put 'plist-put-internal-symbol prop val)
158           (symbol-plist 'plist-put-internal-symbol))
159         (setq current-load-list (cons 'plist-put current-load-list))
160         (put 'plist-put 'defun-maybe t))))
161
162 ;; Emacs 19.23 and later: (minibuffer-prompt-width)
163 (defun-maybe minibuffer-prompt-width ()
164   "Return the display width of the minibuffer prompt."
165   (save-excursion
166     (set-buffer (window-buffer (minibuffer-window)))
167     (current-column)))
168
169 ;; (read-string PROMPT &optional INITIAL-INPUT HISTORY)
170 ;; Emacs 19.29/XEmacs 19.14(?) and later takes optional 3rd arg HISTORY.
171 (static-unless (or (featurep 'xemacs)
172                    (>= emacs-major-version 20)
173                    (and (= emacs-major-version 19)
174                         (>= emacs-minor-version 29)))
175   (or (fboundp 'si:read-string)
176       (progn
177         (fset 'si:read-string (symbol-function 'read-string))
178         (defun read-string (prompt &optional initial-input history)
179           "\
180 Read a string from the minibuffer, prompting with string PROMPT.
181 If non-nil, second arg INITIAL-INPUT is a string to insert before reading.
182 The third arg HISTORY, is dummy for compatibility.
183 See `read-from-minibuffer' for details of HISTORY argument."
184           (si:read-string prompt initial-input)))))
185
186 ;; v18: (string-to-int STRING)
187 ;; v19: (string-to-number STRING)
188 ;; v20: (string-to-number STRING &optional BASE)
189 ;;
190 ;; XXX: `string-to-number' of Emacs 20.3 and earlier is broken.
191 ;;      (string-to-number "1e1" 16) => 10.0, should be 481.
192 (static-condition-case nil
193     ;; compile-time check.
194     (if (= (string-to-number "1e1" 16) 481)
195         (if (get 'string-to-number 'defun-maybe)
196             (error ""))                 ; already redefined.
197       (error ""))                       ; Emacs 20.3 and ealier.
198   (error
199    ;; load-time check.
200    (or (fboundp 'si:string-to-number)
201        (progn
202          (if (fboundp 'string-to-number)
203              (fset 'si:string-to-number (symbol-function 'string-to-number))
204            (fset 'si:string-to-number (symbol-function 'string-to-int))
205            (defalias 'string-to-int 'string-to-number))
206          (put 'string-to-number 'defun-maybe t)
207          (defun string-to-number (string &optional base)
208            "\
209 Convert STRING to a number by parsing it as a decimal number.
210 This parses both integers and floating point numbers.
211 It ignores leading spaces and tabs.
212
213 If BASE, interpret STRING as a number in that base.  If BASE isn't
214 present, base 10 is used.  BASE must be between 2 and 16 (inclusive).
215 If the base used is not 10, floating point is not recognized."
216            (if (or (null base) (= base 10))
217                (si:string-to-number string)
218              (if (or (< base 2)(> base 16))
219                  (signal 'args-out-of-range (cons base nil)))
220              (let ((len (length string))
221                    (pos 0))
222                ;; skip leading whitespace.
223                (while (and (< pos len)
224                            (memq (aref string pos) '(?\  ?\t)))
225                  (setq pos (1+ pos)))
226                (if (= pos len)
227                    0
228                  (let ((number 0)(negative 1)
229                        chr num)
230                    (if (eq (aref string pos) ?-)
231                        (setq negative -1
232                              pos (1+ pos))
233                      (if (eq (aref string pos) ?+)
234                          (setq pos (1+ pos))))
235                    (while (and (< pos len)
236                                (setq chr (aref string pos)
237                                      num (cond
238                                           ((and (<= ?0 chr)(<= chr ?9))
239                                            (- chr ?0))
240                                           ((and (<= ?A chr)(<= chr ?F))
241                                            (+ (- chr ?A) 10))
242                                           ((and (<= ?a chr)(<= chr ?f))
243                                            (+ (- chr ?a) 10))
244                                           (t nil)))
245                                (< num base))
246                      (setq number (+ (* number base) num)
247                            pos (1+ pos)))
248                    (* negative number))))))))))
249
250 ;; Emacs 20.1 and 20.2: (concat-chars &rest CHARS)
251 ;; Emacs 20.3/XEmacs 21.0 and later: (string &rest CHARS)
252 (static-cond
253  ((and (fboundp 'string)
254        (subrp (symbol-function 'string)))
255   ;; Emacs 20.3/XEmacs 21.0 and later.
256   )
257  ((and (fboundp 'concat-chars)
258        (subrp (symbol-function 'concat-chars)))
259   ;; Emacs 20.1 and 20.2.
260   (defalias 'string 'concat-chars))
261  (t
262   ;; Use `defun-maybe' to update `load-history'.
263   (defun-maybe string (&rest chars)
264     "Concatenate all the argument characters and make the result a string."
265     ;; We cannot use (apply 'concat chars) here because `concat' does not
266     ;; work with multibyte chars on Mule 1.* and 2.*.
267     (mapconcat (function char-to-string) chars ""))))
268
269 ;; Mule: (char-before POS)
270 ;; v20: (char-before &optional POS)
271 (static-condition-case nil
272     ;; compile-time check.
273     (progn
274       (char-before)
275       (if (get 'char-before 'defun-maybe)
276           (error "")))                  ; already defined.
277   (wrong-number-of-arguments            ; Mule.
278    ;; load-time check.
279    (or (fboundp 'si:char-before)
280        (progn
281          (fset 'si:char-before (symbol-function 'char-before))
282          (put 'char-before 'defun-maybe t)
283          ;; takes IGNORED for backward compatibility.
284          (defun char-before (&optional pos ignored)
285            "\
286 Return character in current buffer preceding position POS.
287 POS is an integer or a buffer pointer.
288 If POS is out of range, the value is nil."
289            (si:char-before (or pos (point)))))))
290   (void-function                        ; non-Mule.
291    ;; load-time check.
292    (defun-maybe char-before (&optional pos)
293      "\
294 Return character in current buffer preceding position POS.
295 POS is an integer or a buffer pointer.
296 If POS is out of range, the value is nil."
297      (if pos
298          (save-excursion
299            (and (= (goto-char pos) (point))
300                 (not (bobp))
301                 (preceding-char)))
302        (and (not (bobp))
303             (preceding-char)))))
304   (error                                ; found our definition at compile-time.
305    ;; load-time check.
306    (condition-case nil
307        (char-before)
308      (wrong-number-of-arguments         ; Mule.
309       (or (fboundp 'si:char-before)
310           (progn
311             (fset 'si:char-before (symbol-function 'char-before))
312             (put 'char-before 'defun-maybe t)
313             ;; takes IGNORED for backward compatibility.
314             (defun char-before (&optional pos ignored)
315               "\
316 Return character in current buffer preceding position POS.
317 POS is an integer or a buffer pointer.
318 If POS is out of range, the value is nil."
319               (si:char-before (or pos (point)))))))
320      (void-function                     ; non-Mule.
321       (defun-maybe char-before (&optional pos)
322         "\
323 Return character in current buffer preceding position POS.
324 POS is an integer or a buffer pointer.
325 If POS is out of range, the value is nil."
326         (if pos
327             (save-excursion
328               (and (= (goto-char pos) (point))
329                    (not (bobp))
330                    (preceding-char)))
331           (and (not (bobp))
332                (preceding-char))))))))
333
334 ;; v18, v19: (char-after POS)
335 ;; v20: (char-after &optional POS)
336 (static-condition-case nil
337     ;; compile-time check.
338     (progn
339       (char-after)
340       (if (get 'char-after 'defun-maybe)
341           (error "")))                  ; already defined.
342   (wrong-number-of-arguments            ; v18, v19
343    ;; load-time check.
344    (or (fboundp 'si:char-after)
345        (progn
346          (fset 'si:char-after (symbol-function 'char-after))
347          (put 'char-after 'defun-maybe t)
348          (defun char-after (&optional pos)
349            "\
350 Return character in current buffer at position POS.
351 POS is an integer or a buffer pointer.
352 If POS is out of range, the value is nil."
353            (si:char-after (or pos (point)))))))
354   (void-function                        ; NEVER happen?
355    ;; load-time check.
356    (defun-maybe char-after (&optional pos)
357      "\
358 Return character in current buffer at position POS.
359 POS is an integer or a buffer pointer.
360 If POS is out of range, the value is nil."
361      (if pos
362          (save-excursion
363            (and (= (goto-char pos) (point))
364                 (not (eobp))
365                 (following-char)))
366        (and (not (eobp))
367             (following-char)))))
368   (error                                ; found our definition at compile-time.
369    ;; load-time check.
370    (condition-case nil
371        (char-after)
372      (wrong-number-of-arguments         ; v18, v19
373       (or (fboundp 'si:char-after)
374           (progn
375             (fset 'si:char-after (symbol-function 'char-after))
376             (put 'char-after 'defun-maybe t)
377             (defun char-after (&optional pos)
378               "\
379 Return character in current buffer at position POS.
380 POS is an integer or a buffer pointer.
381 If POS is out of range, the value is nil."
382               (si:char-after (or pos (point)))))))
383      (void-function                     ; NEVER happen?
384       (defun-maybe char-after (&optional pos)
385         "\
386 Return character in current buffer at position POS.
387 POS is an integer or a buffer pointer.
388 If POS is out of range, the value is nil."
389         (if pos
390             (save-excursion
391               (and (= (goto-char pos) (point))
392                    (not (eobp))
393                    (following-char)))
394           (and (not (eobp))
395                (following-char))))))))
396
397 ;; Emacs 19.29 and later: (buffer-substring-no-properties START END)
398 (defun-maybe buffer-substring-no-properties (start end)
399   "Return the characters of part of the buffer, without the text properties.
400 The two arguments START and END are character positions;
401 they can be in either order."
402   (let ((string (buffer-substring start end)))
403     (set-text-properties 0 (length string) nil string)
404     string))
405
406 ;; Emacs 19.31 and later: (buffer-live-p OBJECT)
407 (defun-maybe buffer-live-p (object)
408   "Return non-nil if OBJECT is a buffer which has not been killed.
409 Value is nil if OBJECT is not a buffer or if it has been killed."
410   (and object
411        (get-buffer object)
412        (buffer-name (get-buffer object))
413        t))
414
415 ;; Emacs 20: (line-beginning-position &optional N)
416 (defun-maybe line-beginning-position (&optional n)
417   "Return the character position of the first character on the current line.
418 With argument N not nil or 1, move forward N - 1 lines first.
419 If scan reaches end of buffer, return that position.
420 This function does not move point."
421   (save-excursion
422     (forward-line (1- (or n 1)))
423     (point)))
424
425 ;; Emacs 20: (line-end-position &optional N)
426 (defun-maybe line-end-position (&optional n)
427   "Return the character position of the last character on the current line.
428 With argument N not nil or 1, move forward N - 1 lines first.
429 If scan reaches end of buffer, return that position.
430 This function does not move point."
431   (save-excursion
432     (end-of-line (or n 1))
433     (point)))
434 \f
435
436 ;;; @ Basic lisp subroutines emulation. (lisp/subr.el)
437 ;;;
438
439 ;;; @@ Lisp language features.
440
441 (defmacro-maybe push (newelt listname)
442   "Add NEWELT to the list stored in the symbol LISTNAME.
443 This is equivalent to (setq LISTNAME (cons NEWELT LISTNAME)).
444 LISTNAME must be a symbol."
445   (list 'setq listname
446         (list 'cons newelt listname)))
447
448 (defmacro-maybe pop (listname)
449   "Return the first element of LISTNAME's value, and remove it from the list.
450 LISTNAME must be a symbol whose value is a list.
451 If the value is nil, `pop' returns nil but does not actually
452 change the list."
453   (list 'prog1 (list 'car listname)
454         (list 'setq listname (list 'cdr listname))))
455
456 (defmacro-maybe when (cond &rest body)
457   "If COND yields non-nil, do BODY, else return nil."
458   (list 'if cond (cons 'progn body)))
459 ;; (def-edebug-spec when (&rest form))
460
461 (defmacro-maybe unless (cond &rest body)
462   "If COND yields nil, do BODY, else return nil."
463   (cons 'if (cons cond (cons nil body))))
464 ;; (def-edebug-spec unless (&rest form))
465
466 (defsubst-maybe caar (x)
467   "Return the car of the car of X."
468   (car (car x)))
469
470 (defsubst-maybe cadr (x)
471   "Return the car of the cdr of X."
472   (car (cdr x)))
473
474 (defsubst-maybe cdar (x)
475   "Return the cdr of the car of X."
476   (cdr (car x)))
477
478 (defsubst-maybe cddr (x)
479   "Return the cdr of the cdr of X."
480   (cdr (cdr x)))
481
482 (defun-maybe last (x &optional n)
483   "Return the last link of the list X.  Its car is the last element.
484 If X is nil, return nil.
485 If N is non-nil, return the Nth-to-last link of X.
486 If N is bigger than the length of X, return X."
487   (if n
488       (let ((m 0) (p x))
489         (while (consp p)
490           (setq m (1+ m) p (cdr p)))
491         (if (<= n 0) p
492           (if (< n m) (nthcdr (- m n) x) x)))
493     (while (cdr x)
494       (setq x (cdr x)))
495     x))
496
497 ;; Actually, `butlast' and `nbutlast' are defined in lisp/cl.el.
498 (defun-maybe butlast (x &optional n)
499   "Returns a copy of LIST with the last N elements removed."
500   (if (and n (<= n 0)) x
501     (nbutlast (copy-sequence x) n)))
502
503 (defun-maybe nbutlast (x &optional n)
504   "Modifies LIST to remove the last N elements."
505   (let ((m (length x)))
506     (or n (setq n 1))
507     (and (< n m)
508          (progn
509            (if (> n 0) (setcdr (nthcdr (- (1- m) n) x) nil))
510            x))))
511
512 ;; Emacs 20.3 and later: (assoc-default KEY ALIST &optional TEST DEFAULT)
513 (defun-maybe assoc-default (key alist &optional test default)
514   "Find object KEY in a pseudo-alist ALIST.
515 ALIST is a list of conses or objects.  Each element (or the element's car,
516 if it is a cons) is compared with KEY by evaluating (TEST (car elt) KEY).
517 If that is non-nil, the element matches;
518 then `assoc-default' returns the element's cdr, if it is a cons,
519 or DEFAULT if the element is not a cons.
520
521 If no element matches, the value is nil.
522 If TEST is omitted or nil, `equal' is used."
523   (let (found (tail alist) value)
524     (while (and tail (not found))
525       (let ((elt (car tail)))
526         (when (funcall (or test 'equal) (if (consp elt) (car elt) elt) key)
527           (setq found t value (if (consp elt) (cdr elt) default))))
528       (setq tail (cdr tail)))
529     value))
530
531 ;; The following two function use `compare-strings', which we don't
532 ;; support yet.
533 ;; (defun assoc-ignore-case (key alist))
534 ;; (defun assoc-ignore-representation (key alist))
535
536 ;; Emacs 19.29/XEmacs 19.14(?) and later: (rassoc KEY LIST)
537 ;; Actually, `rassoc' is defined in src/fns.c.
538 (defun-maybe rassoc (key list)
539   "Return non-nil if KEY is `equal' to the cdr of an element of LIST.
540 The value is actually the element of LIST whose cdr equals KEY.
541 Elements of LIST that are not conses are ignored."
542   (catch 'found
543     (while list
544       (cond ((not (consp (car list))))
545             ((equal (cdr (car list)) key)
546              (throw 'found (car list))))
547       (setq list (cdr list)))))
548
549 ;;; @@ Hook manipulation functions.
550
551 ;; "localhook" package is written for Emacs 19.28 and earlier.
552 ;; `run-hooks' was a lisp function in Emacs 19.29 and earlier.
553 ;; So, in Emacs 19.29, `run-hooks' and others will be overrided.
554 ;; But, who cares it?
555 (static-unless (subrp (symbol-function 'run-hooks))
556   (require 'localhook))
557
558 ;; Emacs 19.29/XEmacs 19.14(?) and later: (add-to-list LIST-VAR ELEMENT)
559 (defun-maybe add-to-list (list-var element)
560   "Add to the value of LIST-VAR the element ELEMENT if it isn't there yet.
561 The test for presence of ELEMENT is done with `equal'.
562 If you want to use `add-to-list' on a variable that is not defined
563 until a certain package is loaded, you should put the call to `add-to-list'
564 into a hook function that will be run only after loading the package.
565 `eval-after-load' provides one way to do this.  In some cases
566 other hooks, such as major mode hooks, can do the job."
567   (or (member element (symbol-value list-var))
568       (set list-var (cons element (symbol-value list-var)))))
569
570 ;; (eval-after-load FILE FORM)
571 ;; Emacs 19.28 and earlier do not evaluate FORM if FILE is already loaded.
572 ;; XEmacs 20.2 and earlier have `after-load-alist', but refuse to support
573 ;; `eval-after-load'. (see comments in XEmacs/lisp/subr.el.)
574 (static-cond
575  ((featurep 'xemacs)
576   ;; for XEmacs 20.2 and earlier.
577   (defun-maybe eval-after-load (file form)
578     "Arrange that, if FILE is ever loaded, FORM will be run at that time.
579 This makes or adds to an entry on `after-load-alist'.
580 If FILE is already loaded, evaluate FORM right now.
581 It does nothing if FORM is already on the list for FILE.
582 FILE should be the name of a library, with no directory name."
583     ;; Make sure there is an element for FILE.
584     (or (assoc file after-load-alist)
585         (setq after-load-alist (cons (list file) after-load-alist)))
586     ;; Add FORM to the element if it isn't there.
587     (let ((elt (assoc file after-load-alist)))
588       (or (member form (cdr elt))
589           (progn
590             (nconc elt (list form))
591             ;; If the file has been loaded already, run FORM right away.
592             (and (assoc file load-history)
593                  (eval form)))))
594     form))
595  ((>= emacs-major-version 20))
596  ((and (= emacs-major-version 19)
597        (< emacs-minor-version 29))
598   ;; for Emacs 19.28 and earlier.
599   (defun eval-after-load (file form)
600     "Arrange that, if FILE is ever loaded, FORM will be run at that time.
601 This makes or adds to an entry on `after-load-alist'.
602 If FILE is already loaded, evaluate FORM right now.
603 It does nothing if FORM is already on the list for FILE.
604 FILE should be the name of a library, with no directory name."
605     ;; Make sure there is an element for FILE.
606     (or (assoc file after-load-alist)
607         (setq after-load-alist (cons (list file) after-load-alist)))
608     ;; Add FORM to the element if it isn't there.
609     (let ((elt (assoc file after-load-alist)))
610       (or (member form (cdr elt))
611           (progn
612             (nconc elt (list form))
613             ;; If the file has been loaded already, run FORM right away.
614             (and (assoc file load-history)
615                  (eval form)))))
616     form))
617  (t
618   ;; should emulate for v18?
619   ))
620
621 (defun-maybe eval-next-after-load (file)
622   "Read the following input sexp, and run it whenever FILE is loaded.
623 This makes or adds to an entry on `after-load-alist'.
624 FILE should be the name of a library, with no directory name."
625   (eval-after-load file (read)))
626
627 ;;; @@ Input and display facilities.
628
629 ;; XXX: (defun read-passwd (prompt &optional confirm default))
630
631 ;;; @@ Miscellanea.
632
633 ;; Avoid compiler warnings about this variable,
634 ;; which has a special meaning on certain system types.
635 (defvar-maybe buffer-file-type nil
636   "Non-nil if the visited file is a binary file.
637 This variable is meaningful on MS-DOG and Windows NT.
638 On those systems, it is automatically local in every buffer.
639 On other systems, this variable is normally always nil.")
640
641 ;; Emacs 20.1/XEmacs 20.3(?) and later: (save-current-buffer &rest BODY)
642 ;; v20 defines `save-current-buffer' as a C primitive (in src/editfns.c)
643 ;; and introduces a new bytecode Bsave_current_buffer(_1), replacing an
644 ;; obsolete bytecode Bread_char.
645 ;; This is a source of incompatibility of .elc between v18/v19 and v20.
646 ;; (XEmacs compiler takes care of it if compatibility mode is enabled.)
647 (defmacro-maybe save-current-buffer (&rest body)
648   "Save the current buffer; execute BODY; restore the current buffer.
649 Executes BODY just like `progn'."
650   (` (let ((orig-buffer (current-buffer)))
651        (unwind-protect
652            (progn (,@ body))
653          (if (buffer-live-p orig-buffer)
654              (set-buffer orig-buffer))))))
655
656 ;; Emacs 20.1/XEmacs 20.3(?) and later: (with-current-buffer BUFFER &rest BODY)
657 (defmacro-maybe with-current-buffer (buffer &rest body)
658   "Execute the forms in BODY with BUFFER as the current buffer.
659 The value returned is the value of the last form in BODY.
660 See also `with-temp-buffer'."
661   (` (save-current-buffer
662        (set-buffer (, buffer))
663        (,@ body))))
664
665 ;; Emacs 20.1/XEmacs 20.3(?) and later: (with-temp-file FILE &rest FORMS)
666 (defmacro-maybe with-temp-file (file &rest forms)
667   "Create a new buffer, evaluate FORMS there, and write the buffer to FILE.
668 The value of the last form in FORMS is returned, like `progn'.
669 See also `with-temp-buffer'."
670   (let ((temp-file (make-symbol "temp-file"))
671         (temp-buffer (make-symbol "temp-buffer")))
672     (` (let (((, temp-file) (, file))
673              ((, temp-buffer)
674               (get-buffer-create (generate-new-buffer-name " *temp file*"))))
675          (unwind-protect
676              (prog1
677                  (with-current-buffer (, temp-buffer)
678                    (,@ forms))
679                (with-current-buffer (, temp-buffer)
680                  (widen)
681                  (write-region (point-min) (point-max) (, temp-file) nil 0)))
682            (and (buffer-name (, temp-buffer))
683                 (kill-buffer (, temp-buffer))))))))
684
685 ;; Emacs 20.4 and later: (with-temp-message MESSAGE &rest BODY)
686 ;; This macro uses `current-message', which appears in v20.
687 (static-when (and (fboundp 'current-message)
688                   (subrp (symbol-function 'current-message)))
689   (defmacro-maybe with-temp-message (message &rest body)
690     "\
691 Display MESSAGE temporarily if non-nil while BODY is evaluated.
692 The original message is restored to the echo area after BODY has finished.
693 The value returned is the value of the last form in BODY.
694 MESSAGE is written to the message log buffer if `message-log-max' is non-nil.
695 If MESSAGE is nil, the echo area and message log buffer are unchanged.
696 Use a MESSAGE of \"\" to temporarily clear the echo area."
697     (let ((current-message (make-symbol "current-message"))
698           (temp-message (make-symbol "with-temp-message")))
699       (` (let (((, temp-message) (, message))
700                ((, current-message)))
701            (unwind-protect
702                (progn
703                  (when (, temp-message)
704                    (setq (, current-message) (current-message))
705                    (message "%s" (, temp-message))
706                    (,@ body))
707                  (and (, temp-message) (, current-message)
708                       (message "%s" (, current-message))))))))))
709
710 ;; Emacs 20.1/XEmacs 20.3(?) and later: (with-temp-buffer &rest FORMS)
711 (defmacro-maybe with-temp-buffer (&rest forms)
712   "Create a temporary buffer, and evaluate FORMS there like `progn'.
713 See also `with-temp-file' and `with-output-to-string'."
714   (let ((temp-buffer (make-symbol "temp-buffer")))
715     (` (let (((, temp-buffer)
716               (get-buffer-create (generate-new-buffer-name " *temp*"))))
717          (unwind-protect
718              (with-current-buffer (, temp-buffer)
719                (,@ forms))
720            (and (buffer-name (, temp-buffer))
721                 (kill-buffer (, temp-buffer))))))))
722
723 ;; Emacs 20.1/XEmacs 20.3(?) and later: (with-output-to-string &rest BODY)
724 (defmacro-maybe with-output-to-string (&rest body)
725   "Execute BODY, return the text it sent to `standard-output', as a string."
726   (` (let ((standard-output
727             (get-buffer-create (generate-new-buffer-name " *string-output*"))))
728        (let ((standard-output standard-output))
729          (,@ body))
730        (with-current-buffer standard-output
731          (prog1
732              (buffer-string)
733            (kill-buffer nil))))))
734
735 ;; Emacs 20.1 and later: (combine-after-change-calls &rest BODY)
736 (defmacro-maybe combine-after-change-calls (&rest body)
737   "Execute BODY, but don't call the after-change functions till the end.
738 If BODY makes changes in the buffer, they are recorded
739 and the functions on `after-change-functions' are called several times
740 when BODY is finished.
741 The return value is the value of the last form in BODY.
742
743 If `before-change-functions' is non-nil, then calls to the after-change
744 functions can't be deferred, so in that case this macro has no effect.
745
746 Do not alter `after-change-functions' or `before-change-functions'
747 in BODY.
748
749 This emulating macro does not support after-change functions at all,
750 just execute BODY."
751   (cons 'progn body))
752
753 ;; Emacs 19.29/XEmacs 19.14(?) and later: (match-string NUM &optional STRING)
754 (defun-maybe match-string (num &optional string)
755   "Return string of text matched by last search.
756 NUM specifies which parenthesized expression in the last regexp.
757  Value is nil if NUMth pair didn't match, or there were less than NUM pairs.
758 Zero means the entire text matched by the whole regexp or whole string.
759 STRING should be given if the last search was by `string-match' on STRING."
760   (if (match-beginning num)
761       (if string
762           (substring string (match-beginning num) (match-end num))
763         (buffer-substring (match-beginning num) (match-end num)))))
764
765 ;; Emacs 20.3 and later: (match-string-no-properties NUM &optional STRING)
766 (defun-maybe match-string-no-properties (num &optional string)
767   "Return string of text matched by last search, without text properties.
768 NUM specifies which parenthesized expression in the last regexp.
769  Value is nil if NUMth pair didn't match, or there were less than NUM pairs.
770 Zero means the entire text matched by the whole regexp or whole string.
771 STRING should be given if the last search was by `string-match' on STRING."
772   (if (match-beginning num)
773       (if string
774           (let ((result
775                  (substring string (match-beginning num) (match-end num))))
776             (set-text-properties 0 (length result) nil result)
777             result)
778         (buffer-substring-no-properties (match-beginning num)
779                                         (match-end num)))))
780
781 ;; Emacs 20.1/XEmacs 20.3(?) and later: (split-string STRING &optional PATTERN)
782 ;; Here is a XEmacs version.
783 (defun-maybe split-string (string &optional pattern)
784   "Return a list of substrings of STRING which are separated by PATTERN.
785 If PATTERN is omitted, it defaults to \"[ \\f\\t\\n\\r\\v]+\"."
786   (or pattern
787       (setq pattern "[ \f\t\n\r\v]+"))
788   ;; The FSF version of this function takes care not to cons in case
789   ;; of infloop.  Maybe we should synch?
790   (let (parts (start 0))
791     (while (string-match pattern string start)
792       (setq parts (cons (substring string start (match-beginning 0)) parts)
793             start (match-end 0)))
794     (nreverse (cons (substring string start) parts))))
795
796 ;; Emacs 20.1/XEmacs 20.3 (but first appeared in Epoch?): (functionp OBJECT)
797 (defun-maybe functionp (object)
798   "Non-nil if OBJECT is a type of object that can be called as a function."
799   (or (subrp object) (byte-code-function-p object)
800       (eq (car-safe object) 'lambda)
801       (and (symbolp object) (fboundp object))))
802 \f
803
804 ;;; @ Window commands emulation. (lisp/window.el)
805 ;;;
806
807 (defmacro-maybe save-selected-window (&rest body)
808   "Execute BODY, then select the window that was selected before BODY."
809   (list 'let
810         '((save-selected-window-window (selected-window)))
811         (list 'unwind-protect
812               (cons 'progn body)
813               (list 'select-window 'save-selected-window-window))))
814 \f
815
816 ;;; @ Basic editing commands emulation. (lisp/simple.el)
817 ;;;
818 \f
819
820 ;;; @ File input and output commands emulation. (lisp/files.el)
821 ;;;
822
823 (defvar-maybe temporary-file-directory
824   (file-name-as-directory
825    (cond ((memq system-type '(ms-dos windows-nt))
826           (or (getenv "TEMP") (getenv "TMPDIR") (getenv "TMP") "c:/temp"))
827          ((memq system-type '(vax-vms axp-vms))
828           (or (getenv "TMPDIR") (getenv "TMP") (getenv "TEMP") "SYS$SCRATCH:"))
829          (t
830           (or (getenv "TMPDIR") (getenv "TMP") (getenv "TEMP") "/tmp"))))
831   "The directory for writing temporary files.")
832
833 ;; Actually, `path-separator' is defined in src/emacs.c and overrided
834 ;; in dos-w32.el.
835 (defvar-maybe path-separator ":"
836   "The directory separator in search paths, as a string.")
837
838 ;; `convert-standard-filename' is defined in lisp/files.el and overrided
839 ;; in lisp/dos-fns.el and lisp/w32-fns.el for each environment.
840 (cond
841  ;; must be load-time check to share .elc between different systems.
842  ((fboundp 'convert-standard-filename))
843  ((memq system-type '(windows-nt ms-dos))
844   ;; should we do (require 'filename) at load-time ?
845   ;; (require 'filename)
846   ;; filename.el requires many modules, so we do not want to load at
847   ;; compile-time. instead, suppress warnings by this.
848   (eval-when-compile
849     (autoload 'filename-maybe-truncate-by-size "filename")
850     (autoload 'filename-special-filter "filename"))
851   (defun convert-standard-filename (filename)
852     "Convert a standard file's name to something suitable for the current OS.
853 This function's standard definition is trivial; it just returns the argument.
854 However, on some systems, the function is redefined
855 with a definition that really does change some file names.
856 Under `windows-nt' or `ms-dos', it refers `filename-replacement-alist' and
857 `filename-limit-length' for the basic filename and each parent directory name."
858     (require 'filename)
859     (let* ((names (split-string filename "/"))
860            (drive-name (car names))
861            (filter (function
862                     (lambda (string)
863                       (filename-maybe-truncate-by-size
864                        (filename-special-filter string))))))
865       (cond
866        ((eq 1 (length names))
867         (funcall filter drive-name))
868        ((string-match "^[^/]:$" drive-name)
869         (concat drive-name "/" (mapconcat filter (cdr names) "/")))
870        (t
871         (mapconcat filter names "/"))))))
872  (t
873   (defun convert-standard-filename (filename)
874     "Convert a standard file's name to something suitable for the current OS.
875 This function's standard definition is trivial; it just returns the argument.
876 However, on some systems, the function is redefined
877 with a definition that really does change some file names.
878 Under `windows-nt' or `ms-dos', it refers `filename-replacement-alist' and
879 `filename-limit-length' for the basic filename and each parent directory name."
880     filename)))
881
882 (static-cond
883  ((fboundp 'insert-file-contents-literally))
884  ((boundp 'file-name-handler-alist)
885   ;; Use `defun-maybe' to update `load-history'.
886   (defun-maybe insert-file-contents-literally (filename &optional visit
887                                                         beg end replace)
888     "Like `insert-file-contents', q.v., but only reads in the file.
889 A buffer may be modified in several ways after reading into the buffer due
890 to advanced Emacs features, such as file-name-handlers, format decoding,
891 find-file-hooks, etc.
892   This function ensures that none of these modifications will take place."
893     (let (file-name-handler-alist)
894       (insert-file-contents filename visit beg end replace))))
895  (t
896   (defalias 'insert-file-contents-literally 'insert-file-contents)))
897
898 (defun-maybe file-name-sans-extension (filename)
899   "Return FILENAME sans final \"extension\".
900 The extension, in a file name, is the part that follows the last `.'."
901   (save-match-data
902     (let ((file (file-name-sans-versions (file-name-nondirectory filename)))
903           directory)
904       (if (string-match "\\.[^.]*\\'" file)
905           (if (setq directory (file-name-directory filename))
906               (expand-file-name (substring file 0 (match-beginning 0))
907                                 directory)
908             (substring file 0 (match-beginning 0)))
909         filename))))
910 \f
911
912 ;;; @ XEmacs emulation.
913 ;;;
914
915 (defun-maybe find-face (face-or-name)
916   "Retrieve the face of the given name.
917 If FACE-OR-NAME is a face object, it is simply returned.
918 Otherwise, FACE-OR-NAME should be a symbol.  If there is no such face,
919 nil is returned.  Otherwise the associated face object is returned."
920   (car (memq face-or-name (face-list))))
921
922 ;; Emacs 20.5 defines this as an alias for `line-beginning-position'.
923 ;; Therefore, optional 2nd arg BUFFER is not portable.
924 (defun-maybe point-at-bol (&optional n buffer)
925   "Return the character position of the first character on the current line.
926 With argument N not nil or 1, move forward N - 1 lines first.
927 If scan reaches end of buffer, return that position.
928 This function does not move point."
929   (save-excursion
930     (if buffer (set-buffer buffer))
931     (forward-line (1- (or n 1)))
932     (point)))
933
934 ;; Emacs 20.5 defines this as an alias for `line-end-position'.
935 ;; Therefore, optional 2nd arg BUFFER is not portable.
936 (defun-maybe point-at-eol (&optional n buffer)
937   "Return the character position of the last character on the current line.
938 With argument N not nil or 1, move forward N - 1 lines first.
939 If scan reaches end of buffer, return that position.
940 This function does not move point."
941   (save-excursion
942     (if buffer (set-buffer buffer))
943     (end-of-line (or n 1))
944     (point)))
945
946 (defsubst-maybe define-obsolete-function-alias (oldfun newfun)
947   "Define OLDFUN as an obsolete alias for function NEWFUN.
948 This makes calling OLDFUN equivalent to calling NEWFUN and marks OLDFUN
949 as obsolete."
950   (defalias oldfun newfun)
951   (make-obsolete oldfun newfun))
952
953 ;; XEmacs 21: (character-to-event CH &optional EVENT DEVICE)
954 (defun-maybe character-to-event (ch)
955   "Convert keystroke CH into an event structure, replete with bucky bits.
956 Note that CH (the keystroke specifier) can be an integer, a character
957 or a symbol such as 'clear."
958   ch)
959
960 ;; XEmacs 21: (event-to-character EVENT
961 ;;             &optional ALLOW-EXTRA-MODIFIERS ALLOW-META ALLOW-NON-ASCII)
962 (defun-maybe-cond event-to-character (event)
963   "Return the character approximation to the given event object.
964 If the event isn't a keypress, this returns nil."
965   ((and (fboundp 'read-event)
966         (subrp (symbol-function 'read-event)))
967    ;; Emacs 19 and later.
968    (cond
969     ((symbolp event)
970      ;; mask is (BASE-TYPE MODIFIER-BITS) or nil.
971      (let ((mask (get event 'event-symbol-element-mask)))
972        (if mask
973            (let ((base (get (car mask) 'ascii-character)))
974              (if base
975                  (logior base (car (cdr mask))))))))
976     ((integerp event) event)))
977   (t
978    ;; v18. Is this correct?
979    event))
980
981 ;; v18: no event; (read-char)
982 ;; Emacs 19, 20.1 and 20.2: (read-event)
983 ;; Emacs 20.3: (read-event &optional PROMPT SUPPRESS-INPUT-METHOD)
984 ;; Emacs 20.4: (read-event &optional PROMPT INHERIT-INPUT-METHOD)
985 ;; XEmacs: (next-event &optional EVENT PROMPT),
986 ;;         (next-command-event &optional EVENT PROMPT)
987 (defun-maybe-cond next-command-event (&optional event prompt)
988   "Read an event object from the input stream.
989 If EVENT is non-nil, it should be an event object and will be filled
990 in and returned; otherwise a new event object will be created and
991 returned.
992 If PROMPT is non-nil, it should be a string and will be displayed in
993 the echo area while this function is waiting for an event."
994   ((and (>= emacs-major-version 20)
995         (>= emacs-minor-version 4))
996    ;; Emacs 20.4 and later.
997    (read-event prompt))                 ; should specify 2nd arg?
998   ((and (= emacs-major-version 20)
999         (= emacs-minor-version 3))
1000    ;; Emacs 20.3.
1001    (read-event prompt))                 ; should specify 2nd arg?
1002   ((and (fboundp 'read-event)
1003         (subrp (symbol-function 'read-event)))
1004    ;; Emacs 19, 20.1 and 20.2.
1005    (if prompt (message prompt))
1006    (read-event))
1007   (t
1008    (if prompt (message prompt))
1009    (read-char)))
1010 \f
1011
1012 ;;; @ MULE 2 emulation.
1013 ;;;
1014
1015 (defun-maybe-cond cancel-undo-boundary ()
1016   "Cancel undo boundary."
1017   ((boundp 'buffer-undo-list)
1018    ;; for Emacs 19 and later.
1019    (if (and (consp buffer-undo-list)
1020             (null (car buffer-undo-list)))
1021        (setq buffer-undo-list (cdr buffer-undo-list)))))
1022 \f
1023
1024 ;;; @ End.
1025 ;;;
1026
1027 ;;; poe.el ends here