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