(enriched-encode): Allow the 3rd argument ORIG-BUF for old Emacsen.
[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
525 ;; FSF Emacs 19.29 and later
526 ;; (read-file-name PROMPT &optional DIR DEFAULT-FILENAME MUSTMATCH INITIAL)
527 ;; XEmacs 19.14 and later:
528 ;; (read-file-name (PROMPT &optional DIR DEFAULT MUST-MATCH INITIAL-CONTENTS
529 ;;                         HISTORY)
530
531 ;; In FSF Emacs 19.28 and earlier (except for v18) or XEmacs 19.13 and
532 ;; earlier, this function is incompatible with the other Emacsen.
533 ;; For instance, if DEFAULT-FILENAME is nil, INITIAL is not and user
534 ;; enters a null string, it returns the visited file name of the current
535 ;; buffer if it is non-nil.
536
537 ;; It does not assimilate the different numbers of the optional arguments
538 ;; on various Emacsen (yet).
539 (static-cond
540  ((and (not (featurep 'xemacs))
541        (eq emacs-major-version 19)
542        (< emacs-minor-version 29))
543   (if (fboundp 'si:read-file-name)
544       nil
545     (fset 'si:read-file-name (symbol-function 'read-file-name))
546     (defun read-file-name (prompt &optional dir default-filename mustmatch
547                                   initial)
548       "Read file name, prompting with PROMPT and completing in directory DIR.
549 Value is not expanded---you must call `expand-file-name' yourself.
550 Default name to DEFAULT-FILENAME if user enters a null string.
551  (If DEFAULT-FILENAME is omitted, the visited file name is used,
552   except that if INITIAL is specified, that combined with DIR is used.)
553 Fourth arg MUSTMATCH non-nil means require existing file's name.
554  Non-nil and non-t means also require confirmation after completion.
555 Fifth arg INITIAL specifies text to start with.
556 DIR defaults to current buffer's directory default."
557       (si:read-file-name prompt dir
558                          (or default-filename
559                              (if initial
560                                  (expand-file-name initial dir)))
561                          mustmatch initial))))
562  ((and (featurep 'xemacs)
563        (eq emacs-major-version 19)
564        (< emacs-minor-version 14))
565   (if (fboundp 'si:read-file-name)
566       nil
567     (fset 'si:read-file-name (symbol-function 'read-file-name))
568     (defun read-file-name (prompt &optional dir default must-match
569                                   initial-contents history)
570       "Read file name, prompting with PROMPT and completing in directory DIR.
571 This will prompt with a dialog box if appropriate, according to
572  `should-use-dialog-box-p'.
573 Value is not expanded---you must call `expand-file-name' yourself.
574 Value is subject to interpreted by substitute-in-file-name however.
575 Default name to DEFAULT if user enters a null string.
576  (If DEFAULT is omitted, the visited file name is used,
577   except that if INITIAL-CONTENTS is specified, that combined with DIR is
578   used.)
579 Fourth arg MUST-MATCH non-nil means require existing file's name.
580  Non-nil and non-t means also require confirmation after completion.
581 Fifth arg INITIAL-CONTENTS specifies text to start with.
582 Sixth arg HISTORY specifies the history list to use.  Default is
583  `file-name-history'.
584 DIR defaults to current buffer's directory default."
585       (si:read-file-name prompt dir
586                          (or default
587                              (if initial-contents
588                                  (expand-file-name initial-contents dir)))
589                          must-match initial-contents history)))))
590 \f
591
592 ;;; @ Basic lisp subroutines emulation. (lisp/subr.el)
593 ;;;
594
595 ;;; @@ Lisp language features.
596
597 (defmacro-maybe push (newelt listname)
598   "Add NEWELT to the list stored in the symbol LISTNAME.
599 This is equivalent to (setq LISTNAME (cons NEWELT LISTNAME)).
600 LISTNAME must be a symbol."
601   (list 'setq listname
602         (list 'cons newelt listname)))
603
604 (defmacro-maybe pop (listname)
605   "Return the first element of LISTNAME's value, and remove it from the list.
606 LISTNAME must be a symbol whose value is a list.
607 If the value is nil, `pop' returns nil but does not actually
608 change the list."
609   (list 'prog1 (list 'car listname)
610         (list 'setq listname (list 'cdr listname))))
611
612 (defmacro-maybe when (cond &rest body)
613   "If COND yields non-nil, do BODY, else return nil."
614   (list 'if cond (cons 'progn body)))
615 ;; (def-edebug-spec when (&rest form))
616
617 (defmacro-maybe unless (cond &rest body)
618   "If COND yields nil, do BODY, else return nil."
619   (cons 'if (cons cond (cons nil body))))
620 ;; (def-edebug-spec unless (&rest form))
621
622 (defsubst-maybe caar (x)
623   "Return the car of the car of X."
624   (car (car x)))
625
626 (defsubst-maybe cadr (x)
627   "Return the car of the cdr of X."
628   (car (cdr x)))
629
630 (defsubst-maybe cdar (x)
631   "Return the cdr of the car of X."
632   (cdr (car x)))
633
634 (defsubst-maybe cddr (x)
635   "Return the cdr of the cdr of X."
636   (cdr (cdr x)))
637
638 (defun-maybe last (x &optional n)
639   "Return the last link of the list X.  Its car is the last element.
640 If X is nil, return nil.
641 If N is non-nil, return the Nth-to-last link of X.
642 If N is bigger than the length of X, return X."
643   (if n
644       (let ((m 0) (p x))
645         (while (consp p)
646           (setq m (1+ m) p (cdr p)))
647         (if (<= n 0) p
648           (if (< n m) (nthcdr (- m n) x) x)))
649     (while (cdr x)
650       (setq x (cdr x)))
651     x))
652
653 ;; Actually, `butlast' and `nbutlast' are defined in lisp/cl.el.
654 (defun-maybe butlast (x &optional n)
655   "Returns a copy of LIST with the last N elements removed."
656   (if (and n (<= n 0)) x
657     (nbutlast (copy-sequence x) n)))
658
659 (defun-maybe nbutlast (x &optional n)
660   "Modifies LIST to remove the last N elements."
661   (let ((m (length x)))
662     (or n (setq n 1))
663     (and (< n m)
664          (progn
665            (if (> n 0) (setcdr (nthcdr (- (1- m) n) x) nil))
666            x))))
667
668 ;; Emacs 20.3 and later: (assoc-default KEY ALIST &optional TEST DEFAULT)
669 (defun-maybe assoc-default (key alist &optional test default)
670   "Find object KEY in a pseudo-alist ALIST.
671 ALIST is a list of conses or objects.  Each element (or the element's car,
672 if it is a cons) is compared with KEY by evaluating (TEST (car elt) KEY).
673 If that is non-nil, the element matches;
674 then `assoc-default' returns the element's cdr, if it is a cons,
675 or DEFAULT if the element is not a cons.
676
677 If no element matches, the value is nil.
678 If TEST is omitted or nil, `equal' is used."
679   (let (found (tail alist) value)
680     (while (and tail (not found))
681       (let ((elt (car tail)))
682         (when (funcall (or test 'equal) (if (consp elt) (car elt) elt) key)
683           (setq found t value (if (consp elt) (cdr elt) default))))
684       (setq tail (cdr tail)))
685     value))
686
687 ;; The following two function use `compare-strings', which we don't
688 ;; support yet.
689 ;; (defun assoc-ignore-case (key alist))
690 ;; (defun assoc-ignore-representation (key alist))
691
692 ;; Emacs 19.29/XEmacs 19.13 and later: (rassoc KEY LIST)
693 ;; Actually, `rassoc' is defined in src/fns.c.
694 (defun-maybe rassoc (key list)
695   "Return non-nil if KEY is `equal' to the cdr of an element of LIST.
696 The value is actually the element of LIST whose cdr equals KEY.
697 Elements of LIST that are not conses are ignored."
698   (catch 'found
699     (while list
700       (cond ((not (consp (car list))))
701             ((equal (cdr (car list)) key)
702              (throw 'found (car list))))
703       (setq list (cdr list)))))
704
705 ;; XEmacs 19.13 and later: (remassq KEY LIST)
706 (defun-maybe remassq (key list)
707   "Delete by side effect any elements of LIST whose car is `eq' to KEY.
708 The modified LIST is returned.  If the first member of LIST has a car
709 that is `eq' to KEY, there is no way to remove it by side effect;
710 therefore, write `(setq foo (remassq key foo))' to be sure of changing
711 the value of `foo'."
712   (if (setq key (assq key list))
713       (delete key list)
714     list))
715
716 ;; XEmacs 19.13 and later: (remassoc KEY LIST)
717 (defun-maybe remassoc (key list)
718   "Delete by side effect any elements of LIST whose car is `equal' to KEY.
719 The modified LIST is returned.  If the first member of LIST has a car
720 that is `equal' to KEY, there is no way to remove it by side effect;
721 therefore, write `(setq foo (remassoc key foo))' to be sure of changing
722 the value of `foo'."
723   (if (setq key (assoc key list))
724       (delete key list)
725     list))
726
727 ;; XEmacs 19.13 and later: (remrassoc VALUE LIST)
728 (defun-maybe remrassoc (value list)
729   "Delete by side effect any elements of LIST whose cdr is `equal' to VALUE.
730 The modified LIST is returned.  If the first member of LIST has a car
731 that is `equal' to VALUE, there is no way to remove it by side effect;
732 therefore, write `(setq foo (remrassoc value foo))' to be sure of changing
733 the value of `foo'."
734   (if (setq value (rassoc value list))
735       (delete value list)
736     list))
737
738 ;;; Define `functionp' here because "localhook" uses it.
739
740 ;; Emacs 20.1/XEmacs 20.3 (but first appeared in Epoch?): (functionp OBJECT)
741 (defun-maybe functionp (object)
742   "Non-nil if OBJECT is a type of object that can be called as a function."
743   (or (subrp object) (byte-code-function-p object)
744       (eq (car-safe object) 'lambda)
745       (and (symbolp object) (fboundp object))))
746
747 ;;; @@ Hook manipulation functions.
748
749 ;; "localhook" package is written for Emacs 19.28 and earlier.
750 ;; `run-hooks' was a lisp function in Emacs 19.29 and earlier.
751 ;; So, in Emacs 19.29, `run-hooks' and others will be overrided.
752 ;; But, who cares it?
753 (static-unless (subrp (symbol-function 'run-hooks))
754   (require 'localhook))
755
756 ;; Emacs 19.29/XEmacs 19.14(?) and later: (add-to-list LIST-VAR ELEMENT)
757 (defun-maybe add-to-list (list-var element)
758   "Add to the value of LIST-VAR the element ELEMENT if it isn't there yet.
759 The test for presence of ELEMENT is done with `equal'.
760 If you want to use `add-to-list' on a variable that is not defined
761 until a certain package is loaded, you should put the call to `add-to-list'
762 into a hook function that will be run only after loading the package.
763 `eval-after-load' provides one way to do this.  In some cases
764 other hooks, such as major mode hooks, can do the job."
765   (or (member element (symbol-value list-var))
766       (set list-var (cons element (symbol-value list-var)))))
767
768 ;; (eval-after-load FILE FORM)
769 ;; Emacs 19.28 and earlier do not evaluate FORM if FILE is already loaded.
770 ;; XEmacs 20.2 and earlier have `after-load-alist', but refuse to support
771 ;; `eval-after-load'. (see comments in XEmacs/lisp/subr.el.)
772 (static-cond
773  ((featurep 'xemacs)
774   ;; for XEmacs 20.2 and earlier.
775   (defun-maybe eval-after-load (file form)
776     "Arrange that, if FILE is ever loaded, FORM will be run at that time.
777 This makes or adds to an entry on `after-load-alist'.
778 If FILE is already loaded, evaluate FORM right now.
779 It does nothing if FORM is already on the list for FILE.
780 FILE should be the name of a library, with no directory name."
781     ;; Make sure there is an element for FILE.
782     (or (assoc file after-load-alist)
783         (setq after-load-alist (cons (list file) after-load-alist)))
784     ;; Add FORM to the element if it isn't there.
785     (let ((elt (assoc file after-load-alist)))
786       (or (member form (cdr elt))
787           (progn
788             (nconc elt (list form))
789             ;; If the file has been loaded already, run FORM right away.
790             (and (assoc file load-history)
791                  (eval form)))))
792     form))
793  ((>= emacs-major-version 20))
794  ((and (= emacs-major-version 19)
795        (< emacs-minor-version 29))
796   ;; for Emacs 19.28 and earlier.
797   (defun eval-after-load (file form)
798     "Arrange that, if FILE is ever loaded, FORM will be run at that time.
799 This makes or adds to an entry on `after-load-alist'.
800 If FILE is already loaded, evaluate FORM right now.
801 It does nothing if FORM is already on the list for FILE.
802 FILE should be the name of a library, with no directory name."
803     ;; Make sure there is an element for FILE.
804     (or (assoc file after-load-alist)
805         (setq after-load-alist (cons (list file) after-load-alist)))
806     ;; Add FORM to the element if it isn't there.
807     (let ((elt (assoc file after-load-alist)))
808       (or (member form (cdr elt))
809           (progn
810             (nconc elt (list form))
811             ;; If the file has been loaded already, run FORM right away.
812             (and (assoc file load-history)
813                  (eval form)))))
814     form))
815  (t
816   ;; should emulate for v18?
817   ))
818
819 (defun-maybe eval-next-after-load (file)
820   "Read the following input sexp, and run it whenever FILE is loaded.
821 This makes or adds to an entry on `after-load-alist'.
822 FILE should be the name of a library, with no directory name."
823   (eval-after-load file (read)))
824
825 ;;; @@ Input and display facilities.
826
827 ;; XXX: (defun read-passwd (prompt &optional confirm default))
828
829 ;;; @@ Miscellanea.
830
831 ;; Avoid compiler warnings about this variable,
832 ;; which has a special meaning on certain system types.
833 (defvar-maybe buffer-file-type nil
834   "Non-nil if the visited file is a binary file.
835 This variable is meaningful on MS-DOG and Windows NT.
836 On those systems, it is automatically local in every buffer.
837 On other systems, this variable is normally always nil.")
838
839 ;; Emacs 20.1/XEmacs 20.3(?) and later: (save-current-buffer &rest BODY)
840 ;;
841 ;; v20 defines `save-current-buffer' as a C primitive (in src/editfns.c)
842 ;; and introduces a new bytecode Bsave_current_buffer(_1), replacing an
843 ;; obsolete bytecode Bread_char.  To make things worse, Emacs 20.1 and
844 ;; 20.2 have a bug that it will restore the current buffer without
845 ;; confirming that it is alive.
846 ;;
847 ;; This is a source of incompatibility of .elc between v18/v19 and v20.
848 ;; (XEmacs compiler takes care of it if compatibility mode is enabled.)
849 (defmacro-maybe save-current-buffer (&rest body)
850   "Save the current buffer; execute BODY; restore the current buffer.
851 Executes BODY just like `progn'."
852   (` (let ((orig-buffer (current-buffer)))
853        (unwind-protect
854            (progn (,@ body))
855          (if (buffer-live-p orig-buffer)
856              (set-buffer orig-buffer))))))
857
858 ;; Emacs 20.1/XEmacs 20.3(?) and later: (with-current-buffer BUFFER &rest BODY)
859 (defmacro-maybe with-current-buffer (buffer &rest body)
860   "Execute the forms in BODY with BUFFER as the current buffer.
861 The value returned is the value of the last form in BODY.
862 See also `with-temp-buffer'."
863   (` (save-current-buffer
864        (set-buffer (, buffer))
865        (,@ body))))
866
867 ;; Emacs 20.1/XEmacs 20.3(?) and later: (with-temp-file FILE &rest FORMS)
868 (defmacro-maybe with-temp-file (file &rest forms)
869   "Create a new buffer, evaluate FORMS there, and write the buffer to FILE.
870 The value of the last form in FORMS is returned, like `progn'.
871 See also `with-temp-buffer'."
872   (let ((temp-file (make-symbol "temp-file"))
873         (temp-buffer (make-symbol "temp-buffer")))
874     (` (let (((, temp-file) (, file))
875              ((, temp-buffer)
876               (get-buffer-create (generate-new-buffer-name " *temp file*"))))
877          (unwind-protect
878              (prog1
879                  (with-current-buffer (, temp-buffer)
880                    (,@ forms))
881                (with-current-buffer (, temp-buffer)
882                  (widen)
883                  (write-region (point-min) (point-max) (, temp-file) nil 0)))
884            (and (buffer-name (, temp-buffer))
885                 (kill-buffer (, temp-buffer))))))))
886
887 ;; Emacs 20.4 and later: (with-temp-message MESSAGE &rest BODY)
888 ;; This macro uses `current-message', which appears in v20.
889 (static-when (and (fboundp 'current-message)
890                   (subrp (symbol-function 'current-message)))
891   (defmacro-maybe with-temp-message (message &rest body)
892     "\
893 Display MESSAGE temporarily if non-nil while BODY is evaluated.
894 The original message is restored to the echo area after BODY has finished.
895 The value returned is the value of the last form in BODY.
896 MESSAGE is written to the message log buffer if `message-log-max' is non-nil.
897 If MESSAGE is nil, the echo area and message log buffer are unchanged.
898 Use a MESSAGE of \"\" to temporarily clear the echo area."
899     (let ((current-message (make-symbol "current-message"))
900           (temp-message (make-symbol "with-temp-message")))
901       (` (let (((, temp-message) (, message))
902                ((, current-message)))
903            (unwind-protect
904                (progn
905                  (when (, temp-message)
906                    (setq (, current-message) (current-message))
907                    (message "%s" (, temp-message))
908                    (,@ body))
909                  (and (, temp-message) (, current-message)
910                       (message "%s" (, current-message))))))))))
911
912 ;; Emacs 20.1/XEmacs 20.3(?) and later: (with-temp-buffer &rest FORMS)
913 (defmacro-maybe with-temp-buffer (&rest forms)
914   "Create a temporary buffer, and evaluate FORMS there like `progn'.
915 See also `with-temp-file' and `with-output-to-string'."
916   (let ((temp-buffer (make-symbol "temp-buffer")))
917     (` (let (((, temp-buffer)
918               (get-buffer-create (generate-new-buffer-name " *temp*"))))
919          (unwind-protect
920              (with-current-buffer (, temp-buffer)
921                (,@ forms))
922            (and (buffer-name (, temp-buffer))
923                 (kill-buffer (, temp-buffer))))))))
924
925 ;; Emacs 20.1/XEmacs 20.3(?) and later: (with-output-to-string &rest BODY)
926 (defmacro-maybe with-output-to-string (&rest body)
927   "Execute BODY, return the text it sent to `standard-output', as a string."
928   (` (let ((standard-output
929             (get-buffer-create (generate-new-buffer-name " *string-output*"))))
930        (let ((standard-output standard-output))
931          (,@ body))
932        (with-current-buffer standard-output
933          (prog1
934              (buffer-string)
935            (kill-buffer nil))))))
936
937 ;; Emacs 20.1 and later: (combine-after-change-calls &rest BODY)
938 (defmacro-maybe combine-after-change-calls (&rest body)
939   "Execute BODY, but don't call the after-change functions till the end.
940 If BODY makes changes in the buffer, they are recorded
941 and the functions on `after-change-functions' are called several times
942 when BODY is finished.
943 The return value is the value of the last form in BODY.
944
945 If `before-change-functions' is non-nil, then calls to the after-change
946 functions can't be deferred, so in that case this macro has no effect.
947
948 Do not alter `after-change-functions' or `before-change-functions'
949 in BODY.
950
951 This emulating macro does not support after-change functions at all,
952 just execute BODY."
953   (cons 'progn body))
954
955 ;; Emacs 19.29/XEmacs 19.14(?) and later: (match-string NUM &optional STRING)
956 (defun-maybe match-string (num &optional string)
957   "Return string of text matched by last search.
958 NUM specifies which parenthesized expression in the last regexp.
959  Value is nil if NUMth pair didn't match, or there were less than NUM pairs.
960 Zero means the entire text matched by the whole regexp or whole string.
961 STRING should be given if the last search was by `string-match' on STRING."
962   (if (match-beginning num)
963       (if string
964           (substring string (match-beginning num) (match-end num))
965         (buffer-substring (match-beginning num) (match-end num)))))
966
967 ;; Emacs 20.3 and later: (match-string-no-properties NUM &optional STRING)
968 (defun-maybe match-string-no-properties (num &optional string)
969   "Return string of text matched by last search, without text properties.
970 NUM specifies which parenthesized expression in the last regexp.
971  Value is nil if NUMth pair didn't match, or there were less than NUM pairs.
972 Zero means the entire text matched by the whole regexp or whole string.
973 STRING should be given if the last search was by `string-match' on STRING."
974   (if (match-beginning num)
975       (if string
976           (let ((result
977                  (substring string (match-beginning num) (match-end num))))
978             (set-text-properties 0 (length result) nil result)
979             result)
980         (buffer-substring-no-properties (match-beginning num)
981                                         (match-end num)))))
982
983 ;; Emacs 19.28 and earlier
984 ;;  (replace-match NEWTEXT &optional FIXEDCASE LITERAL)
985 ;; Emacs 20.x (?) and later
986 ;;  (replace-match NEWTEXT &optional FIXEDCASE LITERAL STRING SUBEXP)
987 ;; XEmacs 21:
988 ;;  (replace-match NEWTEXT &optional FIXEDCASE LITERAL STRING STRBUFFER)
989 ;; We support following API.
990 ;;  (replace-match NEWTEXT &optional FIXEDCASE LITERAL STRING)
991 (static-condition-case nil
992     ;; compile-time check
993     (progn
994       (string-match "" "")
995       (replace-match "" nil nil "")
996       (if (get 'replace-match 'defun-maybe)
997           (error "`replace-match' is already defined")))
998   (wrong-number-of-arguments ; Emacs 19.28 and earlier
999    ;; load-time check.
1000    (or (fboundp 'si:replace-match)
1001        (progn
1002          (fset 'si:replace-match (symbol-function 'replace-match))
1003          (put 'replace-match 'defun-maybe t)
1004          (defun replace-match (newtext &optional fixedcase literal string)
1005            "Replace text matched by last search with NEWTEXT.
1006 If second arg FIXEDCASE is non-nil, do not alter case of replacement text.
1007 Otherwise maybe capitalize the whole text, or maybe just word initials,
1008 based on the replaced text.
1009 If the replaced text has only capital letters
1010 and has at least one multiletter word, convert NEWTEXT to all caps.
1011 If the replaced text has at least one word starting with a capital letter,
1012 then capitalize each word in NEWTEXT.
1013
1014 If third arg LITERAL is non-nil, insert NEWTEXT literally.
1015 Otherwise treat `\' as special:
1016   `\&' in NEWTEXT means substitute original matched text.
1017   `\N' means substitute what matched the Nth `\(...\)'.
1018        If Nth parens didn't match, substitute nothing.
1019   `\\' means insert one `\'.
1020 FIXEDCASE and LITERAL are optional arguments.
1021 Leaves point at end of replacement text.
1022
1023 The optional fourth argument STRING can be a string to modify.
1024 In that case, this function creates and returns a new string
1025 which is made by replacing the part of STRING that was matched."
1026            (if string
1027                (with-temp-buffer
1028                 (save-match-data
1029                   (insert string)
1030                   (let* ((matched (match-data))
1031                          (beg (nth 0 matched))
1032                          (end (nth 1 matched)))
1033                     (store-match-data
1034                      (list
1035                       (if (markerp beg)
1036                           (move-marker beg (1+ (match-beginning 0)))
1037                         (1+ (match-beginning 0)))
1038                       (if (markerp end)
1039                           (move-marker end (1+ (match-end 0)))
1040                         (1+ (match-end 0))))))
1041                   (si:replace-match newtext fixedcase literal)
1042                   (buffer-string)))
1043              (si:replace-match newtext fixedcase literal))))))
1044   (error ; found our definition at compile-time.
1045    ;; load-time check.
1046    (condition-case nil
1047     (progn
1048       (string-match "" "")
1049       (replace-match "" nil nil ""))
1050     (wrong-number-of-arguments ; Emacs 19.28 and earlier
1051      ;; load-time check.
1052      (or (fboundp 'si:replace-match)
1053          (progn
1054            (fset 'si:replace-match (symbol-function 'replace-match))
1055            (put 'replace-match 'defun-maybe t)
1056            (defun replace-match (newtext &optional fixedcase literal string)
1057              "Replace text matched by last search with NEWTEXT.
1058 If second arg FIXEDCASE is non-nil, do not alter case of replacement text.
1059 Otherwise maybe capitalize the whole text, or maybe just word initials,
1060 based on the replaced text.
1061 If the replaced text has only capital letters
1062 and has at least one multiletter word, convert NEWTEXT to all caps.
1063 If the replaced text has at least one word starting with a capital letter,
1064 then capitalize each word in NEWTEXT.
1065
1066 If third arg LITERAL is non-nil, insert NEWTEXT literally.
1067 Otherwise treat `\' as special:
1068   `\&' in NEWTEXT means substitute original matched text.
1069   `\N' means substitute what matched the Nth `\(...\)'.
1070        If Nth parens didn't match, substitute nothing.
1071   `\\' means insert one `\'.
1072 FIXEDCASE and LITERAL are optional arguments.
1073 Leaves point at end of replacement text.
1074
1075 The optional fourth argument STRING can be a string to modify.
1076 In that case, this function creates and returns a new string
1077 which is made by replacing the part of STRING that was matched."
1078              (if string
1079                  (with-temp-buffer
1080                   (save-match-data
1081                     (insert string)
1082                     (let* ((matched (match-data))
1083                            (beg (nth 0 matched))
1084                            (end (nth 1 matched)))
1085                       (store-match-data
1086                        (list
1087                         (if (markerp beg)
1088                             (move-marker beg (1+ (match-beginning 0)))
1089                           (1+ (match-beginning 0)))
1090                         (if (markerp end)
1091                             (move-marker end (1+ (match-end 0)))
1092                           (1+ (match-end 0))))))
1093                     (si:replace-match newtext fixedcase literal)
1094                     (buffer-string)))
1095                (si:replace-match newtext fixedcase literal)))))))))
1096
1097 ;; Emacs 20: (format-time-string)
1098 ;; The the third optional argument universal is yet to be implemented.
1099 ;; Those format constructs are yet to be implemented.
1100 ;;   %c, %C, %j, %U, %W, %x, %X
1101 ;; Not fully compatible especially when invalid format is specified.
1102 (static-unless (and (fboundp 'format-time-string)
1103                     (not (get 'format-time-string 'defun-maybe)))
1104   (or (fboundp 'format-time-string)
1105   (progn
1106   (defconst format-time-month-list
1107     '(( "Zero" . ("Zero" . 0))
1108       ("Jan" . ("January" . 1)) ("Feb" . ("February" . 2))
1109       ("Mar" . ("March" . 3)) ("Apr" . ("April" . 4)) ("May" . ("May" . 5))
1110       ("Jun" . ("June" . 6))("Jul" . ("July" . 7)) ("Aug" . ("August" . 8))
1111       ("Sep" . ("September" . 9)) ("Oct" . ("October" . 10))
1112       ("Nov" . ("November" . 11)) ("Dec" . ("December" . 12)))
1113     "Alist of months and their number.")
1114
1115   (defconst format-time-week-list
1116     '(("Sun" . ("Sunday" . 0)) ("Mon" . ("Monday" . 1))
1117       ("Tue" . ("Tuesday" . 2)) ("Wed" . ("Wednesday" . 3))
1118       ("Thu" . ("Thursday" . 4)) ("Fri" . ("Friday" . 5))
1119       ("Sat" . ("Saturday" . 6)))
1120     "Alist of weeks and their number.")
1121
1122   (defun format-time-string (format &optional time universal)
1123     "Use FORMAT-STRING to format the time TIME, or now if omitted.
1124 TIME is specified as (HIGH LOW . IGNORED) or (HIGH . LOW), as returned by
1125 `current-time' or `file-attributes'.
1126 The third, optional, argument UNIVERSAL, if non-nil, means describe TIME
1127 as Universal Time; nil means describe TIME in the local time zone.
1128 The value is a copy of FORMAT-STRING, but with certain constructs replaced
1129 by text that describes the specified date and time in TIME:
1130
1131 %Y is the year, %y within the century, %C the century.
1132 %G is the year corresponding to the ISO week, %g within the century.
1133 %m is the numeric month.
1134 %b and %h are the locale's abbreviated month name, %B the full name.
1135 %d is the day of the month, zero-padded, %e is blank-padded.
1136 %u is the numeric day of week from 1 (Monday) to 7, %w from 0 (Sunday) to 6.
1137 %a is the locale's abbreviated name of the day of week, %A the full name.
1138 %U is the week number starting on Sunday, %W starting on Monday,
1139  %V according to ISO 8601.
1140 %j is the day of the year.
1141
1142 %H is the hour on a 24-hour clock, %I is on a 12-hour clock, %k is like %H
1143  only blank-padded, %l is like %I blank-padded.
1144 %p is the locale's equivalent of either AM or PM.
1145 %M is the minute.
1146 %S is the second.
1147 %Z is the time zone name, %z is the numeric form.
1148 %s is the number of seconds since 1970-01-01 00:00:00 +0000.
1149
1150 %c is the locale's date and time format.
1151 %x is the locale's \"preferred\" date format.
1152 %D is like \"%m/%d/%y\".
1153
1154 %R is like \"%H:%M\", %T is like \"%H:%M:%S\", %r is like \"%I:%M:%S %p\".
1155 %X is the locale's \"preferred\" time format.
1156
1157 Finally, %n is a newline, %t is a tab, %% is a literal %.
1158
1159 Certain flags and modifiers are available with some format controls.
1160 The flags are `_' and `-'.  For certain characters X, %_X is like %X,
1161 but padded with blanks; %-X is like %X, but without padding.
1162 %NX (where N stands for an integer) is like %X,
1163 but takes up at least N (a number) positions.
1164 The modifiers are `E' and `O'.  For certain characters X,
1165 %EX is a locale's alternative version of %X;
1166 %OX is like %X, but uses the locale's number symbols.
1167
1168 For example, to produce full ISO 8601 format, use \"%Y-%m-%dT%T%z\".
1169
1170 Compatibility Note.
1171
1172 The the third optional argument universal is yet to be implemented.
1173 Those format constructs are yet to be implemented.
1174   %c, %C, %j, %U, %W, %x, %X
1175 Not fully compatible especially when invalid format is specified."
1176     (let ((fmt-len (length format))
1177           (ind 0)
1178           prev-ind
1179           cur-char
1180           (prev-char nil)
1181           strings-so-far
1182           (result "")
1183           field-width
1184           field-result
1185           pad-left change-case
1186           (paren-level 0)
1187           hour
1188           (time-string (current-time-string time)))
1189       (setq hour (string-to-int (substring time-string 11 13)))
1190       (while (< ind fmt-len)
1191         (setq cur-char (aref format ind))
1192         (setq
1193          result
1194          (concat result
1195         (cond
1196          ((eq cur-char ?%)
1197           ;; eat any additional args to allow for future expansion, not!!
1198           (setq pad-left nil change-case nil field-width "" prev-ind ind
1199                 strings-so-far "")
1200 ;         (catch 'invalid
1201           (while (progn
1202                    (setq ind (1+ ind))
1203                    (setq cur-char (if (< ind fmt-len)
1204                                       (aref format ind)
1205                                     ?\0))
1206                    (or (eq ?- cur-char) ; pad on left
1207                        (eq ?# cur-char) ; case change
1208                        (if (and (string-equal field-width "")
1209                                 (<= ?0 cur-char) (>= ?9 cur-char))
1210                            ;; get format width
1211                            (let ((field-index ind))
1212                              (while (progn
1213                                       (setq ind (1+ ind))
1214                                       (setq cur-char (if (< ind fmt-len)
1215                                                          (aref format ind)
1216                                                        ?\0))
1217                                       (and (<= ?0 cur-char) (>= ?9 cur-char))))
1218                              (setq field-width
1219                                    (substring format field-index ind))
1220                              (setq ind (1- ind)
1221                                    cur-char nil)
1222                              t))))
1223             (setq prev-char cur-char
1224                   strings-so-far (concat strings-so-far
1225                                          (if cur-char
1226                                              (char-to-string cur-char)
1227                                            field-width)))
1228             ;; characters we actually use
1229             (cond ((eq cur-char ?-)
1230                    ;; padding to left must be specified before field-width
1231                    (setq pad-left (string-equal field-width "")))
1232                   ((eq cur-char ?#)
1233                    (setq change-case t))))
1234           (setq field-result
1235                 (cond
1236                  ((eq cur-char ?%)
1237                   "%")
1238                  ;; the abbreviated name of the day of week.             
1239                  ((eq cur-char ?a)
1240                   (substring time-string 0 3))
1241                  ;; the full name of the day of week
1242                  ((eq cur-char ?A)
1243                   (cadr (assoc (substring time-string 0 3)
1244                                format-time-week-list)))
1245                  ;; the abbreviated name of the month
1246                  ((eq cur-char ?b)
1247                   (substring time-string 4 7))
1248                  ;; the full name of the month
1249                  ((eq cur-char ?B)
1250                   (cadr (assoc (substring time-string 4 7)
1251                                format-time-month-list)))
1252                  ;; a synonym for `%x %X' (yet to come)
1253                  ((eq cur-char ?c)
1254                   "")
1255                  ;; locale specific (yet to come)
1256                  ((eq cur-char ?C)
1257                   "")
1258                  ;; the day of month, zero-padded
1259                  ((eq cur-char ?d)      
1260                   (substring time-string 8 10))
1261                  ;; a synonym for `%m/%d/%y'
1262                  ((eq cur-char ?D)
1263                   (format "%02d/%s/%s"
1264                           (cddr (assoc (substring time-string 4 7)
1265                                        format-time-month-list))
1266                           (substring time-string 8 10)
1267                           (substring time-string -2)))
1268                  ;; the day of month, blank-padded
1269                  ((eq cur-char ?e)
1270                   (format "%2d" (string-to-int (substring time-string 8 10))))
1271                  ;; a synonym for `%b'
1272                  ((eq cur-char ?h)
1273                   (substring time-string 4 7))
1274                  ;; the hour (00-23)
1275                  ((eq cur-char ?H)
1276                   (substring time-string 11 13))
1277                  ;; the hour (00-12)
1278                  ((eq cur-char ?I)
1279                   (format "%02d" (if (> hour 12) (- hour 12) hour)))
1280                  ;; the day of the year (001-366) (yet to come)
1281                  ((eq cur-char ?j)
1282                   "")
1283                  ;; the hour (0-23), blank padded
1284                  ((eq cur-char ?k)
1285                   (format "%2d" hour))
1286                  ;; the hour (1-12), blank padded
1287                  ((eq cur-char ?l)
1288                   (format "%2d" (if (> hour 12) (- hour 12) hour)))
1289                  ;; the month (01-12)
1290                  ((eq cur-char ?m)
1291                   (format "%02d" (cddr (assoc (substring time-string 4 7)
1292                                               format-time-month-list))))
1293                  ;; the minute (00-59)
1294                  ((eq cur-char ?M)
1295                   (substring time-string 14 16))
1296                  ;; a newline
1297                  ((eq cur-char ?n)
1298                   "\n")
1299                  ;; `AM' or `PM', as appropriate
1300                  ((eq cur-char ?p)
1301                   (setq change-case (not change-case))
1302                   (if (> hour 12) "pm" "am"))
1303                  ;; a synonym for `%I:%M:%S %p'
1304                  ((eq cur-char ?r)
1305                   (format "%02d:%s:%s %s"
1306                           (if (> hour 12) (- hour 12) hour)
1307                           (substring time-string 14 16)
1308                           (substring time-string 17 19)
1309                           (if (> hour 12) "PM" "AM")))
1310                  ;; a synonym for `%H:%M'
1311                  ((eq cur-char ?R)
1312                   (format "%s:%s"
1313                           (substring time-string 11 13)
1314                           (substring time-string 14 16)))
1315                  ;; the seconds (00-60)
1316                  ((eq cur-char ?S)
1317                   (substring time-string 17 19))
1318                  ;; a tab character
1319                  ((eq cur-char ?t)
1320                   "\t")
1321                  ;; a synonym for `%H:%M:%S'
1322                  ((eq cur-char ?T)
1323                   (format "%s:%s:%s"
1324                           (substring time-string 11 13)
1325                           (substring time-string 14 16)
1326                           (substring time-string 17 19)))
1327                  ;; the week of the year (01-52), assuming that weeks 
1328                  ;; start on Sunday (yet to come)
1329                  ((eq cur-char ?U)
1330                   "")
1331                  ;; the numeric day of week (0-6).  Sunday is day 0
1332                  ((eq cur-char ?w)
1333                   (format "%d" (cddr (assoc (substring time-string 0 3)
1334                                             format-time-week-list))))
1335                  ;; the week of the year (01-52), assuming that weeks
1336                  ;; start on Monday (yet to come)
1337                  ((eq cur-char ?W)
1338                   "")
1339                  ;; locale specific (yet to come)
1340                  ((eq cur-char ?x)
1341                   "")
1342                  ;; locale specific (yet to come)
1343                  ((eq cur-char ?X)
1344                   "")
1345                  ;; the year without century (00-99)
1346                  ((eq cur-char ?y)
1347                   (substring time-string -2))
1348                  ;; the year with century
1349                  ((eq cur-char ?Y)
1350                   (substring time-string -4))
1351                  ;; the time zone abbreviation
1352                  ((eq cur-char ?Z)
1353                   (setq change-case (not change-case))
1354                   (downcase (cadr (current-time-zone))))
1355                  (t
1356                   (concat
1357                    "%"
1358                    strings-so-far
1359                    (char-to-string cur-char)))))
1360 ;                 (setq ind prev-ind)
1361 ;                 (throw 'invalid "%"))))
1362           (if (string-equal field-width "")
1363               (if change-case (upcase field-result) field-result)
1364             (let ((padded-result
1365                    (format (format "%%%s%s%c"
1366                                    ""   ; pad on left is ignored
1367 ;                                  (if pad-left "-" "")
1368                                    field-width
1369                                    ?s)
1370                            (or field-result ""))))
1371               (let ((initial-length (length padded-result))
1372                     (desired-length (string-to-int field-width)))
1373                 (when (and (string-match "^0" field-width)
1374                            (string-match "^ +" padded-result))
1375                   (setq padded-result
1376                         (replace-match
1377                          (make-string
1378                           (length (match-string 0 padded-result)) ?0)
1379                          nil nil padded-result)))
1380                 (if (> initial-length desired-length)
1381                     ;; truncate strings on right, years on left
1382                     (if (stringp field-result)
1383                         (substring padded-result 0 desired-length)
1384                       (if (eq cur-char ?y)
1385                           (substring padded-result (- desired-length))
1386                         padded-result))) ;non-year numbers don't truncate
1387                 (if change-case (upcase padded-result) padded-result))))) ;)
1388          (t
1389           (char-to-string cur-char)))))
1390         (setq ind (1+ ind)))
1391       result))
1392   ;; for `load-history'.
1393   (setq current-load-list (cons 'format-time-string current-load-list))
1394   (put 'format-time-string 'defun-maybe t))))
1395
1396 ;; Emacs 20.1/XEmacs 20.3(?) and later: (split-string STRING &optional PATTERN)
1397 ;; Here is a XEmacs version.
1398 (defun-maybe split-string (string &optional pattern)
1399   "Return a list of substrings of STRING which are separated by PATTERN.
1400 If PATTERN is omitted, it defaults to \"[ \\f\\t\\n\\r\\v]+\"."
1401   (or pattern
1402       (setq pattern "[ \f\t\n\r\v]+"))
1403   ;; The FSF version of this function takes care not to cons in case
1404   ;; of infloop.  Maybe we should synch?
1405   (let (parts (start 0))
1406     (while (string-match pattern string start)
1407       (setq parts (cons (substring string start (match-beginning 0)) parts)
1408             start (match-end 0)))
1409     (nreverse (cons (substring string start) parts))))
1410 \f
1411
1412 ;;; @ Window commands emulation. (lisp/window.el)
1413 ;;;
1414
1415 (defmacro-maybe save-selected-window (&rest body)
1416   "Execute BODY, then select the window that was selected before BODY."
1417   (list 'let
1418         '((save-selected-window-window (selected-window)))
1419         (list 'unwind-protect
1420               (cons 'progn body)
1421               (list 'select-window 'save-selected-window-window))))
1422
1423 ;; Emacs 19.31 and later:
1424 ;;  (get-buffer-window-list &optional BUFFER MINIBUF FRAME)
1425 (defun-maybe get-buffer-window-list (buffer &optional minibuf frame)
1426   "Return windows currently displaying BUFFER, or nil if none.
1427 See `walk-windows' for the meaning of MINIBUF and FRAME."
1428   (let ((buffer (if (bufferp buffer) buffer (get-buffer buffer))) windows)
1429     (walk-windows
1430      (function (lambda (window)
1431                  (if (eq (window-buffer window) buffer)
1432                      (setq windows (cons window windows)))))
1433      minibuf frame)
1434     windows))
1435 \f
1436
1437 ;;; @ Frame commands emulation. (lisp/frame.el)
1438 ;;;
1439
1440 ;; XEmacs 21.0 and later:
1441 ;;  (save-selected-frame &rest BODY)
1442 (defmacro-maybe save-selected-frame (&rest body)
1443   "Execute forms in BODY, then restore the selected frame."
1444   (list 'let
1445         '((save-selected-frame-frame (selected-frame)))
1446         (list 'unwind-protect
1447               (cons 'progn body)
1448               (list 'select-frame 'save-selected-frame-frame))))
1449 \f
1450
1451 ;;; @ Basic editing commands emulation. (lisp/simple.el)
1452 ;;;
1453 \f
1454
1455 ;;; @ File input and output commands emulation. (lisp/files.el)
1456 ;;;
1457
1458 (defvar-maybe temporary-file-directory
1459   (file-name-as-directory
1460    (cond ((memq system-type '(ms-dos windows-nt))
1461           (or (getenv "TEMP") (getenv "TMPDIR") (getenv "TMP") "c:/temp"))
1462          ((memq system-type '(vax-vms axp-vms))
1463           (or (getenv "TMPDIR") (getenv "TMP") (getenv "TEMP") "SYS$SCRATCH:"))
1464          (t
1465           (or (getenv "TMPDIR") (getenv "TMP") (getenv "TEMP") "/tmp"))))
1466   "The directory for writing temporary files.")
1467
1468 ;; Actually, `path-separator' is defined in src/emacs.c and overrided
1469 ;; in dos-w32.el.
1470 (defvar-maybe path-separator ":"
1471   "The directory separator in search paths, as a string.")
1472
1473 ;; `convert-standard-filename' is defined in lisp/files.el and overrided
1474 ;; in lisp/dos-fns.el and lisp/w32-fns.el for each environment.
1475 (cond
1476  ;; must be load-time check to share .elc between different systems.
1477  ((fboundp 'convert-standard-filename))
1478  ((memq system-type '(windows-nt ms-dos))
1479   ;; should we do (require 'filename) at load-time ?
1480   ;; (require 'filename)
1481   ;; filename.el requires many modules, so we do not want to load it
1482   ;; at compile-time. Instead, suppress warnings by these autoloads.
1483   (eval-when-compile
1484     (autoload 'filename-maybe-truncate-by-size "filename")
1485     (autoload 'filename-special-filter "filename"))
1486   (defun convert-standard-filename (filename)
1487     "Convert a standard file's name to something suitable for the current OS.
1488 This function's standard definition is trivial; it just returns the argument.
1489 However, on some systems, the function is redefined
1490 with a definition that really does change some file names.
1491 Under `windows-nt' or `ms-dos', it refers `filename-replacement-alist' and
1492 `filename-limit-length' for the basic filename and each parent directory name."
1493     (require 'filename)
1494     (let* ((names (split-string filename "/"))
1495            (drive-name (car names))
1496            (filter (function
1497                     (lambda (string)
1498                       (filename-maybe-truncate-by-size
1499                        (filename-special-filter string))))))
1500       (cond
1501        ((eq 1 (length names))
1502         (funcall filter drive-name))
1503        ((string-match "^[^/]:$" drive-name)
1504         (concat drive-name "/" (mapconcat filter (cdr names) "/")))
1505        (t
1506         (mapconcat filter names "/"))))))
1507  (t
1508   (defun convert-standard-filename (filename)
1509     "Convert a standard file's name to something suitable for the current OS.
1510 This function's standard definition is trivial; it just returns the argument.
1511 However, on some systems, the function is redefined
1512 with a definition that really does change some file names.
1513 Under `windows-nt' or `ms-dos', it refers `filename-replacement-alist' and
1514 `filename-limit-length' for the basic filename and each parent directory name."
1515     filename)))
1516
1517 (static-cond
1518  ((fboundp 'insert-file-contents-literally))
1519  ((boundp 'file-name-handler-alist)
1520   ;; Use `defun-maybe' to update `load-history'.
1521   (defun-maybe insert-file-contents-literally (filename &optional visit
1522                                                         beg end replace)
1523     "Like `insert-file-contents', q.v., but only reads in the file.
1524 A buffer may be modified in several ways after reading into the buffer due
1525 to advanced Emacs features, such as file-name-handlers, format decoding,
1526 find-file-hooks, etc.
1527   This function ensures that none of these modifications will take place."
1528     (let (file-name-handler-alist)
1529       (insert-file-contents filename visit beg end replace))))
1530  (t
1531   (defalias 'insert-file-contents-literally 'insert-file-contents)))
1532
1533 (defun-maybe file-name-sans-extension (filename)
1534   "Return FILENAME sans final \"extension\".
1535 The extension, in a file name, is the part that follows the last `.'."
1536   (save-match-data
1537     (let ((file (file-name-sans-versions (file-name-nondirectory filename)))
1538           directory)
1539       (if (string-match "\\.[^.]*\\'" file)
1540           (if (setq directory (file-name-directory filename))
1541               (expand-file-name (substring file 0 (match-beginning 0))
1542                                 directory)
1543             (substring file 0 (match-beginning 0)))
1544         filename))))
1545 \f
1546
1547 ;;; @ XEmacs emulation.
1548 ;;;
1549
1550 (defun-maybe find-face (face-or-name)
1551   "Retrieve the face of the given name.
1552 If FACE-OR-NAME is a face object, it is simply returned.
1553 Otherwise, FACE-OR-NAME should be a symbol.  If there is no such face,
1554 nil is returned.  Otherwise the associated face object is returned."
1555   (car (memq face-or-name (face-list))))
1556
1557 ;; Emacs 21.1 defines this as an alias for `line-beginning-position'.
1558 ;; Therefore, optional 2nd arg BUFFER is not portable.
1559 (defun-maybe point-at-bol (&optional n buffer)
1560   "Return the character position of the first character on the current line.
1561 With argument N not nil or 1, move forward N - 1 lines first.
1562 If scan reaches end of buffer, return that position.
1563 This function does not move point."
1564   (save-excursion
1565     (if buffer (set-buffer buffer))
1566     (forward-line (1- (or n 1)))
1567     (point)))
1568
1569 ;; Emacs 21.1 defines this as an alias for `line-end-position'.
1570 ;; Therefore, optional 2nd arg BUFFER is not portable.
1571 (defun-maybe point-at-eol (&optional n buffer)
1572   "Return the character position of the last character on the current line.
1573 With argument N not nil or 1, move forward N - 1 lines first.
1574 If scan reaches end of buffer, return that position.
1575 This function does not move point."
1576   (save-excursion
1577     (if buffer (set-buffer buffer))
1578     (end-of-line (or n 1))
1579     (point)))
1580
1581 (defsubst-maybe define-obsolete-function-alias (oldfun newfun)
1582   "Define OLDFUN as an obsolete alias for function NEWFUN.
1583 This makes calling OLDFUN equivalent to calling NEWFUN and marks OLDFUN
1584 as obsolete."
1585   (defalias oldfun newfun)
1586   (make-obsolete oldfun newfun))
1587
1588 ;; XEmacs 21: (character-to-event CH &optional EVENT DEVICE)
1589 (defun-maybe character-to-event (ch)
1590   "Convert keystroke CH into an event structure, replete with bucky bits.
1591 Note that CH (the keystroke specifier) can be an integer, a character
1592 or a symbol such as 'clear."
1593   ch)
1594
1595 ;; XEmacs 21: (event-to-character EVENT
1596 ;;             &optional ALLOW-EXTRA-MODIFIERS ALLOW-META ALLOW-NON-ASCII)
1597 (defun-maybe-cond event-to-character (event)
1598   "Return the character approximation to the given event object.
1599 If the event isn't a keypress, this returns nil."
1600   ((and (fboundp 'read-event)
1601         (subrp (symbol-function 'read-event)))
1602    ;; Emacs 19 and later.
1603    (cond
1604     ((symbolp event)
1605      ;; mask is (BASE-TYPE MODIFIER-BITS) or nil.
1606      (let ((mask (get event 'event-symbol-element-mask)))
1607        (if mask
1608            (let ((base (get (car mask) 'ascii-character)))
1609              (if base
1610                  (logior base (car (cdr mask))))))))
1611     ((integerp event) event)))
1612   (t
1613    ;; v18. Is this correct?
1614    event))
1615
1616 ;; v18: no event; (read-char)
1617 ;; Emacs 19, 20.1 and 20.2: (read-event)
1618 ;; Emacs 20.3: (read-event &optional PROMPT SUPPRESS-INPUT-METHOD)
1619 ;; Emacs 20.4: (read-event &optional PROMPT INHERIT-INPUT-METHOD)
1620 ;; XEmacs: (next-event &optional EVENT PROMPT),
1621 ;;         (next-command-event &optional EVENT PROMPT)
1622 (defun-maybe-cond next-command-event (&optional event prompt)
1623   "Read an event object from the input stream.
1624 If EVENT is non-nil, it should be an event object and will be filled
1625 in and returned; otherwise a new event object will be created and
1626 returned.
1627 If PROMPT is non-nil, it should be a string and will be displayed in
1628 the echo area while this function is waiting for an event."
1629   ((and (>= emacs-major-version 20)
1630         (>= emacs-minor-version 4))
1631    ;; Emacs 20.4 and later.
1632    (read-event prompt))                 ; should specify 2nd arg?
1633   ((and (= emacs-major-version 20)
1634         (= emacs-minor-version 3))
1635    ;; Emacs 20.3.
1636    (read-event prompt))                 ; should specify 2nd arg?
1637   ((and (fboundp 'read-event)
1638         (subrp (symbol-function 'read-event)))
1639    ;; Emacs 19, 20.1 and 20.2.
1640    (if prompt (message prompt))
1641    (read-event))
1642   (t
1643    (if prompt (message prompt))
1644    (read-char)))
1645 \f
1646
1647 ;;; @ MULE 2 emulation.
1648 ;;;
1649
1650 (defun-maybe-cond cancel-undo-boundary ()
1651   "Cancel undo boundary."
1652   ((boundp 'buffer-undo-list)
1653    ;; for Emacs 19 and later.
1654    (if (and (consp buffer-undo-list)
1655             (null (car buffer-undo-list)))
1656        (setq buffer-undo-list (cdr buffer-undo-list)))))
1657 \f
1658
1659 ;;; @ End.
1660 ;;;
1661
1662 ;;; poe.el ends here