1 ;;; tramp.el --- Transparent Remote Access, Multiple Protocol
3 ;; Copyright (C) 1998-2013 Free Software Foundation, Inc.
5 ;; Author: Kai Großjohann <kai.grossjohann@gmx.net>
6 ;; Michael Albinus <michael.albinus@gmx.de>
7 ;; Keywords: comm, processes
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
27 ;; This package provides remote file editing, similar to ange-ftp.
28 ;; The difference is that ange-ftp uses FTP to transfer files between
29 ;; the local and the remote host, whereas tramp.el uses a combination
30 ;; of rsh and rcp or other work-alike programs, such as ssh/scp.
32 ;; For more detailed instructions, please see the info file.
37 ;; This package only works for Emacs 22.1 and higher, and for XEmacs 21.4
38 ;; and higher. For XEmacs 21, you need the package `fsf-compat' for
39 ;; the `with-timeout' macro.
41 ;; Also see the todo list at the bottom of this file.
43 ;; The current version of Tramp can be retrieved from the following URL:
44 ;; http://ftp.gnu.org/gnu/tramp/
46 ;; There's a mailing list for this, as well. Its name is:
47 ;; tramp-devel@gnu.org
48 ;; You can use the Web to subscribe, under the following URL:
49 ;; http://lists.gnu.org/mailman/listinfo/tramp-devel
51 ;; For the adventurous, the current development sources are available
52 ;; via CVS. You can find instructions about this at the following URL:
53 ;; http://savannah.gnu.org/projects/tramp/
54 ;; Click on "CVS" in the navigation bar near the top.
56 ;; Don't forget to put on your asbestos longjohns, first!
60 (eval-when-compile (require 'cl)) ; ignore-errors
61 (require 'tramp-compat)
63 ;;; User Customizable Internal Variables:
66 "Edit remote files with a combination of ssh, scp, etc."
71 ;; Maybe we need once a real Tramp mode, with key bindings etc.
73 (defcustom tramp-mode t
74 "Whether Tramp is enabled.
75 If it is set to nil, all remote file names are used literally."
79 (defcustom tramp-verbose 3
80 "Verbosity level for Tramp messages.
81 Any level x includes messages for all levels 1 .. x-1. The levels are
83 0 silent (no tramp messages at all)
86 3 connection to remote hosts (default level)
89 6 sent and received strings
91 8 connection properties
99 (when (boundp 'backup-directory-alist)
100 (defcustom tramp-backup-directory-alist nil
101 "Alist of filename patterns and backup directory names.
102 Each element looks like (REGEXP . DIRECTORY), with the same meaning like
103 in `backup-directory-alist'. If a Tramp file is backed up, and DIRECTORY
104 is a local file name, the backup directory is prepended with Tramp file
105 name prefix \(method, user, host\) of file.
107 \(setq tramp-backup-directory-alist backup-directory-alist\)
109 gives the same backup policy for Tramp files on their hosts like the
110 policy for local files."
112 :type '(repeat (cons (regexp :tag "Regexp matching filename")
113 (directory :tag "Backup directory name"))))))
115 ;; XEmacs case. We cannot check for `bkup-backup-directory-info', because
116 ;; the package "backup-dir" might not be loaded yet.
118 (when (featurep 'xemacs)
119 (defcustom tramp-bkup-backup-directory-info nil
120 "Alist of (FILE-REGEXP BACKUP-DIR OPTIONS ...))
121 It has the same meaning like `bkup-backup-directory-info' from package
122 `backup-dir'. If a Tramp file is backed up, and BACKUP-DIR is a local
123 file name, the backup directory is prepended with Tramp file name prefix
124 \(method, user, host\) of file.
126 \(setq tramp-bkup-backup-directory-info bkup-backup-directory-info\)
128 gives the same backup policy for Tramp files on their hosts like the
129 policy for local files."
131 (list (regexp :tag "File regexp")
132 (string :tag "Backup Dir")
137 (const search-upward))))
140 (defcustom tramp-auto-save-directory nil
141 "Put auto-save files in this directory, if set.
142 The idea is to use a local directory so that auto-saving is faster."
144 :type '(choice (const nil) string))
146 (defcustom tramp-encoding-shell
147 (if (memq system-type '(windows-nt))
150 "Use this program for encoding and decoding commands on the local host.
151 This shell is used to execute the encoding and decoding command on the
152 local host, so if you want to use `~' in those commands, you should
153 choose a shell here which groks tilde expansion. `/bin/sh' normally
154 does not understand tilde expansion.
156 For encoding and decoding, commands like the following are executed:
158 /bin/sh -c COMMAND < INPUT > OUTPUT
160 This variable can be used to change the \"/bin/sh\" part. See the
161 variable `tramp-encoding-command-switch' for the \"-c\" part.
163 If the shell must be forced to be interactive, see
164 `tramp-encoding-command-interactive'.
166 Note that this variable is not used for remote commands. There are
167 mechanisms in tramp.el which automatically determine the right shell to
168 use for the remote host."
170 :type '(file :must-match t))
172 (defcustom tramp-encoding-command-switch
173 (if (string-match "cmd\\.exe" tramp-encoding-shell)
176 "Use this switch together with `tramp-encoding-shell' for local commands.
177 See the variable `tramp-encoding-shell' for more information."
181 (defcustom tramp-encoding-command-interactive
182 (unless (string-match "cmd\\.exe" tramp-encoding-shell) "-i")
183 "Use this switch together with `tramp-encoding-shell' for interactive shells.
184 See the variable `tramp-encoding-shell' for more information."
187 :type '(choice (const nil) string))
190 (defvar tramp-methods nil
191 "Alist of methods for remote files.
192 This is a list of entries of the form (NAME PARAM1 PARAM2 ...).
193 Each NAME stands for a remote access method. Each PARAM is a
194 pair of the form (KEY VALUE). The following KEYs are defined:
195 * `tramp-remote-shell'
196 This specifies the shell to use on the remote host. This
197 MUST be a Bourne-like shell. It is normally not necessary to
198 set this to any value other than \"/bin/sh\": Tramp wants to
199 use a shell which groks tilde expansion, but it can search
200 for it. Also note that \"/bin/sh\" exists on all Unixen,
201 this might not be true for the value that you decide to use.
202 You Have Been Warned.
203 * `tramp-remote-shell-args'
204 For implementation of `shell-command', this specifies the
205 arguments to let `tramp-remote-shell' run a single command.
206 * `tramp-login-program'
207 This specifies the name of the program to use for logging in to the
208 remote host. This may be the name of rsh or a workalike program,
209 or the name of telnet or a workalike, or the name of su or a workalike.
211 This specifies the list of arguments to pass to the above
212 mentioned program. Please note that this is a list of list of arguments,
213 that is, normally you don't want to put \"-a -b\" or \"-f foo\"
214 here. Instead, you want a list (\"-a\" \"-b\"), or (\"-f\" \"foo\").
215 There are some patterns: \"%h\" in this list is replaced by the host
216 name, \"%u\" is replaced by the user name, \"%p\" is replaced by the
217 port number, and \"%%\" can be used to obtain a literal percent character.
218 If a list containing \"%h\", \"%u\" or \"%p\" is unchanged during
219 expansion (i.e. no host or no user specified), this list is not used as
220 argument. By this, arguments like (\"-l\" \"%u\") are optional.
221 \"%t\" is replaced by the temporary file name produced with
222 `tramp-make-tramp-temp-file'. \"%k\" indicates the keep-date
223 parameter of a program, if exists.
225 When an asynchronous process is started, we know already that
226 the connection works. Therefore, we can pass additional
227 parameters to suppress diagnostic messages, in order not to
228 tamper the process output.
229 * `tramp-copy-program'
230 This specifies the name of the program to use for remotely copying
231 the file; this might be the absolute filename of rcp or the name of
234 This specifies the list of parameters to pass to the above mentioned
235 program, the hints for `tramp-login-args' also apply here.
236 * `tramp-copy-keep-date'
237 This specifies whether the copying program when the preserves the
238 timestamp of the original file.
239 * `tramp-copy-keep-tmpfile'
240 This specifies whether a temporary local file shall be kept
241 for optimization reasons (useful for \"rsync\" methods).
242 * `tramp-copy-recursive'
243 Whether the operation copies directories recursively.
244 * `tramp-default-port'
245 The default port of a method is needed in case of gateway connections.
246 Additionally, it is used as indication which method is prepared for
249 As the attribute name says, additional arguments are specified here
250 when a method is applied via a gateway.
252 A directory on the remote host for temporary files. If not
253 specified, \"/tmp\" is taken as default.
255 What does all this mean? Well, you should specify `tramp-login-program'
256 for all methods; this program is used to log in to the remote site. Then,
257 there are two ways to actually transfer the files between the local and the
258 remote side. One way is using an additional rcp-like program. If you want
259 to do this, set `tramp-copy-program' in the method.
261 Another possibility for file transfer is inline transfer, i.e. the
262 file is passed through the same buffer used by `tramp-login-program'. In
263 this case, the file contents need to be protected since the
264 `tramp-login-program' might use escape codes or the connection might not
265 be eight-bit clean. Therefore, file contents are encoded for transit.
266 See the variables `tramp-local-coding-commands' and
267 `tramp-remote-coding-commands' for details.
269 So, to summarize: if the method is an out-of-band method, then you
270 must specify `tramp-copy-program' and `tramp-copy-args'. If it is an
271 inline method, then these two parameters should be nil. Methods which
272 are fit for gateways must have `tramp-default-port' at least.
276 When using `su' or `sudo' the phrase `open connection to a remote
277 host' sounds strange, but it is used nevertheless, for consistency.
278 No connection is opened to a remote host, but `su' or `sudo' is
279 started on the local host. You should specify a remote host
280 `localhost' or the name of the local host. Another host name is
281 useful only in combination with `tramp-default-proxies-alist'.")
284 (defconst tramp-ssh-controlmaster-template
288 (call-process "ssh" nil t nil "-o" "ControlMaster")
289 (goto-char (point-min))
290 (when (search-forward-regexp "Missing ControlMaster argument" nil t)
292 '("-o" "ControlPath=%t.%%r@%%h:%%p"
293 "-o" "ControlMaster=auto"))))
296 (call-process "ssh" nil t nil "-o" "ControlPersist")
297 (goto-char (point-min))
298 (when (search-forward-regexp "Missing ControlPersist argument" nil t)
299 (setq result (append result '("-o" "ControlPersist=no")))))))
301 "Call ssh to detect whether it supports the Control* arguments.
302 Return a template to be used in `tramp-methods'.")
304 (defcustom tramp-default-method
305 ;; An external copy method seems to be preferred, because it performs
306 ;; much better for large files, and it hasn't too serious delays
307 ;; for small files. But it must be ensured that there aren't
308 ;; permanent password queries. Either a password agent like
309 ;; "ssh-agent" or "Pageant" shall run, or the optional
310 ;; password-cache.el or auth-sources.el packages shall be active for
311 ;; password caching. If we detect that the user is running OpenSSH
312 ;; 4.0 or newer, we could reuse the connection, which calls also for
313 ;; an external method.
315 ;; PuTTY is installed. We don't take it, if it is installed on a
316 ;; non-windows system, or pscp from the pssh (parallel ssh) package
318 ((and (eq system-type 'windows-nt)
319 (executable-find "pscp"))
320 (if (or (fboundp 'password-read)
321 (fboundp 'auth-source-user-or-password)
322 (fboundp 'auth-source-search)
323 ;; Pageant is running.
324 (tramp-compat-process-running-p "Pageant"))
327 ;; There is an ssh installation.
328 ((executable-find "scp")
329 (if (or (fboundp 'password-read)
330 (fboundp 'auth-source-user-or-password)
331 (fboundp 'auth-source-search)
332 ;; ssh-agent is running.
333 (getenv "SSH_AUTH_SOCK")
334 (getenv "SSH_AGENT_PID")
335 ;; We could reuse the connection.
336 tramp-ssh-controlmaster-template)
341 "Default method to use for transferring files.
342 See `tramp-methods' for possibilities.
343 Also see `tramp-default-method-alist'."
348 (defcustom tramp-default-method-alist nil
349 "Default method to use for specific host/user pairs.
350 This is an alist of items (HOST USER METHOD). The first matching item
351 specifies the method to use for a file name which does not specify a
352 method. HOST and USER are regular expressions or nil, which is
353 interpreted as a regular expression which always matches. If no entry
354 matches, the variable `tramp-default-method' takes effect.
356 If the file name does not specify the user, lookup is done using the
357 empty string for the user name.
359 See `tramp-methods' for a list of possibilities for METHOD."
361 :type '(repeat (list (choice :tag "Host regexp" regexp sexp)
362 (choice :tag "User regexp" regexp sexp)
363 (choice :tag "Method name" string (const nil)))))
365 (defcustom tramp-default-user nil
366 "Default user to use for transferring files.
367 It is nil by default; otherwise settings in configuration files like
368 \"~/.ssh/config\" would be overwritten. Also see `tramp-default-user-alist'.
370 This variable is regarded as obsolete, and will be removed soon."
372 :type '(choice (const nil) string))
375 (defcustom tramp-default-user-alist nil
376 "Default user to use for specific method/host pairs.
377 This is an alist of items (METHOD HOST USER). The first matching item
378 specifies the user to use for a file name which does not specify a
379 user. METHOD and USER are regular expressions or nil, which is
380 interpreted as a regular expression which always matches. If no entry
381 matches, the variable `tramp-default-user' takes effect.
383 If the file name does not specify the method, lookup is done using the
384 empty string for the method name."
386 :type '(repeat (list (choice :tag "Method regexp" regexp sexp)
387 (choice :tag " Host regexp" regexp sexp)
388 (choice :tag " User name" string (const nil)))))
390 (defcustom tramp-default-host (system-name)
391 "Default host to use for transferring files.
392 Useful for su and sudo methods mostly."
397 (defcustom tramp-default-host-alist nil
398 "Default host to use for specific method/user pairs.
399 This is an alist of items (METHOD USER HOST). The first matching item
400 specifies the host to use for a file name which does not specify a
401 host. METHOD and HOST are regular expressions or nil, which is
402 interpreted as a regular expression which always matches. If no entry
403 matches, the variable `tramp-default-host' takes effect.
405 If the file name does not specify the method, lookup is done using the
406 empty string for the method name."
409 :type '(repeat (list (choice :tag "Method regexp" regexp sexp)
410 (choice :tag " User regexp" regexp sexp)
411 (choice :tag " Host name" string (const nil)))))
413 (defcustom tramp-default-proxies-alist nil
414 "Route to be followed for specific host/user pairs.
415 This is an alist of items (HOST USER PROXY). The first matching
416 item specifies the proxy to be passed for a file name located on
417 a remote target matching USER@HOST. HOST and USER are regular
418 expressions. PROXY must be a Tramp filename without a localname
419 part. Method and user name on PROXY are optional, which is
420 interpreted with the default values. PROXY can contain the
421 patterns %h and %u, which are replaced by the strings matching
422 HOST or USER, respectively.
424 HOST, USER or PROXY could also be Lisp forms, which will be
425 evaluated. The result must be a string or nil, which is
426 interpreted as a regular expression which always matches."
428 :type '(repeat (list (choice :tag "Host regexp" regexp sexp)
429 (choice :tag "User regexp" regexp sexp)
430 (choice :tag " Proxy name" string (const nil)))))
432 (defcustom tramp-save-ad-hoc-proxies nil
433 "Whether to save ad-hoc proxies persistently."
438 (defcustom tramp-restricted-shell-hosts-alist
439 (when (memq system-type '(windows-nt))
440 (list (concat "\\`" (regexp-quote (system-name)) "\\'")))
441 "List of hosts, which run a restricted shell.
442 This is a list of regular expressions, which denote hosts running
443 a registered shell like \"rbash\". Those hosts can be used as
444 proxies only, see `tramp-default-proxies-alist'. If the local
445 host runs a registered shell, it shall be added to this list, too."
448 :type '(repeat (regexp :tag "Host regexp")))
451 (defconst tramp-local-host-regexp
455 (list "localhost" "localhost6" (system-name) "127\.0\.0\.1" "::1") t)
457 "Host names which are regarded as local host.")
459 (defvar tramp-completion-function-alist nil
460 "Alist of methods for remote files.
461 This is a list of entries of the form \(NAME PAIR1 PAIR2 ...\).
462 Each NAME stands for a remote access method. Each PAIR is of the form
463 \(FUNCTION FILE\). FUNCTION is responsible to extract user names and host
464 names from FILE for completion. The following predefined FUNCTIONs exists:
466 * `tramp-parse-rhosts' for \"~/.rhosts\" like files,
467 * `tramp-parse-shosts' for \"~/.ssh/known_hosts\" like files,
468 * `tramp-parse-sconfig' for \"~/.ssh/config\" like files,
469 * `tramp-parse-shostkeys' for \"~/.ssh2/hostkeys/*\" like files,
470 * `tramp-parse-sknownhosts' for \"~/.ssh2/knownhosts/*\" like files,
471 * `tramp-parse-hosts' for \"/etc/hosts\" like files,
472 * `tramp-parse-passwd' for \"/etc/passwd\" like files.
473 * `tramp-parse-netrc' for \"~/.netrc\" like files.
474 * `tramp-parse-putty' for PuTTY registered sessions.
476 FUNCTION can also be a customer defined function. For more details see
479 (defconst tramp-echo-mark-marker "_echo"
480 "String marker to surround echoed commands.")
482 (defconst tramp-echo-mark-marker-length (length tramp-echo-mark-marker)
483 "String length of `tramp-echo-mark-marker'.")
485 (defconst tramp-echo-mark
486 (concat tramp-echo-mark-marker
487 (make-string tramp-echo-mark-marker-length ?\b))
488 "String mark to be transmitted around shell commands.
489 Used to separate their echo from the output they produce. This
490 will only be used if we cannot disable remote echo via stty.
491 This string must have no effect on the remote shell except for
492 producing some echo which can later be detected by
493 `tramp-echoed-echo-mark-regexp'. Using `tramp-echo-mark-marker',
494 followed by an equal number of backspaces to erase them will
497 (defconst tramp-echoed-echo-mark-regexp
498 (format "%s\\(\b\\( \b\\)?\\)\\{%d\\}"
499 tramp-echo-mark-marker tramp-echo-mark-marker-length)
500 "Regexp which matches `tramp-echo-mark' as it gets echoed by
503 (defcustom tramp-local-end-of-line
504 (if (memq system-type '(windows-nt)) "\r\n" "\n")
505 "String used for end of line in local processes."
510 (defcustom tramp-rsh-end-of-line "\n"
511 "String used for end of line in rsh connections.
512 I don't think this ever needs to be changed, so please tell me about it
513 if you need to change this."
517 (defcustom tramp-login-prompt-regexp
518 ".*ogin\\( .*\\)?: *"
519 "Regexp matching login-like prompts.
520 The regexp should match at end of buffer.
522 Sometimes the prompt is reported to look like \"login as:\"."
526 (defcustom tramp-shell-prompt-pattern
527 ;; Allow a prompt to start right after a ^M since it indeed would be
528 ;; displayed at the beginning of the line (and Zsh uses it). This
529 ;; regexp works only for GNU Emacs.
530 ;; Allow also [] style prompts. They can appear only during
531 ;; connection initialization; Tramp redefines the prompt afterwards.
532 (concat (if (featurep 'xemacs) "" "\\(?:^\\|\r\\)")
533 "[^]#$%>\n]*#?[]#$%>] *\\(\e\\[[0-9;]*[a-zA-Z] *\\)*")
534 "Regexp to match prompts from remote shell.
535 Normally, Tramp expects you to configure `shell-prompt-pattern'
536 correctly, but sometimes it happens that you are connecting to a
537 remote host which sends a different kind of shell prompt. Therefore,
538 Tramp recognizes things matched by `shell-prompt-pattern' as prompt,
539 and also things matched by this variable. The default value of this
540 variable is similar to the default value of `shell-prompt-pattern',
541 which should work well in many cases.
543 This regexp must match both `tramp-initial-end-of-output' and
544 `tramp-end-of-output'."
548 (defcustom tramp-password-prompt-regexp
549 "^.*\\([pP]assword\\|[pP]assphrase\\).*:\^@? *"
550 "Regexp matching password-like prompts.
551 The regexp should match at end of buffer.
553 The `sudo' program appears to insert a `^@' character into the prompt."
557 (defcustom tramp-wrong-passwd-regexp
559 ;; These strings should be on the last line
560 (regexp-opt '("Permission denied"
565 "Timeout, server not responding."
567 "Name or service not known"
568 "Host key verification failed."
569 "No supported authentication methods left to try!") t)
573 ;; Here comes a list of regexes, separated by \\|
574 "Received signal [0-9]+"
576 "Regexp matching a `login failed' message.
577 The regexp should match at end of buffer."
581 (defcustom tramp-yesno-prompt-regexp
583 (regexp-opt '("Are you sure you want to continue connecting (yes/no)?") t)
585 "Regular expression matching all yes/no queries which need to be confirmed.
586 The confirmation should be done with yes or no.
587 The regexp should match at end of buffer.
588 See also `tramp-yn-prompt-regexp'."
592 (defcustom tramp-yn-prompt-regexp
594 (regexp-opt '("Store key in cache? (y/n)"
595 "Update cached key? (y/n, Return cancels connection)") t)
597 "Regular expression matching all y/n queries which need to be confirmed.
598 The confirmation should be done with y or n.
599 The regexp should match at end of buffer.
600 See also `tramp-yesno-prompt-regexp'."
604 (defcustom tramp-terminal-prompt-regexp
608 "Terminal type\\? \\[.*\\]"
610 "Regular expression matching all terminal setting prompts.
611 The regexp should match at end of buffer.
612 The answer will be provided by `tramp-action-terminal', which see."
616 (defcustom tramp-operation-not-permitted-regexp
617 (concat "\\(" "preserving times.*" "\\|" "set mode" "\\)" ":\\s-*"
618 (regexp-opt '("Operation not permitted") t))
619 "Regular expression matching keep-date problems in (s)cp operations.
620 Copying has been performed successfully already, so this message can
625 (defcustom tramp-copy-failed-regexp
627 (regexp-opt '("Permission denied"
630 "No such file or directory") t)
632 "Regular expression matching copy problems in (s)cp operations."
636 (defcustom tramp-process-alive-regexp
638 "Regular expression indicating a process has finished.
639 In fact this expression is empty by intention, it will be used only to
640 check regularly the status of the associated process.
641 The answer will be provided by `tramp-action-process-alive',
642 `tramp-action-out-of-band', which see."
646 (defconst tramp-temp-name-prefix "tramp."
647 "Prefix to use for temporary files.
648 If this is a relative file name (such as \"tramp.\"), it is considered
649 relative to the directory name returned by the function
650 `tramp-compat-temporary-file-directory' (which see). It may also be an
651 absolute file name; don't forget to include a prefix for the filename
654 (defconst tramp-temp-buffer-name " *tramp temp*"
655 "Buffer name for a temporary buffer.
656 It shall be used in combination with `generate-new-buffer-name'.")
658 (defvar tramp-temp-buffer-file-name nil
659 "File name of a persistent local temporary file.
660 Useful for \"rsync\" like methods.")
661 (make-variable-buffer-local 'tramp-temp-buffer-file-name)
662 (put 'tramp-temp-buffer-file-name 'permanent-local t)
664 ;; XEmacs is distributed with few Lisp packages. Further packages are
665 ;; installed using EFS. If we use a unified filename format, then
666 ;; Tramp is required in addition to EFS. (But why can't Tramp just
667 ;; disable EFS when Tramp is loaded? Then XEmacs can ship with EFS
668 ;; just like before.) Another reason for using a separate filename
669 ;; syntax on XEmacs is that EFS hooks into XEmacs in many places, but
670 ;; Tramp only knows how to deal with `file-name-handler-alist', not
673 ;; Currently, we have the choice between 'ftp, 'sep, and 'url.
675 (defcustom tramp-syntax
676 (if (featurep 'xemacs) 'sep 'ftp)
677 "Tramp filename syntax to be used.
679 It can have the following values:
681 'ftp -- Ange-FTP respective EFS like syntax (GNU Emacs default)
682 'sep -- Syntax as defined for XEmacs (not available yet for GNU Emacs)
683 'url -- URL-like syntax."
685 :type (if (featurep 'xemacs)
686 '(choice (const :tag "EFS" ftp)
687 (const :tag "XEmacs" sep)
688 (const :tag "URL" url))
689 '(choice (const :tag "Ange-FTP" ftp)
690 (const :tag "URL" url))))
692 (defconst tramp-prefix-format
693 (cond ((equal tramp-syntax 'ftp) "/")
694 ((equal tramp-syntax 'sep) "/[")
695 ((equal tramp-syntax 'url) "/")
696 (t (error "Wrong `tramp-syntax' defined")))
697 "String matching the very beginning of Tramp file names.
698 Used in `tramp-make-tramp-file-name'.")
700 (defconst tramp-prefix-regexp
701 (concat "^" (regexp-quote tramp-prefix-format))
702 "Regexp matching the very beginning of Tramp file names.
703 Should always start with \"^\". Derived from `tramp-prefix-format'.")
705 (defconst tramp-method-regexp
707 "Regexp matching methods identifiers.")
709 (defconst tramp-postfix-method-format
710 (cond ((equal tramp-syntax 'ftp) ":")
711 ((equal tramp-syntax 'sep) "/")
712 ((equal tramp-syntax 'url) "://")
713 (t (error "Wrong `tramp-syntax' defined")))
714 "String matching delimiter between method and user or host names.
715 Used in `tramp-make-tramp-file-name'.")
717 (defconst tramp-postfix-method-regexp
718 (regexp-quote tramp-postfix-method-format)
719 "Regexp matching delimiter between method and user or host names.
720 Derived from `tramp-postfix-method-format'.")
722 (defconst tramp-user-regexp "[^/|: \t]+"
723 "Regexp matching user names.")
726 (defconst tramp-prefix-domain-format "%"
727 "String matching delimiter between user and domain names.")
730 (defconst tramp-prefix-domain-regexp
731 (regexp-quote tramp-prefix-domain-format)
732 "Regexp matching delimiter between user and domain names.
733 Derived from `tramp-prefix-domain-format'.")
735 (defconst tramp-domain-regexp "[-a-zA-Z0-9_.]+"
736 "Regexp matching domain names.")
738 (defconst tramp-user-with-domain-regexp
739 (concat "\\(" tramp-user-regexp "\\)"
740 tramp-prefix-domain-regexp
741 "\\(" tramp-domain-regexp "\\)")
742 "Regexp matching user names with domain names.")
744 (defconst tramp-postfix-user-format "@"
745 "String matching delimiter between user and host names.
746 Used in `tramp-make-tramp-file-name'.")
748 (defconst tramp-postfix-user-regexp
749 (regexp-quote tramp-postfix-user-format)
750 "Regexp matching delimiter between user and host names.
751 Derived from `tramp-postfix-user-format'.")
753 (defconst tramp-host-regexp "[a-zA-Z0-9_.-]+"
754 "Regexp matching host names.")
756 (defconst tramp-prefix-ipv6-format
757 (cond ((equal tramp-syntax 'ftp) "[")
758 ((equal tramp-syntax 'sep) "")
759 ((equal tramp-syntax 'url) "[")
760 (t (error "Wrong `tramp-syntax' defined")))
761 "String matching left hand side of IPv6 addresses.
762 Used in `tramp-make-tramp-file-name'.")
764 (defconst tramp-prefix-ipv6-regexp
765 (regexp-quote tramp-prefix-ipv6-format)
766 "Regexp matching left hand side of IPv6 addresses.
767 Derived from `tramp-prefix-ipv6-format'.")
769 ;; The following regexp is a bit sloppy. But it shall serve our
770 ;; purposes. It covers also IPv4 mapped IPv6 addresses, like in
771 ;; "::ffff:192.168.0.1".
772 (defconst tramp-ipv6-regexp
773 "\\(?:\\(?:[a-zA-Z0-9]+\\)?:\\)+[a-zA-Z0-9.]+"
774 "Regexp matching IPv6 addresses.")
776 (defconst tramp-postfix-ipv6-format
777 (cond ((equal tramp-syntax 'ftp) "]")
778 ((equal tramp-syntax 'sep) "")
779 ((equal tramp-syntax 'url) "]")
780 (t (error "Wrong `tramp-syntax' defined")))
781 "String matching right hand side of IPv6 addresses.
782 Used in `tramp-make-tramp-file-name'.")
784 (defconst tramp-postfix-ipv6-regexp
785 (regexp-quote tramp-postfix-ipv6-format)
786 "Regexp matching right hand side of IPv6 addresses.
787 Derived from `tramp-postfix-ipv6-format'.")
789 (defconst tramp-prefix-port-format
790 (cond ((equal tramp-syntax 'ftp) "#")
791 ((equal tramp-syntax 'sep) "#")
792 ((equal tramp-syntax 'url) ":")
793 (t (error "Wrong `tramp-syntax' defined")))
794 "String matching delimiter between host names and port numbers.")
796 (defconst tramp-prefix-port-regexp
797 (regexp-quote tramp-prefix-port-format)
798 "Regexp matching delimiter between host names and port numbers.
799 Derived from `tramp-prefix-port-format'.")
801 (defconst tramp-port-regexp "[0-9]+"
802 "Regexp matching port numbers.")
804 (defconst tramp-host-with-port-regexp
805 (concat "\\(" tramp-host-regexp "\\)"
806 tramp-prefix-port-regexp
807 "\\(" tramp-port-regexp "\\)")
808 "Regexp matching host names with port numbers.")
810 (defconst tramp-postfix-hop-format "|"
811 "String matching delimiter after ad-hoc hop definitions.")
813 (defconst tramp-postfix-hop-regexp
814 (regexp-quote tramp-postfix-hop-format)
815 "Regexp matching delimiter after ad-hoc hop definitions.
816 Derived from `tramp-postfix-hop-format'.")
818 (defconst tramp-postfix-host-format
819 (cond ((equal tramp-syntax 'ftp) ":")
820 ((equal tramp-syntax 'sep) "]")
821 ((equal tramp-syntax 'url) "")
822 (t (error "Wrong `tramp-syntax' defined")))
823 "String matching delimiter between host names and localnames.
824 Used in `tramp-make-tramp-file-name'.")
826 (defconst tramp-postfix-host-regexp
827 (regexp-quote tramp-postfix-host-format)
828 "Regexp matching delimiter between host names and localnames.
829 Derived from `tramp-postfix-host-format'.")
831 (defconst tramp-localname-regexp ".*$"
832 "Regexp matching localnames.")
834 ;;; File name format:
836 (defconst tramp-remote-file-name-spec-regexp
838 "\\(?:" "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp "\\)?"
839 "\\(?:" "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp "\\)?"
840 "\\(" "\\(?:" tramp-host-regexp "\\|"
841 tramp-prefix-ipv6-regexp tramp-ipv6-regexp
842 tramp-postfix-ipv6-regexp "\\)"
843 "\\(?:" tramp-prefix-port-regexp tramp-port-regexp "\\)?" "\\)?")
844 "Regular expression matching a Tramp file name between prefix and postfix.")
846 (defconst tramp-file-name-structure
850 "\\(" "\\(?:" tramp-remote-file-name-spec-regexp
851 tramp-postfix-hop-regexp "\\)+" "\\)?"
852 tramp-remote-file-name-spec-regexp tramp-postfix-host-regexp
853 "\\(" tramp-localname-regexp "\\)")
855 "List of six elements (REGEXP METHOD USER HOST FILE HOP), detailing \
856 the Tramp file name structure.
858 The first element REGEXP is a regular expression matching a Tramp file
859 name. The regex should contain parentheses around the method name,
860 the user name, the host name, and the file name parts.
862 The second element METHOD is a number, saying which pair of
863 parentheses matches the method name. The third element USER is
864 similar, but for the user name. The fourth element HOST is similar,
865 but for the host name. The fifth element FILE is for the file name.
866 The last element HOP is the ad-hoc hop definition, which could be a
867 cascade of several hops.
869 These numbers are passed directly to `match-string', which see. That
870 means the opening parentheses are counted to identify the pair.
872 See also `tramp-file-name-regexp'.")
875 (defconst tramp-file-name-regexp-unified
876 (if (memq system-type '(cygwin windows-nt))
877 "\\`/\\([^[/|:]\\{2,\\}\\|[^/|]\\{2,\\}]\\):"
878 "\\`/\\([^[/|:]+\\|[^/|]+]\\):")
879 "Value for `tramp-file-name-regexp' for unified remoting.
880 Emacs (not XEmacs) uses a unified filename syntax for Ange-FTP and
881 Tramp. See `tramp-file-name-structure' for more explanations.
883 On W32 systems, the volume letter must be ignored.")
886 (defconst tramp-file-name-regexp-separate "\\`/\\[.*\\]"
887 "Value for `tramp-file-name-regexp' for separate remoting.
888 XEmacs uses a separate filename syntax for Tramp and EFS.
889 See `tramp-file-name-structure' for more explanations.")
892 (defconst tramp-file-name-regexp-url "\\`/[^/|:]+://"
893 "Value for `tramp-file-name-regexp' for URL-like remoting.
894 See `tramp-file-name-structure' for more explanations.")
897 (defconst tramp-file-name-regexp
898 (cond ((equal tramp-syntax 'ftp) tramp-file-name-regexp-unified)
899 ((equal tramp-syntax 'sep) tramp-file-name-regexp-separate)
900 ((equal tramp-syntax 'url) tramp-file-name-regexp-url)
901 (t (error "Wrong `tramp-syntax' defined")))
902 "Regular expression matching file names handled by Tramp.
903 This regexp should match Tramp file names but no other file names.
904 When tramp.el is loaded, this regular expression is prepended to
905 `file-name-handler-alist', and that is searched sequentially. Thus,
906 if the Tramp entry appears rather early in the `file-name-handler-alist'
907 and is a bit too general, then some files might be considered Tramp
908 files which are not really Tramp files.
910 Please note that the entry in `file-name-handler-alist' is made when
911 this file \(tramp.el\) is loaded. This means that this variable must be set
912 before loading tramp.el. Alternatively, `file-name-handler-alist' can be
913 updated after changing this variable.
915 Also see `tramp-file-name-structure'.")
918 (defconst tramp-completion-file-name-regexp-unified
919 (if (memq system-type '(cygwin windows-nt))
920 "\\`/[^/]\\{2,\\}\\'" "\\`/[^/]*\\'")
921 "Value for `tramp-completion-file-name-regexp' for unified remoting.
922 GNU Emacs uses a unified filename syntax for Tramp and Ange-FTP.
923 See `tramp-file-name-structure' for more explanations.
925 On W32 systems, the volume letter must be ignored.")
928 (defconst tramp-completion-file-name-regexp-separate
929 "\\`/\\([[][^]]*\\)?\\'"
930 "Value for `tramp-completion-file-name-regexp' for separate remoting.
931 XEmacs uses a separate filename syntax for Tramp and EFS.
932 See `tramp-file-name-structure' for more explanations.")
935 (defconst tramp-completion-file-name-regexp-url
936 "\\`/[^/:]+\\(:\\(/\\(/[^/]*\\)?\\)?\\)?\\'"
937 "Value for `tramp-completion-file-name-regexp' for URL-like remoting.
938 See `tramp-file-name-structure' for more explanations.")
941 (defconst tramp-completion-file-name-regexp
942 (cond ((equal tramp-syntax 'ftp) tramp-completion-file-name-regexp-unified)
943 ((equal tramp-syntax 'sep) tramp-completion-file-name-regexp-separate)
944 ((equal tramp-syntax 'url) tramp-completion-file-name-regexp-url)
945 (t (error "Wrong `tramp-syntax' defined")))
946 "Regular expression matching file names handled by Tramp completion.
947 This regexp should match partial Tramp file names only.
949 Please note that the entry in `file-name-handler-alist' is made when
950 this file \(tramp.el\) is loaded. This means that this variable must be set
951 before loading tramp.el. Alternatively, `file-name-handler-alist' can be
952 updated after changing this variable.
954 Also see `tramp-file-name-structure'.")
956 ;; Chunked sending kludge. We set this to 500 for black-listed constellations
957 ;; known to have a bug in `process-send-string'; some ssh connections appear
958 ;; to drop bytes when data is sent too quickly. There is also a connection
959 ;; buffer local variable, which is computed depending on remote host properties
960 ;; when `tramp-chunksize' is zero or nil.
961 (defcustom tramp-chunksize
962 (when (and (not (featurep 'xemacs))
963 (memq system-type '(hpux)))
965 ;; Parentheses in docstring starting at beginning of line are escaped.
966 ;; Fontification is messed up when
967 ;; `open-paren-in-column-0-is-defun-start' set to t.
968 "If non-nil, chunksize for sending input to local process.
969 It is necessary only on systems which have a buggy `process-send-string'
970 implementation. The necessity, whether this variable must be set, can be
971 checked via the following code:
974 (let* ((user \"xxx\") (host \"yyy\")
976 (sent init) (received init))
977 (while (= sent received)
978 (setq sent (+ sent step))
980 (let ((proc (start-process (buffer-name) (current-buffer)
981 \"ssh\" \"-l\" user host \"wc\" \"-c\")))
982 (when (memq (process-status proc) '(run open))
983 (process-send-string proc (make-string sent ?\\ ))
984 (process-send-eof proc)
985 (process-send-eof proc))
986 (while (not (progn (goto-char (point-min))
987 (re-search-forward \"\\\\w+\" (point-max) t)))
988 (accept-process-output proc 1))
989 (when (memq (process-status proc) '(run open))
990 (setq received (string-to-number (match-string 0)))
991 (delete-process proc)
992 (message \"Bytes sent: %s\\tBytes received: %s\" sent received)
994 (if (> sent (+ init step))
995 (message \"You should set `tramp-chunksize' to a maximum of %s\"
997 (message \"Test does not work\")
998 (display-buffer (current-buffer))
1001 In the Emacs normally running Tramp, evaluate the above code
1002 \(replace \"xxx\" and \"yyy\" by the remote user and host name,
1003 respectively\). You can do this, for example, by pasting it into
1004 the `*scratch*' buffer and then hitting C-j with the cursor after the
1005 last closing parenthesis. Note that it works only if you have configured
1006 \"ssh\" to run without password query, see ssh-agent\(1\).
1008 You will see the number of bytes sent successfully to the remote host.
1009 If that number exceeds 1000, you can stop the execution by hitting
1010 C-g, because your Emacs is likely clean.
1012 When it is necessary to set `tramp-chunksize', you might consider to
1013 use an out-of-the-band method \(like \"scp\"\) instead of an internal one
1014 \(like \"ssh\"\), because setting `tramp-chunksize' to non-nil decreases
1017 If your Emacs is buggy, the code stops and gives you an indication
1018 about the value `tramp-chunksize' should be set. Maybe you could just
1019 experiment a bit, e.g. changing the values of `init' and `step'
1020 in the third line of the code.
1022 Please raise a bug report via \"M-x tramp-bug\" if your system needs
1023 this variable to be set as well."
1025 :type '(choice (const nil) integer))
1027 ;; Logging in to a remote host normally requires obtaining a pty. But
1028 ;; Emacs on MacOS X has process-connection-type set to nil by default,
1029 ;; so on those systems Tramp doesn't obtain a pty. Here, we allow
1030 ;; for an override of the system default.
1031 (defcustom tramp-process-connection-type t
1032 "Overrides `process-connection-type' for connections from Tramp.
1033 Tramp binds `process-connection-type' to the value given here before
1034 opening a connection to a remote host."
1036 :type '(choice (const nil) (const t) (const pty)))
1038 (defcustom tramp-connection-min-time-diff 5
1039 "Defines seconds between two consecutive connection attempts.
1040 This is necessary as self defense mechanism, in order to avoid
1041 yo-yo connection attempts when the remote host is unavailable.
1043 A value of 0 or `nil' suppresses this check. This might be
1044 necessary, when several out-of-order copy operations are
1045 performed, or when several asynchronous processes will be started
1046 in a short time frame. In those cases it is recommended to
1047 let-bind this variable."
1050 :type '(choice (const nil) integer))
1052 (defcustom tramp-completion-reread-directory-timeout 10
1053 "Defines seconds since last remote command before rereading a directory.
1054 A remote directory might have changed its contents. In order to
1055 make it visible during file name completion in the minibuffer,
1056 Tramp flushes its cache and rereads the directory contents when
1057 more than `tramp-completion-reread-directory-timeout' seconds
1058 have been gone since last remote command execution. A value of `t'
1059 would require an immediate reread during filename completion, `nil'
1060 means to use always cached values for the directory contents."
1062 :type '(choice (const nil) (const t) integer))
1064 ;;; Internal Variables:
1066 (defvar tramp-current-method nil
1067 "Connection method for this *tramp* buffer.")
1069 (defvar tramp-current-user nil
1070 "Remote login name for this *tramp* buffer.")
1072 (defvar tramp-current-host nil
1073 "Remote host for this *tramp* buffer.")
1076 (defconst tramp-completion-file-name-handler-alist
1077 '((file-name-all-completions . tramp-completion-handle-file-name-all-completions)
1078 (file-name-completion . tramp-completion-handle-file-name-completion))
1079 "Alist of completion handler functions.
1080 Used for file names matching `tramp-file-name-regexp'. Operations
1081 not mentioned here will be handled by Tramp's file name handler
1082 functions, or the normal Emacs functions.")
1084 ;; Handlers for foreign methods, like FTP or SMB, shall be plugged here.
1085 ;;;###tramp-autoload
1086 (defvar tramp-foreign-file-name-handler-alist nil
1087 "Alist of elements (FUNCTION . HANDLER) for foreign methods handled specially.
1088 If (FUNCTION FILENAME) returns non-nil, then all I/O on that file is done by
1091 ;;; Internal functions which must come first:
1093 ;; Conversion functions between external representation and
1094 ;; internal data structure. Convenience functions for internal
1097 (defun tramp-get-method-parameter (method param)
1098 "Return the method parameter PARAM.
1099 If the `tramp-methods' entry does not exist, return nil."
1100 (let ((entry (assoc param (assoc method tramp-methods))))
1101 (when entry (cadr entry))))
1103 (defun tramp-file-name-p (vec)
1104 "Check, whether VEC is a Tramp object."
1105 (and (vectorp vec) (= 5 (length vec))))
1107 (defun tramp-file-name-method (vec)
1108 "Return method component of VEC."
1109 (and (tramp-file-name-p vec) (aref vec 0)))
1111 (defun tramp-file-name-user (vec)
1112 "Return user component of VEC."
1113 (and (tramp-file-name-p vec) (aref vec 1)))
1115 (defun tramp-file-name-host (vec)
1116 "Return host component of VEC."
1117 (and (tramp-file-name-p vec) (aref vec 2)))
1119 (defun tramp-file-name-localname (vec)
1120 "Return localname component of VEC."
1121 (and (tramp-file-name-p vec) (aref vec 3)))
1123 (defun tramp-file-name-hop (vec)
1124 "Return hop component of VEC."
1125 (and (tramp-file-name-p vec) (aref vec 4)))
1127 ;; The user part of a Tramp file name vector can be of kind
1128 ;; "user%domain". Sometimes, we must extract these parts.
1129 (defun tramp-file-name-real-user (vec)
1130 "Return the user name of VEC without domain."
1132 (let ((user (tramp-file-name-user vec)))
1133 (if (and (stringp user)
1134 (string-match tramp-user-with-domain-regexp user))
1135 (match-string 1 user)
1138 (defun tramp-file-name-domain (vec)
1139 "Return the domain name of VEC."
1141 (let ((user (tramp-file-name-user vec)))
1143 (string-match tramp-user-with-domain-regexp user)
1144 (match-string 2 user)))))
1146 ;; The host part of a Tramp file name vector can be of kind
1147 ;; "host#port". Sometimes, we must extract these parts.
1148 (defun tramp-file-name-real-host (vec)
1149 "Return the host name of VEC without port."
1151 (let ((host (tramp-file-name-host vec)))
1152 (if (and (stringp host)
1153 (string-match tramp-host-with-port-regexp host))
1154 (match-string 1 host)
1157 (defun tramp-file-name-port (vec)
1158 "Return the port number of VEC."
1160 (let ((method (tramp-file-name-method vec))
1161 (host (tramp-file-name-host vec)))
1162 (or (and (stringp host)
1163 (string-match tramp-host-with-port-regexp host)
1164 (string-to-number (match-string 2 host)))
1165 (tramp-get-method-parameter method 'tramp-default-port)))))
1167 ;;;###tramp-autoload
1168 (defun tramp-tramp-file-p (name)
1169 "Return t if NAME is a string with Tramp file name syntax."
1172 (string-match tramp-file-name-regexp name))))
1174 (defun tramp-find-method (method user host)
1175 "Return the right method string to use.
1176 This is METHOD, if non-nil. Otherwise, do a lookup in
1177 `tramp-default-method-alist'."
1179 (let ((choices tramp-default-method-alist)
1182 (setq item (pop choices))
1183 (when (and (string-match (or (nth 0 item) "") (or host ""))
1184 (string-match (or (nth 1 item) "") (or user "")))
1185 (setq lmethod (nth 2 item))
1186 (setq choices nil)))
1188 tramp-default-method))
1190 (defun tramp-find-user (method user host)
1191 "Return the right user string to use.
1192 This is USER, if non-nil. Otherwise, do a lookup in
1193 `tramp-default-user-alist'."
1195 (let ((choices tramp-default-user-alist)
1198 (setq item (pop choices))
1199 (when (and (string-match (or (nth 0 item) "") (or method ""))
1200 (string-match (or (nth 1 item) "") (or host "")))
1201 (setq luser (nth 2 item))
1202 (setq choices nil)))
1204 tramp-default-user))
1206 (defun tramp-find-host (method user host)
1207 "Return the right host string to use.
1208 This is HOST, if non-nil. Otherwise, it is `tramp-default-host'."
1209 (or (and (> (length host) 0) host)
1210 (let ((choices tramp-default-host-alist)
1213 (setq item (pop choices))
1214 (when (and (string-match (or (nth 0 item) "") (or method ""))
1215 (string-match (or (nth 1 item) "") (or user "")))
1216 (setq lhost (nth 2 item))
1217 (setq choices nil)))
1219 tramp-default-host))
1221 (defun tramp-dissect-file-name (name &optional nodefault)
1222 "Return a `tramp-file-name' structure.
1223 The structure consists of remote method, remote user, remote host
1224 and localname (file name on remote host). If NODEFAULT is
1225 non-nil, the file name parts are not expanded to their default
1228 (let ((match (string-match (nth 0 tramp-file-name-structure) name)))
1229 (unless match (error "Not a Tramp file name: %s" name))
1230 (let ((method (match-string (nth 1 tramp-file-name-structure) name))
1231 (user (match-string (nth 2 tramp-file-name-structure) name))
1232 (host (match-string (nth 3 tramp-file-name-structure) name))
1233 (localname (match-string (nth 4 tramp-file-name-structure) name))
1234 (hop (match-string (nth 5 tramp-file-name-structure) name)))
1236 (when (string-match tramp-prefix-ipv6-regexp host)
1237 (setq host (replace-match "" nil t host)))
1238 (when (string-match tramp-postfix-ipv6-regexp host)
1239 (setq host (replace-match "" nil t host))))
1241 (vector method user host localname hop)
1243 (tramp-find-method method user host)
1244 (tramp-find-user method user host)
1245 (tramp-find-host method user host)
1248 (defun tramp-buffer-name (vec)
1249 "A name for the connection buffer VEC."
1250 ;; We must use `tramp-file-name-real-host', because for gateway
1251 ;; methods the default port will be expanded later on, which would
1253 (let ((method (tramp-file-name-method vec))
1254 (user (tramp-file-name-user vec))
1255 (host (tramp-file-name-real-host vec)))
1256 (if (not (zerop (length user)))
1257 (format "*tramp/%s %s@%s*" method user host)
1258 (format "*tramp/%s %s*" method host))))
1260 (defun tramp-make-tramp-file-name (method user host localname &optional hop)
1261 "Constructs a Tramp file name from METHOD, USER, HOST and LOCALNAME.
1262 When not nil, an optional HOP is prepended."
1263 (concat tramp-prefix-format hop
1264 (when (not (zerop (length method)))
1265 (concat method tramp-postfix-method-format))
1266 (when (not (zerop (length user)))
1267 (concat user tramp-postfix-user-format))
1269 (if (string-match tramp-ipv6-regexp host)
1270 (concat tramp-prefix-ipv6-format host tramp-postfix-ipv6-format)
1272 tramp-postfix-host-format
1273 (when localname localname)))
1275 (defun tramp-completion-make-tramp-file-name (method user host localname)
1276 "Constructs a Tramp file name from METHOD, USER, HOST and LOCALNAME.
1277 It must not be a complete Tramp file name, but as long as there are
1278 necessary only. This function will be used in file name completion."
1279 (concat tramp-prefix-format
1280 (when (not (zerop (length method)))
1281 (concat method tramp-postfix-method-format))
1282 (when (not (zerop (length user)))
1283 (concat user tramp-postfix-user-format))
1284 (when (not (zerop (length host)))
1286 (if (string-match tramp-ipv6-regexp host)
1288 tramp-prefix-ipv6-format host tramp-postfix-ipv6-format)
1290 tramp-postfix-host-format))
1291 (when localname localname)))
1293 (defun tramp-get-buffer (vec)
1294 "Get the connection buffer to be used for VEC."
1295 (or (get-buffer (tramp-buffer-name vec))
1296 (with-current-buffer (get-buffer-create (tramp-buffer-name vec))
1297 (setq buffer-undo-list t)
1298 (setq default-directory
1299 (tramp-make-tramp-file-name
1300 (tramp-file-name-method vec)
1301 (tramp-file-name-user vec)
1302 (tramp-file-name-host vec)
1306 (defun tramp-get-connection-buffer (vec)
1307 "Get the connection buffer to be used for VEC.
1308 In case a second asynchronous communication has been started, it is different
1309 from `tramp-get-buffer'."
1310 (or (tramp-get-connection-property vec "process-buffer" nil)
1311 (tramp-get-buffer vec)))
1313 (defun tramp-get-connection-name (vec)
1314 "Get the connection name to be used for VEC.
1315 In case a second asynchronous communication has been started, it is different
1316 from the default one."
1317 (or (tramp-get-connection-property vec "process-name" nil)
1318 (tramp-buffer-name vec)))
1320 (defun tramp-get-connection-process (vec)
1321 "Get the connection process to be used for VEC.
1322 In case a second asynchronous communication has been started, it is different
1323 from the default one."
1324 (get-process (tramp-get-connection-name vec)))
1326 (defun tramp-debug-buffer-name (vec)
1327 "A name for the debug buffer for VEC."
1328 ;; We must use `tramp-file-name-real-host', because for gateway
1329 ;; methods the default port will be expanded later on, which would
1331 (let ((method (tramp-file-name-method vec))
1332 (user (tramp-file-name-user vec))
1333 (host (tramp-file-name-real-host vec)))
1334 (if (not (zerop (length user)))
1335 (format "*debug tramp/%s %s@%s*" method user host)
1336 (format "*debug tramp/%s %s*" method host))))
1338 (defconst tramp-debug-outline-regexp
1339 "[0-9]+:[0-9]+:[0-9]+\\.[0-9]+ [a-z0-9-]+ (\\([0-9]+\\)) #"
1340 "Used for highlighting Tramp debug buffers in `outline-mode'.")
1342 (defun tramp-debug-outline-level ()
1343 "Return the depth to which a statement is nested in the outline.
1344 Point must be at the beginning of a header line.
1346 The outline level is equal to the verbosity of the Tramp message."
1347 (1+ (string-to-number (match-string 1))))
1349 (defun tramp-get-debug-buffer (vec)
1350 "Get the debug buffer for VEC."
1351 (with-current-buffer
1352 (get-buffer-create (tramp-debug-buffer-name vec))
1354 (setq buffer-undo-list t)
1355 ;; So it does not get loaded while `outline-regexp' is let-bound.
1357 ;; Activate `outline-mode'. This runs `text-mode-hook' and
1358 ;; `outline-mode-hook'. We must prevent that local processes
1359 ;; die. Yes: I've seen `flyspell-mode', which starts "ispell".
1360 ;; Furthermore, `outline-regexp' must have the correct value
1361 ;; already, because it is used by `font-lock-compile-keywords'.
1362 (let ((default-directory (tramp-compat-temporary-file-directory))
1363 (outline-regexp tramp-debug-outline-regexp))
1365 (set (make-local-variable 'outline-regexp) tramp-debug-outline-regexp)
1366 (set (make-local-variable 'outline-level) 'tramp-debug-outline-level))
1369 (defsubst tramp-debug-message (vec fmt-string &rest args)
1370 "Append message to debug buffer.
1371 Message is formatted with FMT-STRING as control string and the remaining
1372 ARGS to actually emit the message (if applicable)."
1373 (when (get-buffer (tramp-buffer-name vec))
1374 (with-current-buffer (tramp-get-debug-buffer vec)
1375 (goto-char (point-max))
1380 ";; %sEmacs: %s Tramp: %s -*- mode: outline; -*-"
1381 (if (featurep 'sxemacs) "SX" (if (featurep 'xemacs) "X" "GNU "))
1382 emacs-version tramp-version)))
1386 (let ((now (current-time)))
1387 (insert (format-time-string "%T." now))
1388 (insert (format "%06d " (nth 2 now))))
1389 ;; Calling Tramp function. We suppress compat and trace
1390 ;; functions from being displayed.
1391 (let ((btn 1) btf fn)
1393 (setq btf (nth 1 (backtrace-frame btn)))
1397 (setq fn (symbol-name btf))
1400 (string-match "^tramp" fn)
1407 "tramp-compat-condition-case-unless-debug"
1408 "tramp-compat-funcall"
1409 "tramp-compat-with-temp-message"
1410 "tramp-condition-case-unless-debug"
1411 "tramp-debug-message"
1413 "tramp-error-with-buffer"
1419 (setq btn (1+ btn))))
1420 ;; The following code inserts filename and line number.
1421 ;; Should be inactive by default, because it is time
1423 ; (let ((ffn (find-function-noselect (intern fn))))
1427 ; (file-name-nondirectory (buffer-file-name (car ffn)))
1428 ; (with-current-buffer (car ffn)
1429 ; (1+ (count-lines (point-min) (cdr ffn)))))))
1430 (insert (format "%s " fn)))
1432 (insert (apply 'format fmt-string args)))))
1434 (defvar tramp-message-show-message t
1435 "Show Tramp message in the minibuffer.
1436 This variable is used to disable messages from `tramp-error'.
1437 The messages are visible anyway, because an error is raised.")
1439 (defvar tramp-message-show-progress-reporter-message t
1440 "Show Tramp progress reporter message in the minibuffer.
1441 This variable is used to disable recursive progress reporter messages.")
1443 (defsubst tramp-message (vec-or-proc level fmt-string &rest args)
1444 "Emit a message depending on verbosity level.
1445 VEC-OR-PROC identifies the Tramp buffer to use. It can be either a
1446 vector or a process. LEVEL says to be quiet if `tramp-verbose' is
1447 less than LEVEL. The message is emitted only if `tramp-verbose' is
1448 greater than or equal to LEVEL.
1450 The message is also logged into the debug buffer when `tramp-verbose'
1451 is greater than or equal 4.
1453 Calls functions `message' and `tramp-debug-message' with FMT-STRING as
1454 control string and the remaining ARGS to actually emit the message (if
1457 (when (<= level tramp-verbose)
1458 ;; Match data must be preserved!
1460 ;; Display only when there is a minimum level.
1461 (when (and tramp-message-show-message (<= level 3))
1467 ((= level 2) "Warning: ")
1471 ;; Log only when there is a minimum level.
1472 (when (>= tramp-verbose 4)
1473 (when (and vec-or-proc
1474 (processp vec-or-proc)
1475 (buffer-name (process-buffer vec-or-proc)))
1476 (with-current-buffer (process-buffer vec-or-proc)
1477 ;; Translate proc to vec.
1478 (setq vec-or-proc (tramp-dissect-file-name default-directory))))
1479 (when (and vec-or-proc (vectorp vec-or-proc))
1480 (apply 'tramp-debug-message
1482 (concat (format "(%d) # " level) fmt-string)
1485 (defsubst tramp-error (vec-or-proc signal fmt-string &rest args)
1487 VEC-OR-PROC identifies the connection to use, SIGNAL is the
1488 signal identifier to be raised, remaining args passed to
1489 `tramp-message'. Finally, signal SIGNAL is raised."
1490 (let (tramp-message-show-message)
1493 (error-message-string
1495 (get signal 'error-message)
1496 (apply 'format fmt-string args))))
1497 (signal signal (list (apply 'format fmt-string args)))))
1499 (defsubst tramp-error-with-buffer
1500 (buffer vec-or-proc signal fmt-string &rest args)
1501 "Emit an error, and show BUFFER.
1502 If BUFFER is nil, show the connection buffer. Wait for 30\", or until
1503 an input event arrives. The other arguments are passed to `tramp-error'."
1504 (save-window-excursion
1506 (apply 'tramp-error vec-or-proc signal fmt-string args)
1507 (when (and vec-or-proc
1508 tramp-message-show-message
1509 (not (zerop tramp-verbose))
1510 (not (tramp-completion-mode-p)))
1511 (let ((enable-recursive-minibuffers t))
1513 (or (and (bufferp buffer) buffer)
1514 (and (processp vec-or-proc) (process-buffer vec-or-proc))
1515 (tramp-get-connection-buffer vec-or-proc)))
1516 (when (string-equal fmt-string "Process died")
1519 "Tramp failed to connect. If this happens repeatedly, try"
1520 "`M-x tramp-cleanup-this-connection'"))
1523 (defsubst tramp-backtrace (vec-or-proc)
1524 "Dump a backtrace into the debug buffer.
1525 This function is meant for debugging purposes."
1526 (tramp-message vec-or-proc 10 "\n%s" (with-output-to-string (backtrace))))
1528 (defmacro with-parsed-tramp-file-name (filename var &rest body)
1529 "Parse a Tramp filename and make components available in the body.
1531 First arg FILENAME is evaluated and dissected into its components.
1532 Second arg VAR is a symbol. It is used as a variable name to hold
1533 the filename structure. It is also used as a prefix for the variables
1534 holding the components. For example, if VAR is the symbol `foo', then
1535 `foo' will be bound to the whole structure, `foo-method' will be bound to
1536 the method component, and so on for `foo-user', `foo-host', `foo-localname',
1539 Remaining args are Lisp expressions to be evaluated (inside an implicit
1542 If VAR is nil, then we bind `v' to the structure and `method', `user',
1543 `host', `localname', `hop' to the components."
1544 `(let* ((,(or var 'v) (tramp-dissect-file-name ,filename))
1545 (,(if var (intern (concat (symbol-name var) "-method")) 'method)
1546 (tramp-file-name-method ,(or var 'v)))
1547 (,(if var (intern (concat (symbol-name var) "-user")) 'user)
1548 (tramp-file-name-user ,(or var 'v)))
1549 (,(if var (intern (concat (symbol-name var) "-host")) 'host)
1550 (tramp-file-name-host ,(or var 'v)))
1551 (,(if var (intern (concat (symbol-name var) "-localname")) 'localname)
1552 (tramp-file-name-localname ,(or var 'v)))
1553 (,(if var (intern (concat (symbol-name var) "-hop")) 'hop)
1554 (tramp-file-name-hop ,(or var 'v))))
1557 (put 'with-parsed-tramp-file-name 'lisp-indent-function 2)
1558 (put 'with-parsed-tramp-file-name 'edebug-form-spec '(form symbolp body))
1559 (tramp-compat-font-lock-add-keywords
1560 'emacs-lisp-mode '("\\<with-parsed-tramp-file-name\\>"))
1562 (defun tramp-progress-reporter-update (reporter &optional value)
1563 (let* ((parameters (cdr reporter))
1564 (message (aref parameters 3)))
1565 (when (string-match message (or (current-message) ""))
1566 (tramp-compat-funcall 'progress-reporter-update reporter value))))
1568 (defmacro with-tramp-progress-reporter (vec level message &rest body)
1569 "Executes BODY, spinning a progress reporter with MESSAGE.
1570 If LEVEL does not fit for visible messages, or if this is a
1571 nested call of the macro, there are only traces without a visible
1573 (declare (indent 3) (debug t))
1575 (tramp-message ,vec ,level "%s..." ,message)
1576 ;; We start a pulsing progress reporter after 3 seconds. Feature
1577 ;; introduced in Emacs 24.1.
1578 (when (and tramp-message-show-progress-reporter-message
1579 tramp-message-show-message
1580 ;; Display only when there is a minimum level.
1581 (<= ,level (min tramp-verbose 3)))
1583 (setq pr (tramp-compat-funcall 'make-progress-reporter ,message)
1585 (run-at-time 3 0.1 'tramp-progress-reporter-update pr)))))
1587 ;; Execute the body. Suppress concurrent progress reporter
1589 (let ((tramp-message-show-progress-reporter-message
1590 (and tramp-message-show-progress-reporter-message (not tm))))
1592 ;; Stop progress reporter.
1593 (if tm (tramp-compat-funcall 'cancel-timer tm))
1594 (tramp-message ,vec ,level "%s...done" ,message))))
1596 (tramp-compat-font-lock-add-keywords
1597 'emacs-lisp-mode '("\\<with-tramp-progress-reporter\\>"))
1599 (defmacro with-tramp-file-property (vec file property &rest body)
1600 "Check in Tramp cache for PROPERTY, otherwise execute BODY and set cache.
1601 FILE must be a local file name on a connection identified via VEC."
1602 `(if (file-name-absolute-p ,file)
1603 (let ((value (tramp-get-file-property ,vec ,file ,property 'undef)))
1604 (when (eq value 'undef)
1605 ;; We cannot pass @body as parameter to
1606 ;; `tramp-set-file-property' because it mangles our
1608 (setq value (progn ,@body))
1609 (tramp-set-file-property ,vec ,file ,property value))
1613 (put 'with-tramp-file-property 'lisp-indent-function 3)
1614 (put 'with-tramp-file-property 'edebug-form-spec t)
1615 (tramp-compat-font-lock-add-keywords
1616 'emacs-lisp-mode '("\\<with-tramp-file-property\\>"))
1618 (defmacro with-tramp-connection-property (key property &rest body)
1619 "Check in Tramp for property PROPERTY, otherwise executes BODY and set."
1620 `(let ((value (tramp-get-connection-property ,key ,property 'undef)))
1621 (when (eq value 'undef)
1622 ;; We cannot pass ,@body as parameter to
1623 ;; `tramp-set-connection-property' because it mangles our debug
1625 (setq value (progn ,@body))
1626 (tramp-set-connection-property ,key ,property value))
1629 (put 'with-tramp-connection-property 'lisp-indent-function 2)
1630 (put 'with-tramp-connection-property 'edebug-form-spec t)
1631 (tramp-compat-font-lock-add-keywords
1632 'emacs-lisp-mode '("\\<with-tramp-connection-property\\>"))
1634 (defalias 'tramp-drop-volume-letter
1635 (if (memq system-type '(cygwin windows-nt))
1637 "Cut off unnecessary drive letter from file NAME.
1638 The functions `tramp-*-handle-expand-file-name' call `expand-file-name'
1639 locally on a remote file name. When the local system is a W32 system
1640 but the remote system is Unix, this introduces a superfluous drive
1641 letter into the file name. This function removes it."
1643 (if (string-match "\\`[a-zA-Z]:/" name)
1644 (replace-match "/" nil t name)
1649 (if (featurep 'xemacs)
1650 (defalias 'tramp-drop-volume-letter 'identity))
1652 (defun tramp-cleanup (vec)
1653 "Cleanup connection VEC, but keep the debug buffer."
1654 (with-current-buffer (tramp-get-debug-buffer vec)
1655 ;; Keep the debug buffer.
1657 (generate-new-buffer-name tramp-temp-buffer-name) 'unique)
1658 (tramp-cleanup-connection vec)
1659 (if (= (point-min) (point-max))
1661 (rename-buffer (tramp-debug-buffer-name vec) 'unique))
1662 ;; We call `tramp-get-buffer' in order to keep the debug buffer.
1663 (tramp-get-buffer vec)))
1665 ;;; Config Manipulation Functions:
1667 ;;;###tramp-autoload
1668 (defun tramp-set-completion-function (method function-list)
1669 "Sets the list of completion functions for METHOD.
1670 FUNCTION-LIST is a list of entries of the form (FUNCTION FILE).
1671 The FUNCTION is intended to parse FILE according its syntax.
1672 It might be a predefined FUNCTION, or a user defined FUNCTION.
1673 For the list of predefined FUNCTIONs see `tramp-completion-function-alist'.
1677 (tramp-set-completion-function
1679 '((tramp-parse-sconfig \"/etc/ssh_config\")
1680 (tramp-parse-sconfig \"~/.ssh/config\")))"
1682 (let ((r function-list)
1684 (setq tramp-completion-function-alist
1685 (delete (assoc method tramp-completion-function-alist)
1686 tramp-completion-function-alist))
1689 ;; Remove double entries.
1690 (when (member (car v) (cdr v))
1691 (setcdr v (delete (car v) (cdr v))))
1692 ;; Check for function and file or registry key.
1693 (unless (and (functionp (nth 0 (car v)))
1694 (if (string-match "^HKEY_CURRENT_USER" (nth 1 (car v)))
1695 ;; Windows registry.
1696 (and (memq system-type '(cygwin windows-nt))
1698 (tramp-compat-call-process
1699 "reg" nil nil nil "query" (nth 1 (car v)))))
1700 ;; Configuration file.
1701 (file-exists-p (nth 1 (car v)))))
1702 (setq r (delete (car v) r)))
1706 (add-to-list 'tramp-completion-function-alist
1709 (defun tramp-get-completion-function (method)
1710 "Returns a list of completion functions for METHOD.
1711 For definition of that list see `tramp-set-completion-function'."
1713 ;; Hosts visited once shall be remembered.
1714 `(tramp-parse-connection-properties ,method)
1715 ;; The method related defaults.
1716 (cdr (assoc method tramp-completion-function-alist))))
1719 ;;; Fontification of `read-file-name':
1721 ;; rfn-eshadow.el is part of Emacs 22. It is autoloaded.
1722 (defvar tramp-rfn-eshadow-overlay)
1723 (make-variable-buffer-local 'tramp-rfn-eshadow-overlay)
1725 (defun tramp-rfn-eshadow-setup-minibuffer ()
1726 "Set up a minibuffer for `file-name-shadow-mode'.
1727 Adds another overlay hiding filename parts according to Tramp's
1728 special handling of `substitute-in-file-name'."
1729 (when (symbol-value 'minibuffer-completing-file-name)
1730 (setq tramp-rfn-eshadow-overlay
1731 (tramp-compat-funcall
1733 (tramp-compat-funcall 'minibuffer-prompt-end)
1734 (tramp-compat-funcall 'minibuffer-prompt-end)))
1735 ;; Copy rfn-eshadow-overlay properties.
1736 (let ((props (tramp-compat-funcall
1737 'overlay-properties (symbol-value 'rfn-eshadow-overlay))))
1739 ;; The `field' property prevents correct minibuffer
1740 ;; completion; we exclude it.
1741 (if (not (eq (car props) 'field))
1742 (tramp-compat-funcall
1743 'overlay-put tramp-rfn-eshadow-overlay (pop props) (pop props))
1744 (pop props) (pop props))))))
1746 (when (boundp 'rfn-eshadow-setup-minibuffer-hook)
1747 (add-hook 'rfn-eshadow-setup-minibuffer-hook
1748 'tramp-rfn-eshadow-setup-minibuffer)
1749 (add-hook 'tramp-unload-hook
1751 (remove-hook 'rfn-eshadow-setup-minibuffer-hook
1752 'tramp-rfn-eshadow-setup-minibuffer))))
1754 (defconst tramp-rfn-eshadow-update-overlay-regexp
1755 (format "[^%s/~]*\\(/\\|~\\)" tramp-postfix-host-format))
1757 (defun tramp-rfn-eshadow-update-overlay ()
1758 "Update `rfn-eshadow-overlay' to cover shadowed part of minibuffer input.
1759 This is intended to be used as a minibuffer `post-command-hook' for
1760 `file-name-shadow-mode'; the minibuffer should have already
1761 been set up by `rfn-eshadow-setup-minibuffer'."
1762 ;; In remote files name, there is a shadowing just for the local part.
1764 (let ((end (or (tramp-compat-funcall
1765 'overlay-end (symbol-value 'rfn-eshadow-overlay))
1766 (tramp-compat-funcall 'minibuffer-prompt-end)))
1767 ;; We do not want to send any remote command.
1771 (tramp-compat-funcall
1772 'buffer-substring-no-properties end (point-max)))
1776 (1+ (or (string-match
1777 tramp-rfn-eshadow-update-overlay-regexp
1778 (buffer-string) end)
1781 (let ((rfn-eshadow-overlay tramp-rfn-eshadow-overlay)
1782 (rfn-eshadow-update-overlay-hook nil)
1783 file-name-handler-alist)
1784 (tramp-compat-funcall
1785 'move-overlay rfn-eshadow-overlay (point-max) (point-max))
1786 (tramp-compat-funcall 'rfn-eshadow-update-overlay))))))))
1788 (when (boundp 'rfn-eshadow-update-overlay-hook)
1789 (add-hook 'rfn-eshadow-update-overlay-hook
1790 'tramp-rfn-eshadow-update-overlay)
1791 (add-hook 'tramp-unload-hook
1793 (remove-hook 'rfn-eshadow-update-overlay-hook
1794 'tramp-rfn-eshadow-update-overlay))))
1796 ;; Inodes don't exist for some file systems. Therefore we must
1797 ;; generate virtual ones. Used in `find-buffer-visiting'. The method
1798 ;; applied might be not so efficient (Ange-FTP uses hashes). But
1799 ;; performance isn't the major issue given that file transfer will
1801 (defvar tramp-inodes 0
1802 "Keeps virtual inodes numbers.")
1804 ;; Devices must distinguish physical file systems. The device numbers
1805 ;; provided by "lstat" aren't unique, because we operate on different hosts.
1806 ;; So we use virtual device numbers, generated by Tramp. Both Ange-FTP and
1807 ;; EFS use device number "-1". In order to be different, we use device number
1808 ;; (-1 . x), whereby "x" is unique for a given (method user host).
1809 (defvar tramp-devices 0
1810 "Keeps virtual device numbers.")
1812 (defun tramp-default-file-modes (filename)
1813 "Return file modes of FILENAME as integer.
1814 If the file modes of FILENAME cannot be determined, return the
1815 value of `default-file-modes', without execute permissions."
1816 (or (file-modes filename)
1817 (logand (default-file-modes) (tramp-compat-octal-to-decimal "0666"))))
1819 (defun tramp-replace-environment-variables (filename)
1820 "Replace environment variables in FILENAME.
1821 Return the string with the replaced variables."
1823 (tramp-compat-funcall 'substitute-env-vars filename 'only-defined))
1824 ;; We need an own implementation.
1826 (let ((idx (string-match "$\\(\\w+\\)" filename)))
1827 ;; `$' is coded as `$$'.
1829 (or (zerop idx) (not (eq ?$ (aref filename (1- idx)))))
1830 (getenv (match-string 1 filename)))
1833 (substitute-in-file-name (match-string 0 filename))
1837 ;; In XEmacs, electricity is implemented via a key map for ?/ and ?~,
1838 ;; which calls corresponding functions (see minibuf.el).
1839 (when (fboundp 'minibuffer-electric-separator)
1844 (around ,(intern (format "tramp-advice-%s" x)) activate)
1845 "Invoke `substitute-in-file-name' for Tramp files."
1846 (if (and (symbol-value 'minibuffer-electric-file-name-behavior)
1847 (tramp-tramp-file-p (buffer-substring)))
1848 ;; We don't need to handle `last-input-event', because
1849 ;; due to the key map we know it must be ?/ or ?~.
1850 (let ((s (concat (buffer-substring (point-min) (point))
1851 (string last-command-char))))
1852 (delete-region (point-min) (point))
1853 (insert (substitute-in-file-name s))
1854 (setq ad-return-value last-command-char))
1860 (ad-remove-advice ',x 'around ',(intern (format "tramp-advice-%s" x)))
1861 (ad-activate ',x)))))
1863 '(minibuffer-electric-separator
1864 minibuffer-electric-tilde)))
1866 (defun tramp-find-file-name-coding-system-alist (filename tmpname)
1867 "Like `find-operation-coding-system' for Tramp filenames.
1868 Tramp's `insert-file-contents' and `write-region' work over
1869 temporary file names. If `file-coding-system-alist' contains an
1870 expression, which matches more than the file name suffix, the
1871 coding system might not be determined. This function repairs it."
1873 (dolist (elt file-coding-system-alist result)
1874 (when (and (consp elt) (string-match (car elt) filename))
1875 ;; We found a matching entry in `file-coding-system-alist'.
1876 ;; So we add a similar entry, but with the temporary file name
1879 'result (cons (regexp-quote tmpname) (cdr elt)) 'append)))))
1882 (progn (defun tramp-run-real-handler (operation args)
1883 "Invoke normal file name handler for OPERATION.
1884 First arg specifies the OPERATION, second arg is a list of arguments to
1885 pass to the OPERATION."
1886 (let* ((inhibit-file-name-handlers
1887 `(tramp-file-name-handler
1888 tramp-vc-file-name-handler
1889 tramp-completion-file-name-handler
1890 cygwin-mount-name-hook-function
1891 cygwin-mount-map-drive-hook-function
1893 ,(and (eq inhibit-file-name-operation operation)
1894 inhibit-file-name-handlers)))
1895 (inhibit-file-name-operation operation))
1896 (apply operation args))))
1899 (progn (defun tramp-completion-run-real-handler (operation args)
1900 "Invoke `tramp-file-name-handler' for OPERATION.
1901 First arg specifies the OPERATION, second arg is a list of arguments to
1902 pass to the OPERATION."
1903 (let* ((inhibit-file-name-handlers
1904 `(tramp-completion-file-name-handler
1905 cygwin-mount-name-hook-function
1906 cygwin-mount-map-drive-hook-function
1908 ,(and (eq inhibit-file-name-operation operation)
1909 inhibit-file-name-handlers)))
1910 (inhibit-file-name-operation operation))
1911 (apply operation args))))
1913 ;; We handle here all file primitives. Most of them have the file
1914 ;; name as first parameter; nevertheless we check for them explicitly
1915 ;; in order to be signaled if a new primitive appears. This
1916 ;; scenario is needed because there isn't a way to decide by
1917 ;; syntactical means whether a foreign method must be called. It would
1918 ;; ease the life if `file-name-handler-alist' would support a decision
1919 ;; function as well but regexp only.
1920 (defun tramp-file-name-for-operation (operation &rest args)
1921 "Return file name related to OPERATION file primitive.
1922 ARGS are the arguments OPERATION has been called with."
1924 ;; FILE resp DIRECTORY.
1926 (list 'access-file 'byte-compiler-base-file-name 'delete-directory
1927 'delete-file 'diff-latest-backup-file 'directory-file-name
1928 'directory-files 'directory-files-and-attributes
1929 'dired-compress-file 'dired-uncache
1930 'file-accessible-directory-p 'file-attributes
1931 'file-directory-p 'file-executable-p 'file-exists-p
1932 'file-local-copy 'file-remote-p 'file-modes
1933 'file-name-as-directory 'file-name-directory
1934 'file-name-nondirectory 'file-name-sans-versions
1935 'file-ownership-preserved-p 'file-readable-p
1936 'file-regular-p 'file-symlink-p 'file-truename
1937 'file-writable-p 'find-backup-file-name 'find-file-noselect
1938 'get-file-buffer 'insert-directory 'insert-file-contents
1939 'load 'make-directory 'make-directory-internal
1940 'set-file-modes 'substitute-in-file-name
1941 'unhandled-file-name-directory 'vc-registered
1945 'file-acl 'file-selinux-context
1946 'set-file-acl 'set-file-selinux-context
1948 'abbreviate-file-name 'create-file-buffer
1949 'dired-file-modtime 'dired-make-compressed-filename
1950 'dired-recursive-delete-directory 'dired-set-file-modtime
1951 'dired-shell-unhandle-file-name 'dired-uucode-file
1952 'insert-file-contents-literally 'make-temp-name 'recover-file
1953 'vm-imap-check-mail 'vm-pop-check-mail 'vm-spool-check-mail))
1954 (if (file-name-absolute-p (nth 0 args))
1956 (expand-file-name (nth 0 args))))
1957 ;; FILE DIRECTORY resp FILE1 FILE2.
1959 (list 'add-name-to-file 'copy-file 'expand-file-name
1960 'file-name-all-completions 'file-name-completion
1961 'file-newer-than-file-p 'make-symbolic-link 'rename-file
1965 'file-in-directory-p 'file-equal-p
1967 'dired-make-relative-symlink
1968 'vm-imap-move-mail 'vm-pop-move-mail 'vm-spool-move-mail))
1971 ((string-match tramp-file-name-regexp (nth 0 args)) (nth 0 args))
1972 ((string-match tramp-file-name-regexp (nth 1 args)) (nth 1 args))
1973 (t (buffer-file-name (current-buffer))))))
1975 ((eq operation 'write-region)
1979 (list 'set-visited-file-modtime 'verify-visited-file-modtime
1981 'make-auto-save-file-name
1985 (if (bufferp (nth 0 args)) (nth 0 args) (current-buffer))))
1988 (list ;; not in Emacs 23+.
1997 'dired-print-file 'dired-shell-call-process))
1999 ;; Unknown file primitive.
2000 (t (error "unknown file I/O primitive: %s" operation))))
2002 (defun tramp-find-foreign-file-name-handler (filename)
2003 "Return foreign file name handler if exists."
2004 (when (tramp-tramp-file-p filename)
2005 (let ((v (tramp-dissect-file-name filename t))
2006 (handler tramp-foreign-file-name-handler-alist)
2008 ;; When we are not fully sure that filename completion is safe,
2009 ;; we should not return a handler.
2010 (when (or (tramp-file-name-method v) (tramp-file-name-user v)
2011 (and (tramp-file-name-host v)
2012 (not (member (tramp-file-name-host v)
2013 (mapcar 'car tramp-methods))))
2014 (not (tramp-completion-mode-p)))
2016 (setq elt (car handler)
2017 handler (cdr handler))
2018 (when (funcall (car elt) filename)
2023 (defvar tramp-debug-on-error nil
2024 "Like `debug-on-error' but used Tramp internal.")
2026 (defmacro tramp-condition-case-unless-debug
2027 (var bodyform &rest handlers)
2028 "Like `condition-case-unless-debug' but `tramp-debug-on-error'."
2029 `(let ((debug-on-error tramp-debug-on-error))
2030 (tramp-compat-condition-case-unless-debug ,var ,bodyform ,@handlers)))
2034 (defun tramp-file-name-handler (operation &rest args)
2035 "Invoke Tramp file name handler.
2036 Falls back to normal file name handler if no Tramp file name handler exists."
2040 (tramp-replace-environment-variables
2041 (apply 'tramp-file-name-for-operation operation args)))
2042 (completion (tramp-completion-mode-p))
2043 (foreign (tramp-find-foreign-file-name-handler filename)))
2044 (with-parsed-tramp-file-name filename nil
2045 ;; Call the backend function.
2047 (tramp-condition-case-unless-debug err
2048 (let ((sf (symbol-function foreign))
2050 ;; Some packages set the default directory to a
2051 ;; remote path, before respective Tramp packages
2052 ;; are already loaded. This results in
2053 ;; recursive loading. Therefore, we load the
2054 ;; Tramp packages locally.
2055 (when (and (listp sf) (eq (car sf) 'autoload))
2056 (let ((default-directory
2057 (tramp-compat-temporary-file-directory)))
2058 (load (cadr sf) 'noerror 'nomessage)))
2059 ;; If `non-essential' is non-nil, Tramp shall
2060 ;; not open a new connection.
2061 ;; If Tramp detects that it shouldn't continue
2062 ;; to work, it throws the `suppress' event.
2063 ;; This could happen for example, when Tramp
2064 ;; tries to open the same connection twice in a
2065 ;; short time frame.
2066 ;; In both cases, we try the default handler then.
2068 (catch 'non-essential
2070 (apply foreign operation args))))
2072 ((eq result 'non-essential)
2074 v 5 "Non-essential received in operation %s"
2075 (append (list operation) args))
2076 (tramp-run-real-handler operation args))
2077 ((eq result 'suppress)
2078 (let (tramp-message-show-message)
2080 v 1 "Suppress received in operation %s"
2081 (append (list operation) args))
2083 (tramp-run-real-handler operation args)))
2086 ;; Trace that somebody has interrupted the operation.
2088 (let (tramp-message-show-message)
2090 v 1 "Interrupt received in operation %s"
2091 (append (list operation) args)))
2092 ;; Propagate the quit signal.
2093 (signal (car err) (cdr err)))
2095 ;; When we are in completion mode, some failed
2096 ;; operations shall return at least a default value
2097 ;; in order to give the user a chance to correct the
2098 ;; file name in the minibuffer.
2099 ;; In order to get a full backtrace, one could apply
2100 ;; (setq tramp-debug-on-error t)
2103 ((and completion (zerop (length localname))
2104 (memq operation '(file-exists-p file-directory-p)))
2106 ((and completion (zerop (length localname))
2108 '(expand-file-name file-name-as-directory)))
2110 ;; Propagate the error.
2111 (t (signal (car err) (cdr err))))))
2113 ;; Nothing to do for us.
2114 (tramp-run-real-handler operation args)))))
2116 ;; When `tramp-mode' is not enabled, we don't do anything.
2117 (tramp-run-real-handler operation args)))
2119 ;; In Emacs, there is some concurrency due to timers. If a timer
2120 ;; interrupts Tramp and wishes to use the same connection buffer as
2121 ;; the "main" Emacs, then garbage might occur in the connection
2122 ;; buffer. Therefore, we need to make sure that a timer does not use
2123 ;; the same connection buffer as the "main" Emacs. We implement a
2124 ;; cheap global lock, instead of locking each connection buffer
2125 ;; separately. The global lock is based on two variables,
2126 ;; `tramp-locked' and `tramp-locker'. `tramp-locked' is set to true
2127 ;; (with setq) to indicate a lock. But Tramp also calls itself during
2128 ;; processing of a single file operation, so we need to allow
2129 ;; recursive calls. That's where the `tramp-locker' variable comes in
2130 ;; -- it is let-bound to t during the execution of the current
2131 ;; handler. So if `tramp-locked' is t and `tramp-locker' is also t,
2132 ;; then we should just proceed because we have been called
2133 ;; recursively. But if `tramp-locker' is nil, then we are a timer
2134 ;; interrupting the "main" Emacs, and then we signal an error.
2136 (defvar tramp-locked nil
2137 "If non-nil, then Tramp is currently busy.
2138 Together with `tramp-locker', this implements a locking mechanism
2139 preventing reentrant calls of Tramp.")
2141 (defvar tramp-locker nil
2142 "If non-nil, then a caller has locked Tramp.
2143 Together with `tramp-locked', this implements a locking mechanism
2144 preventing reentrant calls of Tramp.")
2147 (progn (defun tramp-completion-file-name-handler (operation &rest args)
2148 "Invoke Tramp file name completion handler.
2149 Falls back to normal file name handler if no Tramp file name handler exists."
2150 ;; We bind `directory-sep-char' here for XEmacs on Windows, which
2151 ;; would otherwise use backslash.
2152 (let ((directory-sep-char ?/)
2153 (fn (assoc operation tramp-completion-file-name-handler-alist)))
2155 ;; When `tramp-mode' is not enabled, we don't do anything.
2157 ;; For other syntaxes than `sep', the regexp matches many common
2158 ;; situations where the user doesn't actually want to use Tramp.
2159 ;; So to avoid autoloading Tramp after typing just "/s", we
2160 ;; disable this part of the completion, unless the user implicitly
2161 ;; indicated his interest in using a fancier completion system.
2162 (or (eq tramp-syntax 'sep)
2163 (featurep 'tramp) ;; If it's loaded, we may as well use it.
2164 ;; `partial-completion-mode' does not exist in XEmacs.
2165 ;; It is obsoleted with Emacs 24.1.
2166 (and (boundp 'partial-completion-mode)
2167 (symbol-value 'partial-completion-mode))
2168 ;; FIXME: These may have been loaded even if the user never
2169 ;; intended to use them.
2171 (featurep 'icicles)))
2172 (save-match-data (apply (cdr fn) args))
2173 (tramp-completion-run-real-handler operation args)))))
2176 (progn (defun tramp-register-file-name-handlers ()
2177 "Add Tramp file name handlers to `file-name-handler-alist'."
2178 ;; Remove autoloaded handlers from file name handler alist. Useful,
2179 ;; if `tramp-syntax' has been changed.
2180 (let ((a1 (rassq 'tramp-file-name-handler file-name-handler-alist)))
2181 (setq file-name-handler-alist (delq a1 file-name-handler-alist)))
2183 'tramp-completion-file-name-handler file-name-handler-alist)))
2184 (setq file-name-handler-alist (delq a1 file-name-handler-alist)))
2185 ;; Add the handlers.
2186 (add-to-list 'file-name-handler-alist
2187 (cons tramp-file-name-regexp 'tramp-file-name-handler))
2188 (put 'tramp-file-name-handler 'safe-magic t)
2189 (add-to-list 'file-name-handler-alist
2190 (cons tramp-completion-file-name-regexp
2191 'tramp-completion-file-name-handler))
2192 (put 'tramp-completion-file-name-handler 'safe-magic t)
2193 ;; If jka-compr or epa-file are already loaded, move them to the
2194 ;; front of `file-name-handler-alist'.
2195 (dolist (fnh '(epa-file-handler jka-compr-handler))
2196 (let ((entry (rassoc fnh file-name-handler-alist)))
2198 (setq file-name-handler-alist
2199 (cons entry (delete entry file-name-handler-alist))))))))
2201 ;; `tramp-file-name-handler' must be registered before evaluation of
2202 ;; site-start and init files, because there might exist remote files
2203 ;; already, f.e. files kept via recentf-mode.
2205 (tramp-register-file-name-handlers)
2207 (defun tramp-exists-file-name-handler (operation &rest args)
2208 "Check, whether OPERATION runs a file name handler."
2209 ;; The file name handler is determined on base of either an
2210 ;; argument, `buffer-file-name', or `default-directory'.
2212 (let* ((buffer-file-name "/")
2213 (default-directory "/")
2214 (fnha file-name-handler-alist)
2215 (check-file-name-operation operation)
2216 (file-name-handler-alist
2219 (lambda (operation &rest args)
2220 "Returns OPERATION if it is the one to be checked."
2221 (if (equal check-file-name-operation operation)
2223 (let ((file-name-handler-alist fnha))
2224 (apply operation args))))))))
2225 (equal (apply operation args) operation))))
2228 (defun tramp-unload-file-name-handlers ()
2229 (setq file-name-handler-alist
2230 (delete (rassoc 'tramp-file-name-handler
2231 file-name-handler-alist)
2232 (delete (rassoc 'tramp-completion-file-name-handler
2233 file-name-handler-alist)
2234 file-name-handler-alist))))
2236 (add-hook 'tramp-unload-hook 'tramp-unload-file-name-handlers)
2238 ;;; File name handler functions for completion mode:
2240 (defvar tramp-completion-mode nil
2241 "If non-nil, external packages signal that they are in file name completion.
2243 This is necessary, because Tramp uses a heuristic depending on last
2244 input event. This fails when external packages use other characters
2245 but <TAB>, <SPACE> or ?\\? for file name completion. This variable
2246 should never be set globally, the intention is to let-bind it.")
2248 ;; Necessary because `tramp-file-name-regexp-unified' and
2249 ;; `tramp-completion-file-name-regexp-unified' aren't different. If
2250 ;; nil, `tramp-completion-run-real-handler' is called (i.e. forwarding
2251 ;; to `tramp-file-name-handler'). Otherwise, it takes
2252 ;; `tramp-run-real-handler'. Using `last-input-event' is a little bit
2253 ;; risky, because completing a file might require loading other files,
2254 ;; like "~/.netrc", and for them it shouldn't be decided based on that
2255 ;; variable. On the other hand, those files shouldn't have partial
2256 ;; Tramp file name syntax. Maybe another variable should be introduced
2257 ;; overwriting this check in such cases. Or we change Tramp file name
2258 ;; syntax in order to avoid ambiguities, like in XEmacs ...
2259 ;;;###tramp-autoload
2260 (defun tramp-completion-mode-p ()
2261 "Check, whether method / user name / host name completion is active."
2263 ;; Signal from outside. `non-essential' has been introduced in Emacs 24.
2264 (and (boundp 'non-essential) (symbol-value 'non-essential))
2265 tramp-completion-mode
2267 (equal last-input-event 'tab)
2268 (and (natnump last-input-event)
2270 ;; ?\t has event-modifier 'control.
2271 (equal last-input-event ?\t)
2272 (and (not (event-modifiers last-input-event))
2273 (or (equal last-input-event ?\?)
2274 (equal last-input-event ?\ )))))
2276 (and (featurep 'xemacs)
2277 ;; `last-input-event' might be nil.
2278 (not (null last-input-event))
2279 ;; `last-input-event' may have no character approximation.
2280 (tramp-compat-funcall 'event-to-character last-input-event)
2282 ;; ?\t has event-modifier 'control.
2284 (tramp-compat-funcall 'event-to-character last-input-event) ?\t)
2285 (and (not (event-modifiers last-input-event))
2287 (tramp-compat-funcall 'event-to-character last-input-event)
2290 (tramp-compat-funcall 'event-to-character last-input-event)
2293 (defun tramp-connectable-p (filename)
2294 "Check, whether it is possible to connect the remote host w/o side-effects.
2295 This is true, if either the remote host is already connected, or if we are
2296 not in completion mode."
2297 (and (tramp-tramp-file-p filename)
2298 (with-parsed-tramp-file-name filename nil
2299 (or (not (tramp-completion-mode-p))
2300 (let ((p (tramp-get-connection-process v)))
2301 (and p (processp p) (memq (process-status p) '(run open))))))))
2303 ;; Method, host name and user name completion.
2304 ;; `tramp-completion-dissect-file-name' returns a list of
2305 ;; tramp-file-name structures. For all of them we return possible completions.
2307 (defun tramp-completion-handle-file-name-all-completions (filename directory)
2308 "Like `file-name-all-completions' for partial Tramp files."
2311 (tramp-drop-volume-letter (expand-file-name filename directory)))
2314 ;; Suppress hop from completion.
2318 "\\(" "\\(" tramp-remote-file-name-spec-regexp
2319 tramp-postfix-hop-regexp
2322 (setq hop (match-string 1 fullname)
2323 fullname (replace-match "" nil nil fullname 1)))
2325 ;; Possible completion structures.
2326 (dolist (elt (tramp-completion-dissect-file-name fullname))
2327 (let* ((method (tramp-file-name-method elt))
2328 (user (tramp-file-name-user elt))
2329 (host (tramp-file-name-host elt))
2330 (localname (tramp-file-name-localname elt))
2331 (m (tramp-find-method method user host))
2332 (tramp-current-user user) ; see `tramp-parse-passwd'
2335 (unless localname ;; Nothing to complete.
2339 ;; Method dependent user / host combinations.
2343 (setq all-user-hosts
2344 (append all-user-hosts
2345 (funcall (nth 0 x) (nth 1 x)))))
2346 (tramp-get-completion-function m))
2352 (tramp-get-completion-user-host
2353 method user host (nth 0 x) (nth 1 x)))
2354 (delq nil all-user-hosts)))))
2356 ;; Possible methods.
2358 (append result (tramp-get-completion-methods m)))))))
2360 ;; Unify list, add hop, remove nil elements.
2361 (dolist (elt result)
2363 (string-match tramp-prefix-regexp elt)
2364 (setq elt (replace-match (concat tramp-prefix-format hop) nil nil elt))
2367 (substring elt (length (tramp-drop-volume-letter directory))))))
2369 ;; Complete local parts.
2373 (apply (if (tramp-connectable-p fullname)
2374 'tramp-completion-run-real-handler
2375 'tramp-run-real-handler)
2376 'file-name-all-completions (list (list filename directory)))))))
2378 ;; Method, host name and user name completion for a file.
2380 (defun tramp-completion-handle-file-name-completion
2381 (filename directory &optional predicate)
2382 "Like `file-name-completion' for Tramp files."
2385 (mapcar 'list (file-name-all-completions filename directory))
2386 (when (and predicate
2387 (tramp-connectable-p (expand-file-name filename directory)))
2388 (lambda (x) (funcall predicate (expand-file-name (car x) directory))))))
2390 ;; I misuse a little bit the tramp-file-name structure in order to handle
2391 ;; completion possibilities for partial methods / user names / host names.
2392 ;; Return value is a list of tramp-file-name structures according to possible
2393 ;; completions. If "localname" is non-nil it means there
2394 ;; shouldn't be a completion anymore.
2396 ;; Expected results:
2398 ;; "/x" "/[x" "/x@" "/[x@" "/x@y" "/[x@y"
2399 ;; [nil nil "x" nil] [nil "x" nil nil] [nil "x" "y" nil]
2400 ;; [nil "x" nil nil]
2401 ;; ["x" nil nil nil]
2403 ;; "/x:" "/x:y" "/x:y:"
2404 ;; [nil nil "x" ""] [nil nil "x" "y"] ["x" nil "y" ""]
2406 ;; ["x" nil "" nil] ["x" nil "y" nil]
2407 ;; ["x" "" nil nil] ["x" "y" nil nil]
2409 ;; "/x:y@" "/x:y@z" "/x:y@z:"
2410 ;; [nil nil "x" "y@"] [nil nil "x" "y@z"] ["x" "y" "z" ""]
2411 ;; "/[x/y@" "/[x/y@z"
2412 ;; ["x" nil "y" nil] ["x" "y" "z" nil]
2413 (defun tramp-completion-dissect-file-name (name)
2414 "Returns a list of `tramp-file-name' structures.
2415 They are collected by `tramp-completion-dissect-file-name1'."
2419 (tramp-completion-ipv6-regexp
2422 (if (zerop (length tramp-postfix-ipv6-format))
2423 tramp-postfix-host-format
2424 tramp-postfix-ipv6-format)))
2425 ;; "/method" "/[method"
2426 (tramp-completion-file-name-structure1
2427 (list (concat tramp-prefix-regexp "\\(" tramp-method-regexp x-nil "\\)$")
2430 (tramp-completion-file-name-structure2
2431 (list (concat tramp-prefix-regexp "\\(" tramp-user-regexp x-nil "\\)$")
2434 (tramp-completion-file-name-structure3
2435 (list (concat tramp-prefix-regexp "\\(" tramp-host-regexp x-nil "\\)$")
2437 ;; "/[ipv6" "/[ipv6"
2438 (tramp-completion-file-name-structure4
2439 (list (concat tramp-prefix-regexp
2440 tramp-prefix-ipv6-regexp
2441 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
2443 ;; "/user@host" "/[user@host"
2444 (tramp-completion-file-name-structure5
2445 (list (concat tramp-prefix-regexp
2446 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
2447 "\\(" tramp-host-regexp x-nil "\\)$")
2449 ;; "/user@[ipv6" "/[user@ipv6"
2450 (tramp-completion-file-name-structure6
2451 (list (concat tramp-prefix-regexp
2452 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
2453 tramp-prefix-ipv6-regexp
2454 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
2456 ;; "/method:user" "/[method/user" "/method://user"
2457 (tramp-completion-file-name-structure7
2458 (list (concat tramp-prefix-regexp
2459 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
2460 "\\(" tramp-user-regexp x-nil "\\)$")
2462 ;; "/method:host" "/[method/host" "/method://host"
2463 (tramp-completion-file-name-structure8
2464 (list (concat tramp-prefix-regexp
2465 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
2466 "\\(" tramp-host-regexp x-nil "\\)$")
2468 ;; "/method:[ipv6" "/[method/ipv6" "/method://[ipv6"
2469 (tramp-completion-file-name-structure9
2470 (list (concat tramp-prefix-regexp
2471 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
2472 tramp-prefix-ipv6-regexp
2473 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
2475 ;; "/method:user@host" "/[method/user@host" "/method://user@host"
2476 (tramp-completion-file-name-structure10
2477 (list (concat tramp-prefix-regexp
2478 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
2479 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
2480 "\\(" tramp-host-regexp x-nil "\\)$")
2482 ;; "/method:user@[ipv6" "/[method/user@ipv6" "/method://user@[ipv6"
2483 (tramp-completion-file-name-structure11
2484 (list (concat tramp-prefix-regexp
2485 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
2486 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
2487 tramp-prefix-ipv6-regexp
2488 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
2490 ;; "/method: "/method:/"
2491 (tramp-completion-file-name-structure12
2493 (if (equal tramp-syntax 'url)
2494 (concat tramp-prefix-regexp
2495 "\\(" tramp-method-regexp "\\)"
2496 "\\(" (substring tramp-postfix-method-regexp 0 1)
2497 "\\|" (substring tramp-postfix-method-regexp 1 2) "\\)"
2499 ;; Should not match if not URL syntax.
2500 (concat tramp-prefix-regexp "/$"))
2502 ;; "/method: "/method:/"
2503 (tramp-completion-file-name-structure13
2505 (if (equal tramp-syntax 'url)
2506 (concat tramp-prefix-regexp
2507 "\\(" tramp-method-regexp "\\)"
2508 "\\(" (substring tramp-postfix-method-regexp 0 1)
2509 "\\|" (substring tramp-postfix-method-regexp 1 2) "\\)"
2511 ;; Should not match if not URL syntax.
2512 (concat tramp-prefix-regexp "/$"))
2515 (mapc (lambda (structure)
2516 (add-to-list 'result
2517 (tramp-completion-dissect-file-name1 structure name)))
2519 tramp-completion-file-name-structure1
2520 tramp-completion-file-name-structure2
2521 tramp-completion-file-name-structure3
2522 tramp-completion-file-name-structure4
2523 tramp-completion-file-name-structure5
2524 tramp-completion-file-name-structure6
2525 tramp-completion-file-name-structure7
2526 tramp-completion-file-name-structure8
2527 tramp-completion-file-name-structure9
2528 tramp-completion-file-name-structure10
2529 tramp-completion-file-name-structure11
2530 tramp-completion-file-name-structure12
2531 tramp-completion-file-name-structure13
2532 tramp-file-name-structure))
2536 (defun tramp-completion-dissect-file-name1 (structure name)
2537 "Returns a `tramp-file-name' structure matching STRUCTURE.
2538 The structure consists of remote method, remote user,
2539 remote host and localname (filename on remote host)."
2542 (when (string-match (nth 0 structure) name)
2543 (let ((method (and (nth 1 structure)
2544 (match-string (nth 1 structure) name)))
2545 (user (and (nth 2 structure)
2546 (match-string (nth 2 structure) name)))
2547 (host (and (nth 3 structure)
2548 (match-string (nth 3 structure) name)))
2549 (localname (and (nth 4 structure)
2550 (match-string (nth 4 structure) name))))
2551 (vector method user host localname nil)))))
2553 ;; This function returns all possible method completions, adding the
2554 ;; trailing method delimiter.
2555 (defun tramp-get-completion-methods (partial-method)
2556 "Returns all method completions for PARTIAL-METHOD."
2560 (string-match (concat "^" (regexp-quote partial-method)) method)
2561 (tramp-completion-make-tramp-file-name method nil nil nil)))
2562 (mapcar 'car tramp-methods)))
2564 ;; Compares partial user and host names with possible completions.
2565 (defun tramp-get-completion-user-host
2566 (method partial-user partial-host user host)
2567 "Returns the most expanded string for user and host name completion.
2568 PARTIAL-USER must match USER, PARTIAL-HOST must match HOST."
2571 ((and partial-user partial-host)
2573 (string-match (concat "^" (regexp-quote partial-host)) host)
2574 (string-equal partial-user (or user partial-user)))
2575 (setq user partial-user)
2582 (and user (string-match (concat "^" (regexp-quote partial-user)) user))
2588 (and host (string-match (concat "^" (regexp-quote partial-host)) host))
2594 (unless (zerop (+ (length user) (length host)))
2595 (tramp-completion-make-tramp-file-name method user host nil)))
2597 ;; Generic function.
2598 (defun tramp-parse-group (regexp match-level skip-regexp)
2599 "Return a (user host) tuple allowed to access.
2600 User is always nil."
2602 (when (re-search-forward regexp (point-at-eol) t)
2603 (setq result (list nil (match-string match-level))))
2605 (> (skip-chars-forward skip-regexp) 0)
2609 ;; Generic function.
2610 (defun tramp-parse-file (filename function)
2611 "Return a list of (user host) tuples allowed to access.
2612 User is always nil."
2613 ;; On Windows, there are problems in completion when
2614 ;; `default-directory' is remote.
2615 (let ((default-directory (tramp-compat-temporary-file-directory)))
2616 (when (file-readable-p filename)
2618 (insert-file-contents filename)
2619 (goto-char (point-min))
2620 (loop while (not (eobp)) collect (funcall function))))))
2622 ;;;###tramp-autoload
2623 (defun tramp-parse-rhosts (filename)
2624 "Return a list of (user host) tuples allowed to access.
2625 Either user or host may be nil."
2626 (tramp-parse-file filename 'tramp-parse-rhosts-group))
2628 (defun tramp-parse-rhosts-group ()
2629 "Return a (user host) tuple allowed to access.
2630 Either user or host may be nil."
2634 "^\\(" tramp-host-regexp "\\)"
2635 "\\([ \t]+" "\\(" tramp-user-regexp "\\)" "\\)?")))
2636 (when (re-search-forward regexp (point-at-eol) t)
2637 (setq result (append (list (match-string 3) (match-string 1)))))
2641 ;;;###tramp-autoload
2642 (defun tramp-parse-shosts (filename)
2643 "Return a list of (user host) tuples allowed to access.
2644 User is always nil."
2645 (tramp-parse-file filename 'tramp-parse-shosts-group))
2647 (defun tramp-parse-shosts-group ()
2648 "Return a (user host) tuple allowed to access.
2649 User is always nil."
2650 (tramp-parse-group (concat "^\\(" tramp-host-regexp "\\)") 1 ","))
2652 ;;;###tramp-autoload
2653 (defun tramp-parse-sconfig (filename)
2654 "Return a list of (user host) tuples allowed to access.
2655 User is always nil."
2656 (tramp-parse-file filename 'tramp-parse-sconfig-group))
2658 (defun tramp-parse-sconfig-group ()
2659 "Return a (user host) tuple allowed to access.
2660 User is always nil."
2662 (concat "^[ \t]*Host[ \t]+" "\\(" tramp-host-regexp "\\)") 1 ","))
2664 ;; Generic function.
2665 (defun tramp-parse-shostkeys-sknownhosts (dirname regexp)
2666 "Return a list of (user host) tuples allowed to access.
2667 User is always nil."
2668 ;; On Windows, there are problems in completion when
2669 ;; `default-directory' is remote.
2670 (let* ((default-directory (tramp-compat-temporary-file-directory))
2671 (files (and (file-directory-p dirname) (directory-files dirname))))
2672 (loop for f in files
2673 when (and (not (string-match "^\\.\\.?$" f)) (string-match regexp f))
2674 collect (list nil (match-string 1 f)))))
2676 ;;;###tramp-autoload
2677 (defun tramp-parse-shostkeys (dirname)
2678 "Return a list of (user host) tuples allowed to access.
2679 User is always nil."
2680 (tramp-parse-shostkeys-sknownhosts
2681 dirname (concat "^key_[0-9]+_\\(" tramp-host-regexp "\\)\\.pub$")))
2683 ;;;###tramp-autoload
2684 (defun tramp-parse-sknownhosts (dirname)
2685 "Return a list of (user host) tuples allowed to access.
2686 User is always nil."
2687 (tramp-parse-shostkeys-sknownhosts
2689 (concat "^\\(" tramp-host-regexp "\\)\\.ssh-\\(dss\\|rsa\\)\\.pub$")))
2691 ;;;###tramp-autoload
2692 (defun tramp-parse-hosts (filename)
2693 "Return a list of (user host) tuples allowed to access.
2694 User is always nil."
2695 (tramp-parse-file filename 'tramp-parse-hosts-group))
2697 (defun tramp-parse-hosts-group ()
2698 "Return a (user host) tuple allowed to access.
2699 User is always nil."
2701 (concat "^\\(" tramp-ipv6-regexp "\\|" tramp-host-regexp "\\)") 1 " \t"))
2703 ;; For su-alike methods it would be desirable to return "root@localhost"
2704 ;; as default. Unfortunately, we have no information whether any user name
2705 ;; has been typed already. So we use `tramp-current-user' as indication,
2706 ;; assuming it is set in `tramp-completion-handle-file-name-all-completions'.
2707 ;;;###tramp-autoload
2708 (defun tramp-parse-passwd (filename)
2709 "Return a list of (user host) tuples allowed to access.
2710 Host is always \"localhost\"."
2711 (if (zerop (length tramp-current-user))
2713 (tramp-parse-file filename 'tramp-parse-passwd-group)))
2715 (defun tramp-parse-passwd-group ()
2716 "Return a (user host) tuple allowed to access.
2717 Host is always \"localhost\"."
2719 (regexp (concat "^\\(" tramp-user-regexp "\\):")))
2720 (when (re-search-forward regexp (point-at-eol) t)
2721 (setq result (list (match-string 1) "localhost")))
2725 ;;;###tramp-autoload
2726 (defun tramp-parse-netrc (filename)
2727 "Return a list of (user host) tuples allowed to access.
2729 (tramp-parse-file filename 'tramp-parse-netrc-group))
2731 (defun tramp-parse-netrc-group ()
2732 "Return a (user host) tuple allowed to access.
2737 "^[ \t]*machine[ \t]+" "\\(" tramp-host-regexp "\\)"
2738 "\\([ \t]+login[ \t]+" "\\(" tramp-user-regexp "\\)" "\\)?")))
2739 (when (re-search-forward regexp (point-at-eol) t)
2740 (setq result (list (match-string 3) (match-string 1))))
2744 ;;;###tramp-autoload
2745 (defun tramp-parse-putty (registry-or-dirname)
2746 "Return a list of (user host) tuples allowed to access.
2747 User is always nil."
2748 (if (memq system-type '(windows-nt))
2750 (when (zerop (tramp-compat-call-process
2751 "reg" nil t nil "query" registry-or-dirname))
2752 (goto-char (point-min))
2753 (loop while (not (eobp)) collect
2754 (tramp-parse-putty-group registry-or-dirname))))
2756 (tramp-parse-shostkeys-sknownhosts
2757 registry-or-dirname (concat "^\\(" tramp-host-regexp "\\)$"))))
2759 (defun tramp-parse-putty-group (registry)
2760 "Return a (user host) tuple allowed to access.
2761 User is always nil."
2763 (regexp (concat (regexp-quote registry) "\\\\\\(.+\\)")))
2764 (when (re-search-forward regexp (point-at-eol) t)
2765 (setq result (list nil (match-string 1))))
2769 ;;; Common file name handler functions for different backends:
2771 (defvar tramp-handle-file-local-copy-hook nil
2772 "Normal hook to be run at the end of `tramp-*-handle-file-local-copy'.")
2774 (defvar tramp-handle-write-region-hook nil
2775 "Normal hook to be run at the end of `tramp-*-handle-write-region'.")
2777 (defun tramp-handle-directory-file-name (directory)
2778 "Like `directory-file-name' for Tramp files."
2779 ;; If localname component of filename is "/", leave it unchanged.
2780 ;; Otherwise, remove any trailing slash from localname component.
2781 ;; Method, host, etc, are unchanged. Does it make sense to try
2782 ;; to avoid parsing the filename?
2783 (with-parsed-tramp-file-name directory nil
2784 (if (and (not (zerop (length localname)))
2785 (eq (aref localname (1- (length localname))) ?/)
2786 (not (string= localname "/")))
2787 (substring directory 0 -1)
2790 (defun tramp-handle-directory-files
2791 (directory &optional full match nosort files-only)
2792 "Like `directory-files' for Tramp files."
2793 ;; FILES-ONLY is valid for XEmacs only.
2794 (when (file-directory-p directory)
2795 (setq directory (file-name-as-directory (expand-file-name directory)))
2796 (let ((temp (nreverse (file-name-all-completions "" directory)))
2800 (setq item (directory-file-name (pop temp)))
2801 (when (and (or (null match) (string-match match item))
2802 (or (null files-only)
2804 (and (equal files-only t) (file-regular-p item))
2805 ;; Directories only.
2806 (file-directory-p item)))
2807 (push (if full (concat directory item) item)
2809 (if nosort result (sort result 'string<)))))
2811 (defun tramp-handle-directory-files-and-attributes
2812 (directory &optional full match nosort id-format)
2813 "Like `directory-files-and-attributes' for Tramp files."
2816 (cons x (tramp-compat-file-attributes
2817 (if full x (expand-file-name x directory)) id-format)))
2818 (directory-files directory full match nosort)))
2820 (defun tramp-handle-dired-uncache (dir &optional dir-p)
2821 "Like `dired-uncache' for Tramp files."
2822 ;; DIR-P is valid for XEmacs only.
2823 (with-parsed-tramp-file-name
2824 (if (or dir-p (file-directory-p dir)) dir (file-name-directory dir)) nil
2825 (tramp-flush-directory-property v localname)))
2827 (defun tramp-handle-file-accessible-directory-p (filename)
2828 "Like `file-accessible-directory-p' for Tramp files."
2829 (and (file-directory-p filename)
2830 (file-executable-p filename)))
2832 (defun tramp-handle-file-exists-p (filename)
2833 "Like `file-exists-p' for Tramp files."
2834 (not (null (file-attributes filename))))
2836 (defun tramp-handle-file-modes (filename)
2837 "Like `file-modes' for Tramp files."
2838 (let ((truename (or (file-truename filename) filename)))
2839 (when (file-exists-p truename)
2840 (tramp-mode-string-to-int (nth 8 (file-attributes truename))))))
2842 ;; Localname manipulation functions that grok Tramp localnames...
2843 (defun tramp-handle-file-name-as-directory (file)
2844 "Like `file-name-as-directory' but aware of Tramp files."
2845 ;; `file-name-as-directory' would be sufficient except localname is
2846 ;; the empty string.
2847 (let ((v (tramp-dissect-file-name file t)))
2848 ;; Run the command on the localname portion only.
2849 (tramp-make-tramp-file-name
2850 (tramp-file-name-method v)
2851 (tramp-file-name-user v)
2852 (tramp-file-name-host v)
2853 (tramp-run-real-handler
2854 'file-name-as-directory (list (or (tramp-file-name-localname v) ""))))))
2856 (defun tramp-handle-file-name-completion
2857 (filename directory &optional predicate)
2858 "Like `file-name-completion' for Tramp files."
2859 (unless (tramp-tramp-file-p directory)
2861 "tramp-handle-file-name-completion invoked on non-tramp directory `%s'"
2865 (mapcar 'list (file-name-all-completions filename directory))
2867 (lambda (x) (funcall predicate (expand-file-name (car x) directory))))))
2869 (defun tramp-handle-file-name-directory (file)
2870 "Like `file-name-directory' but aware of Tramp files."
2871 ;; Everything except the last filename thing is the directory. We
2872 ;; cannot apply `with-parsed-tramp-file-name', because this expands
2873 ;; the remote file name parts. This is a problem when we are in
2874 ;; file name completion.
2875 (let ((v (tramp-dissect-file-name file t)))
2876 ;; Run the command on the localname portion only.
2877 (tramp-make-tramp-file-name
2878 (tramp-file-name-method v)
2879 (tramp-file-name-user v)
2880 (tramp-file-name-host v)
2881 (tramp-run-real-handler
2882 'file-name-directory (list (or (tramp-file-name-localname v) ""))))))
2884 (defun tramp-handle-file-name-nondirectory (file)
2885 "Like `file-name-nondirectory' but aware of Tramp files."
2886 (with-parsed-tramp-file-name file nil
2887 (tramp-run-real-handler 'file-name-nondirectory (list localname))))
2889 (defun tramp-handle-file-newer-than-file-p (file1 file2)
2890 "Like `file-newer-than-file-p' for Tramp files."
2892 ((not (file-exists-p file1)) nil)
2893 ((not (file-exists-p file2)) t)
2894 (t (tramp-time-less-p (nth 5 (file-attributes file2))
2895 (nth 5 (file-attributes file1))))))
2897 (defun tramp-handle-file-regular-p (filename)
2898 "Like `file-regular-p' for Tramp files."
2899 (and (file-exists-p filename)
2900 (eq ?- (aref (nth 8 (file-attributes filename)) 0))))
2902 (defun tramp-handle-file-remote-p (filename &optional identification connected)
2903 "Like `file-remote-p' for Tramp files."
2904 (let ((tramp-verbose 3))
2905 (when (tramp-tramp-file-p filename)
2906 (let* ((v (tramp-dissect-file-name filename))
2907 (p (tramp-get-connection-process v))
2908 (c (and p (processp p) (memq (process-status p) '(run open)))))
2909 ;; We expand the file name only, if there is already a connection.
2910 (with-parsed-tramp-file-name
2911 (if c (expand-file-name filename) filename) nil
2912 (and (or (not connected) c)
2914 ((eq identification 'method) method)
2915 ((eq identification 'user) user)
2916 ((eq identification 'host) host)
2917 ((eq identification 'localname) localname)
2918 (t (tramp-make-tramp-file-name method user host "")))))))))
2920 (defun tramp-handle-file-symlink-p (filename)
2921 "Like `file-symlink-p' for Tramp files."
2922 (with-parsed-tramp-file-name filename nil
2923 (let ((x (car (file-attributes filename))))
2925 ;; When Tramp is running on VMS, then `file-name-absolute-p'
2926 ;; might do weird things.
2927 (if (file-name-absolute-p x)
2928 (tramp-make-tramp-file-name method user host x)
2931 (defun tramp-handle-find-backup-file-name (filename)
2932 "Like `find-backup-file-name' for Tramp files."
2933 (with-parsed-tramp-file-name filename nil
2934 ;; We set both variables. It doesn't matter whether it is
2936 (let ((backup-directory-alist
2938 (when (boundp 'backup-directory-alist)
2939 (if (symbol-value 'tramp-backup-directory-alist)
2944 (if (and (stringp (cdr x))
2945 (file-name-absolute-p (cdr x))
2946 (not (tramp-file-name-p (cdr x))))
2947 (tramp-make-tramp-file-name method user host (cdr x))
2949 (symbol-value 'tramp-backup-directory-alist))
2950 (symbol-value 'backup-directory-alist))))
2952 (bkup-backup-directory-info
2954 (when (boundp 'bkup-backup-directory-info)
2955 (if (symbol-value 'tramp-bkup-backup-directory-info)
2961 (if (and (stringp (car (cdr x)))
2962 (file-name-absolute-p (car (cdr x)))
2963 (not (tramp-file-name-p (car (cdr x)))))
2964 (tramp-make-tramp-file-name
2965 method user host (car (cdr x)))
2968 (symbol-value 'tramp-bkup-backup-directory-info))
2969 (symbol-value 'bkup-backup-directory-info)))))
2971 (tramp-run-real-handler 'find-backup-file-name (list filename)))))
2973 (defun tramp-handle-insert-file-contents
2974 (filename &optional visit beg end replace)
2975 "Like `insert-file-contents' for Tramp files."
2976 (barf-if-buffer-read-only)
2977 (setq filename (expand-file-name filename))
2978 (let (result local-copy remote-copy)
2979 (with-parsed-tramp-file-name filename nil
2980 (with-tramp-progress-reporter
2981 v 3 (format "Inserting `%s'" filename)
2983 (if (not (file-exists-p filename))
2984 ;; We don't raise a Tramp error, because it might be
2985 ;; suppressed, like in `find-file-noselect-1'.
2987 (list "File not found on remote host" filename))
2989 (if (and (tramp-local-host-p v)
2990 (let (file-name-handler-alist)
2991 (file-readable-p localname)))
2992 ;; Short track: if we are on the local host, we can
2995 (tramp-run-real-handler
2996 'insert-file-contents
2997 (list localname visit beg end replace)))
2999 ;; When we shall insert only a part of the file, we
3002 (setq remote-copy (tramp-make-tramp-temp-file v))
3003 ;; This is defined in tramp-sh.el. Let's assume
3004 ;; this is loaded already.
3005 (tramp-compat-funcall
3010 (format "dd bs=1 skip=%d if=%s count=%d of=%s"
3011 beg (tramp-shell-quote-argument localname)
3012 (- end beg) remote-copy))
3014 (format "dd bs=1 skip=%d if=%s of=%s"
3015 beg (tramp-shell-quote-argument localname)
3018 (format "dd bs=1 count=%d if=%s of=%s"
3019 end (tramp-shell-quote-argument localname)
3022 ;; `insert-file-contents-literally' takes care to
3023 ;; avoid calling jka-compr. By let-binding
3024 ;; `inhibit-file-name-operation', we propagate that
3025 ;; care to the `file-local-copy' operation.
3027 (let ((inhibit-file-name-operation
3028 (when (eq inhibit-file-name-operation
3029 'insert-file-contents)
3032 ((stringp remote-copy)
3034 (tramp-make-tramp-file-name
3035 method user host remote-copy)))
3036 ((stringp tramp-temp-buffer-file-name)
3037 (copy-file filename tramp-temp-buffer-file-name 'ok)
3038 tramp-temp-buffer-file-name)
3039 (t (file-local-copy filename)))))
3041 ;; When the file is not readable for the owner, it
3042 ;; cannot be inserted, even if it is readable for the
3043 ;; group or for everybody.
3045 local-copy (tramp-compat-octal-to-decimal "0600"))
3047 (when (and (null remote-copy)
3048 (tramp-get-method-parameter
3049 method 'tramp-copy-keep-tmpfile))
3050 ;; We keep the local file for performance reasons,
3051 ;; useful for "rsync".
3052 (setq tramp-temp-buffer-file-name local-copy))
3054 ;; We must ensure that `file-coding-system-alist'
3055 ;; matches `local-copy'. We must also use `visit',
3056 ;; otherwise there might be an error in the
3057 ;; `revert-buffer' function under XEmacs.
3058 (let ((file-coding-system-alist
3059 (tramp-find-file-name-coding-system-alist
3060 filename local-copy)))
3062 (insert-file-contents
3063 local-copy visit nil nil replace)))))
3068 (setq buffer-file-name filename)
3069 (setq buffer-read-only (not (file-writable-p filename)))
3070 (set-visited-file-modtime)
3071 (set-buffer-modified-p nil))
3072 (when (and (stringp local-copy)
3073 (or remote-copy (null tramp-temp-buffer-file-name)))
3074 (delete-file local-copy))
3075 (when (stringp remote-copy)
3077 (tramp-make-tramp-file-name method user host remote-copy)))))))
3080 (list (expand-file-name filename)
3083 (defun tramp-handle-load (file &optional noerror nomessage nosuffix must-suffix)
3084 "Like `load' for Tramp files."
3085 (with-parsed-tramp-file-name (expand-file-name file) nil
3087 (cond ((file-exists-p (concat file ".elc"))
3088 (setq file (concat file ".elc")))
3089 ((file-exists-p (concat file ".el"))
3090 (setq file (concat file ".el")))))
3092 ;; The first condition is always true for absolute file names.
3093 ;; Included for safety's sake.
3094 (unless (or (file-name-directory file)
3095 (string-match "\\.elc?\\'" file))
3098 "File `%s' does not include a `.el' or `.elc' suffix" file)))
3100 (when (not (file-exists-p file))
3101 (tramp-error v 'file-error "Cannot load nonexistent file `%s'" file)))
3102 (if (not (file-exists-p file))
3104 (let ((tramp-message-show-message (not nomessage)))
3105 (with-tramp-progress-reporter v 0 (format "Loading %s" file)
3106 (let ((local-copy (file-local-copy file)))
3107 ;; MUST-SUFFIX doesn't exist on XEmacs, so let it default to nil.
3109 (load local-copy noerror t t)
3110 (delete-file local-copy)))))
3113 (defun tramp-handle-shell-command
3114 (command &optional output-buffer error-buffer)
3115 "Like `shell-command' for Tramp files."
3116 (let* ((asynchronous (string-match "[ \t]*&[ \t]*\\'" command))
3117 ;; We cannot use `shell-file-name' and `shell-command-switch',
3118 ;; they are variables of the local host.
3121 (tramp-get-method-parameter
3122 (tramp-file-name-method
3123 (tramp-dissect-file-name default-directory))
3124 'tramp-remote-shell)
3125 (tramp-get-method-parameter
3126 (tramp-file-name-method
3127 (tramp-dissect-file-name default-directory))
3128 'tramp-remote-shell-args))
3129 (list (substring command 0 asynchronous))))
3133 ((bufferp output-buffer) output-buffer)
3134 ((stringp output-buffer) (get-buffer-create output-buffer))
3136 (setq current-buffer-p t)
3138 (t (get-buffer-create
3140 "*Async Shell Command*"
3141 "*Shell Command Output*")))))
3144 ((bufferp error-buffer) error-buffer)
3145 ((stringp error-buffer) (get-buffer-create error-buffer))))
3147 (if (and (not asynchronous) error-buffer)
3148 (with-parsed-tramp-file-name default-directory nil
3149 (list output-buffer (tramp-make-tramp-temp-file v)))
3151 (p (get-buffer-process output-buffer)))
3153 ;; Check whether there is another process running. Tramp does not
3154 ;; support 2 (asynchronous) processes in parallel.
3156 (if (yes-or-no-p "A command is running. Kill it? ")
3157 (ignore-errors (kill-process p))
3158 (error "Shell command in progress")))
3160 (if current-buffer-p
3162 (barf-if-buffer-read-only)
3164 (with-current-buffer output-buffer
3165 (setq buffer-read-only nil)
3168 (if (and (not current-buffer-p) (integerp asynchronous))
3171 (setq p (apply 'start-file-process "*Async Shell*" buffer args))
3173 (pop-to-buffer output-buffer)
3174 (setq mode-line-process '(":%s"))
3176 (set-process-sentinel p 'shell-command-sentinel)
3177 (set-process-filter p 'comint-output-filter))
3181 (apply 'process-file (car args) nil buffer nil (cdr args))
3182 ;; Insert error messages if they were separated.
3183 (when (listp buffer)
3184 (with-current-buffer error-buffer
3185 (insert-file-contents (cadr buffer)))
3186 (delete-file (cadr buffer)))
3187 (if current-buffer-p
3188 ;; This is like exchange-point-and-mark, but doesn't
3189 ;; activate the mark. It is cleaner to avoid activation,
3190 ;; even though the command loop would deactivate the mark
3191 ;; because we inserted text.
3192 (goto-char (prog1 (mark t)
3193 (set-marker (mark-marker) (point)
3195 ;; There's some output, display it.
3196 (when (with-current-buffer output-buffer (> (point-max) (point-min)))
3197 (if (functionp 'display-message-or-buffer)
3198 (tramp-compat-funcall 'display-message-or-buffer output-buffer)
3199 (pop-to-buffer output-buffer))))))))
3201 (defun tramp-handle-substitute-in-file-name (filename)
3202 "Like `substitute-in-file-name' for Tramp files.
3203 \"//\" and \"/~\" substitute only in the local filename part.
3204 If the URL Tramp syntax is chosen, \"//\" as method delimiter and \"/~\" at
3205 beginning of local filename are not substituted."
3206 ;; First, we must replace environment variables.
3207 (setq filename (tramp-replace-environment-variables filename))
3208 (with-parsed-tramp-file-name filename nil
3209 (if (equal tramp-syntax 'url)
3210 ;; We need to check localname only. The other parts cannot contain
3212 (if (and (> (length localname) 1)
3213 (or (string-match "//" localname)
3214 (string-match "/~" localname 1)))
3215 (tramp-run-real-handler 'substitute-in-file-name (list filename))
3216 (tramp-make-tramp-file-name
3217 (when method (substitute-in-file-name method))
3218 (when user (substitute-in-file-name user))
3219 (when host (substitute-in-file-name host))
3221 (tramp-run-real-handler
3222 'substitute-in-file-name (list localname)))))
3223 ;; Ignore in LOCALNAME everything before "//" or "/~".
3224 (when (and (stringp localname) (string-match ".+?/\\(/\\|~\\)" localname))
3226 (concat (file-remote-p filename)
3227 (replace-match "\\1" nil nil localname)))
3228 ;; "/m:h:~" does not work for completion. We use "/m:h:~/".
3229 (when (string-match "~$" filename)
3230 (setq filename (concat filename "/"))))
3231 (tramp-run-real-handler 'substitute-in-file-name (list filename)))))
3233 (defun tramp-handle-unhandled-file-name-directory (filename)
3234 "Like `unhandled-file-name-directory' for Tramp files."
3235 ;; With Emacs 23, we could simply return `nil'. But we must keep it
3236 ;; for backward compatibility.
3237 (expand-file-name "~/"))
3239 ;;; Functions for establishing connection:
3241 ;; The following functions are actions to be taken when seeing certain
3242 ;; prompts from the remote host. See the variable
3243 ;; `tramp-actions-before-shell' for usage of these functions.
3245 (defun tramp-action-login (proc vec)
3246 "Send the login name."
3247 (when (not (stringp tramp-current-user))
3248 (setq tramp-current-user
3249 (with-tramp-connection-property vec "login-as"
3250 (save-window-excursion
3251 (let ((enable-recursive-minibuffers t))
3252 (pop-to-buffer (tramp-get-connection-buffer vec))
3253 (read-string (match-string 0)))))))
3254 (with-current-buffer (tramp-get-connection-buffer vec)
3255 (tramp-message vec 6 "\n%s" (buffer-string)))
3256 (tramp-message vec 3 "Sending login name `%s'" tramp-current-user)
3257 (tramp-send-string vec (concat tramp-current-user tramp-local-end-of-line)))
3259 (defun tramp-action-password (proc vec)
3260 "Query the user for a password."
3261 (with-current-buffer (process-buffer proc)
3262 (let ((enable-recursive-minibuffers t))
3263 (tramp-check-for-regexp proc tramp-password-prompt-regexp)
3264 (tramp-message vec 3 "Sending %s" (match-string 1))
3265 ;; We don't call `tramp-send-string' in order to hide the
3266 ;; password from the debug buffer.
3267 (process-send-string
3268 proc (concat (tramp-read-passwd proc) tramp-local-end-of-line))
3269 ;; Hide password prompt.
3270 (narrow-to-region (point-max) (point-max)))))
3272 (defun tramp-action-succeed (proc vec)
3273 "Signal success in finding shell prompt."
3274 (throw 'tramp-action 'ok))
3276 (defun tramp-action-permission-denied (proc vec)
3277 "Signal permission denied."
3279 (throw 'tramp-action 'permission-denied))
3281 (defun tramp-action-yesno (proc vec)
3282 "Ask the user for confirmation using `yes-or-no-p'.
3283 Send \"yes\" to remote process on confirmation, abort otherwise.
3284 See also `tramp-action-yn'."
3285 (save-window-excursion
3286 (let ((enable-recursive-minibuffers t))
3287 (save-match-data (pop-to-buffer (tramp-get-connection-buffer vec)))
3288 (unless (yes-or-no-p (match-string 0))
3290 (throw 'tramp-action 'permission-denied))
3291 (with-current-buffer (tramp-get-connection-buffer vec)
3292 (tramp-message vec 6 "\n%s" (buffer-string)))
3293 (tramp-send-string vec (concat "yes" tramp-local-end-of-line)))))
3295 (defun tramp-action-yn (proc vec)
3296 "Ask the user for confirmation using `y-or-n-p'.
3297 Send \"y\" to remote process on confirmation, abort otherwise.
3298 See also `tramp-action-yesno'."
3299 (save-window-excursion
3300 (let ((enable-recursive-minibuffers t))
3301 (save-match-data (pop-to-buffer (tramp-get-connection-buffer vec)))
3302 (unless (y-or-n-p (match-string 0))
3304 (throw 'tramp-action 'permission-denied))
3305 (with-current-buffer (tramp-get-connection-buffer vec)
3306 (tramp-message vec 6 "\n%s" (buffer-string)))
3307 (tramp-send-string vec (concat "y" tramp-local-end-of-line)))))
3309 (defun tramp-action-terminal (proc vec)
3310 "Tell the remote host which terminal type to use.
3311 The terminal type can be configured with `tramp-terminal-type'."
3312 (tramp-message vec 5 "Setting `%s' as terminal type." tramp-terminal-type)
3313 (with-current-buffer (tramp-get-connection-buffer vec)
3314 (tramp-message vec 6 "\n%s" (buffer-string)))
3315 (tramp-send-string vec (concat tramp-terminal-type tramp-local-end-of-line)))
3317 (defun tramp-action-process-alive (proc vec)
3318 "Check, whether a process has finished."
3319 (unless (memq (process-status proc) '(run open))
3320 (throw 'tramp-action 'process-died)))
3322 (defun tramp-action-out-of-band (proc vec)
3323 "Check, whether an out-of-band copy has finished."
3324 (cond ((and (memq (process-status proc) '(stop exit))
3325 (zerop (process-exit-status proc)))
3326 (tramp-message vec 3 "Process has finished.")
3327 (throw 'tramp-action 'ok))
3328 ((or (and (memq (process-status proc) '(stop exit))
3329 (not (zerop (process-exit-status proc))))
3330 (memq (process-status proc) '(signal)))
3331 ;; `scp' could have copied correctly, but set modes could have failed.
3332 ;; This can be ignored.
3333 (with-current-buffer (process-buffer proc)
3334 (goto-char (point-min))
3335 (if (re-search-forward tramp-operation-not-permitted-regexp nil t)
3337 (tramp-message vec 5 "'set mode' error ignored.")
3338 (tramp-message vec 3 "Process has finished.")
3339 (throw 'tramp-action 'ok))
3340 (tramp-message vec 3 "Process has died.")
3341 (throw 'tramp-action 'process-died))))
3344 ;;; Functions for processing the actions:
3346 (defun tramp-process-one-action (proc vec actions)
3347 "Wait for output from the shell and perform one action."
3348 (let (found todo item pattern action)
3350 ;; Reread output once all actions have been performed.
3351 ;; Obviously, the output was not complete.
3352 (tramp-accept-process-output proc 1)
3355 (setq item (pop todo))
3356 (setq pattern (format "\\(%s\\)\\'" (symbol-value (nth 0 item))))
3357 (setq action (nth 1 item))
3359 vec 5 "Looking for regexp \"%s\" from remote shell" pattern)
3360 (when (tramp-check-for-regexp proc pattern)
3361 (tramp-message vec 5 "Call `%s'" (symbol-name action))
3362 (setq found (funcall action proc vec)))))
3365 (defun tramp-process-actions (proc vec pos actions &optional timeout)
3366 "Perform ACTIONS until success or TIMEOUT.
3367 PROC and VEC indicate the remote connection to be used. POS, if
3368 set, is the starting point of the region to be deleted in the
3370 ;; Preserve message for `progress-reporter'.
3371 (tramp-compat-with-temp-message ""
3372 ;; Enable `auth-source' and `password-cache'. We must use
3373 ;; tramp-current-* variables in case we have several hops.
3374 (tramp-set-connection-property
3375 (tramp-dissect-file-name
3376 (tramp-make-tramp-file-name
3377 tramp-current-method tramp-current-user tramp-current-host ""))
3378 "first-password-request" t)
3382 (tramp-message proc 3 "Waiting for prompts from remote shell")
3384 (catch 'tramp-action
3386 (with-timeout (timeout)
3387 (tramp-process-one-action proc vec actions))
3388 (tramp-process-one-action proc vec actions)))))
3389 (with-current-buffer (tramp-get-connection-buffer vec)
3391 (tramp-message vec 6 "\n%s" (buffer-string)))
3392 (unless (eq exit 'ok)
3393 (tramp-clear-passwd vec)
3394 (tramp-error-with-buffer
3397 ((eq exit 'permission-denied) "Permission denied")
3398 ((eq exit 'process-died) "Process died")
3399 (t "Login failed"))))
3401 (with-current-buffer (tramp-get-connection-buffer vec)
3402 (let (buffer-read-only) (delete-region pos (point)))))))))
3404 :;; Utility functions:
3406 (defun tramp-accept-process-output (&optional proc timeout timeout-msecs)
3407 "Like `accept-process-output' for Tramp processes.
3408 This is needed in order to hide `last-coding-system-used', which is set
3409 for process communication also."
3410 (with-current-buffer (process-buffer proc)
3411 (tramp-message proc 10 "%s %s" proc (process-status proc))
3412 (let (buffer-read-only last-coding-system-used)
3413 ;; Under Windows XP, accept-process-output doesn't return
3414 ;; sometimes. So we add an additional timeout.
3415 (with-timeout ((or timeout 1))
3416 (if (featurep 'xemacs)
3417 (accept-process-output proc timeout timeout-msecs)
3418 (accept-process-output proc timeout timeout-msecs (and proc t)))))
3419 (tramp-message proc 10 "\n%s" (buffer-string))))
3421 (defun tramp-check-for-regexp (proc regexp)
3422 "Check, whether REGEXP is contained in process buffer of PROC.
3423 Erase echoed commands if exists."
3424 (with-current-buffer (process-buffer proc)
3425 (goto-char (point-min))
3427 ;; Check whether we need to remove echo output.
3428 (when (and (tramp-get-connection-property proc "check-remote-echo" nil)
3429 (re-search-forward tramp-echoed-echo-mark-regexp nil t))
3430 (let ((begin (match-beginning 0)))
3431 (when (re-search-forward tramp-echoed-echo-mark-regexp nil t)
3432 ;; Discard echo from remote output.
3433 (tramp-set-connection-property proc "check-remote-echo" nil)
3434 (tramp-message proc 5 "echo-mark found")
3436 (delete-region begin (point))
3437 (goto-char (point-min)))))
3439 (when (or (not (tramp-get-connection-property proc "check-remote-echo" nil))
3440 ;; Sometimes, the echo string is suppressed on the remote side.
3442 (tramp-compat-funcall
3443 'substring-no-properties tramp-echo-mark-marker
3444 0 (min tramp-echo-mark-marker-length (1- (point-max))))
3445 (tramp-compat-funcall
3446 'buffer-substring-no-properties
3448 (min (+ (point-min) tramp-echo-mark-marker-length)
3450 ;; No echo to be handled, now we can look for the regexp.
3451 ;; Sometimes, lines are much to long, and we run into a "Stack
3452 ;; overflow in regexp matcher". For example, //DIRED// lines of
3453 ;; directory listings with some thousand files. Therefore, we
3454 ;; look from the end.
3455 (goto-char (point-max))
3456 (ignore-errors (re-search-backward regexp nil t)))))
3458 (defun tramp-wait-for-regexp (proc timeout regexp)
3459 "Wait for a REGEXP to appear from process PROC within TIMEOUT seconds.
3460 Expects the output of PROC to be sent to the current buffer. Returns
3461 the string that matched, or nil. Waits indefinitely if TIMEOUT is
3463 (with-current-buffer (process-buffer proc)
3464 (let ((found (tramp-check-for-regexp proc regexp))
3465 (start-time (current-time)))
3467 ;; Work around a bug in XEmacs 21, where the timeout
3468 ;; expires faster than it should. This degenerates
3469 ;; to polling for buggy XEmacsen, but oh, well.
3470 (while (and (not found)
3471 (< (tramp-time-diff (current-time) start-time)
3473 (with-timeout (timeout)
3475 (tramp-accept-process-output proc 1)
3476 (unless (memq (process-status proc) '(run open))
3477 (tramp-error-with-buffer
3478 nil proc 'file-error "Process has died"))
3479 (setq found (tramp-check-for-regexp proc regexp))))))
3482 (tramp-accept-process-output proc 1)
3483 (unless (memq (process-status proc) '(run open))
3484 (tramp-error-with-buffer
3485 nil proc 'file-error "Process has died"))
3486 (setq found (tramp-check-for-regexp proc regexp)))))
3487 (tramp-message proc 6 "\n%s" (buffer-string))
3491 proc 'file-error "[[Regexp `%s' not found in %d secs]]"
3493 (tramp-error proc 'file-error "[[Regexp `%s' not found]]" regexp)))
3496 ;; It seems that Tru64 Unix does not like it if long strings are sent
3497 ;; to it in one go. (This happens when sending the Perl
3498 ;; `file-attributes' implementation, for instance.) Therefore, we
3499 ;; have this function which sends the string in chunks.
3500 (defun tramp-send-string (vec string)
3501 "Send the STRING via connection VEC.
3503 The STRING is expected to use Unix line-endings, but the lines sent to
3504 the remote host use line-endings as defined in the variable
3505 `tramp-rsh-end-of-line'. The communication buffer is erased before sending."
3506 (let* ((p (tramp-get-connection-process vec))
3507 (chunksize (tramp-get-connection-property p "chunksize" nil)))
3510 vec 'file-error "Can't send string to remote host -- not logged in"))
3511 (tramp-set-connection-property p "last-cmd-time" (current-time))
3512 (tramp-message vec 10 "%s" string)
3513 (with-current-buffer (tramp-get-connection-buffer vec)
3514 ;; Clean up the buffer. We cannot call `erase-buffer' because
3515 ;; narrowing might be in effect.
3516 (let (buffer-read-only) (delete-region (point-min) (point-max)))
3517 ;; Replace "\n" by `tramp-rsh-end-of-line'.
3519 (mapconcat 'identity
3520 (tramp-compat-split-string string "\n")
3521 tramp-rsh-end-of-line))
3522 (unless (or (string= string "")
3523 (string-equal (substring string -1) tramp-rsh-end-of-line))
3524 (setq string (concat string tramp-rsh-end-of-line)))
3526 (if (and chunksize (not (zerop chunksize)))
3528 (end (length string)))
3531 vec 10 "Sending chunk from %s to %s"
3532 pos (min (+ pos chunksize) end))
3533 (process-send-string
3534 p (substring string pos (min (+ pos chunksize) end)))
3535 (setq pos (+ pos chunksize))))
3536 (process-send-string p string)))))
3538 (defun tramp-get-inode (vec)
3539 "Returns the virtual inode number.
3540 If it doesn't exist, generate a new one."
3541 (with-tramp-file-property vec (tramp-file-name-localname vec) "inode"
3542 (setq tramp-inodes (1+ tramp-inodes))))
3544 (defun tramp-get-device (vec)
3545 "Returns the virtual device number.
3546 If it doesn't exist, generate a new one."
3547 (with-tramp-connection-property (tramp-get-connection-process vec) "device"
3548 (cons -1 (setq tramp-devices (1+ tramp-devices)))))
3550 (defun tramp-equal-remote (file1 file2)
3551 "Check, whether the remote parts of FILE1 and FILE2 are identical.
3552 The check depends on method, user and host name of the files. If
3553 one of the components is missing, the default values are used.
3554 The local file name parts of FILE1 and FILE2 are not taken into
3559 (tramp-equal-remote \"/ssh::/etc\" \"/<your host name>:/home\")
3561 would yield `t'. On the other hand, the following check results in nil:
3563 (tramp-equal-remote \"/sudo::/etc\" \"/su::/etc\")"
3564 (and (stringp (file-remote-p file1))
3565 (stringp (file-remote-p file2))
3566 (string-equal (file-remote-p file1) (file-remote-p file2))))
3568 ;;;###tramp-autoload
3569 (defun tramp-mode-string-to-int (mode-string)
3570 "Converts a ten-letter `drwxrwxrwx'-style mode string into mode bits."
3571 (let* (case-fold-search
3572 (mode-chars (string-to-vector mode-string))
3573 (owner-read (aref mode-chars 1))
3574 (owner-write (aref mode-chars 2))
3575 (owner-execute-or-setid (aref mode-chars 3))
3576 (group-read (aref mode-chars 4))
3577 (group-write (aref mode-chars 5))
3578 (group-execute-or-setid (aref mode-chars 6))
3579 (other-read (aref mode-chars 7))
3580 (other-write (aref mode-chars 8))
3581 (other-execute-or-sticky (aref mode-chars 9)))
3585 ((char-equal owner-read ?r) (tramp-compat-octal-to-decimal "00400"))
3586 ((char-equal owner-read ?-) 0)
3587 (t (error "Second char `%c' must be one of `r-'" owner-read)))
3589 ((char-equal owner-write ?w) (tramp-compat-octal-to-decimal "00200"))
3590 ((char-equal owner-write ?-) 0)
3591 (t (error "Third char `%c' must be one of `w-'" owner-write)))
3593 ((char-equal owner-execute-or-setid ?x)
3594 (tramp-compat-octal-to-decimal "00100"))
3595 ((char-equal owner-execute-or-setid ?S)
3596 (tramp-compat-octal-to-decimal "04000"))
3597 ((char-equal owner-execute-or-setid ?s)
3598 (tramp-compat-octal-to-decimal "04100"))
3599 ((char-equal owner-execute-or-setid ?-) 0)
3600 (t (error "Fourth char `%c' must be one of `xsS-'"
3601 owner-execute-or-setid)))
3603 ((char-equal group-read ?r) (tramp-compat-octal-to-decimal "00040"))
3604 ((char-equal group-read ?-) 0)
3605 (t (error "Fifth char `%c' must be one of `r-'" group-read)))
3607 ((char-equal group-write ?w) (tramp-compat-octal-to-decimal "00020"))
3608 ((char-equal group-write ?-) 0)
3609 (t (error "Sixth char `%c' must be one of `w-'" group-write)))
3611 ((char-equal group-execute-or-setid ?x)
3612 (tramp-compat-octal-to-decimal "00010"))
3613 ((char-equal group-execute-or-setid ?S)
3614 (tramp-compat-octal-to-decimal "02000"))
3615 ((char-equal group-execute-or-setid ?s)
3616 (tramp-compat-octal-to-decimal "02010"))
3617 ((char-equal group-execute-or-setid ?-) 0)
3618 (t (error "Seventh char `%c' must be one of `xsS-'"
3619 group-execute-or-setid)))
3621 ((char-equal other-read ?r)
3622 (tramp-compat-octal-to-decimal "00004"))
3623 ((char-equal other-read ?-) 0)
3624 (t (error "Eighth char `%c' must be one of `r-'" other-read)))
3626 ((char-equal other-write ?w) (tramp-compat-octal-to-decimal "00002"))
3627 ((char-equal other-write ?-) 0)
3628 (t (error "Ninth char `%c' must be one of `w-'" other-write)))
3630 ((char-equal other-execute-or-sticky ?x)
3631 (tramp-compat-octal-to-decimal "00001"))
3632 ((char-equal other-execute-or-sticky ?T)
3633 (tramp-compat-octal-to-decimal "01000"))
3634 ((char-equal other-execute-or-sticky ?t)
3635 (tramp-compat-octal-to-decimal "01001"))
3636 ((char-equal other-execute-or-sticky ?-) 0)
3637 (t (error "Tenth char `%c' must be one of `xtT-'"
3638 other-execute-or-sticky)))))))
3640 ;;;###tramp-autoload
3641 (defun tramp-local-host-p (vec)
3642 "Return t if this points to the local host, nil otherwise."
3643 ;; We cannot use `tramp-file-name-real-host'. A port is an
3644 ;; indication for an ssh tunnel or alike.
3645 (let ((host (tramp-file-name-host vec)))
3648 (string-match tramp-local-host-regexp host)
3649 ;; The method shall be applied to one of the shell file name
3650 ;; handler. `tramp-local-host-p' is also called for "smb" and
3651 ;; alike, where it must fail.
3652 (tramp-get-method-parameter
3653 (tramp-file-name-method vec) 'tramp-login-program)
3654 ;; The local temp directory must be writable for the other user.
3656 (tramp-make-tramp-file-name
3657 (tramp-file-name-method vec)
3658 (tramp-file-name-user vec)
3660 (tramp-compat-temporary-file-directory)))
3661 ;; On some systems, chown runs only for root.
3662 (or (zerop (user-uid))
3663 ;; This is defined in tramp-sh.el. Let's assume this is
3665 (zerop (tramp-compat-funcall 'tramp-get-remote-uid vec 'integer))))))
3667 (defun tramp-get-remote-tmpdir (vec)
3668 "Return directory for temporary files on the remote host identified by VEC."
3669 (with-tramp-connection-property vec "tmpdir"
3670 (let ((dir (tramp-make-tramp-file-name
3671 (tramp-file-name-method vec)
3672 (tramp-file-name-user vec)
3673 (tramp-file-name-host vec)
3675 (tramp-get-method-parameter
3676 (tramp-file-name-method vec) 'tramp-tmpdir)
3678 (if (and (file-directory-p dir) (file-writable-p dir))
3680 (tramp-error vec 'file-error "Directory %s not accessible" dir)))))
3682 ;;;###tramp-autoload
3683 (defun tramp-make-tramp-temp-file (vec)
3684 "Create a temporary file on the remote host identified by VEC.
3685 Return the local name of the temporary file."
3686 (let ((prefix (expand-file-name
3687 tramp-temp-name-prefix (tramp-get-remote-tmpdir vec)))
3690 ;; `make-temp-file' would be the natural choice for
3691 ;; implementation. But it calls `write-region' internally,
3692 ;; which also needs a temporary file - we would end in an
3694 (setq result (make-temp-name prefix))
3695 (if (file-exists-p result)
3697 ;; This creates the file by side effect.
3698 (set-file-times result)
3699 (set-file-modes result (tramp-compat-octal-to-decimal "0700"))))
3701 ;; Return the local part.
3702 (with-parsed-tramp-file-name result nil localname)))
3704 (defun tramp-delete-temp-file-function ()
3705 "Remove temporary files related to current buffer."
3706 (when (stringp tramp-temp-buffer-file-name)
3707 (ignore-errors (delete-file tramp-temp-buffer-file-name))))
3709 (add-hook 'kill-buffer-hook 'tramp-delete-temp-file-function)
3710 (add-hook 'tramp-unload-hook
3712 (remove-hook 'kill-buffer-hook
3713 'tramp-delete-temp-file-function)))
3715 ;;; Auto saving to a special directory:
3717 (unless (tramp-exists-file-name-handler 'make-auto-save-file-name)
3718 (defadvice make-auto-save-file-name
3719 (around tramp-advice-make-auto-save-file-name () activate)
3720 "Invoke `tramp-*-handle-make-auto-save-file-name' for Tramp files."
3721 (if (tramp-tramp-file-p (buffer-file-name))
3722 ;; We cannot call `tramp-handle-make-auto-save-file-name'
3723 ;; directly, because this would bypass the locking mechanism.
3724 (setq ad-return-value
3725 (tramp-file-name-handler 'make-auto-save-file-name))
3731 'make-auto-save-file-name
3732 'around 'tramp-advice-make-auto-save-file-name)
3733 (ad-activate 'make-auto-save-file-name))))
3735 ;; In XEmacs < 21.5, autosaved remote files have permission 0666 minus
3736 ;; umask. This is a security threat.
3738 (defun tramp-set-auto-save-file-modes ()
3739 "Set permissions of autosaved remote files to the original permissions."
3740 (let ((bfn (buffer-file-name)))
3741 (when (and (tramp-tramp-file-p bfn)
3743 (stringp buffer-auto-save-file-name)
3744 (not (equal bfn buffer-auto-save-file-name)))
3745 (unless (file-exists-p buffer-auto-save-file-name)
3746 (write-region "" nil buffer-auto-save-file-name))
3747 ;; Permissions should be set always, because there might be an old
3748 ;; auto-saved file belonging to another original file. This could
3749 ;; be a security threat.
3751 buffer-auto-save-file-name
3752 (or (file-modes bfn) (tramp-compat-octal-to-decimal "0600"))))))
3754 (unless (and (featurep 'xemacs)
3755 (= emacs-major-version 21)
3756 (> emacs-minor-version 4))
3757 (add-hook 'auto-save-hook 'tramp-set-auto-save-file-modes)
3758 (add-hook 'tramp-unload-hook
3760 (remove-hook 'auto-save-hook 'tramp-set-auto-save-file-modes))))
3762 (defun tramp-subst-strs-in-string (alist string)
3763 "Replace all occurrences of the string FROM with TO in STRING.
3764 ALIST is of the form ((FROM . TO) ...)."
3767 (let* ((pr (car alist))
3770 (while (string-match (regexp-quote from) string)
3771 (setq string (replace-match to t t string)))
3772 (setq alist (cdr alist))))
3775 ;;; Compatibility functions section:
3777 ;;;###tramp-autoload
3778 (defun tramp-read-passwd (proc &optional prompt)
3779 "Read a password from user (compat function).
3780 Consults the auth-source package.
3781 Invokes `password-read' if available, `read-passwd' else."
3782 (let* ((key (tramp-make-tramp-file-name
3783 tramp-current-method tramp-current-user
3784 tramp-current-host ""))
3787 (with-current-buffer (process-buffer proc)
3788 (tramp-check-for-regexp proc tramp-password-prompt-regexp)
3789 (format "%s for %s " (capitalize (match-string 1)) key))))
3790 auth-info auth-passwd)
3791 (with-parsed-tramp-file-name key nil
3794 ;; See if auth-sources contains something useful, if it's
3795 ;; bound. `auth-source-user-or-password' is an obsoleted
3796 ;; function, it has been replaced by `auth-source-search'.
3797 (and (boundp 'auth-sources)
3798 (tramp-get-connection-property v "first-password-request" nil)
3799 ;; Try with Tramp's current method.
3800 (if (fboundp 'auth-source-search)
3802 (tramp-compat-funcall
3805 :user (or tramp-current-user t)
3806 :host tramp-current-host
3807 :port tramp-current-method)
3808 auth-passwd (plist-get (nth 0 auth-info) :secret)
3809 auth-passwd (if (functionp auth-passwd)
3810 (funcall auth-passwd)
3812 (tramp-compat-funcall
3813 'auth-source-user-or-password
3814 "password" tramp-current-host tramp-current-method)))
3815 ;; Try the password cache.
3816 (when (functionp 'password-read)
3817 (unless (tramp-get-connection-property
3818 v "first-password-request" nil)
3819 (tramp-compat-funcall 'password-cache-remove key))
3821 (tramp-compat-funcall 'password-read pw-prompt key)))
3822 (tramp-compat-funcall 'password-cache-add key password)
3824 ;; Else, get the password interactively.
3825 (read-passwd pw-prompt))
3826 (tramp-set-connection-property v "first-password-request" nil)))))
3828 ;;;###tramp-autoload
3829 (defun tramp-clear-passwd (vec)
3830 "Clear password cache for connection related to VEC."
3831 (tramp-compat-funcall
3832 'password-cache-remove
3833 (tramp-make-tramp-file-name
3834 (tramp-file-name-method vec)
3835 (tramp-file-name-user vec)
3836 (tramp-file-name-host vec)
3839 ;; Snarfed code from time-date.el and parse-time.el
3841 (defconst tramp-half-a-year '(241 17024)
3842 "Evaluated by \"(days-to-time 183)\".")
3844 (defconst tramp-parse-time-months
3845 '(("jan" . 1) ("feb" . 2) ("mar" . 3)
3846 ("apr" . 4) ("may" . 5) ("jun" . 6)
3847 ("jul" . 7) ("aug" . 8) ("sep" . 9)
3848 ("oct" . 10) ("nov" . 11) ("dec" . 12))
3849 "Alist mapping month names to integers.")
3851 ;; FIXME: Shouldn't this also look at any subseconds parts of T1 and T2?
3852 ;;;###tramp-autoload
3853 (defun tramp-time-less-p (t1 t2)
3854 "Say whether time value T1 is less than time value T2."
3855 (unless t1 (setq t1 '(0 0)))
3856 (unless t2 (setq t2 '(0 0)))
3857 (or (< (car t1) (car t2))
3858 (and (= (car t1) (car t2))
3859 (< (nth 1 t1) (nth 1 t2)))))
3861 ;; FIXME: Shouldn't this also look at any subseconds parts of T1 and T2?
3862 (defun tramp-time-subtract (t1 t2)
3863 "Subtract two time values.
3864 Return the difference in the format of a time value."
3865 (unless t1 (setq t1 '(0 0)))
3866 (unless t2 (setq t2 '(0 0)))
3867 (let ((borrow (< (cadr t1) (cadr t2))))
3868 (list (- (car t1) (car t2) (if borrow 1 0))
3869 (- (+ (if borrow 65536 0) (cadr t1)) (cadr t2)))))
3871 ;;;###tramp-autoload
3872 (defun tramp-time-diff (t1 t2)
3873 "Return the difference between the two times, in seconds.
3874 T1 and T2 are time values (as returned by `current-time' for example)."
3875 (cond ((and (fboundp 'subtract-time)
3876 (fboundp 'float-time))
3877 (tramp-compat-funcall
3878 'float-time (tramp-compat-funcall 'subtract-time t1 t2)))
3879 ((and (fboundp 'subtract-time)
3880 (fboundp 'time-to-seconds))
3881 (tramp-compat-funcall
3882 'time-to-seconds (tramp-compat-funcall 'subtract-time t1 t2)))
3883 ((fboundp 'itimer-time-difference)
3884 (tramp-compat-funcall
3885 'itimer-time-difference
3886 (if (< (length t1) 3) (append t1 '(0)) t1)
3887 (if (< (length t2) 3) (append t2 '(0)) t2)))
3889 (let ((time (tramp-time-subtract t1 t2)))
3890 (+ (* (car time) 65536.0)
3892 (/ (or (nth 2 time) 0) 1000000.0))))))
3894 ;; Currently (as of Emacs 20.5), the function `shell-quote-argument'
3895 ;; does not deal well with newline characters. Newline is replaced by
3896 ;; backslash newline. But if, say, the string `a backslash newline b'
3897 ;; is passed to a shell, the shell will expand this into "ab",
3898 ;; completely omitting the newline. This is not what was intended.
3899 ;; It does not appear to be possible to make the function
3900 ;; `shell-quote-argument' work with newlines without making it
3901 ;; dependent on the shell used. But within this package, we know that
3902 ;; we will always use a Bourne-like shell, so we use an approach which
3905 ;; The approach is simple: we call `shell-quote-argument', then
3906 ;; massage the newline part of the result.
3908 ;; This function should produce a string which is grokked by a Unix
3909 ;; shell, even if the Emacs is running on Windows. Since this is the
3910 ;; kludges section, we bind `system-type' in such a way that
3911 ;; `shell-quote-arguments' behaves as if on Unix.
3913 ;; Thanks to Mario DeWeerd for the hint that it is sufficient for this
3914 ;; function to work with Bourne-like shells.
3916 ;; CCC: This function should be rewritten so that
3917 ;; `shell-quote-argument' is not used. This way, we are safe from
3918 ;; changes in `shell-quote-argument'.
3919 ;;;###tramp-autoload
3920 (defun tramp-shell-quote-argument (s)
3921 "Similar to `shell-quote-argument', but groks newlines.
3922 Only works for Bourne-like shells."
3923 (let ((system-type 'not-windows))
3925 (let ((result (shell-quote-argument s))
3926 (nl (regexp-quote (format "\\%s" tramp-rsh-end-of-line))))
3927 (when (and (>= (length result) 2)
3928 (string= (substring result 0 2) "\\~"))
3929 (setq result (substring result 1)))
3930 (while (string-match nl result)
3931 (setq result (replace-match (format "'%s'" tramp-rsh-end-of-line)
3935 ;;; Integration of eshell.el:
3938 (defvar eshell-path-env))
3940 ;; eshell.el keeps the path in `eshell-path-env'. We must change it
3941 ;; when `default-directory' points to another host.
3942 (defun tramp-eshell-directory-change ()
3943 "Set `eshell-path-env' to $PATH of the host related to `default-directory'."
3944 (setq eshell-path-env
3945 (if (file-remote-p default-directory)
3946 (with-parsed-tramp-file-name default-directory nil
3950 ;; When `tramp-own-remote-path' is in `tramp-remote-path',
3951 ;; the remote path is only set in the session cache.
3952 (tramp-get-connection-property
3953 (tramp-get-connection-process v) "remote-path" nil)
3954 (tramp-get-connection-property v "remote-path" nil))
3958 (eval-after-load "esh-util"
3960 (tramp-eshell-directory-change)
3961 (add-hook 'eshell-directory-change-hook
3962 'tramp-eshell-directory-change)
3963 (add-hook 'tramp-unload-hook
3965 (remove-hook 'eshell-directory-change-hook
3966 'tramp-eshell-directory-change)))))
3968 ;; Checklist for `tramp-unload-hook'
3969 ;; - Unload all `tramp-*' packages
3970 ;; - Reset `file-name-handler-alist'
3971 ;; - Cleanup hooks where Tramp functions are in
3972 ;; - Cleanup advised functions
3973 ;; - Cleanup autoloads
3975 (defun tramp-unload-tramp ()
3976 "Discard Tramp from loading remote files."
3978 ;; ange-ftp settings must be enabled.
3979 (tramp-compat-funcall 'tramp-ftp-enable-ange-ftp)
3980 ;; Maybe it's not loaded yet.
3981 (ignore-errors (unload-feature 'tramp 'force)))
3987 ;; * Rewrite `tramp-shell-quote-argument' to abstain from using
3988 ;; `shell-quote-argument'.
3989 ;; * In Emacs 21, `insert-directory' shows total number of bytes used
3990 ;; by the files in that directory. Add this here.
3991 ;; * Avoid screen blanking when hitting `g' in dired. (Eli Tziperman)
3992 ;; * abbreviate-file-name
3993 ;; * Better error checking. At least whenever we see something
3994 ;; strange when doing zerop, we should kill the process and start
3995 ;; again. (Greg Stark)
3996 ;; * Username and hostname completion.
3997 ;; ** Try to avoid usage of `last-input-event' in `tramp-completion-mode-p'.
3998 ;; * Make `tramp-default-user' obsolete.
3999 ;; * Implement a general server-local-variable mechanism, as there are
4000 ;; probably other variables that need different values for different
4001 ;; servers too. The user could then configure a variable (such as
4002 ;; tramp-server-local-variable-alist) to define any such variables
4003 ;; that they need to, which would then be let bound as appropriate
4004 ;; in tramp functions. (Jason Rumney)
4005 ;; * IMHO, it's a drawback that currently Tramp doesn't support
4006 ;; Unicode in Dired file names by default. Is it possible to
4007 ;; improve Tramp to set LC_ALL to "C" only for commands where Tramp
4008 ;; expects English? Or just to set LC_MESSAGES to "C" if Tramp
4009 ;; expects only English messages? (Juri Linkov)
4010 ;; * Make shadowfile.el grok Tramp filenames. (Bug#4526, Bug#4846)
4011 ;; * I was wondering if it would be possible to use tramp even if I'm
4012 ;; actually using sshfs. But when I launch a command I would like
4013 ;; to get it executed on the remote machine where the files really
4014 ;; are. (Andrea Crotti)
4015 ;; * Run emerge on two remote files. Bug is described here:
4016 ;; <http://www.mail-archive.com/tramp-devel@nongnu.org/msg01041.html>.
4019 ;;; tramp.el ends here