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