Initial Commit
[packages] / xemacs-packages / tramp / lisp / tramp-compat.el
1 ;;; tramp-compat.el --- Tramp compatibility functions
2
3 ;; Copyright (C) 2007-2015 Free Software Foundation, Inc.
4
5 ;; Author: Michael Albinus <michael.albinus@gmx.de>
6 ;; Keywords: comm, processes
7 ;; Package: tramp
8
9 ;; This file is part of GNU Emacs.
10
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
15
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19 ;; GNU General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
23
24 ;;; Commentary:
25
26 ;; Tramp's main Emacs version for development is Emacs 24.  This
27 ;; package provides compatibility functions for Emacs 22, Emacs 23,
28 ;; XEmacs 21.4+ and SXEmacs 22.
29
30 ;;; Code:
31
32 ;; Pacify byte-compiler.
33 (eval-when-compile
34   (require 'cl))
35
36 (eval-and-compile
37
38   ;; GNU Emacs 22.
39   (unless (fboundp 'ignore-errors)
40     (load "cl" 'noerror)
41     (load "cl-macs" 'noerror))
42
43   ;; Some packages must be required for XEmacs, because we compile
44   ;; with -no-autoloads.
45   (when (featurep 'xemacs)
46     (require 'cus-edit)
47     (require 'env)
48     (require 'executable)
49     (require 'outline)
50     (require 'passwd)
51     (require 'pp)
52     (require 'regexp-opt)
53     (require 'time-date))
54
55   (require 'advice)
56   (require 'custom)
57   (require 'format-spec)
58   (require 'shell)
59
60   (require 'trampver)
61   (require 'tramp-loaddefs)
62
63   ;; As long as password.el is not part of (X)Emacs, it shouldn't be
64   ;; mandatory.
65   (if (featurep 'xemacs)
66       (load "password" 'noerror)
67     (or (require 'password-cache nil 'noerror)
68         (require 'password nil 'noerror))) ; Part of contrib.
69
70   ;; auth-source is relatively new.
71   (if (featurep 'xemacs)
72       (load "auth-source" 'noerror)
73     (require 'auth-source nil 'noerror))
74
75   ;; Load the appropriate timer package.
76   (if (featurep 'xemacs)
77       (require 'timer-funcs)
78     (require 'timer))
79
80   ;; Avoid byte-compiler warnings if the byte-compiler supports this.
81   ;; Currently, XEmacs supports this.
82   (when (featurep 'xemacs)
83     (unless (boundp 'byte-compile-default-warnings)
84       (defvar byte-compile-default-warnings nil))
85     (delq 'unused-vars byte-compile-default-warnings))
86
87   ;; `last-coding-system-used' is unknown in XEmacs.
88   (unless (boundp 'last-coding-system-used)
89     (defvar last-coding-system-used nil))
90
91   ;; `directory-sep-char' is an obsolete variable in Emacs.  But it is
92   ;; used in XEmacs, so we set it here and there.  The following is
93   ;; needed to pacify Emacs byte-compiler.
94   ;; Note that it was removed altogether in Emacs 24.1.
95   (when (boundp 'directory-sep-char)
96     (defvar byte-compile-not-obsolete-var nil)
97     (setq byte-compile-not-obsolete-var 'directory-sep-char)
98     ;; Emacs 23.2.
99     (defvar byte-compile-not-obsolete-vars nil)
100     (setq byte-compile-not-obsolete-vars '(directory-sep-char)))
101
102   ;; `remote-file-name-inhibit-cache' has been introduced with Emacs 24.1.
103   ;; Besides t, nil, and integer, we use also timestamps (as
104   ;; returned by `current-time') internally.
105   (unless (boundp 'remote-file-name-inhibit-cache)
106     (defvar remote-file-name-inhibit-cache nil))
107
108   ;; For not existing functions, or functions with a changed argument
109   ;; list, there are compiler warnings.  We want to avoid them in
110   ;; cases we know what we do.
111   (defmacro tramp-compat-funcall (function &rest arguments)
112     (if (featurep 'xemacs)
113         `(funcall (symbol-function ,function) ,@arguments)
114       `(when (or (subrp ,function) (functionp ,function))
115          (with-no-warnings (funcall ,function ,@arguments)))))
116
117   ;; `set-buffer-multibyte' comes from Emacs Leim.
118   (unless (fboundp 'set-buffer-multibyte)
119     (defalias 'set-buffer-multibyte 'ignore))
120
121   ;; The following functions cannot be aliases of the corresponding
122   ;; `tramp-handle-*' functions, because this would bypass the locking
123   ;; mechanism.
124
125   ;; `process-file' does not exist in XEmacs.
126   (unless (fboundp 'process-file)
127     (defalias 'process-file
128       (lambda (program &optional infile buffer display &rest args)
129         (when (tramp-tramp-file-p default-directory)
130           (apply
131            'tramp-file-name-handler
132            'process-file program infile buffer display args)))))
133
134   ;; `start-file-process' is new in Emacs 23.
135   (unless (fboundp 'start-file-process)
136     (defalias 'start-file-process
137       (lambda (name buffer program &rest program-args)
138         (when (tramp-tramp-file-p default-directory)
139           (apply
140            'tramp-file-name-handler
141            'start-file-process name buffer program program-args)))))
142
143   ;; `set-file-times' is also new in Emacs 23.
144   (unless (fboundp 'set-file-times)
145     (defalias 'set-file-times
146       (lambda (filename &optional time)
147         (when (tramp-tramp-file-p filename)
148           (tramp-compat-funcall
149            'tramp-file-name-handler 'set-file-times filename time)))))
150
151   ;; We currently use "[" and "]" in the filename format for IPv6
152   ;; hosts of GNU Emacs.  This means that Emacs wants to expand
153   ;; wildcards if `find-file-wildcards' is non-nil, and then barfs
154   ;; because no expansion could be found.  We detect this situation
155   ;; and do something really awful: we have `file-expand-wildcards'
156   ;; return the original filename if it can't expand anything.  Let's
157   ;; just hope that this doesn't break anything else.
158   ;; It is not needed anymore since GNU Emacs 23.2.
159   (unless (or (featurep 'xemacs)
160               ;; `featurep' has only one argument in XEmacs.
161               (funcall 'featurep 'files 'remote-wildcards))
162     (defadvice file-expand-wildcards
163       (around tramp-advice-file-expand-wildcards activate)
164       (let ((name (ad-get-arg 0)))
165         ;; If it's a Tramp file, look if wildcards need to be expanded
166         ;; at all.
167         (if (and
168              (tramp-tramp-file-p name)
169              (not (string-match
170                    "[[*?]" (tramp-compat-funcall
171                             'file-remote-p name 'localname))))
172             (setq ad-return-value (list name))
173           ;; Otherwise, just run the original function.
174           ad-do-it)))
175     (add-hook
176      'tramp-unload-hook
177      (lambda ()
178        (ad-remove-advice
179         'file-expand-wildcards 'around 'tramp-advice-file-expand-wildcards)
180        (ad-activate 'file-expand-wildcards))))
181
182   ;; `redisplay' does not exist in XEmacs.
183   (unless (fboundp 'redisplay)
184     (defalias 'redisplay 'ignore)))
185
186 ;; `with-temp-message' does not exist in XEmacs.
187 (if (fboundp 'with-temp-message)
188     (defalias 'tramp-compat-with-temp-message 'with-temp-message)
189   (defmacro tramp-compat-with-temp-message (_message &rest body)
190     "Display MESSAGE temporarily if non-nil while BODY is evaluated."
191     `(progn ,@body)))
192
193 ;; `condition-case-unless-debug' is introduced with Emacs 24.
194 (if (fboundp 'condition-case-unless-debug)
195     (defalias 'tramp-compat-condition-case-unless-debug
196       'condition-case-unless-debug)
197   (defmacro tramp-compat-condition-case-unless-debug
198     (var bodyform &rest handlers)
199   "Like `condition-case' except that it does not catch anything when debugging."
200     (declare (debug condition-case) (indent 2))
201     (let ((bodysym (make-symbol "body")))
202       `(let ((,bodysym (lambda () ,bodyform)))
203          (if debug-on-error
204              (funcall ,bodysym)
205            (condition-case ,var
206                (funcall ,bodysym)
207              ,@handlers))))))
208
209 ;; `font-lock-add-keywords' does not exist in XEmacs.
210 (defun tramp-compat-font-lock-add-keywords (mode keywords &optional how)
211   "Add highlighting KEYWORDS for MODE."
212   (ignore-errors
213     (tramp-compat-funcall 'font-lock-add-keywords mode keywords how)))
214
215 (defsubst tramp-compat-temporary-file-directory ()
216   "Return name of directory for temporary files (compat function).
217 For Emacs, this is the variable `temporary-file-directory', for XEmacs
218 this is the function `temp-directory'."
219   (let (file-name-handler-alist)
220     ;; We must return a local directory.  If it is remote, we could
221     ;; run into an infloop.
222     (cond
223      ((and (boundp 'temporary-file-directory)
224            (eval (car (get 'temporary-file-directory 'standard-value)))))
225      ((fboundp 'temp-directory) (tramp-compat-funcall 'temp-directory))
226      ((let ((d (getenv "TEMP"))) (and d (file-directory-p d)))
227       (file-name-as-directory (getenv "TEMP")))
228      ((let ((d (getenv "TMP"))) (and d (file-directory-p d)))
229       (file-name-as-directory (getenv "TMP")))
230      ((let ((d (getenv "TMPDIR"))) (and d (file-directory-p d)))
231       (file-name-as-directory (getenv "TMPDIR")))
232      ((file-exists-p "c:/temp") (file-name-as-directory "c:/temp"))
233      (t (message (concat "Neither `temporary-file-directory' nor "
234                          "`temp-directory' is defined -- using /tmp."))
235         (file-name-as-directory "/tmp")))))
236
237 ;; `make-temp-file' exists in Emacs only.  On XEmacs, we use our own
238 ;; implementation with `make-temp-name', creating the temporary file
239 ;; immediately in order to avoid a security hole.
240 (defsubst tramp-compat-make-temp-file (f &optional dir-flag)
241   "Create a temporary file (compat function).
242 Add the extension of F, if existing."
243   (let* (file-name-handler-alist
244          (prefix (expand-file-name
245                   (symbol-value 'tramp-temp-name-prefix)
246                   (tramp-compat-temporary-file-directory)))
247          (extension (file-name-extension f t))
248          result)
249     (condition-case nil
250         (setq result
251               (tramp-compat-funcall 'make-temp-file prefix dir-flag extension))
252       (error
253        ;; We use our own implementation, taken from files.el.
254        (while
255            (condition-case ()
256                (progn
257                  (setq result (concat (make-temp-name prefix) extension))
258                  (if dir-flag
259                      (make-directory result)
260                    (write-region "" nil result nil 'silent))
261                  nil)
262              (file-already-exists t))
263          ;; The file was somehow created by someone else between
264          ;; `make-temp-name' and `write-region', let's try again.
265          nil)))
266     result))
267
268 ;; `most-positive-fixnum' does not exist in XEmacs.
269 (defsubst tramp-compat-most-positive-fixnum ()
270   "Return largest positive integer value (compat function)."
271   (cond
272    ((boundp 'most-positive-fixnum) (symbol-value 'most-positive-fixnum))
273    ;; Default value in XEmacs.
274    (t 134217727)))
275
276 (defun tramp-compat-decimal-to-octal (i)
277   "Return a string consisting of the octal digits of I.
278 Not actually used.  Use `(format \"%o\" i)' instead?"
279   (cond ((< i 0) (error "Cannot convert negative number to octal"))
280         ((not (integerp i)) (error "Cannot convert non-integer to octal"))
281         ((zerop i) "0")
282         (t (concat (tramp-compat-decimal-to-octal (/ i 8))
283                    (number-to-string (% i 8))))))
284
285 ;; Kudos to Gerd Moellmann for this suggestion.
286 (defun tramp-compat-octal-to-decimal (ostr)
287   "Given a string of octal digits, return a decimal number."
288   (let ((x (or ostr "")))
289     ;; `save-match' is in `tramp-mode-string-to-int' which calls this.
290     (unless (string-match "\\`[0-7]*\\'" x)
291       (error "Non-octal junk in string `%s'" x))
292     (string-to-number ostr 8)))
293
294 ;; ID-FORMAT does not exist in XEmacs.
295 (defun tramp-compat-file-attributes (filename &optional id-format)
296   "Like `file-attributes' for Tramp files (compat function)."
297   (cond
298    ((or (null id-format) (eq id-format 'integer))
299     (file-attributes filename))
300    ((tramp-tramp-file-p filename)
301     (tramp-compat-funcall
302      'tramp-file-name-handler 'file-attributes filename id-format))
303    (t (condition-case nil
304           (tramp-compat-funcall 'file-attributes filename id-format)
305         (wrong-number-of-arguments (file-attributes filename))))))
306
307 ;; PRESERVE-UID-GID does not exist in XEmacs.
308 ;; PRESERVE-EXTENDED-ATTRIBUTES has been introduced with Emacs 24.1
309 ;; (as PRESERVE-SELINUX-CONTEXT), and renamed in Emacs 24.3.
310 (defun tramp-compat-copy-file
311   (filename newname &optional ok-if-already-exists keep-date
312             preserve-uid-gid preserve-extended-attributes)
313   "Like `copy-file' for Tramp files (compat function)."
314   (cond
315    (preserve-extended-attributes
316     (condition-case nil
317         (tramp-compat-funcall
318          'copy-file filename newname ok-if-already-exists keep-date
319          preserve-uid-gid preserve-extended-attributes)
320       (wrong-number-of-arguments
321        (tramp-compat-copy-file
322         filename newname ok-if-already-exists keep-date preserve-uid-gid))))
323    (preserve-uid-gid
324     (condition-case nil
325         (tramp-compat-funcall
326          'copy-file filename newname ok-if-already-exists keep-date
327          preserve-uid-gid)
328       (wrong-number-of-arguments
329        (tramp-compat-copy-file
330         filename newname ok-if-already-exists keep-date))))
331    (t
332     (copy-file filename newname ok-if-already-exists keep-date))))
333
334 ;; `copy-directory' is a new function in Emacs 23.2.  Implementation
335 ;; is taken from there.
336 (defun tramp-compat-copy-directory
337   (directory newname &optional keep-time parents copy-contents)
338   "Make a copy of DIRECTORY (compat function)."
339   (condition-case nil
340       (tramp-compat-funcall
341        'copy-directory directory newname keep-time parents copy-contents)
342
343     ;; `copy-directory' is either not implemented, or it does not
344     ;; support the the COPY-CONTENTS flag.  For the time being, we
345     ;; ignore COPY-CONTENTS as well.
346
347     (error
348      ;; If `default-directory' is a remote directory, make sure we
349      ;; find its `copy-directory' handler.
350      (let ((handler (or (find-file-name-handler directory 'copy-directory)
351                         (find-file-name-handler newname 'copy-directory))))
352        (if handler
353            (funcall handler 'copy-directory directory newname keep-time parents)
354
355          ;; Compute target name.
356          (setq directory (directory-file-name (expand-file-name directory))
357                newname   (directory-file-name (expand-file-name newname)))
358          (if (and (file-directory-p newname)
359                   (not (string-equal (file-name-nondirectory directory)
360                                      (file-name-nondirectory newname))))
361              (setq newname
362                    (expand-file-name
363                     (file-name-nondirectory directory) newname)))
364          (if (not (file-directory-p newname)) (make-directory newname parents))
365
366          ;; Copy recursively.
367          (mapc
368           (lambda (file)
369             (if (file-directory-p file)
370                 (tramp-compat-copy-directory file newname keep-time parents)
371               (copy-file file newname t keep-time)))
372           ;; We do not want to delete "." and "..".
373           (directory-files
374            directory 'full "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
375
376          ;; Set directory attributes.
377          (set-file-modes newname (file-modes directory))
378          (if keep-time
379              (set-file-times newname (nth 5 (file-attributes directory)))))))))
380
381 ;; TRASH has been introduced with Emacs 24.1.
382 (defun tramp-compat-delete-file (filename &optional trash)
383   "Like `delete-file' for Tramp files (compat function)."
384   (condition-case nil
385       (tramp-compat-funcall 'delete-file filename trash)
386     ;; This Emacs version does not support the TRASH flag.
387     (wrong-number-of-arguments
388      (let ((delete-by-moving-to-trash
389             (and (boundp 'delete-by-moving-to-trash)
390                  (symbol-value 'delete-by-moving-to-trash)
391                  trash)))
392        (delete-file filename)))))
393
394 ;; RECURSIVE has been introduced with Emacs 23.2.  TRASH has been
395 ;; introduced with Emacs 24.1.
396 (defun tramp-compat-delete-directory (directory &optional recursive trash)
397   "Like `delete-directory' for Tramp files (compat function)."
398   (condition-case nil
399       (cond
400        (trash
401         (tramp-compat-funcall 'delete-directory directory recursive trash))
402        (recursive
403         (tramp-compat-funcall 'delete-directory directory recursive))
404        (t
405         (delete-directory directory)))
406     ;; This Emacs version does not support the RECURSIVE or TRASH flag.  We
407     ;; use the implementation from Emacs 23.2.
408     (wrong-number-of-arguments
409      (setq directory (directory-file-name (expand-file-name directory)))
410      (if (not (file-symlink-p directory))
411          (mapc (lambda (file)
412                  (if (eq t (car (file-attributes file)))
413                      (tramp-compat-delete-directory file recursive trash)
414                    (tramp-compat-delete-file file trash)))
415                (directory-files
416                 directory 'full "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*")))
417      (delete-directory directory))))
418
419 ;; MUST-SUFFIX doesn't exist on XEmacs.
420 (defun tramp-compat-load (file &optional noerror nomessage nosuffix must-suffix)
421   "Like `load' for Tramp files (compat function)."
422   (if must-suffix
423       (tramp-compat-funcall 'load file noerror nomessage nosuffix must-suffix)
424     (load file noerror nomessage nosuffix)))
425
426 ;; `number-sequence' does not exist in XEmacs.  Implementation is
427 ;; taken from Emacs 23.
428 (defun tramp-compat-number-sequence (from &optional to inc)
429   "Return a sequence of numbers from FROM to TO as a list (compat function)."
430   (if (or (subrp 'number-sequence) (symbol-file 'number-sequence))
431       (tramp-compat-funcall 'number-sequence from to inc)
432     (if (or (not to) (= from to))
433         (list from)
434       (or inc (setq inc 1))
435       (when (zerop inc) (error "The increment can not be zero"))
436       (let (seq (n 0) (next from))
437         (if (> inc 0)
438             (while (<= next to)
439               (setq seq (cons next seq)
440                     n (1+ n)
441                     next (+ from (* n inc))))
442           (while (>= next to)
443             (setq seq (cons next seq)
444                   n (1+ n)
445                   next (+ from (* n inc)))))
446         (nreverse seq)))))
447
448 (defun tramp-compat-split-string (string pattern)
449   "Like `split-string' but omit empty strings.
450 In Emacs, (split-string \"/foo/bar\" \"/\") returns (\"foo\" \"bar\").
451 This is, the first, empty, element is omitted.  In XEmacs, the first
452 element is not omitted."
453   (delete "" (split-string string pattern)))
454
455 (defun tramp-compat-process-running-p (process-name)
456   "Returns t if system process PROCESS-NAME is running for `user-login-name'."
457   (when (stringp process-name)
458     (cond
459      ;; GNU Emacs 22 on w32.
460      ((fboundp 'w32-window-exists-p)
461       (tramp-compat-funcall 'w32-window-exists-p process-name process-name))
462
463      ;; GNU Emacs 23.
464      ((and (fboundp 'list-system-processes) (fboundp 'process-attributes))
465       (let (result)
466         (dolist (pid (tramp-compat-funcall 'list-system-processes) result)
467           (let ((attributes (tramp-compat-funcall 'process-attributes pid)))
468             (when (and (string-equal
469                         (cdr (assoc 'user attributes)) (user-login-name))
470                        (let ((comm (cdr (assoc 'comm attributes))))
471                          ;; The returned command name could be truncated
472                          ;; to 15 characters.  Therefore, we cannot check
473                          ;; for `string-equal'.
474                          (and comm (string-match
475                                     (concat "^" (regexp-quote comm))
476                                     process-name))))
477               (setq result t))))))
478
479      ;; Fallback, if there is no Lisp support yet.
480      (t (let ((default-directory
481                 (if (tramp-tramp-file-p default-directory)
482                     (tramp-compat-temporary-file-directory)
483                   default-directory))
484               (unix95 (getenv "UNIX95"))
485               result)
486           (setenv "UNIX95" "1")
487           (when (member
488                  (user-login-name)
489                  (tramp-compat-split-string
490                   (shell-command-to-string
491                    (format "ps -C %s -o user=" process-name))
492                   "[ \f\t\n\r\v]+"))
493             (setq result t))
494           (setenv "UNIX95" unix95)
495           result)))))
496
497 ;; The following functions do not exist in XEmacs.  We ignore this;
498 ;; they are used for checking a remote tty.
499 (defun tramp-compat-process-get (process propname)
500   "Return the value of PROCESS' PROPNAME property.
501 This is the last value stored with `(process-put PROCESS PROPNAME VALUE)'."
502   (ignore-errors (tramp-compat-funcall 'process-get process propname)))
503
504 (defun tramp-compat-process-put (process propname value)
505   "Change PROCESS' PROPNAME property to VALUE.
506 It can be retrieved with `(process-get PROCESS PROPNAME)'."
507   (ignore-errors (tramp-compat-funcall 'process-put process propname value)))
508
509 (defun tramp-compat-set-process-query-on-exit-flag (process flag)
510   "Specify if query is needed for process when Emacs is exited.
511 If the second argument flag is non-nil, Emacs will query the user before
512 exiting if process is running."
513   (if (fboundp 'set-process-query-on-exit-flag)
514       (tramp-compat-funcall 'set-process-query-on-exit-flag process flag)
515     (tramp-compat-funcall 'process-kill-without-query process flag)))
516
517 ;; There exist different implementations for this function.
518 (defun tramp-compat-coding-system-change-eol-conversion (coding-system eol-type)
519   "Return a coding system like CODING-SYSTEM but with given EOL-TYPE.
520 EOL-TYPE can be one of `dos', `unix', or `mac'."
521   (cond ((fboundp 'coding-system-change-eol-conversion)
522          (tramp-compat-funcall
523           'coding-system-change-eol-conversion coding-system eol-type))
524         ((fboundp 'subsidiary-coding-system)
525          (tramp-compat-funcall
526           'subsidiary-coding-system coding-system
527           (cond ((eq eol-type 'dos) 'crlf)
528                 ((eq eol-type 'unix) 'lf)
529                 ((eq eol-type 'mac) 'cr)
530                 (t (error
531                     "Unknown EOL-TYPE `%s', must be `dos', `unix', or `mac'"
532                     eol-type)))))
533         (t (error "Can't change EOL conversion -- is MULE missing?"))))
534
535 ;; `replace-regexp-in-string' does not exist in XEmacs.
536 ;; Implementation is taken from Emacs 24.
537 (if (fboundp 'replace-regexp-in-string)
538     (defalias 'tramp-compat-replace-regexp-in-string 'replace-regexp-in-string)
539   (defun tramp-compat-replace-regexp-in-string
540     (regexp rep string &optional fixedcase literal subexp start)
541     "Replace all matches for REGEXP with REP in STRING.
542
543 Return a new string containing the replacements.
544
545 Optional arguments FIXEDCASE, LITERAL and SUBEXP are like the
546 arguments with the same names of function `replace-match'.  If START
547 is non-nil, start replacements at that index in STRING.
548
549 REP is either a string used as the NEWTEXT arg of `replace-match' or a
550 function.  If it is a function, it is called with the actual text of each
551 match, and its value is used as the replacement text.  When REP is called,
552 the match data are the result of matching REGEXP against a substring
553 of STRING.
554
555 To replace only the first match (if any), make REGEXP match up to \\'
556 and replace a sub-expression, e.g.
557   (replace-regexp-in-string \"\\\\(foo\\\\).*\\\\'\" \"bar\" \" foo foo\" nil nil 1)
558     => \" bar foo\""
559
560     (let ((l (length string))
561           (start (or start 0))
562           matches str mb me)
563       (save-match-data
564         (while (and (< start l) (string-match regexp string start))
565           (setq mb (match-beginning 0)
566                 me (match-end 0))
567           ;; If we matched the empty string, make sure we advance by one char
568           (when (= me mb) (setq me (min l (1+ mb))))
569           ;; Generate a replacement for the matched substring.
570           ;; Operate only on the substring to minimize string consing.
571           ;; Set up match data for the substring for replacement;
572           ;; presumably this is likely to be faster than munging the
573           ;; match data directly in Lisp.
574           (string-match regexp (setq str (substring string mb me)))
575           (setq matches
576                 (cons (replace-match (if (stringp rep)
577                                          rep
578                                        (funcall rep (match-string 0 str)))
579                                      fixedcase literal str subexp)
580                       (cons (substring string start mb) ; unmatched prefix
581                             matches)))
582           (setq start me))
583         ;; Reconstruct a string from the pieces.
584         (setq matches (cons (substring string start l) matches)) ; leftover
585         (apply #'concat (nreverse matches))))))
586
587 ;; `default-toplevel-value' has been declared in Emacs 24.
588 (unless (fboundp 'default-toplevel-value)
589   (defalias 'default-toplevel-value 'symbol-value))
590
591 ;; `format-message' is new in Emacs 25, and does not exist in XEmacs.
592 (unless (fboundp 'format-message)
593   (defalias 'format-message 'format))
594
595 ;; `delete-dups' does not exist in XEmacs 21.4.
596 (if (fboundp 'delete-dups)
597     (defalias 'tramp-compat-delete-dups 'delete-dups)
598   (defun tramp-compat-delete-dups (list)
599   "Destructively remove `equal' duplicates from LIST.
600 Store the result in LIST and return it.  LIST must be a proper list.
601 Of several `equal' occurrences of an element in LIST, the first
602 one is kept."
603   (tramp-compat-funcall
604    'cl-delete-duplicates list '(:test equal :from-end) nil)))
605
606 (add-hook 'tramp-unload-hook
607           (lambda ()
608             (unload-feature 'tramp-loaddefs 'force)
609             (unload-feature 'tramp-compat 'force)))
610
611 (provide 'tramp-compat)
612
613 ;;; TODO:
614
615 ;;; tramp-compat.el ends here