(Download): Renamed from "Anonymous FTP"; modify for
[elisp/apel.git] / poe.el
1 ;;; poe.el --- Portable Outfit for Emacsen
2
3 ;; Copyright (C) 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2005,
4 ;;   2008 Free Software Foundation, Inc.
5
6 ;; Author: MORIOKA Tomohiko <tomo@m17n.org>
7 ;;      Shuhei KOBAYASHI <shuhei@aqua.ocn.ne.jp>
8 ;; Keywords: emulation, compatibility, Nemacs, MULE, Emacs/mule, XEmacs
9
10 ;; This file is part of APEL (A Portable Emacs Library).
11
12 ;; This program is free software; you can redistribute it and/or
13 ;; modify it under the terms of the GNU General Public License as
14 ;; published by the Free Software Foundation; either version 2, or (at
15 ;; your option) any later version.
16
17 ;; This program is distributed in the hope that it will be useful, but
18 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20 ;; General Public License for more details.
21
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
24 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25 ;; Boston, MA 02110-1301, USA.
26
27 ;;; Commentary:
28
29 ;;; Code:
30
31 (require 'product)
32 (product-provide (provide 'poe) (require 'apel-ver))
33
34 (require 'pym)
35
36
37 ;;; @ Version information.
38 ;;;
39
40 (static-when (= emacs-major-version 18)
41   (require 'poe-18))
42
43 ;; Some ancient version of XEmacs did not provide 'xemacs.
44 (static-when (string-match "XEmacs" emacs-version)
45   (provide 'xemacs))
46
47 ;; `file-coding' was appeared in the spring of 1998, just before XEmacs
48 ;; 21.0. Therefore it is not provided in XEmacs with MULE versions 20.4
49 ;; or earlier.
50 (static-when (featurep 'xemacs)
51   ;; must be load-time check to share .elc between w/ MULE and w/o MULE.
52   (when (featurep 'mule)
53     (provide 'file-coding)))
54
55 (static-when (featurep 'xemacs)
56   (require 'poe-xemacs))
57
58 ;; must be load-time check to share .elc between different systems.
59 (or (fboundp 'open-network-stream)
60     (require 'tcp))
61 \f
62
63 ;;; @ C primitives emulation.
64 ;;;
65
66 ;; Emacs 20.3 and earlier: (require FEATURE &optional FILENAME)
67 ;; Emacs 20.4 and later: (require FEATURE &optional FILENAME NOERROR)
68 (static-condition-case nil
69     ;; compile-time check.
70     (progn
71       (require 'nofeature "nofile" 'noerror)
72       (if (get 'require 'defun-maybe)
73           (error "`require' is already redefined")))
74   (error
75    ;; load-time check.
76    (or (fboundp 'si:require)
77        (progn
78          (fset 'si:require (symbol-function 'require))
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          ;; for `load-history'.
95          (setq current-load-list (cons 'require current-load-list))
96          (put 'require 'defun-maybe t)))))
97
98 ;; Emacs 19.29 and later: (plist-get PLIST PROP)
99 ;; (defun-maybe plist-get (plist prop)
100 ;;   (while (and plist
101 ;;               (not (eq (car plist) prop)))
102 ;;     (setq plist (cdr (cdr plist))))
103 ;;   (car (cdr plist)))
104 (static-unless (and (fboundp 'plist-get)
105                     (not (get 'plist-get 'defun-maybe)))
106   (or (fboundp 'plist-get)
107       (progn
108         (defvar plist-get-internal-symbol)
109         (defun plist-get (plist prop)
110           "\
111 Extract a value from a property list.
112 PLIST is a property list, which is a list of the form
113 \(PROP1 VALUE1 PROP2 VALUE2...\).  This function returns the value
114 corresponding to the given PROP, or nil if PROP is not
115 one of the properties on the list."
116           (setplist 'plist-get-internal-symbol plist)
117           (get 'plist-get-internal-symbol prop))
118         ;; for `load-history'.
119         (setq current-load-list (cons 'plist-get current-load-list))
120         (put 'plist-get 'defun-maybe t))))
121
122 ;; Emacs 19.29 and later: (plist-put PLIST PROP VAL)
123 ;; (defun-maybe plist-put (plist prop val)
124 ;;   (catch 'found
125 ;;     (let ((tail plist)
126 ;;           (prev nil))
127 ;;       (while (and tail (cdr tail))
128 ;;         (if (eq (car tail) prop)
129 ;;             (progn
130 ;;               (setcar (cdr tail) val)
131 ;;               (throw 'found plist))
132 ;;           (setq prev tail
133 ;;                 tail (cdr (cdr tail)))))
134 ;;       (if prev
135 ;;           (progn
136 ;;             (setcdr (cdr prev) (list prop val))
137 ;;             plist)
138 ;;         (list prop val)))))
139 (static-unless (and (fboundp 'plist-put)
140                     (not (get 'plist-put 'defun-maybe)))
141   (or (fboundp 'plist-put)
142       (progn
143         (defvar plist-put-internal-symbol)
144         (defun plist-put (plist prop val)
145           "\
146 Change value in PLIST of PROP to VAL.
147 PLIST is a property list, which is a list of the form
148 \(PROP1 VALUE1 PROP2 VALUE2 ...\).  PROP is a symbol and VAL is any object.
149 If PROP is already a property on the list, its value is set to VAL,
150 otherwise the new PROP VAL pair is added.  The new plist is returned;
151 use `\(setq x \(plist-put x prop val\)\)' to be sure to use the new value.
152 The PLIST is modified by side effects."
153           (setplist 'plist-put-internal-symbol plist)
154           (put 'plist-put-internal-symbol prop val)
155           (symbol-plist 'plist-put-internal-symbol))
156         ;; for `load-history'.
157         (setq current-load-list (cons 'plist-put current-load-list))
158         (put 'plist-put 'defun-maybe t))))
159
160 ;; Emacs 19.23 and later: (minibuffer-prompt-width)
161 (defun-maybe minibuffer-prompt-width ()
162   "Return the display width of the minibuffer prompt."
163   (save-excursion
164     (set-buffer (window-buffer (minibuffer-window)))
165     (current-column)))
166
167 ;; (read-string PROMPT &optional INITIAL-INPUT HISTORY)
168 ;; Emacs 19.29/XEmacs 19.14(?) and later takes optional 3rd arg HISTORY.
169 (static-unless (or (featurep 'xemacs)
170                    (>= emacs-major-version 20)
171                    (and (= emacs-major-version 19)
172                         (>= emacs-minor-version 29)))
173   (or (fboundp 'si:read-string)
174       (progn
175         (fset 'si:read-string (symbol-function 'read-string))
176         (defun read-string (prompt &optional initial-input history)
177           "\
178 Read a string from the minibuffer, prompting with string PROMPT.
179 If non-nil, second arg INITIAL-INPUT is a string to insert before reading.
180 The third arg HISTORY, is dummy for compatibility.
181 See `read-from-minibuffer' for details of HISTORY argument."
182           (si:read-string prompt initial-input)))))
183
184 ;; (completing-read prompt table &optional
185 ;; FSF Emacs
186 ;;      --19.7  : predicate require-match init
187 ;; 19.7 --19.34 : predicate require-match init hist
188 ;; 20.1 --      : predicate require-match init hist def inherit-input-method
189 ;; XEmacs
190 ;;      --19.(?): predicate require-match init
191 ;;      --21.2  : predicate require-match init hist
192 ;; 21.2 --      : predicate require-match init hist def
193 ;; )
194
195 ;; We support following API.
196 ;; (completing-read prompt table
197 ;;                  &optional predicate require-match init hist def)
198 (static-cond
199  ;; add 'hist' and 'def' argument.
200  ((< emacs-major-version 19)
201   (or (fboundp 'si:completing-read)
202       (progn
203         (fset 'si:completing-read (symbol-function 'completing-read))
204         (defun completing-read
205           (prompt table &optional predicate require-match init
206                                   hist def)
207         "Read a string in the minibuffer, with completion.
208 PROMPT is a string to prompt with; normally it ends in a colon and a space.
209 TABLE is an alist whose elements' cars are strings, or an obarray.
210 PREDICATE limits completion to a subset of TABLE.
211 See `try-completion' and `all-completions' for more details
212  on completion, TABLE, and PREDICATE.
213
214 If REQUIRE-MATCH is non-nil, the user is not allowed to exit unless
215  the input is (or completes to) an element of TABLE or is null.
216  If it is also not t, Return does not exit if it does non-null completion.
217 If the input is null, `completing-read' returns an empty string,
218  regardless of the value of REQUIRE-MATCH.
219
220 If INIT is non-nil, insert it in the minibuffer initially.
221   If it is (STRING . POSITION), the initial input
222   is STRING, but point is placed POSITION characters into the string.
223 HIST is ignored in this implementation.
224 DEF, if non-nil, is the default value.
225
226 Completion ignores case if the ambient value of
227   `completion-ignore-case' is non-nil."
228         (let ((string (si:completing-read prompt table predicate
229                                           require-match init)))
230           (if (and (string= string "") def)
231               def string))))))
232  ;; add 'def' argument.
233  ((or (and (featurep 'xemacs)
234            (or (and (eq emacs-major-version 21)
235                     (< emacs-minor-version 2))
236                (< emacs-major-version 21)))
237       (< emacs-major-version 20))
238   (or (fboundp 'si:completing-read)
239       (progn
240         (fset 'si:completing-read (symbol-function 'completing-read))
241         (defun completing-read
242           (prompt table &optional predicate require-match init
243                                   hist def)
244         "Read a string in the minibuffer, with completion.
245 PROMPT is a string to prompt with; normally it ends in a colon and a space.
246 TABLE is an alist whose elements' cars are strings, or an obarray.
247 PREDICATE limits completion to a subset of TABLE.
248 See `try-completion' and `all-completions' for more details
249  on completion, TABLE, and PREDICATE.
250
251 If REQUIRE-MATCH is non-nil, the user is not allowed to exit unless
252  the input is (or completes to) an element of TABLE or is null.
253  If it is also not t, Return does not exit if it does non-null completion.
254 If the input is null, `completing-read' returns an empty string,
255  regardless of the value of REQUIRE-MATCH.
256
257 If INIT is non-nil, insert it in the minibuffer initially.
258   If it is (STRING . POSITION), the initial input
259   is STRING, but point is placed POSITION characters into the string.
260 HIST, if non-nil, specifies a history list
261   and optionally the initial position in the list.
262   It can be a symbol, which is the history list variable to use,
263   or it can be a cons cell (HISTVAR . HISTPOS).
264   In that case, HISTVAR is the history list variable to use,
265   and HISTPOS is the initial position (the position in the list
266   which INIT corresponds to).
267   Positions are counted starting from 1 at the beginning of the list.
268 DEF, if non-nil, is the default value.
269
270 Completion ignores case if the ambient value of
271   `completion-ignore-case' is non-nil."
272         (let ((string (si:completing-read prompt table predicate
273                                           require-match init hist)))
274           (if (and (string= string "") def)
275               def string)))))))
276
277 ;; v18: (string-to-int STRING)
278 ;; v19: (string-to-number STRING)
279 ;; v20: (string-to-number STRING &optional BASE)
280 ;;
281 ;; XXX: `string-to-number' of Emacs 20.3 and earlier is broken.
282 ;;      (string-to-number "1e1" 16) => 10.0, should be 481.
283 (static-condition-case nil
284     ;; compile-time check.
285     (if (= (string-to-number "1e1" 16) 481)
286         (if (get 'string-to-number 'defun-maybe)
287             (error "`string-to-number' is already redefined"))
288       (error "`string-to-number' is broken"))
289   (error
290    ;; load-time check.
291    (or (fboundp 'si:string-to-number)
292        (progn
293          (if (fboundp 'string-to-number)
294              (fset 'si:string-to-number (symbol-function 'string-to-number))
295            (fset 'si:string-to-number (symbol-function 'string-to-int))
296            ;; XXX: In v18, this causes infinite loop while byte-compiling.
297            ;; (defalias 'string-to-int 'string-to-number)
298            )
299          (put 'string-to-number 'defun-maybe t)
300          (defun string-to-number (string &optional base)
301            "\
302 Convert STRING to a number by parsing it as a decimal number.
303 This parses both integers and floating point numbers.
304 It ignores leading spaces and tabs.
305
306 If BASE, interpret STRING as a number in that base.  If BASE isn't
307 present, base 10 is used.  BASE must be between 2 and 16 (inclusive).
308 If the base used is not 10, floating point is not recognized."
309            (if (or (null base) (= base 10))
310                (si:string-to-number string)
311              (if (or (< base 2)(> base 16))
312                  (signal 'args-out-of-range (cons base nil)))
313              (let ((len (length string))
314                    (pos 0))
315                ;; skip leading whitespace.
316                (while (and (< pos len)
317                            (memq (aref string pos) '(?\  ?\t)))
318                  (setq pos (1+ pos)))
319                (if (= pos len)
320                    0
321                  (let ((number 0)(negative 1)
322                        chr num)
323                    (if (eq (aref string pos) ?-)
324                        (setq negative -1
325                              pos (1+ pos))
326                      (if (eq (aref string pos) ?+)
327                          (setq pos (1+ pos))))
328                    (while (and (< pos len)
329                                (setq chr (aref string pos)
330                                      num (cond
331                                           ((and (<= ?0 chr)(<= chr ?9))
332                                            (- chr ?0))
333                                           ((and (<= ?A chr)(<= chr ?F))
334                                            (+ (- chr ?A) 10))
335                                           ((and (<= ?a chr)(<= chr ?f))
336                                            (+ (- chr ?a) 10))
337                                           (t nil)))
338                                (< num base))
339                      (setq number (+ (* number base) num)
340                            pos (1+ pos)))
341                    (* negative number))))))))))
342
343 ;; Emacs 20.1 and 20.2: (concat-chars &rest CHARS)
344 ;; Emacs 20.3/XEmacs 21.0 and later: (string &rest CHARS)
345 (static-cond
346  ((and (fboundp 'string)
347        (subrp (symbol-function 'string)))
348   ;; Emacs 20.3/XEmacs 21.0 and later.
349   )
350  ((and (fboundp 'concat-chars)
351        (subrp (symbol-function 'concat-chars)))
352   ;; Emacs 20.1 and 20.2.
353   (defalias 'string 'concat-chars))
354  (t
355   ;; Use `defun-maybe' to update `load-history'.
356   (defun-maybe string (&rest chars)
357     "Concatenate all the argument characters and make the result a string."
358     ;; We cannot use (apply 'concat chars) here because `concat' does not
359     ;; work with multibyte chars on Mule 1.* and 2.*.
360     (mapconcat (function char-to-string) chars ""))))
361
362 ;; Mule: (char-before POS)
363 ;; v20: (char-before &optional POS)
364 (static-condition-case nil
365     ;; compile-time check.
366     (progn
367       (char-before)
368       (if (get 'char-before 'defun-maybe)
369           (error "`char-before' is already defined")))
370   (wrong-number-of-arguments            ; Mule.
371    ;; load-time check.
372    (or (fboundp 'si:char-before)
373        (progn
374          (fset 'si:char-before (symbol-function 'char-before))
375          (put 'char-before 'defun-maybe t)
376          ;; takes IGNORED for backward compatibility.
377          (defun char-before (&optional pos ignored)
378            "\
379 Return character in current buffer preceding position POS.
380 POS is an integer or a buffer pointer.
381 If POS is out of range, the value is nil."
382            (si:char-before (or pos (point)))))))
383   (void-function                        ; non-Mule.
384    ;; load-time check.
385    (defun-maybe char-before (&optional pos)
386      "\
387 Return character in current buffer preceding position POS.
388 POS is an integer or a buffer pointer.
389 If POS is out of range, the value is nil."
390      (if pos
391          (save-excursion
392            (and (= (goto-char pos) (point))
393                 (not (bobp))
394                 (preceding-char)))
395        (and (not (bobp))
396             (preceding-char)))))
397   (error                                ; found our definition at compile-time.
398    ;; load-time check.
399    (condition-case nil
400        (char-before)
401      (wrong-number-of-arguments         ; Mule.
402       (or (fboundp 'si:char-before)
403           (progn
404             (fset 'si:char-before (symbol-function 'char-before))
405             (put 'char-before 'defun-maybe t)
406             ;; takes IGNORED for backward compatibility.
407             (defun char-before (&optional pos ignored)
408               "\
409 Return character in current buffer preceding position POS.
410 POS is an integer or a buffer pointer.
411 If POS is out of range, the value is nil."
412               (si:char-before (or pos (point)))))))
413      (void-function                     ; non-Mule.
414       (defun-maybe char-before (&optional pos)
415         "\
416 Return character in current buffer preceding position POS.
417 POS is an integer or a buffer pointer.
418 If POS is out of range, the value is nil."
419         (if pos
420             (save-excursion
421               (and (= (goto-char pos) (point))
422                    (not (bobp))
423                    (preceding-char)))
424           (and (not (bobp))
425                (preceding-char))))))))
426
427 ;; v18, v19: (char-after POS)
428 ;; v20: (char-after &optional POS)
429 (static-condition-case nil
430     ;; compile-time check.
431     (progn
432       (char-after)
433       (if (get 'char-after 'defun-maybe)
434           (error "`char-after' is already redefined")))
435   (wrong-number-of-arguments            ; v18, v19
436    ;; load-time check.
437    (or (fboundp 'si:char-after)
438        (progn
439          (fset 'si:char-after (symbol-function 'char-after))
440          (put 'char-after 'defun-maybe t)
441          (defun char-after (&optional pos)
442            "\
443 Return character in current buffer at position POS.
444 POS is an integer or a buffer pointer.
445 If POS is out of range, the value is nil."
446            (si:char-after (or pos (point)))))))
447   (void-function                        ; NEVER happen?
448    ;; load-time check.
449    (defun-maybe char-after (&optional pos)
450      "\
451 Return character in current buffer at position POS.
452 POS is an integer or a buffer pointer.
453 If POS is out of range, the value is nil."
454      (if pos
455          (save-excursion
456            (and (= (goto-char pos) (point))
457                 (not (eobp))
458                 (following-char)))
459        (and (not (eobp))
460             (following-char)))))
461   (error                                ; found our definition at compile-time.
462    ;; load-time check.
463    (condition-case nil
464        (char-after)
465      (wrong-number-of-arguments         ; v18, v19
466       (or (fboundp 'si:char-after)
467           (progn
468             (fset 'si:char-after (symbol-function 'char-after))
469             (put 'char-after 'defun-maybe t)
470             (defun char-after (&optional pos)
471               "\
472 Return character in current buffer at position POS.
473 POS is an integer or a buffer pointer.
474 If POS is out of range, the value is nil."
475               (si:char-after (or pos (point)))))))
476      (void-function                     ; NEVER happen?
477       (defun-maybe char-after (&optional pos)
478         "\
479 Return character in current buffer at position POS.
480 POS is an integer or a buffer pointer.
481 If POS is out of range, the value is nil."
482         (if pos
483             (save-excursion
484               (and (= (goto-char pos) (point))
485                    (not (eobp))
486                    (following-char)))
487           (and (not (eobp))
488                (following-char))))))))
489
490 ;; Emacs 19.29 and later: (buffer-substring-no-properties START END)
491 (defun-maybe buffer-substring-no-properties (start end)
492   "Return the characters of part of the buffer, without the text properties.
493 The two arguments START and END are character positions;
494 they can be in either order."
495   (let ((string (buffer-substring start end)))
496     (set-text-properties 0 (length string) nil string)
497     string))
498
499 ;; Emacs 19.31 and later: (buffer-live-p OBJECT)
500 (defun-maybe buffer-live-p (object)
501   "Return non-nil if OBJECT is a buffer which has not been killed.
502 Value is nil if OBJECT is not a buffer or if it has been killed."
503   (and object
504        (get-buffer object)
505        (buffer-name (get-buffer object))
506        t))
507
508 ;; Emacs 20: (line-beginning-position &optional N)
509 (defun-maybe line-beginning-position (&optional n)
510   "Return the character position of the first character on the current line.
511 With argument N not nil or 1, move forward N - 1 lines first.
512 If scan reaches end of buffer, return that position.
513 This function does not move point."
514   (save-excursion
515     (forward-line (1- (or n 1)))
516     (point)))
517
518 ;; Emacs 20: (line-end-position &optional N)
519 (defun-maybe line-end-position (&optional n)
520   "Return the character position of the last character on the current line.
521 With argument N not nil or 1, move forward N - 1 lines first.
522 If scan reaches end of buffer, return that position.
523 This function does not move point."
524   (save-excursion
525     (end-of-line (or n 1))
526     (point)))
527
528 ;; FSF Emacs 19.29 and later
529 ;; (read-file-name PROMPT &optional DIR DEFAULT-FILENAME MUSTMATCH INITIAL)
530 ;; XEmacs 19.14 and later:
531 ;; (read-file-name (PROMPT &optional DIR DEFAULT MUST-MATCH INITIAL-CONTENTS
532 ;;                         HISTORY)
533
534 ;; In FSF Emacs 19.28 and earlier (except for v18) or XEmacs 19.13 and
535 ;; earlier, this function is incompatible with the other Emacsen.
536 ;; For instance, if DEFAULT-FILENAME is nil, INITIAL is not and user
537 ;; enters a null string, it returns the visited file name of the current
538 ;; buffer if it is non-nil.
539
540 ;; It does not assimilate the different numbers of the optional arguments
541 ;; on various Emacsen (yet).
542 (static-cond
543  ((and (not (featurep 'xemacs))
544        (eq emacs-major-version 19)
545        (< emacs-minor-version 29))
546   (if (fboundp 'si:read-file-name)
547       nil
548     (fset 'si:read-file-name (symbol-function 'read-file-name))
549     (defun read-file-name (prompt &optional dir default-filename mustmatch
550                                   initial)
551       "Read file name, prompting with PROMPT and completing in directory DIR.
552 Value is not expanded---you must call `expand-file-name' yourself.
553 Default name to DEFAULT-FILENAME if user enters a null string.
554  (If DEFAULT-FILENAME is omitted, the visited file name is used,
555   except that if INITIAL is specified, that combined with DIR is used.)
556 Fourth arg MUSTMATCH non-nil means require existing file's name.
557  Non-nil and non-t means also require confirmation after completion.
558 Fifth arg INITIAL specifies text to start with.
559 DIR defaults to current buffer's directory default."
560       (si:read-file-name prompt dir
561                          (or default-filename
562                              (if initial
563                                  (expand-file-name initial dir)))
564                          mustmatch initial))))
565  ((and (featurep 'xemacs)
566        (eq emacs-major-version 19)
567        (< emacs-minor-version 14))
568   (if (fboundp 'si:read-file-name)
569       nil
570     (fset 'si:read-file-name (symbol-function 'read-file-name))
571     (defun read-file-name (prompt &optional dir default must-match
572                                   initial-contents history)
573       "Read file name, prompting with PROMPT and completing in directory DIR.
574 This will prompt with a dialog box if appropriate, according to
575  `should-use-dialog-box-p'.
576 Value is not expanded---you must call `expand-file-name' yourself.
577 Value is subject to interpreted by substitute-in-file-name however.
578 Default name to DEFAULT if user enters a null string.
579  (If DEFAULT is omitted, the visited file name is used,
580   except that if INITIAL-CONTENTS is specified, that combined with DIR is
581   used.)
582 Fourth arg MUST-MATCH non-nil means require existing file's name.
583  Non-nil and non-t means also require confirmation after completion.
584 Fifth arg INITIAL-CONTENTS specifies text to start with.
585 Sixth arg HISTORY specifies the history list to use.  Default is
586  `file-name-history'.
587 DIR defaults to current buffer's directory default."
588       (si:read-file-name prompt dir
589                          (or default
590                              (if initial-contents
591                                  (expand-file-name initial-contents dir)))
592                          must-match initial-contents history)))))
593 \f
594
595 ;;; @ Basic lisp subroutines emulation. (lisp/subr.el)
596 ;;;
597
598 ;;; @@ Lisp language features.
599
600 (defmacro-maybe push (newelt listname)
601   "Add NEWELT to the list stored in the symbol LISTNAME.
602 This is equivalent to (setq LISTNAME (cons NEWELT LISTNAME)).
603 LISTNAME must be a symbol."
604   (list 'setq listname
605         (list 'cons newelt listname)))
606
607 (defmacro-maybe pop (listname)
608   "Return the first element of LISTNAME's value, and remove it from the list.
609 LISTNAME must be a symbol whose value is a list.
610 If the value is nil, `pop' returns nil but does not actually
611 change the list."
612   (list 'prog1 (list 'car listname)
613         (list 'setq listname (list 'cdr listname))))
614
615 (defmacro-maybe when (cond &rest body)
616   "If COND yields non-nil, do BODY, else return nil."
617   (list 'if cond (cons 'progn body)))
618 ;; (def-edebug-spec when (&rest form))
619
620 (defmacro-maybe unless (cond &rest body)
621   "If COND yields nil, do BODY, else return nil."
622   (cons 'if (cons cond (cons nil body))))
623 ;; (def-edebug-spec unless (&rest form))
624
625 (defsubst-maybe caar (x)
626   "Return the car of the car of X."
627   (car (car x)))
628
629 (defsubst-maybe cadr (x)
630   "Return the car of the cdr of X."
631   (car (cdr x)))
632
633 (defsubst-maybe cdar (x)
634   "Return the cdr of the car of X."
635   (cdr (car x)))
636
637 (defsubst-maybe cddr (x)
638   "Return the cdr of the cdr of X."
639   (cdr (cdr x)))
640
641 (defun-maybe last (x &optional n)
642   "Return the last link of the list X.  Its car is the last element.
643 If X is nil, return nil.
644 If N is non-nil, return the Nth-to-last link of X.
645 If N is bigger than the length of X, return X."
646   (if n
647       (let ((m 0) (p x))
648         (while (consp p)
649           (setq m (1+ m) p (cdr p)))
650         (if (<= n 0) p
651           (if (< n m) (nthcdr (- m n) x) x)))
652     (while (cdr x)
653       (setq x (cdr x)))
654     x))
655
656 ;; Actually, `butlast' and `nbutlast' are defined in lisp/cl.el.
657 (defun-maybe butlast (x &optional n)
658   "Returns a copy of LIST with the last N elements removed."
659   (if (and n (<= n 0)) x
660     (nbutlast (copy-sequence x) n)))
661
662 (defun-maybe nbutlast (x &optional n)
663   "Modifies LIST to remove the last N elements."
664   (let ((m (length x)))
665     (or n (setq n 1))
666     (and (< n m)
667          (progn
668            (if (> n 0) (setcdr (nthcdr (- (1- m) n) x) nil))
669            x))))
670
671 ;; Emacs 20.3 and later: (assoc-default KEY ALIST &optional TEST DEFAULT)
672 (defun-maybe assoc-default (key alist &optional test default)
673   "Find object KEY in a pseudo-alist ALIST.
674 ALIST is a list of conses or objects.  Each element (or the element's car,
675 if it is a cons) is compared with KEY by evaluating (TEST (car elt) KEY).
676 If that is non-nil, the element matches;
677 then `assoc-default' returns the element's cdr, if it is a cons,
678 or DEFAULT if the element is not a cons.
679
680 If no element matches, the value is nil.
681 If TEST is omitted or nil, `equal' is used."
682   (let (found (tail alist) value)
683     (while (and tail (not found))
684       (let ((elt (car tail)))
685         (when (funcall (or test 'equal) (if (consp elt) (car elt) elt) key)
686           (setq found t value (if (consp elt) (cdr elt) default))))
687       (setq tail (cdr tail)))
688     value))
689
690 ;; The following two function use `compare-strings', which we don't
691 ;; support yet.
692 ;; (defun assoc-ignore-case (key alist))
693 ;; (defun assoc-ignore-representation (key alist))
694
695 ;; Emacs 19.29/XEmacs 19.13 and later: (rassoc KEY LIST)
696 ;; Actually, `rassoc' is defined in src/fns.c.
697 (defun-maybe rassoc (key list)
698   "Return non-nil if KEY is `equal' to the cdr of an element of LIST.
699 The value is actually the element of LIST whose cdr equals KEY.
700 Elements of LIST that are not conses are ignored."
701   (catch 'found
702     (while list
703       (cond ((not (consp (car list))))
704             ((equal (cdr (car list)) key)
705              (throw 'found (car list))))
706       (setq list (cdr list)))))
707
708 ;; XEmacs 19.13 and later: (remassoc KEY ALIST)
709 (defun-maybe remassoc (key alist)
710   "Delete by side effect any elements of ALIST whose car is `equal' to KEY.
711 The modified ALIST is returned.  If the first member of ALIST has a car
712 that is `equal' to KEY, there is no way to remove it by side effect;
713 therefore, write `(setq foo (remassoc key foo))' to be sure of changing
714 the value of `foo'."
715   (while (and (consp alist)
716               (or (not (consp (car alist)))
717                   (equal (car (car alist)) key)))
718     (setq alist (cdr alist)))
719   (if (consp alist)
720       (let ((prev alist)
721             (tail (cdr alist)))
722         (while (consp tail)
723           (if (and (consp (car alist))
724                    (equal (car (car tail)) key))
725               ;; `(setcdr CELL NEWCDR)' returns NEWCDR.
726               (setq tail (setcdr prev (cdr tail)))
727             (setq prev (cdr prev)
728                   tail (cdr tail))))))
729   alist)
730
731 ;; XEmacs 19.13 and later: (remassq KEY ALIST)
732 (defun-maybe remassq (key alist)
733   "Delete by side effect any elements of ALIST whose car is `eq' to KEY.
734 The modified ALIST is returned.  If the first member of ALIST has a car
735 that is `eq' to KEY, there is no way to remove it by side effect;
736 therefore, write `(setq foo (remassq key foo))' to be sure of changing
737 the value of `foo'."
738   (while (and (consp alist)
739               (or (not (consp (car alist)))
740                   (eq (car (car alist)) key)))
741     (setq alist (cdr alist)))
742   (if (consp alist)
743       (let ((prev alist)
744             (tail (cdr alist)))
745         (while (consp tail)
746           (if (and (consp (car tail))
747                    (eq (car (car tail)) key))
748               ;; `(setcdr CELL NEWCDR)' returns NEWCDR.
749               (setq tail (setcdr prev (cdr tail)))
750             (setq prev (cdr prev)
751                   tail (cdr tail))))))
752   alist)
753
754 ;; XEmacs 19.13 and later: (remrassoc VALUE ALIST)
755 (defun-maybe remrassoc (value alist)
756   "Delete by side effect any elements of ALIST whose cdr is `equal' to VALUE.
757 The modified ALIST is returned.  If the first member of ALIST has a car
758 that is `equal' to VALUE, there is no way to remove it by side effect;
759 therefore, write `(setq foo (remrassoc value foo))' to be sure of changing
760 the value of `foo'."
761   (while (and (consp alist)
762               (or (not (consp (car alist)))
763                   (equal (cdr (car alist)) value)))
764     (setq alist (cdr alist)))
765   (if (consp alist)
766       (let ((prev alist)
767             (tail (cdr alist)))
768         (while (consp tail)
769           (if (and (consp (car tail))
770                    (equal (cdr (car tail)) value))
771               ;; `(setcdr CELL NEWCDR)' returns NEWCDR.
772               (setq tail (setcdr prev (cdr tail)))
773             (setq prev (cdr prev)
774                   tail (cdr tail))))))
775   alist)
776
777 ;; XEmacs 19.13 and later: (remrassq VALUE ALIST)
778 (defun-maybe remrassq (value alist)
779   "Delete by side effect any elements of ALIST whose cdr is `eq' to VALUE.
780 The modified ALIST is returned.  If the first member of ALIST has a car
781 that is `eq' to VALUE, there is no way to remove it by side effect;
782 therefore, write `(setq foo (remrassq value foo))' to be sure of changing
783 the value of `foo'."
784   (while (and (consp alist)
785               (or (not (consp (car alist)))
786                   (eq (cdr (car alist)) value)))
787     (setq alist (cdr alist)))
788   (if (consp alist)
789       (let ((prev alist)
790             (tail (cdr alist)))
791         (while (consp tail)
792           (if (and (consp (car tail))
793                    (eq (cdr (car tail)) value))
794               ;; `(setcdr CELL NEWCDR)' returns NEWCDR.
795               (setq tail (setcdr prev (cdr tail)))
796             (setq prev (cdr prev)
797                   tail (cdr tail))))))
798   alist)
799
800 ;;; Define `functionp' here because "localhook" uses it.
801
802 ;; Emacs 20.1/XEmacs 20.3 (but first appeared in Epoch?): (functionp OBJECT)
803 (defun-maybe functionp (object)
804   "Non-nil if OBJECT is a type of object that can be called as a function."
805   (or (subrp object) (byte-code-function-p object)
806       (eq (car-safe object) 'lambda)
807       (and (symbolp object) (fboundp object))))
808
809 ;;; @@ Hook manipulation functions.
810
811 ;; "localhook" package is written for Emacs 19.28 and earlier.
812 ;; `run-hooks' was a lisp function in Emacs 19.29 and earlier.
813 ;; So, in Emacs 19.29, `run-hooks' and others will be overrided.
814 ;; But, who cares it?
815 (static-unless (subrp (symbol-function 'run-hooks))
816   (require 'localhook))
817
818 ;; Emacs 19.29/XEmacs 19.14(?) and later: (add-to-list LIST-VAR ELEMENT)
819 (defun-maybe add-to-list (list-var element)
820   "Add to the value of LIST-VAR the element ELEMENT if it isn't there yet.
821 The test for presence of ELEMENT is done with `equal'.
822 If you want to use `add-to-list' on a variable that is not defined
823 until a certain package is loaded, you should put the call to `add-to-list'
824 into a hook function that will be run only after loading the package.
825 `eval-after-load' provides one way to do this.  In some cases
826 other hooks, such as major mode hooks, can do the job."
827   (or (member element (symbol-value list-var))
828       (set list-var (cons element (symbol-value list-var)))))
829
830 ;; (eval-after-load FILE FORM)
831 ;; Emacs 19.28 and earlier do not evaluate FORM if FILE is already loaded.
832 ;; XEmacs 20.2 and earlier have `after-load-alist', but refuse to support
833 ;; `eval-after-load'. (see comments in XEmacs/lisp/subr.el.)
834 (static-cond
835  ((featurep 'xemacs)
836   ;; for XEmacs 20.2 and earlier.
837   (defun-maybe eval-after-load (file form)
838     "Arrange that, if FILE is ever loaded, FORM will be run at that time.
839 This makes or adds to an entry on `after-load-alist'.
840 If FILE is already loaded, evaluate FORM right now.
841 It does nothing if FORM is already on the list for FILE.
842 FILE should be the name of a library, with no directory name."
843     ;; Make sure there is an element for FILE.
844     (or (assoc file after-load-alist)
845         (setq after-load-alist (cons (list file) after-load-alist)))
846     ;; Add FORM to the element if it isn't there.
847     (let ((elt (assoc file after-load-alist)))
848       (or (member form (cdr elt))
849           (progn
850             (nconc elt (list form))
851             ;; If the file has been loaded already, run FORM right away.
852             (and (assoc file load-history)
853                  (eval form)))))
854     form))
855  ((>= emacs-major-version 20))
856  ((and (= emacs-major-version 19)
857        (< emacs-minor-version 29))
858   ;; for Emacs 19.28 and earlier.
859   (defun eval-after-load (file form)
860     "Arrange that, if FILE is ever loaded, FORM will be run at that time.
861 This makes or adds to an entry on `after-load-alist'.
862 If FILE is already loaded, evaluate FORM right now.
863 It does nothing if FORM is already on the list for FILE.
864 FILE should be the name of a library, with no directory name."
865     ;; Make sure there is an element for FILE.
866     (or (assoc file after-load-alist)
867         (setq after-load-alist (cons (list file) after-load-alist)))
868     ;; Add FORM to the element if it isn't there.
869     (let ((elt (assoc file after-load-alist)))
870       (or (member form (cdr elt))
871           (progn
872             (nconc elt (list form))
873             ;; If the file has been loaded already, run FORM right away.
874             (and (assoc file load-history)
875                  (eval form)))))
876     form))
877  (t
878   ;; should emulate for v18?
879   ))
880
881 (defun-maybe eval-next-after-load (file)
882   "Read the following input sexp, and run it whenever FILE is loaded.
883 This makes or adds to an entry on `after-load-alist'.
884 FILE should be the name of a library, with no directory name."
885   (eval-after-load file (read)))
886
887 ;;; @@ Input and display facilities.
888
889 ;; XXX: (defun read-passwd (prompt &optional confirm default))
890
891 ;;; @@ Miscellanea.
892
893 ;; Avoid compiler warnings about this variable,
894 ;; which has a special meaning on certain system types.
895 (defvar-maybe buffer-file-type nil
896   "Non-nil if the visited file is a binary file.
897 This variable is meaningful on MS-DOG and Windows NT.
898 On those systems, it is automatically local in every buffer.
899 On other systems, this variable is normally always nil.")
900
901 ;; Emacs 20.3 or later.
902 (defvar-maybe minor-mode-overriding-map-alist nil
903   "Alist of keymaps to use for minor modes, in current major mode.
904 APEL provides this as dummy for compatibility.")
905
906 ;; Emacs 20.1/XEmacs 20.3(?) and later: (save-current-buffer &rest BODY)
907 ;;
908 ;; v20 defines `save-current-buffer' as a C primitive (in src/editfns.c)
909 ;; and introduces a new bytecode Bsave_current_buffer(_1), replacing an
910 ;; obsolete bytecode Bread_char.  To make things worse, Emacs 20.1 and
911 ;; 20.2 have a bug that it will restore the current buffer without
912 ;; confirming that it is alive.
913 ;;
914 ;; This is a source of incompatibility of .elc between v18/v19 and v20.
915 ;; (XEmacs compiler takes care of it if compatibility mode is enabled.)
916 (defmacro-maybe save-current-buffer (&rest body)
917   "Save the current buffer; execute BODY; restore the current buffer.
918 Executes BODY just like `progn'."
919   (` (let ((orig-buffer (current-buffer)))
920        (unwind-protect
921            (progn (,@ body))
922          (if (buffer-live-p orig-buffer)
923              (set-buffer orig-buffer))))))
924
925 ;; Emacs 20.1/XEmacs 20.3(?) and later: (with-current-buffer BUFFER &rest BODY)
926 (defmacro-maybe with-current-buffer (buffer &rest body)
927   "Execute the forms in BODY with BUFFER as the current buffer.
928 The value returned is the value of the last form in BODY.
929 See also `with-temp-buffer'."
930   (` (save-current-buffer
931        (set-buffer (, buffer))
932        (,@ body))))
933
934 ;; Emacs 20.1/XEmacs 20.3(?) and later: (with-temp-file FILE &rest FORMS)
935 (defmacro-maybe with-temp-file (file &rest forms)
936   "Create a new buffer, evaluate FORMS there, and write the buffer to FILE.
937 The value of the last form in FORMS is returned, like `progn'.
938 See also `with-temp-buffer'."
939   (let ((temp-file (make-symbol "temp-file"))
940         (temp-buffer (make-symbol "temp-buffer")))
941     (` (let (((, temp-file) (, file))
942              ((, temp-buffer)
943               (get-buffer-create (generate-new-buffer-name " *temp file*"))))
944          (unwind-protect
945              (prog1
946                  (with-current-buffer (, temp-buffer)
947                    (,@ forms))
948                (with-current-buffer (, temp-buffer)
949                  (widen)
950                  (write-region (point-min) (point-max) (, temp-file) nil 0)))
951            (and (buffer-name (, temp-buffer))
952                 (kill-buffer (, temp-buffer))))))))
953
954 ;; Emacs 20.4 and later: (with-temp-message MESSAGE &rest BODY)
955 ;; This macro uses `current-message', which appears in v20.
956 (static-when (and (fboundp 'current-message)
957                   (subrp (symbol-function 'current-message)))
958   (defmacro-maybe with-temp-message (message &rest body)
959     "\
960 Display MESSAGE temporarily if non-nil while BODY is evaluated.
961 The original message is restored to the echo area after BODY has finished.
962 The value returned is the value of the last form in BODY.
963 MESSAGE is written to the message log buffer if `message-log-max' is non-nil.
964 If MESSAGE is nil, the echo area and message log buffer are unchanged.
965 Use a MESSAGE of \"\" to temporarily clear the echo area."
966     (let ((current-message (make-symbol "current-message"))
967           (temp-message (make-symbol "with-temp-message")))
968       (` (let (((, temp-message) (, message))
969                ((, current-message)))
970            (unwind-protect
971                (progn
972                  (when (, temp-message)
973                    (setq (, current-message) (current-message))
974                    (message "%s" (, temp-message))
975                    (,@ body))
976                  (and (, temp-message) (, current-message)
977                       (message "%s" (, current-message))))))))))
978
979 ;; Emacs 20.1/XEmacs 20.3(?) and later: (with-temp-buffer &rest FORMS)
980 (defmacro-maybe with-temp-buffer (&rest forms)
981   "Create a temporary buffer, and evaluate FORMS there like `progn'.
982 See also `with-temp-file' and `with-output-to-string'."
983   (let ((temp-buffer (make-symbol "temp-buffer")))
984     (` (let (((, temp-buffer)
985               (get-buffer-create (generate-new-buffer-name " *temp*"))))
986          (unwind-protect
987              (with-current-buffer (, temp-buffer)
988                (,@ forms))
989            (and (buffer-name (, temp-buffer))
990                 (kill-buffer (, temp-buffer))))))))
991
992 ;; Emacs 20.1/XEmacs 20.3(?) and later: (with-output-to-string &rest BODY)
993 (defmacro-maybe with-output-to-string (&rest body)
994   "Execute BODY, return the text it sent to `standard-output', as a string."
995   (` (let ((standard-output
996             (get-buffer-create (generate-new-buffer-name " *string-output*"))))
997        (let ((standard-output standard-output))
998          (,@ body))
999        (with-current-buffer standard-output
1000          (prog1
1001              (buffer-string)
1002            (kill-buffer nil))))))
1003
1004 ;; Emacs 20.1 and later: (combine-after-change-calls &rest BODY)
1005 (defmacro-maybe combine-after-change-calls (&rest body)
1006   "Execute BODY, but don't call the after-change functions till the end.
1007 If BODY makes changes in the buffer, they are recorded
1008 and the functions on `after-change-functions' are called several times
1009 when BODY is finished.
1010 The return value is the value of the last form in BODY.
1011
1012 If `before-change-functions' is non-nil, then calls to the after-change
1013 functions can't be deferred, so in that case this macro has no effect.
1014
1015 Do not alter `after-change-functions' or `before-change-functions'
1016 in BODY.
1017
1018 This emulating macro does not support after-change functions at all,
1019 just execute BODY."
1020   (cons 'progn body))
1021
1022 ;; Emacs 19.29/XEmacs 19.14(?) and later: (match-string NUM &optional STRING)
1023 (defun-maybe match-string (num &optional string)
1024   "Return string of text matched by last search.
1025 NUM specifies which parenthesized expression in the last regexp.
1026  Value is nil if NUMth pair didn't match, or there were less than NUM pairs.
1027 Zero means the entire text matched by the whole regexp or whole string.
1028 STRING should be given if the last search was by `string-match' on STRING."
1029   (if (match-beginning num)
1030       (if string
1031           (substring string (match-beginning num) (match-end num))
1032         (buffer-substring (match-beginning num) (match-end num)))))
1033
1034 ;; Emacs 20.3 and later: (match-string-no-properties NUM &optional STRING)
1035 (defun-maybe match-string-no-properties (num &optional string)
1036   "Return string of text matched by last search, without text properties.
1037 NUM specifies which parenthesized expression in the last regexp.
1038  Value is nil if NUMth pair didn't match, or there were less than NUM pairs.
1039 Zero means the entire text matched by the whole regexp or whole string.
1040 STRING should be given if the last search was by `string-match' on STRING."
1041   (if (match-beginning num)
1042       (if string
1043           (let ((result
1044                  (substring string (match-beginning num) (match-end num))))
1045             (set-text-properties 0 (length result) nil result)
1046             result)
1047         (buffer-substring-no-properties (match-beginning num)
1048                                         (match-end num)))))
1049
1050 ;; Emacs 19.28 and earlier
1051 ;;  (replace-match NEWTEXT &optional FIXEDCASE LITERAL)
1052 ;; Emacs 20.x (?) and later
1053 ;;  (replace-match NEWTEXT &optional FIXEDCASE LITERAL STRING SUBEXP)
1054 ;; XEmacs 21:
1055 ;;  (replace-match NEWTEXT &optional FIXEDCASE LITERAL STRING STRBUFFER)
1056 ;; We support following API.
1057 ;;  (replace-match NEWTEXT &optional FIXEDCASE LITERAL STRING)
1058 (static-condition-case nil
1059     ;; compile-time check
1060     (progn
1061       (string-match "" "")
1062       (replace-match "" nil nil "")
1063       (if (get 'replace-match 'defun-maybe)
1064           (error "`replace-match' is already defined")))
1065   (wrong-number-of-arguments ; Emacs 19.28 and earlier
1066    ;; load-time check.
1067    (or (fboundp 'si:replace-match)
1068        (progn
1069          (fset 'si:replace-match (symbol-function 'replace-match))
1070          (put 'replace-match 'defun-maybe t)
1071          (defun replace-match (newtext &optional fixedcase literal string)
1072            "Replace text matched by last search with NEWTEXT.
1073 If second arg FIXEDCASE is non-nil, do not alter case of replacement text.
1074 Otherwise maybe capitalize the whole text, or maybe just word initials,
1075 based on the replaced text.
1076 If the replaced text has only capital letters
1077 and has at least one multiletter word, convert NEWTEXT to all caps.
1078 If the replaced text has at least one word starting with a capital letter,
1079 then capitalize each word in NEWTEXT.
1080
1081 If third arg LITERAL is non-nil, insert NEWTEXT literally.
1082 Otherwise treat `\' as special:
1083   `\&' in NEWTEXT means substitute original matched text.
1084   `\N' means substitute what matched the Nth `\(...\)'.
1085        If Nth parens didn't match, substitute nothing.
1086   `\\' means insert one `\'.
1087 FIXEDCASE and LITERAL are optional arguments.
1088 Leaves point at end of replacement text.
1089
1090 The optional fourth argument STRING can be a string to modify.
1091 In that case, this function creates and returns a new string
1092 which is made by replacing the part of STRING that was matched."
1093            (if string
1094                (with-temp-buffer
1095                 (save-match-data
1096                   (insert string)
1097                   (let* ((matched (match-data))
1098                          (beg (nth 0 matched))
1099                          (end (nth 1 matched)))
1100                     (store-match-data
1101                      (list
1102                       (if (markerp beg)
1103                           (move-marker beg (1+ (match-beginning 0)))
1104                         (1+ (match-beginning 0)))
1105                       (if (markerp end)
1106                           (move-marker end (1+ (match-end 0)))
1107                         (1+ (match-end 0))))))
1108                   (si:replace-match newtext fixedcase literal)
1109                   (buffer-string)))
1110              (si:replace-match newtext fixedcase literal))))))
1111   (error ; found our definition at compile-time.
1112    ;; load-time check.
1113    (condition-case nil
1114     (progn
1115       (string-match "" "")
1116       (replace-match "" nil nil ""))
1117     (wrong-number-of-arguments ; Emacs 19.28 and earlier
1118      ;; load-time check.
1119      (or (fboundp 'si:replace-match)
1120          (progn
1121            (fset 'si:replace-match (symbol-function 'replace-match))
1122            (put 'replace-match 'defun-maybe t)
1123            (defun replace-match (newtext &optional fixedcase literal string)
1124              "Replace text matched by last search with NEWTEXT.
1125 If second arg FIXEDCASE is non-nil, do not alter case of replacement text.
1126 Otherwise maybe capitalize the whole text, or maybe just word initials,
1127 based on the replaced text.
1128 If the replaced text has only capital letters
1129 and has at least one multiletter word, convert NEWTEXT to all caps.
1130 If the replaced text has at least one word starting with a capital letter,
1131 then capitalize each word in NEWTEXT.
1132
1133 If third arg LITERAL is non-nil, insert NEWTEXT literally.
1134 Otherwise treat `\' as special:
1135   `\&' in NEWTEXT means substitute original matched text.
1136   `\N' means substitute what matched the Nth `\(...\)'.
1137        If Nth parens didn't match, substitute nothing.
1138   `\\' means insert one `\'.
1139 FIXEDCASE and LITERAL are optional arguments.
1140 Leaves point at end of replacement text.
1141
1142 The optional fourth argument STRING can be a string to modify.
1143 In that case, this function creates and returns a new string
1144 which is made by replacing the part of STRING that was matched."
1145              (if string
1146                  (with-temp-buffer
1147                   (save-match-data
1148                     (insert string)
1149                     (let* ((matched (match-data))
1150                            (beg (nth 0 matched))
1151                            (end (nth 1 matched)))
1152                       (store-match-data
1153                        (list
1154                         (if (markerp beg)
1155                             (move-marker beg (1+ (match-beginning 0)))
1156                           (1+ (match-beginning 0)))
1157                         (if (markerp end)
1158                             (move-marker end (1+ (match-end 0)))
1159                           (1+ (match-end 0))))))
1160                     (si:replace-match newtext fixedcase literal)
1161                     (buffer-string)))
1162                (si:replace-match newtext fixedcase literal)))))))))
1163
1164 ;; Emacs 20: (format-time-string FORMAT &optional TIME UNIVERSAL)
1165 ;; Those format constructs are yet to be implemented.
1166 ;;   %c, %C, %j, %U, %W, %x, %X
1167 ;; Not fully compatible especially when invalid format is specified.
1168 (static-unless (and (fboundp 'format-time-string)
1169                     (not (get 'format-time-string 'defun-maybe)))
1170   (or (fboundp 'format-time-string)
1171   (progn
1172   (defconst format-time-month-list
1173     '(( "Zero" . ("Zero" . 0))
1174       ("Jan" . ("January" . 1)) ("Feb" . ("February" . 2))
1175       ("Mar" . ("March" . 3)) ("Apr" . ("April" . 4)) ("May" . ("May" . 5))
1176       ("Jun" . ("June" . 6))("Jul" . ("July" . 7)) ("Aug" . ("August" . 8))
1177       ("Sep" . ("September" . 9)) ("Oct" . ("October" . 10))
1178       ("Nov" . ("November" . 11)) ("Dec" . ("December" . 12)))
1179     "Alist of months and their number.")
1180
1181   (defconst format-time-week-list
1182     '(("Sun" . ("Sunday" . 0)) ("Mon" . ("Monday" . 1))
1183       ("Tue" . ("Tuesday" . 2)) ("Wed" . ("Wednesday" . 3))
1184       ("Thu" . ("Thursday" . 4)) ("Fri" . ("Friday" . 5))
1185       ("Sat" . ("Saturday" . 6)))
1186     "Alist of weeks and their number.")
1187
1188   (defun format-time-string (format &optional time universal)
1189     "Use FORMAT-STRING to format the time TIME, or now if omitted.
1190 TIME is specified as (HIGH LOW . IGNORED) or (HIGH . LOW), as returned by
1191 `current-time' or `file-attributes'.
1192 The third, optional, argument UNIVERSAL, if non-nil, means describe TIME
1193 as Universal Time; nil means describe TIME in the local time zone.
1194 The value is a copy of FORMAT-STRING, but with certain constructs replaced
1195 by text that describes the specified date and time in TIME:
1196
1197 %Y is the year, %y within the century, %C the century.
1198 %G is the year corresponding to the ISO week, %g within the century.
1199 %m is the numeric month.
1200 %b and %h are the locale's abbreviated month name, %B the full name.
1201 %d is the day of the month, zero-padded, %e is blank-padded.
1202 %u is the numeric day of week from 1 (Monday) to 7, %w from 0 (Sunday) to 6.
1203 %a is the locale's abbreviated name of the day of week, %A the full name.
1204 %U is the week number starting on Sunday, %W starting on Monday,
1205  %V according to ISO 8601.
1206 %j is the day of the year.
1207
1208 %H is the hour on a 24-hour clock, %I is on a 12-hour clock, %k is like %H
1209  only blank-padded, %l is like %I blank-padded.
1210 %p is the locale's equivalent of either AM or PM.
1211 %M is the minute.
1212 %S is the second.
1213 %Z is the time zone name, %z is the numeric form.
1214 %s is the number of seconds since 1970-01-01 00:00:00 +0000.
1215
1216 %c is the locale's date and time format.
1217 %x is the locale's \"preferred\" date format.
1218 %D is like \"%m/%d/%y\".
1219
1220 %R is like \"%H:%M\", %T is like \"%H:%M:%S\", %r is like \"%I:%M:%S %p\".
1221 %X is the locale's \"preferred\" time format.
1222
1223 Finally, %n is a newline, %t is a tab, %% is a literal %.
1224
1225 Certain flags and modifiers are available with some format controls.
1226 The flags are `_' and `-'.  For certain characters X, %_X is like %X,
1227 but padded with blanks; %-X is like %X, but without padding.
1228 %NX (where N stands for an integer) is like %X,
1229 but takes up at least N (a number) positions.
1230 The modifiers are `E' and `O'.  For certain characters X,
1231 %EX is a locale's alternative version of %X;
1232 %OX is like %X, but uses the locale's number symbols.
1233
1234 For example, to produce full ISO 8601 format, use \"%Y-%m-%dT%T%z\".
1235
1236 Compatibility Note.
1237
1238 Those format constructs are yet to be implemented.
1239   %c, %C, %j, %U, %W, %x, %X
1240 Not fully compatible especially when invalid format is specified."
1241     (let ((fmt-len (length format))
1242           (ind 0)
1243           prev-ind
1244           cur-char
1245           (prev-char nil)
1246           strings-so-far
1247           (result "")
1248           field-width
1249           field-result
1250           pad-left change-case
1251           (paren-level 0)
1252           hour ms ls
1253           (tz (car (current-time-zone)))
1254           time-string)
1255       (if universal
1256           (progn
1257             (or time
1258                 (setq time (current-time)))
1259             (setq ms (car time)
1260                   ls (- (nth 1 time) tz))
1261             (cond ((< ls 0)
1262                    (setq ms (1- ms)
1263                          ls (+ ls 65536)))
1264                   ((>= ls 65536)
1265                    (setq ms (1+ ms)
1266                          ls (- ls 65536))))
1267             (setq time (append (list ms ls) (nth 2 time)))))
1268       (setq time-string (current-time-string time)
1269             hour (string-to-int (substring time-string 11 13)))
1270       (while (< ind fmt-len)
1271         (setq cur-char (aref format ind))
1272         (setq
1273          result
1274          (concat result
1275         (cond
1276          ((eq cur-char ?%)
1277           ;; eat any additional args to allow for future expansion, not!!
1278           (setq pad-left nil change-case nil field-width "" prev-ind ind
1279                 strings-so-far "")
1280 ;         (catch 'invalid
1281           (while (progn
1282                    (setq ind (1+ ind))
1283                    (setq cur-char (if (< ind fmt-len)
1284                                       (aref format ind)
1285                                     ?\0))
1286                    (or (eq ?- cur-char) ; pad on left
1287                        (eq ?# cur-char) ; case change
1288                        (if (and (string-equal field-width "")
1289                                 (<= ?0 cur-char) (>= ?9 cur-char))
1290                            ;; get format width
1291                            (let ((field-index ind))
1292                              (while (progn
1293                                       (setq ind (1+ ind))
1294                                       (setq cur-char (if (< ind fmt-len)
1295                                                          (aref format ind)
1296                                                        ?\0))
1297                                       (and (<= ?0 cur-char) (>= ?9 cur-char))))
1298                              (setq field-width
1299                                    (substring format field-index ind))
1300                              (setq ind (1- ind)
1301                                    cur-char nil)
1302                              t))))
1303             (setq prev-char cur-char
1304                   strings-so-far (concat strings-so-far
1305                                          (if cur-char
1306                                              (char-to-string cur-char)
1307                                            field-width)))
1308             ;; characters we actually use
1309             (cond ((eq cur-char ?-)
1310                    ;; padding to left must be specified before field-width
1311                    (setq pad-left (string-equal field-width "")))
1312                   ((eq cur-char ?#)
1313                    (setq change-case t))))
1314           (setq field-result
1315                 (cond
1316                  ((eq cur-char ?%)
1317                   "%")
1318                  ;; the abbreviated name of the day of week.
1319                  ((eq cur-char ?a)
1320                   (substring time-string 0 3))
1321                  ;; the full name of the day of week
1322                  ((eq cur-char ?A)
1323                   (cadr (assoc (substring time-string 0 3)
1324                                format-time-week-list)))
1325                  ;; the abbreviated name of the month
1326                  ((eq cur-char ?b)
1327                   (substring time-string 4 7))
1328                  ;; the full name of the month
1329                  ((eq cur-char ?B)
1330                   (cadr (assoc (substring time-string 4 7)
1331                                format-time-month-list)))
1332                  ;; a synonym for `%x %X' (yet to come)
1333                  ((eq cur-char ?c)
1334                   "")
1335                  ;; locale specific (yet to come)
1336                  ((eq cur-char ?C)
1337                   "")
1338                  ;; the day of month, zero-padded
1339                  ((eq cur-char ?d)
1340                   (format "%02d" (string-to-int (substring time-string 8 10))))
1341                  ;; a synonym for `%m/%d/%y'
1342                  ((eq cur-char ?D)
1343                   (format "%02d/%02d/%s"
1344                           (cddr (assoc (substring time-string 4 7)
1345                                        format-time-month-list))
1346                           (string-to-int (substring time-string 8 10))
1347                           (substring time-string -2)))
1348                  ;; the day of month, blank-padded
1349                  ((eq cur-char ?e)
1350                   (format "%2d" (string-to-int (substring time-string 8 10))))
1351                  ;; a synonym for `%b'
1352                  ((eq cur-char ?h)
1353                   (substring time-string 4 7))
1354                  ;; the hour (00-23)
1355                  ((eq cur-char ?H)
1356                   (substring time-string 11 13))
1357                  ;; the hour (00-12)
1358                  ((eq cur-char ?I)
1359                   (format "%02d" (if (> hour 12) (- hour 12) hour)))
1360                  ;; the day of the year (001-366) (yet to come)
1361                  ((eq cur-char ?j)
1362                   "")
1363                  ;; the hour (0-23), blank padded
1364                  ((eq cur-char ?k)
1365                   (format "%2d" hour))
1366                  ;; the hour (1-12), blank padded
1367                  ((eq cur-char ?l)
1368                   (format "%2d" (if (> hour 12) (- hour 12) hour)))
1369                  ;; the month (01-12)
1370                  ((eq cur-char ?m)
1371                   (format "%02d" (cddr (assoc (substring time-string 4 7)
1372                                               format-time-month-list))))
1373                  ;; the minute (00-59)
1374                  ((eq cur-char ?M)
1375                   (substring time-string 14 16))
1376                  ;; a newline
1377                  ((eq cur-char ?n)
1378                   "\n")
1379                  ;; `AM' or `PM', as appropriate
1380                  ((eq cur-char ?p)
1381                   (setq change-case (not change-case))
1382                   (if (> hour 12) "pm" "am"))
1383                  ;; a synonym for `%I:%M:%S %p'
1384                  ((eq cur-char ?r)
1385                   (format "%02d:%s:%s %s"
1386                           (if (> hour 12) (- hour 12) hour)
1387                           (substring time-string 14 16)
1388                           (substring time-string 17 19)
1389                           (if (> hour 12) "PM" "AM")))
1390                  ;; a synonym for `%H:%M'
1391                  ((eq cur-char ?R)
1392                   (format "%s:%s"
1393                           (substring time-string 11 13)
1394                           (substring time-string 14 16)))
1395                  ;; the seconds (00-60)
1396                  ((eq cur-char ?S)
1397                   (substring time-string 17 19))
1398                  ;; a tab character
1399                  ((eq cur-char ?t)
1400                   "\t")
1401                  ;; a synonym for `%H:%M:%S'
1402                  ((eq cur-char ?T)
1403                   (format "%s:%s:%s"
1404                           (substring time-string 11 13)
1405                           (substring time-string 14 16)
1406                           (substring time-string 17 19)))
1407                  ;; the week of the year (01-52), assuming that weeks
1408                  ;; start on Sunday (yet to come)
1409                  ((eq cur-char ?U)
1410                   "")
1411                  ;; the numeric day of week (0-6).  Sunday is day 0
1412                  ((eq cur-char ?w)
1413                   (format "%d" (cddr (assoc (substring time-string 0 3)
1414                                             format-time-week-list))))
1415                  ;; the week of the year (01-52), assuming that weeks
1416                  ;; start on Monday (yet to come)
1417                  ((eq cur-char ?W)
1418                   "")
1419                  ;; locale specific (yet to come)
1420                  ((eq cur-char ?x)
1421                   "")
1422                  ;; locale specific (yet to come)
1423                  ((eq cur-char ?X)
1424                   "")
1425                  ;; the year without century (00-99)
1426                  ((eq cur-char ?y)
1427                   (substring time-string -2))
1428                  ;; the year with century
1429                  ((eq cur-char ?Y)
1430                   (substring time-string -4))
1431                  ;; the time zone abbreviation
1432                  ((eq cur-char ?Z)
1433                   (if universal
1434                       "UTC"
1435                     (setq change-case (not change-case))
1436                     (downcase (cadr (current-time-zone)))))
1437                  ((eq cur-char ?z)
1438                   (if universal
1439                       "+0000"
1440                     (if (< tz 0)
1441                         (format "-%02d%02d"
1442                                 (/ (- tz) 3600) (/ (% (- tz) 3600) 60))
1443                       (format "+%02d%02d"
1444                               (/ tz 3600) (/ (% tz 3600) 60)))))
1445                  (t
1446                   (concat
1447                    "%"
1448                    strings-so-far
1449                    (char-to-string cur-char)))))
1450 ;                 (setq ind prev-ind)
1451 ;                 (throw 'invalid "%"))))
1452           (if (string-equal field-width "")
1453               (if change-case (upcase field-result) field-result)
1454             (let ((padded-result
1455                    (format (format "%%%s%s%c"
1456                                    ""   ; pad on left is ignored
1457 ;                                  (if pad-left "-" "")
1458                                    field-width
1459                                    ?s)
1460                            (or field-result ""))))
1461               (let ((initial-length (length padded-result))
1462                     (desired-length (string-to-int field-width)))
1463                 (when (and (string-match "^0" field-width)
1464                            (string-match "^ +" padded-result))
1465                   (setq padded-result
1466                         (replace-match
1467                          (make-string
1468                           (length (match-string 0 padded-result)) ?0)
1469                          nil nil padded-result)))
1470                 (if (> initial-length desired-length)
1471                     ;; truncate strings on right, years on left
1472                     (if (stringp field-result)
1473                         (substring padded-result 0 desired-length)
1474                       (if (eq cur-char ?y)
1475                           (substring padded-result (- desired-length))
1476                         padded-result))) ;non-year numbers don't truncate
1477                 (if change-case (upcase padded-result) padded-result))))) ;)
1478          (t
1479           (char-to-string cur-char)))))
1480         (setq ind (1+ ind)))
1481       result))
1482   ;; for `load-history'.
1483   (setq current-load-list (cons 'format-time-string current-load-list))
1484   (put 'format-time-string 'defun-maybe t))))
1485
1486 ;; Emacs 19.29-19.34/XEmacs: `format-time-string' neither supports the
1487 ;; format string "%z" nor the third argument `universal'.
1488 (unless (string-match "\\`[---+][0-9]+\\'"
1489                       (format-time-string "%z" (current-time)))
1490   (defadvice format-time-string
1491     (before support-timezone-in-numeric-form-and-3rd-arg
1492             (format-string &optional time universal) activate compile)
1493     "Advice to support the construct `%z' and the third argument `universal'."
1494     (let ((tz (car (current-time-zone)))
1495           case-fold-search ms ls)
1496       (while (string-match "\\(\\(\\`\\|[^%]\\)\\(%%\\)*\\)%z" format-string)
1497         (setq format-string
1498               (concat (substring format-string 0 (match-end 1))
1499                       (if universal
1500                           "+0000"
1501                         (if (< tz 0)
1502                             (format "-%02d%02d"
1503                                     (/ (- tz) 3600) (/ (% (- tz) 3600) 60))
1504                           (format "+%02d%02d"
1505                                   (/ tz 3600) (/ (% tz 3600) 60))))
1506                       (substring format-string (match-end 0)))))
1507       (if universal
1508           (progn
1509             (while (string-match "\\(\\(\\`\\|[^%]\\)\\(%%\\)*\\)%Z"
1510                                  format-string)
1511               (setq format-string
1512                     (concat (substring format-string 0 (match-end 1))
1513                             "UTC"
1514                             (substring format-string (match-end 0)))))
1515             (or time
1516                 (setq time (current-time)))
1517             (setq ms (car time)
1518                   ls (- (nth 1 time) tz))
1519             (cond ((< ls 0)
1520                    (setq ms (1- ms)
1521                          ls (+ ls 65536)))
1522                   ((>= ls 65536)
1523                    (setq ms (1+ ms)
1524                          ls (- ls 65536))))
1525             (setq time (append (list ms ls) (nth 2 time))))))))
1526
1527 (defconst-maybe split-string-default-separators "[ \f\t\n\r\v]+"
1528   "The default value of separators for `split-string'.
1529
1530 A regexp matching strings of whitespace.  May be locale-dependent
1531 \(as yet unimplemented).  Should not match non-breaking spaces.
1532
1533 Warning: binding this to a different value and using it as default is
1534 likely to have undesired semantics.")
1535
1536 ;; Here is a Emacs 22 version. OMIT-NULLS
1537 (defun-maybe split-string (string &optional separators omit-nulls)
1538   "Split STRING into substrings bounded by matches for SEPARATORS.
1539
1540 The beginning and end of STRING, and each match for SEPARATORS, are
1541 splitting points.  The substrings matching SEPARATORS are removed, and
1542 the substrings between the splitting points are collected as a list,
1543 which is returned.
1544
1545 If SEPARATORS is non-nil, it should be a regular expression matching text
1546 which separates, but is not part of, the substrings.  If nil it defaults to
1547 `split-string-default-separators', normally \"[ \\f\\t\\n\\r\\v]+\", and
1548 OMIT-NULLS is forced to t.
1549
1550 If OMIT-NULLS is t, zero-length substrings are omitted from the list \(so
1551 that for the default value of SEPARATORS leading and trailing whitespace
1552 are effectively trimmed).  If nil, all zero-length substrings are retained,
1553 which correctly parses CSV format, for example.
1554
1555 Note that the effect of `(split-string STRING)' is the same as
1556 `(split-string STRING split-string-default-separators t)').  In the rare
1557 case that you wish to retain zero-length substrings when splitting on
1558 whitespace, use `(split-string STRING split-string-default-separators)'.
1559
1560 Modifies the match data; use `save-match-data' if necessary."
1561   (let ((keep-nulls (not (if separators omit-nulls t)))
1562         (rexp (or separators split-string-default-separators))
1563         (start 0)
1564         notfirst
1565         (list nil))
1566     (while (and (string-match rexp string
1567                               (if (and notfirst
1568                                        (= start (match-beginning 0))
1569                                        (< start (length string)))
1570                                   (1+ start) start))
1571                 (< start (length string)))
1572       (setq notfirst t)
1573       (if (or keep-nulls (< start (match-beginning 0)))
1574           (setq list
1575                 (cons (substring string start (match-beginning 0))
1576                       list)))
1577       (setq start (match-end 0)))
1578     (if (or keep-nulls (< start (length string)))
1579         (setq list
1580               (cons (substring string start)
1581                     list)))
1582     (nreverse list)))
1583 \f
1584
1585 ;;; @ Window commands emulation. (lisp/window.el)
1586 ;;;
1587
1588 (defmacro-maybe save-selected-window (&rest body)
1589   "Execute BODY, then select the window that was selected before BODY."
1590   (list 'let
1591         '((save-selected-window-window (selected-window)))
1592         (list 'unwind-protect
1593               (cons 'progn body)
1594               (list 'select-window 'save-selected-window-window))))
1595
1596 ;; Emacs 19.31 and later:
1597 ;;  (get-buffer-window-list &optional BUFFER MINIBUF FRAME)
1598 (defun-maybe get-buffer-window-list (buffer &optional minibuf frame)
1599   "Return windows currently displaying BUFFER, or nil if none.
1600 See `walk-windows' for the meaning of MINIBUF and FRAME."
1601   (let ((buffer (if (bufferp buffer) buffer (get-buffer buffer))) windows)
1602     (walk-windows
1603      (function (lambda (window)
1604                  (if (eq (window-buffer window) buffer)
1605                      (setq windows (cons window windows)))))
1606      minibuf frame)
1607     windows))
1608 \f
1609
1610 ;;; @ Frame commands emulation. (lisp/frame.el)
1611 ;;;
1612
1613 ;; XEmacs 21.0 and later:
1614 ;;  (save-selected-frame &rest BODY)
1615 (defmacro-maybe save-selected-frame (&rest body)
1616   "Execute forms in BODY, then restore the selected frame."
1617   (list 'let
1618         '((save-selected-frame-frame (selected-frame)))
1619         (list 'unwind-protect
1620               (cons 'progn body)
1621               (list 'select-frame 'save-selected-frame-frame))))
1622 \f
1623
1624 ;;; @ Basic editing commands emulation. (lisp/simple.el)
1625 ;;;
1626 \f
1627
1628 ;;; @ File input and output commands emulation. (lisp/files.el)
1629 ;;;
1630
1631 (defvar-maybe temporary-file-directory
1632   (file-name-as-directory
1633    (cond ((memq system-type '(ms-dos windows-nt))
1634           (or (getenv "TEMP") (getenv "TMPDIR") (getenv "TMP") "c:/temp"))
1635          ((memq system-type '(vax-vms axp-vms))
1636           (or (getenv "TMPDIR") (getenv "TMP") (getenv "TEMP") "SYS$SCRATCH:"))
1637          (t
1638           (or (getenv "TMPDIR") (getenv "TMP") (getenv "TEMP") "/tmp"))))
1639   "The directory for writing temporary files.")
1640
1641 ;; Emacs 21 CVS         ; nothing to do.
1642 ;;  (make-temp-file PREFIX &optional DIR-FLAG SUFFIX)
1643 ;;
1644 ;; Emacs 21.1-21.3      ; replace with CVS version of `make-temp-file'.
1645 ;;  (make-temp-file PREFIX &optional DIR-FLAG)
1646 ;;
1647 ;; Emacs 20 and earlier ; install our version of `make-temp-file', for
1648 ;;  or XEmacs           ; single-user system or for multi-user system.
1649 (eval-when-compile
1650   (cond
1651    ((get 'make-temp-file 'defun-maybe)
1652     ;; this form is already evaluated during compilation.
1653     )
1654    ((not (fboundp 'make-temp-file))
1655     ;; Emacs 20 and earlier, or XEmacs.
1656     (put 'make-temp-file 'defun-maybe 'none))
1657    (t
1658     (let* ((object (symbol-function 'make-temp-file))
1659            (arglist (cond
1660                      ((byte-code-function-p object)
1661                       (if (fboundp 'compiled-function-arglist)
1662                           (compiled-function-arglist object)
1663                         (aref object 0)))
1664                      ((eq (car-safe object) 'lambda)
1665                       (nth 1 object))
1666                      ;; `make-temp-file' is a built-in.
1667                      )))
1668       ;; arglist: (prefix &optional dir-flag suffix)
1669       (cond
1670        ((not arglist)
1671         ;; `make-temp-file' is a built-in; expects 3-args.
1672         (put 'make-temp-file 'defun-maybe '3-args))
1673        ((> (length arglist) 3)
1674         ;; Emacs 21 CVS.
1675         (put 'make-temp-file 'defun-maybe '3-args))
1676        (t
1677         ;; Emacs 21.1-21.3
1678         (put 'make-temp-file 'defun-maybe '2-args)))))))
1679
1680 (static-cond
1681  ((eq (get 'make-temp-file 'defun-maybe) '3-args)
1682   (put 'make-temp-file 'defun-maybe '3-args))
1683  ((eq (get 'make-temp-file 'defun-maybe) '2-args)
1684   (put 'make-temp-file 'defun-maybe '2-args)
1685   (or (fboundp 'si:make-temp-file)
1686       (fset 'si:make-temp-file (symbol-function 'make-temp-file)))
1687   (setq current-load-list (cons 'make-temp-file current-load-list))
1688   (defun make-temp-file (prefix &optional dir-flag suffix)
1689     "\
1690 Create a temporary file.
1691 The returned file name (created by appending some random characters at the end
1692 of PREFIX, and expanding against `temporary-file-directory' if necessary),
1693 is guaranteed to point to a newly created empty file.
1694 You can then use `write-region' to write new data into the file.
1695
1696 If DIR-FLAG is non-nil, create a new empty directory instead of a file.
1697
1698 If SUFFIX is non-nil, add that at the end of the file name."
1699     (let ((umask (default-file-modes))
1700           file)
1701       (unwind-protect
1702           (progn
1703             ;; Create temp files with strict access rights.  
1704             ;; It's easy toloosen them later, whereas it's impossible
1705             ;;  to close the time-window of loose permissions otherwise.
1706             (set-default-file-modes 448)
1707             (while (condition-case ()
1708                        (progn
1709                          (setq file
1710                                (make-temp-name
1711                                 (expand-file-name
1712                                  prefix temporary-file-directory)))
1713                          (if suffix
1714                              (setq file (concat file suffix)))
1715                          (if dir-flag
1716                              (make-directory file)
1717                            (write-region "" nil file nil
1718                                          'silent nil 'excl))
1719                          nil)
1720                      (file-already-exists t))
1721               ;; the file was somehow created by someone else between
1722               ;; `make-temp-name' and `write-region', let's try again.
1723               nil)
1724             file)
1725         ;; Reset the umask.
1726         (set-default-file-modes umask)))))
1727  ((eq (get 'make-temp-file 'defun-maybe) 'none)
1728   (put 'make-temp-file 'defun-maybe 'none)
1729   (setq current-load-list (cons 'make-temp-file current-load-list))
1730   ;; must be load-time check to share .elc between different systems.
1731   (cond
1732    ((memq system-type '(windows-nt ms-dos OS/2 emx))
1733     ;; for single-user systems.
1734     (defun make-temp-file (prefix &optional dir-flag suffix)
1735       "Create a temporary file.
1736 The returned file name (created by appending some random characters at the end
1737 of PREFIX, and expanding against `temporary-file-directory' if necessary),
1738 is guaranteed to point to a newly created empty file.
1739 You can then use `write-region' to write new data into the file.
1740
1741 If DIR-FLAG is non-nil, create a new empty directory instead of a file.
1742
1743 If SUFFIX is non-nil, add that at the end of the file name."
1744       (let ((file (make-temp-name
1745                    (expand-file-name prefix temporary-file-directory))))
1746         (if suffix
1747             (setq file (concat file suffix)))
1748         (if dir-flag
1749             (make-directory file)
1750           (write-region "" nil file nil 'silent))
1751         file)))
1752    (t
1753     ;; for multi-user systems.
1754     (defun make-temp-file (prefix &optional dir-flag suffix)
1755       "Create a temporary file.
1756 The returned file name (created by appending some random characters at the end
1757 of PREFIX, and expanding against `temporary-file-directory' if necessary),
1758 is guaranteed to point to a newly created empty file.
1759 You can then use `write-region' to write new data into the file.
1760
1761 If DIR-FLAG is non-nil, create a new empty directory instead of a file.
1762
1763 If SUFFIX is non-nil, add that at the end of the file name."
1764       (let ((prefix (expand-file-name prefix temporary-file-directory)))
1765         (if dir-flag
1766             ;; Create a new empty directory.
1767             (let (dir)
1768               (while (condition-case ()
1769                          (progn
1770                            (setq dir (make-temp-name prefix))
1771                            (if suffix
1772                                (setq dir (concat dir suffix)))
1773                            ;; `make-directory' returns nil for success,
1774                            ;; otherwise signals an error.
1775                            (make-directory dir))
1776                        ;; the dir was somehow created by someone else
1777                        ;; between `make-temp-name' and `make-directory',
1778                        ;; let's try again.
1779                        (file-already-exists t)))
1780               (set-file-modes dir 448)
1781               dir)
1782           ;; Create a new empty file.
1783           (let (tempdir tempfile)
1784             (unwind-protect
1785                 (let (file)
1786                   ;; First, create a temporary directory.
1787                   (while (condition-case ()
1788                              (progn
1789                                (setq tempdir (make-temp-name
1790                                               (concat
1791                                                (file-name-directory prefix)
1792                                                "DIR")))
1793                                ;; return nil or signal an error.
1794                                (make-directory tempdir))
1795                            ;; let's try again.
1796                            (file-already-exists t)))
1797                   (set-file-modes tempdir 448)
1798                   ;; Second, create a temporary file in the tempdir.
1799                   ;; There *is* a race condition between `make-temp-name'
1800                   ;; and `write-region', but we don't care it since we are
1801                   ;; in a private directory now.
1802                   (setq tempfile (make-temp-name (concat tempdir "/EMU")))
1803                   (write-region "" nil tempfile nil 'silent)
1804                   (set-file-modes tempfile 384)
1805                   ;; Finally, make a hard-link from the tempfile.
1806                   (while (condition-case ()
1807                              (progn
1808                                (setq file (make-temp-name prefix))
1809                                (if suffix
1810                                    (setq file (concat file suffix)))
1811                                ;; return nil or signal an error.
1812                                (add-name-to-file tempfile file))
1813                            ;; let's try again.
1814                            (file-already-exists t)))
1815                   file)
1816               ;; Cleanup the tempfile.
1817               (and tempfile
1818                    (file-exists-p tempfile)
1819                    (delete-file tempfile))
1820               ;; Cleanup the tempdir.
1821               (and tempdir
1822                    (file-directory-p tempdir)
1823                    (delete-directory tempdir)))))))))))
1824
1825 ;; Actually, `path-separator' is defined in src/emacs.c and overrided
1826 ;; in dos-w32.el.
1827 (defvar-maybe path-separator ":"
1828   "The directory separator in search paths, as a string.")
1829
1830 ;; `convert-standard-filename' is defined in lisp/files.el and overrided
1831 ;; in lisp/dos-fns.el and lisp/w32-fns.el for each environment.
1832 (cond
1833  ;; must be load-time check to share .elc between different systems.
1834  ((fboundp 'convert-standard-filename))
1835  ((memq system-type '(windows-nt ms-dos))
1836   ;; should we do (require 'filename) at load-time ?
1837   ;; (require 'filename)
1838   ;; filename.el requires many modules, so we do not want to load it
1839   ;; at compile-time. Instead, suppress warnings by these autoloads.
1840   (eval-when-compile
1841     (autoload 'filename-maybe-truncate-by-size "filename")
1842     (autoload 'filename-special-filter "filename"))
1843   (defun convert-standard-filename (filename)
1844     "Convert a standard file's name to something suitable for the current OS.
1845 This function's standard definition is trivial; it just returns the argument.
1846 However, on some systems, the function is redefined
1847 with a definition that really does change some file names.
1848 Under `windows-nt' or `ms-dos', it refers `filename-replacement-alist' and
1849 `filename-limit-length' for the basic filename and each parent directory name."
1850     (require 'filename)
1851     (let* ((names (split-string filename "/"))
1852            (drive-name (car names))
1853            (filter (function
1854                     (lambda (string)
1855                       (filename-maybe-truncate-by-size
1856                        (filename-special-filter string))))))
1857       (cond
1858        ((eq 1 (length names))
1859         (funcall filter drive-name))
1860        ((string-match "^[^/]:$" drive-name)
1861         (concat drive-name "/" (mapconcat filter (cdr names) "/")))
1862        (t
1863         (mapconcat filter names "/"))))))
1864  (t
1865   (defun convert-standard-filename (filename)
1866     "Convert a standard file's name to something suitable for the current OS.
1867 This function's standard definition is trivial; it just returns the argument.
1868 However, on some systems, the function is redefined
1869 with a definition that really does change some file names.
1870 Under `windows-nt' or `ms-dos', it refers `filename-replacement-alist' and
1871 `filename-limit-length' for the basic filename and each parent directory name."
1872     filename)))
1873
1874 (static-cond
1875  ((fboundp 'insert-file-contents-literally))
1876  ((boundp 'file-name-handler-alist)
1877   ;; Use `defun-maybe' to update `load-history'.
1878   (defun-maybe insert-file-contents-literally (filename &optional visit
1879                                                         beg end replace)
1880     "Like `insert-file-contents', q.v., but only reads in the file.
1881 A buffer may be modified in several ways after reading into the buffer due
1882 to advanced Emacs features, such as file-name-handlers, format decoding,
1883 find-file-hooks, etc.
1884   This function ensures that none of these modifications will take place."
1885     (let (file-name-handler-alist)
1886       (insert-file-contents filename visit beg end replace))))
1887  (t
1888   (defalias 'insert-file-contents-literally 'insert-file-contents)))
1889
1890 (defun-maybe file-name-sans-extension (filename)
1891   "Return FILENAME sans final \"extension\".
1892 The extension, in a file name, is the part that follows the last `.'."
1893   (save-match-data
1894     (let ((file (file-name-sans-versions (file-name-nondirectory filename)))
1895           directory)
1896       (if (string-match "\\.[^.]*\\'" file)
1897           (if (setq directory (file-name-directory filename))
1898               (expand-file-name (substring file 0 (match-beginning 0))
1899                                 directory)
1900             (substring file 0 (match-beginning 0)))
1901         filename))))
1902 \f
1903
1904 ;;; @ Miscellanea.
1905
1906 ;; Emacs 19.29 and later: (current-fill-column)
1907 (defun-maybe current-fill-column ()
1908   "Return the fill-column to use for this line."
1909   fill-column)
1910
1911 ;; Emacs 19.29 and later: (current-left-margin)
1912 (defun-maybe current-left-margin ()
1913   "Return the left margin to use for this line."
1914   left-margin)
1915 \f
1916
1917 ;;; @ XEmacs emulation.
1918 ;;;
1919
1920 (defun-maybe find-face (face-or-name)
1921   "Retrieve the face of the given name.
1922 If FACE-OR-NAME is a face object, it is simply returned.
1923 Otherwise, FACE-OR-NAME should be a symbol.  If there is no such face,
1924 nil is returned.  Otherwise the associated face object is returned."
1925   (car (memq face-or-name (face-list))))
1926
1927 ;; Emacs 21.1 defines this as an alias for `line-beginning-position'.
1928 ;; Therefore, optional 2nd arg BUFFER is not portable.
1929 (defun-maybe point-at-bol (&optional n buffer)
1930   "Return the character position of the first character on the current line.
1931 With argument N not nil or 1, move forward N - 1 lines first.
1932 If scan reaches end of buffer, return that position.
1933 This function does not move point."
1934   (save-excursion
1935     (if buffer (set-buffer buffer))
1936     (forward-line (1- (or n 1)))
1937     (point)))
1938
1939 ;; Emacs 21.1 defines this as an alias for `line-end-position'.
1940 ;; Therefore, optional 2nd arg BUFFER is not portable.
1941 (defun-maybe point-at-eol (&optional n buffer)
1942   "Return the character position of the last character on the current line.
1943 With argument N not nil or 1, move forward N - 1 lines first.
1944 If scan reaches end of buffer, return that position.
1945 This function does not move point."
1946   (save-excursion
1947     (if buffer (set-buffer buffer))
1948     (end-of-line (or n 1))
1949     (point)))
1950
1951 (defsubst-maybe define-obsolete-function-alias (oldfun newfun)
1952   "Define OLDFUN as an obsolete alias for function NEWFUN.
1953 This makes calling OLDFUN equivalent to calling NEWFUN and marks OLDFUN
1954 as obsolete."
1955   (defalias oldfun newfun)
1956   (make-obsolete oldfun newfun))
1957
1958 ;; XEmacs 21: (character-to-event CH &optional EVENT DEVICE)
1959 (defun-maybe character-to-event (ch)
1960   "Convert keystroke CH into an event structure, replete with bucky bits.
1961 Note that CH (the keystroke specifier) can be an integer, a character
1962 or a symbol such as 'clear."
1963   ch)
1964
1965 ;; XEmacs 21: (event-to-character EVENT
1966 ;;             &optional ALLOW-EXTRA-MODIFIERS ALLOW-META ALLOW-NON-ASCII)
1967 (defun-maybe-cond event-to-character (event)
1968   "Return the character approximation to the given event object.
1969 If the event isn't a keypress, this returns nil."
1970   ((and (fboundp 'read-event)
1971         (subrp (symbol-function 'read-event)))
1972    ;; Emacs 19 and later.
1973    (cond
1974     ((symbolp event)
1975      ;; mask is (BASE-TYPE MODIFIER-BITS) or nil.
1976      (let ((mask (get event 'event-symbol-element-mask)))
1977        (if mask
1978            (let ((base (get (car mask) 'ascii-character)))
1979              (if base
1980                  (logior base (car (cdr mask))))))))
1981     ((integerp event) event)))
1982   (t
1983    ;; v18. Is this correct?
1984    event))
1985
1986 ;; v18: no event; (read-char)
1987 ;; Emacs 19, 20.1 and 20.2: (read-event)
1988 ;; Emacs 20.3: (read-event &optional PROMPT SUPPRESS-INPUT-METHOD)
1989 ;; Emacs 20.4: (read-event &optional PROMPT INHERIT-INPUT-METHOD)
1990 ;; XEmacs: (next-event &optional EVENT PROMPT),
1991 ;;         (next-command-event &optional EVENT PROMPT)
1992 (defun-maybe-cond next-command-event (&optional event prompt)
1993   "Read an event object from the input stream.
1994 If EVENT is non-nil, it should be an event object and will be filled
1995 in and returned; otherwise a new event object will be created and
1996 returned.
1997 If PROMPT is non-nil, it should be a string and will be displayed in
1998 the echo area while this function is waiting for an event."
1999   ((and (>= emacs-major-version 20)
2000         (>= emacs-minor-version 4))
2001    ;; Emacs 20.4 and later.
2002    (read-event prompt))                 ; should specify 2nd arg?
2003   ((and (= emacs-major-version 20)
2004         (= emacs-minor-version 3))
2005    ;; Emacs 20.3.
2006    (read-event prompt))                 ; should specify 2nd arg?
2007   ((and (fboundp 'read-event)
2008         (subrp (symbol-function 'read-event)))
2009    ;; Emacs 19, 20.1 and 20.2.
2010    (if prompt (message "%s" prompt))
2011    (read-event))
2012   (t
2013    (if prompt (message "%s" prompt))
2014    (read-char)))
2015 \f
2016
2017 ;;; @ MULE 2 emulation.
2018 ;;;
2019
2020 (defun-maybe-cond cancel-undo-boundary ()
2021   "Cancel undo boundary."
2022   ((boundp 'buffer-undo-list)
2023    ;; for Emacs 19 and later.
2024    (if (and (consp buffer-undo-list)
2025             (null (car buffer-undo-list)))
2026        (setq buffer-undo-list (cdr buffer-undo-list)))))
2027 \f
2028
2029 ;;; @ End.
2030 ;;;
2031
2032 ;;; poe.el ends here