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. \"%c\" adds additional
224 `tramp-ssh-controlmaster-options' options for the first hop.
226 When an asynchronous process is started, we know already that
227 the connection works. Therefore, we can pass additional
228 parameters to suppress diagnostic messages, in order not to
229 tamper the process output.
230 * `tramp-copy-program'
231 This specifies the name of the program to use for remotely copying
232 the file; this might be the absolute filename of rcp or the name of
235 This specifies the list of parameters to pass to the above mentioned
236 program, the hints for `tramp-login-args' also apply here.
237 * `tramp-copy-keep-date'
238 This specifies whether the copying program when the preserves the
239 timestamp of the original file.
240 * `tramp-copy-keep-tmpfile'
241 This specifies whether a temporary local file shall be kept
242 for optimization reasons (useful for \"rsync\" methods).
243 * `tramp-copy-recursive'
244 Whether the operation copies directories recursively.
245 * `tramp-default-port'
246 The default port of a method is needed in case of gateway connections.
247 Additionally, it is used as indication which method is prepared for
250 As the attribute name says, additional arguments are specified here
251 when a method is applied via a gateway.
253 A directory on the remote host for temporary files. If not
254 specified, \"/tmp\" is taken as default.
255 * `tramp-connection-timeout'
256 This is the maximum time to be spent for establishing a connection.
257 In general, the global default value shall be used, but for
258 some methods, like \"su\" or \"sudo\", a shorter timeout
261 What does all this mean? Well, you should specify `tramp-login-program'
262 for all methods; this program is used to log in to the remote site. Then,
263 there are two ways to actually transfer the files between the local and the
264 remote side. One way is using an additional rcp-like program. If you want
265 to do this, set `tramp-copy-program' in the method.
267 Another possibility for file transfer is inline transfer, i.e. the
268 file is passed through the same buffer used by `tramp-login-program'. In
269 this case, the file contents need to be protected since the
270 `tramp-login-program' might use escape codes or the connection might not
271 be eight-bit clean. Therefore, file contents are encoded for transit.
272 See the variables `tramp-local-coding-commands' and
273 `tramp-remote-coding-commands' for details.
275 So, to summarize: if the method is an out-of-band method, then you
276 must specify `tramp-copy-program' and `tramp-copy-args'. If it is an
277 inline method, then these two parameters should be nil. Methods which
278 are fit for gateways must have `tramp-default-port' at least.
282 When using `su' or `sudo' the phrase `open connection to a remote
283 host' sounds strange, but it is used nevertheless, for consistency.
284 No connection is opened to a remote host, but `su' or `sudo' is
285 started on the local host. You should specify a remote host
286 `localhost' or the name of the local host. Another host name is
287 useful only in combination with `tramp-default-proxies-alist'.")
290 (defconst tramp-ssh-controlmaster-options
294 (call-process "ssh" nil t nil "-o" "ControlMaster")
295 (goto-char (point-min))
296 (when (search-forward-regexp "Missing ControlMaster argument" nil t)
297 (setq result "-o ControlPath=%t.%%r@%%h:%%p -o ControlMaster=auto")))
300 (call-process "ssh" nil t nil "-o" "ControlPersist")
301 (goto-char (point-min))
302 (when (search-forward-regexp "Missing ControlPersist argument" nil t)
303 (setq result (concat result " -o ControlPersist=no"))))))
305 "Call ssh to detect whether it supports the Control* arguments.
306 Return a string to be used in `tramp-methods'.")
309 (defcustom tramp-use-ssh-controlmaster-options
310 (not (zerop (length tramp-ssh-controlmaster-options)))
311 "Whether to use `tramp-ssh-controlmaster-options'."
316 (defcustom tramp-default-method
317 ;; An external copy method seems to be preferred, because it performs
318 ;; much better for large files, and it hasn't too serious delays
319 ;; for small files. But it must be ensured that there aren't
320 ;; permanent password queries. Either a password agent like
321 ;; "ssh-agent" or "Pageant" shall run, or the optional
322 ;; password-cache.el or auth-sources.el packages shall be active for
323 ;; password caching. If we detect that the user is running OpenSSH
324 ;; 4.0 or newer, we could reuse the connection, which calls also for
325 ;; an external method.
327 ;; PuTTY is installed. We don't take it, if it is installed on a
328 ;; non-windows system, or pscp from the pssh (parallel ssh) package
330 ((and (eq system-type 'windows-nt)
331 (executable-find "pscp"))
332 (if (or (fboundp 'password-read)
333 (fboundp 'auth-source-user-or-password)
334 (fboundp 'auth-source-search)
335 ;; Pageant is running.
336 (tramp-compat-process-running-p "Pageant"))
339 ;; There is an ssh installation.
340 ((executable-find "scp")
341 (if (or (fboundp 'password-read)
342 (fboundp 'auth-source-user-or-password)
343 (fboundp 'auth-source-search)
344 ;; ssh-agent is running.
345 (getenv "SSH_AUTH_SOCK")
346 (getenv "SSH_AGENT_PID")
347 ;; We could reuse the connection.
348 (> (length tramp-ssh-controlmaster-options) 0))
353 "Default method to use for transferring files.
354 See `tramp-methods' for possibilities.
355 Also see `tramp-default-method-alist'."
360 (defcustom tramp-default-method-alist nil
361 "Default method to use for specific host/user pairs.
362 This is an alist of items (HOST USER METHOD). The first matching item
363 specifies the method to use for a file name which does not specify a
364 method. HOST and USER are regular expressions or nil, which is
365 interpreted as a regular expression which always matches. If no entry
366 matches, the variable `tramp-default-method' takes effect.
368 If the file name does not specify the user, lookup is done using the
369 empty string for the user name.
371 See `tramp-methods' for a list of possibilities for METHOD."
373 :type '(repeat (list (choice :tag "Host regexp" regexp sexp)
374 (choice :tag "User regexp" regexp sexp)
375 (choice :tag "Method name" string (const nil)))))
377 (defcustom tramp-default-user nil
378 "Default user to use for transferring files.
379 It is nil by default; otherwise settings in configuration files like
380 \"~/.ssh/config\" would be overwritten. Also see `tramp-default-user-alist'.
382 This variable is regarded as obsolete, and will be removed soon."
384 :type '(choice (const nil) string))
387 (defcustom tramp-default-user-alist nil
388 "Default user to use for specific method/host pairs.
389 This is an alist of items (METHOD HOST USER). The first matching item
390 specifies the user to use for a file name which does not specify a
391 user. METHOD and USER are regular expressions or nil, which is
392 interpreted as a regular expression which always matches. If no entry
393 matches, the variable `tramp-default-user' takes effect.
395 If the file name does not specify the method, lookup is done using the
396 empty string for the method name."
398 :type '(repeat (list (choice :tag "Method regexp" regexp sexp)
399 (choice :tag " Host regexp" regexp sexp)
400 (choice :tag " User name" string (const nil)))))
402 (defcustom tramp-default-host (system-name)
403 "Default host to use for transferring files.
404 Useful for su and sudo methods mostly."
409 (defcustom tramp-default-host-alist nil
410 "Default host to use for specific method/user pairs.
411 This is an alist of items (METHOD USER HOST). The first matching item
412 specifies the host to use for a file name which does not specify a
413 host. METHOD and HOST are regular expressions or nil, which is
414 interpreted as a regular expression which always matches. If no entry
415 matches, the variable `tramp-default-host' takes effect.
417 If the file name does not specify the method, lookup is done using the
418 empty string for the method name."
421 :type '(repeat (list (choice :tag "Method regexp" regexp sexp)
422 (choice :tag " User regexp" regexp sexp)
423 (choice :tag " Host name" string (const nil)))))
425 (defcustom tramp-default-proxies-alist nil
426 "Route to be followed for specific host/user pairs.
427 This is an alist of items (HOST USER PROXY). The first matching
428 item specifies the proxy to be passed for a file name located on
429 a remote target matching USER@HOST. HOST and USER are regular
430 expressions. PROXY must be a Tramp filename without a localname
431 part. Method and user name on PROXY are optional, which is
432 interpreted with the default values. PROXY can contain the
433 patterns %h and %u, which are replaced by the strings matching
434 HOST or USER, respectively.
436 HOST, USER or PROXY could also be Lisp forms, which will be
437 evaluated. The result must be a string or nil, which is
438 interpreted as a regular expression which always matches."
440 :type '(repeat (list (choice :tag "Host regexp" regexp sexp)
441 (choice :tag "User regexp" regexp sexp)
442 (choice :tag " Proxy name" string (const nil)))))
444 (defcustom tramp-save-ad-hoc-proxies nil
445 "Whether to save ad-hoc proxies persistently."
450 (defcustom tramp-restricted-shell-hosts-alist
451 (when (memq system-type '(windows-nt))
452 (list (concat "\\`" (regexp-quote (system-name)) "\\'")))
453 "List of hosts, which run a restricted shell.
454 This is a list of regular expressions, which denote hosts running
455 a registered shell like \"rbash\". Those hosts can be used as
456 proxies only, see `tramp-default-proxies-alist'. If the local
457 host runs a registered shell, it shall be added to this list, too."
460 :type '(repeat (regexp :tag "Host regexp")))
463 (defconst tramp-local-host-regexp
467 (list "localhost" "localhost6" (system-name) "127\.0\.0\.1" "::1") t)
469 "Host names which are regarded as local host.")
471 (defvar tramp-completion-function-alist nil
472 "Alist of methods for remote files.
473 This is a list of entries of the form \(NAME PAIR1 PAIR2 ...\).
474 Each NAME stands for a remote access method. Each PAIR is of the form
475 \(FUNCTION FILE\). FUNCTION is responsible to extract user names and host
476 names from FILE for completion. The following predefined FUNCTIONs exists:
478 * `tramp-parse-rhosts' for \"~/.rhosts\" like files,
479 * `tramp-parse-shosts' for \"~/.ssh/known_hosts\" like files,
480 * `tramp-parse-sconfig' for \"~/.ssh/config\" like files,
481 * `tramp-parse-shostkeys' for \"~/.ssh2/hostkeys/*\" like files,
482 * `tramp-parse-sknownhosts' for \"~/.ssh2/knownhosts/*\" like files,
483 * `tramp-parse-hosts' for \"/etc/hosts\" like files,
484 * `tramp-parse-passwd' for \"/etc/passwd\" like files.
485 * `tramp-parse-netrc' for \"~/.netrc\" like files.
486 * `tramp-parse-putty' for PuTTY registered sessions.
488 FUNCTION can also be a customer defined function. For more details see
491 (defconst tramp-echo-mark-marker "_echo"
492 "String marker to surround echoed commands.")
494 (defconst tramp-echo-mark-marker-length (length tramp-echo-mark-marker)
495 "String length of `tramp-echo-mark-marker'.")
497 (defconst tramp-echo-mark
498 (concat tramp-echo-mark-marker
499 (make-string tramp-echo-mark-marker-length ?\b))
500 "String mark to be transmitted around shell commands.
501 Used to separate their echo from the output they produce. This
502 will only be used if we cannot disable remote echo via stty.
503 This string must have no effect on the remote shell except for
504 producing some echo which can later be detected by
505 `tramp-echoed-echo-mark-regexp'. Using `tramp-echo-mark-marker',
506 followed by an equal number of backspaces to erase them will
509 (defconst tramp-echoed-echo-mark-regexp
510 (format "%s\\(\b\\( \b\\)?\\)\\{%d\\}"
511 tramp-echo-mark-marker tramp-echo-mark-marker-length)
512 "Regexp which matches `tramp-echo-mark' as it gets echoed by
515 (defcustom tramp-local-end-of-line
516 (if (memq system-type '(windows-nt)) "\r\n" "\n")
517 "String used for end of line in local processes."
522 (defcustom tramp-rsh-end-of-line "\n"
523 "String used for end of line in rsh connections.
524 I don't think this ever needs to be changed, so please tell me about it
525 if you need to change this."
529 (defcustom tramp-login-prompt-regexp
530 ".*ogin\\( .*\\)?: *"
531 "Regexp matching login-like prompts.
532 The regexp should match at end of buffer.
534 Sometimes the prompt is reported to look like \"login as:\"."
538 (defcustom tramp-shell-prompt-pattern
539 ;; Allow a prompt to start right after a ^M since it indeed would be
540 ;; displayed at the beginning of the line (and Zsh uses it). This
541 ;; regexp works only for GNU Emacs.
542 ;; Allow also [] style prompts. They can appear only during
543 ;; connection initialization; Tramp redefines the prompt afterwards.
544 (concat (if (featurep 'xemacs) "" "\\(?:^\\|\r\\)")
545 "[^]#$%>\n]*#?[]#$%>] *\\(\e\\[[0-9;]*[a-zA-Z] *\\)*")
546 "Regexp to match prompts from remote shell.
547 Normally, Tramp expects you to configure `shell-prompt-pattern'
548 correctly, but sometimes it happens that you are connecting to a
549 remote host which sends a different kind of shell prompt. Therefore,
550 Tramp recognizes things matched by `shell-prompt-pattern' as prompt,
551 and also things matched by this variable. The default value of this
552 variable is similar to the default value of `shell-prompt-pattern',
553 which should work well in many cases.
555 This regexp must match both `tramp-initial-end-of-output' and
556 `tramp-end-of-output'."
560 (defcustom tramp-password-prompt-regexp
561 "^.*\\([pP]assword\\|[pP]assphrase\\).*:\^@? *"
562 "Regexp matching password-like prompts.
563 The regexp should match at end of buffer.
565 The `sudo' program appears to insert a `^@' character into the prompt."
569 (defcustom tramp-wrong-passwd-regexp
571 ;; These strings should be on the last line
572 (regexp-opt '("Permission denied"
577 "Timeout, server not responding."
579 "Name or service not known"
580 "Host key verification failed."
581 "No supported authentication methods left to try!") t)
585 ;; Here comes a list of regexes, separated by \\|
586 "Received signal [0-9]+"
588 "Regexp matching a `login failed' message.
589 The regexp should match at end of buffer."
593 (defcustom tramp-yesno-prompt-regexp
595 (regexp-opt '("Are you sure you want to continue connecting (yes/no)?") t)
597 "Regular expression matching all yes/no queries which need to be confirmed.
598 The confirmation should be done with yes or no.
599 The regexp should match at end of buffer.
600 See also `tramp-yn-prompt-regexp'."
604 (defcustom tramp-yn-prompt-regexp
606 (regexp-opt '("Store key in cache? (y/n)"
607 "Update cached key? (y/n, Return cancels connection)") t)
609 "Regular expression matching all y/n queries which need to be confirmed.
610 The confirmation should be done with y or n.
611 The regexp should match at end of buffer.
612 See also `tramp-yesno-prompt-regexp'."
616 (defcustom tramp-terminal-prompt-regexp
620 "Terminal type\\? \\[.*\\]"
622 "Regular expression matching all terminal setting prompts.
623 The regexp should match at end of buffer.
624 The answer will be provided by `tramp-action-terminal', which see."
628 (defcustom tramp-operation-not-permitted-regexp
629 (concat "\\(" "preserving times.*" "\\|" "set mode" "\\)" ":\\s-*"
630 (regexp-opt '("Operation not permitted") t))
631 "Regular expression matching keep-date problems in (s)cp operations.
632 Copying has been performed successfully already, so this message can
637 (defcustom tramp-copy-failed-regexp
639 (regexp-opt '("Permission denied"
642 "No such file or directory") t)
644 "Regular expression matching copy problems in (s)cp operations."
648 (defcustom tramp-process-alive-regexp
650 "Regular expression indicating a process has finished.
651 In fact this expression is empty by intention, it will be used only to
652 check regularly the status of the associated process.
653 The answer will be provided by `tramp-action-process-alive',
654 `tramp-action-out-of-band', which see."
658 (defconst tramp-temp-name-prefix "tramp."
659 "Prefix to use for temporary files.
660 If this is a relative file name (such as \"tramp.\"), it is considered
661 relative to the directory name returned by the function
662 `tramp-compat-temporary-file-directory' (which see). It may also be an
663 absolute file name; don't forget to include a prefix for the filename
666 (defconst tramp-temp-buffer-name " *tramp temp*"
667 "Buffer name for a temporary buffer.
668 It shall be used in combination with `generate-new-buffer-name'.")
670 (defvar tramp-temp-buffer-file-name nil
671 "File name of a persistent local temporary file.
672 Useful for \"rsync\" like methods.")
673 (make-variable-buffer-local 'tramp-temp-buffer-file-name)
674 (put 'tramp-temp-buffer-file-name 'permanent-local t)
676 ;; XEmacs is distributed with few Lisp packages. Further packages are
677 ;; installed using EFS. If we use a unified filename format, then
678 ;; Tramp is required in addition to EFS. (But why can't Tramp just
679 ;; disable EFS when Tramp is loaded? Then XEmacs can ship with EFS
680 ;; just like before.) Another reason for using a separate filename
681 ;; syntax on XEmacs is that EFS hooks into XEmacs in many places, but
682 ;; Tramp only knows how to deal with `file-name-handler-alist', not
685 ;; Currently, we have the choice between 'ftp, 'sep, and 'url.
687 (defcustom tramp-syntax
688 (if (featurep 'xemacs) 'sep 'ftp)
689 "Tramp filename syntax to be used.
691 It can have the following values:
693 'ftp -- Ange-FTP respective EFS like syntax (GNU Emacs default)
694 'sep -- Syntax as defined for XEmacs (not available yet for GNU Emacs)
695 'url -- URL-like syntax."
697 :type (if (featurep 'xemacs)
698 '(choice (const :tag "EFS" ftp)
699 (const :tag "XEmacs" sep)
700 (const :tag "URL" url))
701 '(choice (const :tag "Ange-FTP" ftp)
702 (const :tag "URL" url))))
704 (defconst tramp-prefix-format
705 (cond ((equal tramp-syntax 'ftp) "/")
706 ((equal tramp-syntax 'sep) "/[")
707 ((equal tramp-syntax 'url) "/")
708 (t (error "Wrong `tramp-syntax' defined")))
709 "String matching the very beginning of Tramp file names.
710 Used in `tramp-make-tramp-file-name'.")
712 (defconst tramp-prefix-regexp
713 (concat "^" (regexp-quote tramp-prefix-format))
714 "Regexp matching the very beginning of Tramp file names.
715 Should always start with \"^\". Derived from `tramp-prefix-format'.")
717 (defconst tramp-method-regexp
719 "Regexp matching methods identifiers.")
721 (defconst tramp-postfix-method-format
722 (cond ((equal tramp-syntax 'ftp) ":")
723 ((equal tramp-syntax 'sep) "/")
724 ((equal tramp-syntax 'url) "://")
725 (t (error "Wrong `tramp-syntax' defined")))
726 "String matching delimiter between method and user or host names.
727 Used in `tramp-make-tramp-file-name'.")
729 (defconst tramp-postfix-method-regexp
730 (regexp-quote tramp-postfix-method-format)
731 "Regexp matching delimiter between method and user or host names.
732 Derived from `tramp-postfix-method-format'.")
734 (defconst tramp-user-regexp "[^/|: \t]+"
735 "Regexp matching user names.")
738 (defconst tramp-prefix-domain-format "%"
739 "String matching delimiter between user and domain names.")
742 (defconst tramp-prefix-domain-regexp
743 (regexp-quote tramp-prefix-domain-format)
744 "Regexp matching delimiter between user and domain names.
745 Derived from `tramp-prefix-domain-format'.")
747 (defconst tramp-domain-regexp "[-a-zA-Z0-9_.]+"
748 "Regexp matching domain names.")
750 (defconst tramp-user-with-domain-regexp
751 (concat "\\(" tramp-user-regexp "\\)"
752 tramp-prefix-domain-regexp
753 "\\(" tramp-domain-regexp "\\)")
754 "Regexp matching user names with domain names.")
756 (defconst tramp-postfix-user-format "@"
757 "String matching delimiter between user and host names.
758 Used in `tramp-make-tramp-file-name'.")
760 (defconst tramp-postfix-user-regexp
761 (regexp-quote tramp-postfix-user-format)
762 "Regexp matching delimiter between user and host names.
763 Derived from `tramp-postfix-user-format'.")
765 (defconst tramp-host-regexp "[a-zA-Z0-9_.-]+"
766 "Regexp matching host names.")
768 (defconst tramp-prefix-ipv6-format
769 (cond ((equal tramp-syntax 'ftp) "[")
770 ((equal tramp-syntax 'sep) "")
771 ((equal tramp-syntax 'url) "[")
772 (t (error "Wrong `tramp-syntax' defined")))
773 "String matching left hand side of IPv6 addresses.
774 Used in `tramp-make-tramp-file-name'.")
776 (defconst tramp-prefix-ipv6-regexp
777 (regexp-quote tramp-prefix-ipv6-format)
778 "Regexp matching left hand side of IPv6 addresses.
779 Derived from `tramp-prefix-ipv6-format'.")
781 ;; The following regexp is a bit sloppy. But it shall serve our
782 ;; purposes. It covers also IPv4 mapped IPv6 addresses, like in
783 ;; "::ffff:192.168.0.1".
784 (defconst tramp-ipv6-regexp
785 "\\(?:\\(?:[a-zA-Z0-9]+\\)?:\\)+[a-zA-Z0-9.]+"
786 "Regexp matching IPv6 addresses.")
788 (defconst tramp-postfix-ipv6-format
789 (cond ((equal tramp-syntax 'ftp) "]")
790 ((equal tramp-syntax 'sep) "")
791 ((equal tramp-syntax 'url) "]")
792 (t (error "Wrong `tramp-syntax' defined")))
793 "String matching right hand side of IPv6 addresses.
794 Used in `tramp-make-tramp-file-name'.")
796 (defconst tramp-postfix-ipv6-regexp
797 (regexp-quote tramp-postfix-ipv6-format)
798 "Regexp matching right hand side of IPv6 addresses.
799 Derived from `tramp-postfix-ipv6-format'.")
801 (defconst tramp-prefix-port-format
802 (cond ((equal tramp-syntax 'ftp) "#")
803 ((equal tramp-syntax 'sep) "#")
804 ((equal tramp-syntax 'url) ":")
805 (t (error "Wrong `tramp-syntax' defined")))
806 "String matching delimiter between host names and port numbers.")
808 (defconst tramp-prefix-port-regexp
809 (regexp-quote tramp-prefix-port-format)
810 "Regexp matching delimiter between host names and port numbers.
811 Derived from `tramp-prefix-port-format'.")
813 (defconst tramp-port-regexp "[0-9]+"
814 "Regexp matching port numbers.")
816 (defconst tramp-host-with-port-regexp
817 (concat "\\(" tramp-host-regexp "\\)"
818 tramp-prefix-port-regexp
819 "\\(" tramp-port-regexp "\\)")
820 "Regexp matching host names with port numbers.")
822 (defconst tramp-postfix-hop-format "|"
823 "String matching delimiter after ad-hoc hop definitions.")
825 (defconst tramp-postfix-hop-regexp
826 (regexp-quote tramp-postfix-hop-format)
827 "Regexp matching delimiter after ad-hoc hop definitions.
828 Derived from `tramp-postfix-hop-format'.")
830 (defconst tramp-postfix-host-format
831 (cond ((equal tramp-syntax 'ftp) ":")
832 ((equal tramp-syntax 'sep) "]")
833 ((equal tramp-syntax 'url) "")
834 (t (error "Wrong `tramp-syntax' defined")))
835 "String matching delimiter between host names and localnames.
836 Used in `tramp-make-tramp-file-name'.")
838 (defconst tramp-postfix-host-regexp
839 (regexp-quote tramp-postfix-host-format)
840 "Regexp matching delimiter between host names and localnames.
841 Derived from `tramp-postfix-host-format'.")
843 (defconst tramp-localname-regexp ".*$"
844 "Regexp matching localnames.")
846 ;;; File name format:
848 (defconst tramp-remote-file-name-spec-regexp
850 "\\(?:" "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp "\\)?"
851 "\\(?:" "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp "\\)?"
852 "\\(" "\\(?:" tramp-host-regexp "\\|"
853 tramp-prefix-ipv6-regexp tramp-ipv6-regexp
854 tramp-postfix-ipv6-regexp "\\)"
855 "\\(?:" tramp-prefix-port-regexp tramp-port-regexp "\\)?" "\\)?")
856 "Regular expression matching a Tramp file name between prefix and postfix.")
858 (defconst tramp-file-name-structure
862 "\\(" "\\(?:" tramp-remote-file-name-spec-regexp
863 tramp-postfix-hop-regexp "\\)+" "\\)?"
864 tramp-remote-file-name-spec-regexp tramp-postfix-host-regexp
865 "\\(" tramp-localname-regexp "\\)")
867 "List of six elements (REGEXP METHOD USER HOST FILE HOP), detailing \
868 the Tramp file name structure.
870 The first element REGEXP is a regular expression matching a Tramp file
871 name. The regex should contain parentheses around the method name,
872 the user name, the host name, and the file name parts.
874 The second element METHOD is a number, saying which pair of
875 parentheses matches the method name. The third element USER is
876 similar, but for the user name. The fourth element HOST is similar,
877 but for the host name. The fifth element FILE is for the file name.
878 The last element HOP is the ad-hoc hop definition, which could be a
879 cascade of several hops.
881 These numbers are passed directly to `match-string', which see. That
882 means the opening parentheses are counted to identify the pair.
884 See also `tramp-file-name-regexp'.")
887 (defconst tramp-file-name-regexp-unified
888 (if (memq system-type '(cygwin windows-nt))
889 "\\`/\\([^[/|:]\\{2,\\}\\|[^/|]\\{2,\\}]\\):"
890 "\\`/\\([^[/|:]+\\|[^/|]+]\\):")
891 "Value for `tramp-file-name-regexp' for unified remoting.
892 Emacs (not XEmacs) uses a unified filename syntax for Ange-FTP and
893 Tramp. See `tramp-file-name-structure' for more explanations.
895 On W32 systems, the volume letter must be ignored.")
898 (defconst tramp-file-name-regexp-separate "\\`/\\[.*\\]"
899 "Value for `tramp-file-name-regexp' for separate remoting.
900 XEmacs uses a separate filename syntax for Tramp and EFS.
901 See `tramp-file-name-structure' for more explanations.")
904 (defconst tramp-file-name-regexp-url "\\`/[^/|:]+://"
905 "Value for `tramp-file-name-regexp' for URL-like remoting.
906 See `tramp-file-name-structure' for more explanations.")
909 (defconst tramp-file-name-regexp
910 (cond ((equal tramp-syntax 'ftp) tramp-file-name-regexp-unified)
911 ((equal tramp-syntax 'sep) tramp-file-name-regexp-separate)
912 ((equal tramp-syntax 'url) tramp-file-name-regexp-url)
913 (t (error "Wrong `tramp-syntax' defined")))
914 "Regular expression matching file names handled by Tramp.
915 This regexp should match Tramp file names but no other file names.
916 When tramp.el is loaded, this regular expression is prepended to
917 `file-name-handler-alist', and that is searched sequentially. Thus,
918 if the Tramp entry appears rather early in the `file-name-handler-alist'
919 and is a bit too general, then some files might be considered Tramp
920 files which are not really Tramp files.
922 Please note that the entry in `file-name-handler-alist' is made when
923 this file \(tramp.el\) is loaded. This means that this variable must be set
924 before loading tramp.el. Alternatively, `file-name-handler-alist' can be
925 updated after changing this variable.
927 Also see `tramp-file-name-structure'.")
930 (defconst tramp-completion-file-name-regexp-unified
931 (if (memq system-type '(cygwin windows-nt))
932 "\\`/[^/]\\{2,\\}\\'" "\\`/[^/]*\\'")
933 "Value for `tramp-completion-file-name-regexp' for unified remoting.
934 GNU Emacs uses a unified filename syntax for Tramp and Ange-FTP.
935 See `tramp-file-name-structure' for more explanations.
937 On W32 systems, the volume letter must be ignored.")
940 (defconst tramp-completion-file-name-regexp-separate
941 "\\`/\\([[][^]]*\\)?\\'"
942 "Value for `tramp-completion-file-name-regexp' for separate remoting.
943 XEmacs uses a separate filename syntax for Tramp and EFS.
944 See `tramp-file-name-structure' for more explanations.")
947 (defconst tramp-completion-file-name-regexp-url
948 "\\`/[^/:]+\\(:\\(/\\(/[^/]*\\)?\\)?\\)?\\'"
949 "Value for `tramp-completion-file-name-regexp' for URL-like remoting.
950 See `tramp-file-name-structure' for more explanations.")
953 (defconst tramp-completion-file-name-regexp
954 (cond ((equal tramp-syntax 'ftp) tramp-completion-file-name-regexp-unified)
955 ((equal tramp-syntax 'sep) tramp-completion-file-name-regexp-separate)
956 ((equal tramp-syntax 'url) tramp-completion-file-name-regexp-url)
957 (t (error "Wrong `tramp-syntax' defined")))
958 "Regular expression matching file names handled by Tramp completion.
959 This regexp should match partial Tramp file names only.
961 Please note that the entry in `file-name-handler-alist' is made when
962 this file \(tramp.el\) is loaded. This means that this variable must be set
963 before loading tramp.el. Alternatively, `file-name-handler-alist' can be
964 updated after changing this variable.
966 Also see `tramp-file-name-structure'.")
968 ;; Chunked sending kludge. We set this to 500 for black-listed constellations
969 ;; known to have a bug in `process-send-string'; some ssh connections appear
970 ;; to drop bytes when data is sent too quickly. There is also a connection
971 ;; buffer local variable, which is computed depending on remote host properties
972 ;; when `tramp-chunksize' is zero or nil.
973 (defcustom tramp-chunksize
974 (when (and (not (featurep 'xemacs))
975 (memq system-type '(hpux)))
977 ;; Parentheses in docstring starting at beginning of line are escaped.
978 ;; Fontification is messed up when
979 ;; `open-paren-in-column-0-is-defun-start' set to t.
980 "If non-nil, chunksize for sending input to local process.
981 It is necessary only on systems which have a buggy `process-send-string'
982 implementation. The necessity, whether this variable must be set, can be
983 checked via the following code:
986 (let* ((user \"xxx\") (host \"yyy\")
988 (sent init) (received init))
989 (while (= sent received)
990 (setq sent (+ sent step))
992 (let ((proc (start-process (buffer-name) (current-buffer)
993 \"ssh\" \"-l\" user host \"wc\" \"-c\")))
994 (when (memq (process-status proc) '(run open))
995 (process-send-string proc (make-string sent ?\\ ))
996 (process-send-eof proc)
997 (process-send-eof proc))
998 (while (not (progn (goto-char (point-min))
999 (re-search-forward \"\\\\w+\" (point-max) t)))
1000 (accept-process-output proc 1))
1001 (when (memq (process-status proc) '(run open))
1002 (setq received (string-to-number (match-string 0)))
1003 (delete-process proc)
1004 (message \"Bytes sent: %s\\tBytes received: %s\" sent received)
1006 (if (> sent (+ init step))
1007 (message \"You should set `tramp-chunksize' to a maximum of %s\"
1009 (message \"Test does not work\")
1010 (display-buffer (current-buffer))
1013 In the Emacs normally running Tramp, evaluate the above code
1014 \(replace \"xxx\" and \"yyy\" by the remote user and host name,
1015 respectively\). You can do this, for example, by pasting it into
1016 the `*scratch*' buffer and then hitting C-j with the cursor after the
1017 last closing parenthesis. Note that it works only if you have configured
1018 \"ssh\" to run without password query, see ssh-agent\(1\).
1020 You will see the number of bytes sent successfully to the remote host.
1021 If that number exceeds 1000, you can stop the execution by hitting
1022 C-g, because your Emacs is likely clean.
1024 When it is necessary to set `tramp-chunksize', you might consider to
1025 use an out-of-the-band method \(like \"scp\"\) instead of an internal one
1026 \(like \"ssh\"\), because setting `tramp-chunksize' to non-nil decreases
1029 If your Emacs is buggy, the code stops and gives you an indication
1030 about the value `tramp-chunksize' should be set. Maybe you could just
1031 experiment a bit, e.g. changing the values of `init' and `step'
1032 in the third line of the code.
1034 Please raise a bug report via \"M-x tramp-bug\" if your system needs
1035 this variable to be set as well."
1037 :type '(choice (const nil) integer))
1039 ;; Logging in to a remote host normally requires obtaining a pty. But
1040 ;; Emacs on MacOS X has process-connection-type set to nil by default,
1041 ;; so on those systems Tramp doesn't obtain a pty. Here, we allow
1042 ;; for an override of the system default.
1043 (defcustom tramp-process-connection-type t
1044 "Overrides `process-connection-type' for connections from Tramp.
1045 Tramp binds `process-connection-type' to the value given here before
1046 opening a connection to a remote host."
1048 :type '(choice (const nil) (const t) (const pty)))
1050 (defcustom tramp-connection-timeout 60
1051 "Defines the max time to wait for establishing a connection (in seconds).
1052 This can be overwritten for different connection types in `tramp-methods'."
1057 (defcustom tramp-connection-min-time-diff 5
1058 "Defines seconds between two consecutive connection attempts.
1059 This is necessary as self defense mechanism, in order to avoid
1060 yo-yo connection attempts when the remote host is unavailable.
1062 A value of 0 or `nil' suppresses this check. This might be
1063 necessary, when several out-of-order copy operations are
1064 performed, or when several asynchronous processes will be started
1065 in a short time frame. In those cases it is recommended to
1066 let-bind this variable."
1069 :type '(choice (const nil) integer))
1071 (defcustom tramp-completion-reread-directory-timeout 10
1072 "Defines seconds since last remote command before rereading a directory.
1073 A remote directory might have changed its contents. In order to
1074 make it visible during file name completion in the minibuffer,
1075 Tramp flushes its cache and rereads the directory contents when
1076 more than `tramp-completion-reread-directory-timeout' seconds
1077 have been gone since last remote command execution. A value of `t'
1078 would require an immediate reread during filename completion, `nil'
1079 means to use always cached values for the directory contents."
1081 :type '(choice (const nil) (const t) integer))
1083 ;;; Internal Variables:
1085 (defvar tramp-current-method nil
1086 "Connection method for this *tramp* buffer.")
1088 (defvar tramp-current-user nil
1089 "Remote login name for this *tramp* buffer.")
1091 (defvar tramp-current-host nil
1092 "Remote host for this *tramp* buffer.")
1094 (defvar tramp-current-connection nil
1095 "Last connection timestamp.")
1098 (defconst tramp-completion-file-name-handler-alist
1099 '((file-name-all-completions . tramp-completion-handle-file-name-all-completions)
1100 (file-name-completion . tramp-completion-handle-file-name-completion))
1101 "Alist of completion handler functions.
1102 Used for file names matching `tramp-file-name-regexp'. Operations
1103 not mentioned here will be handled by Tramp's file name handler
1104 functions, or the normal Emacs functions.")
1106 ;; Handlers for foreign methods, like FTP or SMB, shall be plugged here.
1107 ;;;###tramp-autoload
1108 (defvar tramp-foreign-file-name-handler-alist nil
1109 "Alist of elements (FUNCTION . HANDLER) for foreign methods handled specially.
1110 If (FUNCTION FILENAME) returns non-nil, then all I/O on that file is done by
1113 ;;; Internal functions which must come first:
1115 ;; Conversion functions between external representation and
1116 ;; internal data structure. Convenience functions for internal
1119 (defun tramp-get-method-parameter (method param)
1120 "Return the method parameter PARAM.
1121 If the `tramp-methods' entry does not exist, return nil."
1122 (let ((entry (assoc param (assoc method tramp-methods))))
1123 (when entry (cadr entry))))
1125 (defun tramp-file-name-p (vec)
1126 "Check, whether VEC is a Tramp object."
1127 (and (vectorp vec) (= 5 (length vec))))
1129 (defun tramp-file-name-method (vec)
1130 "Return method component of VEC."
1131 (and (tramp-file-name-p vec) (aref vec 0)))
1133 (defun tramp-file-name-user (vec)
1134 "Return user component of VEC."
1135 (and (tramp-file-name-p vec) (aref vec 1)))
1137 (defun tramp-file-name-host (vec)
1138 "Return host component of VEC."
1139 (and (tramp-file-name-p vec) (aref vec 2)))
1141 (defun tramp-file-name-localname (vec)
1142 "Return localname component of VEC."
1143 (and (tramp-file-name-p vec) (aref vec 3)))
1145 (defun tramp-file-name-hop (vec)
1146 "Return hop component of VEC."
1147 (and (tramp-file-name-p vec) (aref vec 4)))
1149 ;; The user part of a Tramp file name vector can be of kind
1150 ;; "user%domain". Sometimes, we must extract these parts.
1151 (defun tramp-file-name-real-user (vec)
1152 "Return the user name of VEC without domain."
1154 (let ((user (tramp-file-name-user vec)))
1155 (if (and (stringp user)
1156 (string-match tramp-user-with-domain-regexp user))
1157 (match-string 1 user)
1160 (defun tramp-file-name-domain (vec)
1161 "Return the domain name of VEC."
1163 (let ((user (tramp-file-name-user vec)))
1165 (string-match tramp-user-with-domain-regexp user)
1166 (match-string 2 user)))))
1168 ;; The host part of a Tramp file name vector can be of kind
1169 ;; "host#port". Sometimes, we must extract these parts.
1170 (defun tramp-file-name-real-host (vec)
1171 "Return the host name of VEC without port."
1173 (let ((host (tramp-file-name-host vec)))
1174 (if (and (stringp host)
1175 (string-match tramp-host-with-port-regexp host))
1176 (match-string 1 host)
1179 (defun tramp-file-name-port (vec)
1180 "Return the port number of VEC."
1182 (let ((method (tramp-file-name-method vec))
1183 (host (tramp-file-name-host vec)))
1184 (or (and (stringp host)
1185 (string-match tramp-host-with-port-regexp host)
1186 (string-to-number (match-string 2 host)))
1187 (tramp-get-method-parameter method 'tramp-default-port)))))
1189 ;;;###tramp-autoload
1190 (defun tramp-tramp-file-p (name)
1191 "Return t if NAME is a string with Tramp file name syntax."
1194 (string-match tramp-file-name-regexp name))))
1196 ;; Obsoleted with Tramp 2.2.7.
1197 (defconst tramp-obsolete-methods
1198 '("ssh1" "ssh2" "scp1" "scp2" "scpc" "rsyncc" "plink1")
1199 "Obsolete methods.")
1201 (defvar tramp-warned-obsolete-methods nil
1202 "Which methods the user has been warned to be obsolete.")
1204 (defun tramp-find-method (method user host)
1205 "Return the right method string to use.
1206 This is METHOD, if non-nil. Otherwise, do a lookup in
1207 `tramp-default-method-alist'. It maps also obsolete methods to
1211 (let ((choices tramp-default-method-alist)
1214 (setq item (pop choices))
1215 (when (and (string-match (or (nth 0 item) "") (or host ""))
1216 (string-match (or (nth 1 item) "") (or user "")))
1217 (setq lmethod (nth 2 item))
1218 (setq choices nil)))
1220 tramp-default-method)))
1221 ;; This is needed for a transition period only.
1222 (when (member result tramp-obsolete-methods)
1223 (unless (member result tramp-warned-obsolete-methods)
1225 (warn "Method %s is obsolete, using %s"
1226 result (substring result 0 -1))
1227 (unless (y-or-n-p (format "Method %s is obsolete, use %s? "
1228 result (substring result 0 -1)))
1229 (tramp-compat-user-error "Method \"%s\" not supported" result)))
1230 (add-to-list 'tramp-warned-obsolete-methods result))
1231 ;; This works with the current set of `tramp-obsolete-methods'.
1232 ;; Must be improved, if their are more sophisticated replacements.
1233 (setq result (substring result 0 -1)))
1236 (defun tramp-find-user (method user host)
1237 "Return the right user string to use.
1238 This is USER, if non-nil. Otherwise, do a lookup in
1239 `tramp-default-user-alist'."
1241 (let ((choices tramp-default-user-alist)
1244 (setq item (pop choices))
1245 (when (and (string-match (or (nth 0 item) "") (or method ""))
1246 (string-match (or (nth 1 item) "") (or host "")))
1247 (setq luser (nth 2 item))
1248 (setq choices nil)))
1250 tramp-default-user))
1252 (defun tramp-find-host (method user host)
1253 "Return the right host string to use.
1254 This is HOST, if non-nil. Otherwise, it is `tramp-default-host'."
1255 (or (and (> (length host) 0) host)
1256 (let ((choices tramp-default-host-alist)
1259 (setq item (pop choices))
1260 (when (and (string-match (or (nth 0 item) "") (or method ""))
1261 (string-match (or (nth 1 item) "") (or user "")))
1262 (setq lhost (nth 2 item))
1263 (setq choices nil)))
1265 tramp-default-host))
1267 (defun tramp-dissect-file-name (name &optional nodefault)
1268 "Return a `tramp-file-name' structure.
1269 The structure consists of remote method, remote user, remote host
1270 and localname (file name on remote host). If NODEFAULT is
1271 non-nil, the file name parts are not expanded to their default
1274 (let ((match (string-match (nth 0 tramp-file-name-structure) name)))
1275 (unless match (tramp-compat-user-error "Not a Tramp file name: %s" name))
1276 (let ((method (match-string (nth 1 tramp-file-name-structure) name))
1277 (user (match-string (nth 2 tramp-file-name-structure) name))
1278 (host (match-string (nth 3 tramp-file-name-structure) name))
1279 (localname (match-string (nth 4 tramp-file-name-structure) name))
1280 (hop (match-string (nth 5 tramp-file-name-structure) name)))
1282 (when (string-match tramp-prefix-ipv6-regexp host)
1283 (setq host (replace-match "" nil t host)))
1284 (when (string-match tramp-postfix-ipv6-regexp host)
1285 (setq host (replace-match "" nil t host)))
1286 (when (and (equal tramp-syntax 'ftp) (null method) (null user)
1287 (member host (mapcar 'car tramp-methods))
1288 (not (tramp-completion-mode-p)))
1289 (tramp-compat-user-error
1290 "Host name must not match method `%s'" host)))
1292 (vector method user host localname hop)
1294 (tramp-find-method method user host)
1295 (tramp-find-user method user host)
1296 (tramp-find-host method user host)
1299 (defun tramp-buffer-name (vec)
1300 "A name for the connection buffer VEC."
1301 ;; We must use `tramp-file-name-real-host', because for gateway
1302 ;; methods the default port will be expanded later on, which would
1304 (let ((method (tramp-file-name-method vec))
1305 (user (tramp-file-name-user vec))
1306 (host (tramp-file-name-real-host vec)))
1307 (if (not (zerop (length user)))
1308 (format "*tramp/%s %s@%s*" method user host)
1309 (format "*tramp/%s %s*" method host))))
1311 (defun tramp-make-tramp-file-name (method user host localname &optional hop)
1312 "Constructs a Tramp file name from METHOD, USER, HOST and LOCALNAME.
1313 When not nil, an optional HOP is prepended."
1314 (concat tramp-prefix-format hop
1315 (when (not (zerop (length method)))
1316 (concat method tramp-postfix-method-format))
1317 (when (not (zerop (length user)))
1318 (concat user tramp-postfix-user-format))
1320 (if (string-match tramp-ipv6-regexp host)
1321 (concat tramp-prefix-ipv6-format host tramp-postfix-ipv6-format)
1323 tramp-postfix-host-format
1324 (when localname localname)))
1326 (defun tramp-completion-make-tramp-file-name (method user host localname)
1327 "Constructs a Tramp file name from METHOD, USER, HOST and LOCALNAME.
1328 It must not be a complete Tramp file name, but as long as there are
1329 necessary only. This function will be used in file name completion."
1330 (concat tramp-prefix-format
1331 (when (not (zerop (length method)))
1332 (concat method tramp-postfix-method-format))
1333 (when (not (zerop (length user)))
1334 (concat user tramp-postfix-user-format))
1335 (when (not (zerop (length host)))
1337 (if (string-match tramp-ipv6-regexp host)
1339 tramp-prefix-ipv6-format host tramp-postfix-ipv6-format)
1341 tramp-postfix-host-format))
1342 (when localname localname)))
1344 (defun tramp-get-buffer (vec)
1345 "Get the connection buffer to be used for VEC."
1346 (or (get-buffer (tramp-buffer-name vec))
1347 (with-current-buffer (get-buffer-create (tramp-buffer-name vec))
1348 (setq buffer-undo-list t)
1349 (setq default-directory
1350 (tramp-make-tramp-file-name
1351 (tramp-file-name-method vec)
1352 (tramp-file-name-user vec)
1353 (tramp-file-name-host vec)
1357 (defun tramp-get-connection-buffer (vec)
1358 "Get the connection buffer to be used for VEC.
1359 In case a second asynchronous communication has been started, it is different
1360 from `tramp-get-buffer'."
1361 (or (tramp-get-connection-property vec "process-buffer" nil)
1362 (tramp-get-buffer vec)))
1364 (defun tramp-get-connection-name (vec)
1365 "Get the connection name to be used for VEC.
1366 In case a second asynchronous communication has been started, it is different
1367 from the default one."
1368 (or (tramp-get-connection-property vec "process-name" nil)
1369 (tramp-buffer-name vec)))
1371 (defun tramp-get-connection-process (vec)
1372 "Get the connection process to be used for VEC.
1373 In case a second asynchronous communication has been started, it is different
1374 from the default one."
1375 (get-process (tramp-get-connection-name vec)))
1377 (defun tramp-debug-buffer-name (vec)
1378 "A name for the debug buffer for VEC."
1379 ;; We must use `tramp-file-name-real-host', because for gateway
1380 ;; methods the default port will be expanded later on, which would
1382 (let ((method (tramp-file-name-method vec))
1383 (user (tramp-file-name-user vec))
1384 (host (tramp-file-name-real-host vec)))
1385 (if (not (zerop (length user)))
1386 (format "*debug tramp/%s %s@%s*" method user host)
1387 (format "*debug tramp/%s %s*" method host))))
1389 (defconst tramp-debug-outline-regexp
1390 "[0-9]+:[0-9]+:[0-9]+\\.[0-9]+ [a-z0-9-]+ (\\([0-9]+\\)) #"
1391 "Used for highlighting Tramp debug buffers in `outline-mode'.")
1393 (defun tramp-debug-outline-level ()
1394 "Return the depth to which a statement is nested in the outline.
1395 Point must be at the beginning of a header line.
1397 The outline level is equal to the verbosity of the Tramp message."
1398 (1+ (string-to-number (match-string 1))))
1400 (defun tramp-get-debug-buffer (vec)
1401 "Get the debug buffer for VEC."
1402 (with-current-buffer
1403 (get-buffer-create (tramp-debug-buffer-name vec))
1405 (setq buffer-undo-list t)
1406 ;; So it does not get loaded while `outline-regexp' is let-bound.
1408 ;; Activate `outline-mode'. This runs `text-mode-hook' and
1409 ;; `outline-mode-hook'. We must prevent that local processes
1410 ;; die. Yes: I've seen `flyspell-mode', which starts "ispell".
1411 ;; Furthermore, `outline-regexp' must have the correct value
1412 ;; already, because it is used by `font-lock-compile-keywords'.
1413 (let ((default-directory (tramp-compat-temporary-file-directory))
1414 (outline-regexp tramp-debug-outline-regexp))
1416 (set (make-local-variable 'outline-regexp) tramp-debug-outline-regexp)
1417 (set (make-local-variable 'outline-level) 'tramp-debug-outline-level))
1420 (defsubst tramp-debug-message (vec fmt-string &rest args)
1421 "Append message to debug buffer.
1422 Message is formatted with FMT-STRING as control string and the remaining
1423 ARGS to actually emit the message (if applicable)."
1424 (when (get-buffer (tramp-buffer-name vec))
1425 (with-current-buffer (tramp-get-debug-buffer vec)
1426 (goto-char (point-max))
1431 ";; %sEmacs: %s Tramp: %s -*- mode: outline; -*-"
1432 (if (featurep 'sxemacs) "SX" (if (featurep 'xemacs) "X" "GNU "))
1433 emacs-version tramp-version)))
1437 (let ((now (current-time)))
1438 (insert (format-time-string "%T." now))
1439 (insert (format "%06d " (nth 2 now))))
1440 ;; Calling Tramp function. We suppress compat and trace
1441 ;; functions from being displayed.
1442 (let ((btn 1) btf fn)
1444 (setq btf (nth 1 (backtrace-frame btn)))
1448 (setq fn (symbol-name btf))
1451 (string-match "^tramp" fn)
1458 "tramp-compat-condition-case-unless-debug"
1459 "tramp-compat-funcall"
1460 "tramp-compat-with-temp-message"
1461 "tramp-condition-case-unless-debug"
1462 "tramp-debug-message"
1464 "tramp-error-with-buffer"
1470 (setq btn (1+ btn))))
1471 ;; The following code inserts filename and line number.
1472 ;; Should be inactive by default, because it is time
1474 ; (let ((ffn (find-function-noselect (intern fn))))
1478 ; (file-name-nondirectory (buffer-file-name (car ffn)))
1479 ; (with-current-buffer (car ffn)
1480 ; (1+ (count-lines (point-min) (cdr ffn)))))))
1481 (insert (format "%s " fn)))
1483 (insert (apply 'format fmt-string args)))))
1485 (defvar tramp-message-show-message t
1486 "Show Tramp message in the minibuffer.
1487 This variable is used to disable messages from `tramp-error'.
1488 The messages are visible anyway, because an error is raised.")
1490 (defsubst tramp-message (vec-or-proc level fmt-string &rest args)
1491 "Emit a message depending on verbosity level.
1492 VEC-OR-PROC identifies the Tramp buffer to use. It can be either a
1493 vector or a process. LEVEL says to be quiet if `tramp-verbose' is
1494 less than LEVEL. The message is emitted only if `tramp-verbose' is
1495 greater than or equal to LEVEL.
1497 The message is also logged into the debug buffer when `tramp-verbose'
1498 is greater than or equal 4.
1500 Calls functions `message' and `tramp-debug-message' with FMT-STRING as
1501 control string and the remaining ARGS to actually emit the message (if
1504 (when (<= level tramp-verbose)
1505 ;; Match data must be preserved!
1507 ;; Display only when there is a minimum level.
1508 (when (and tramp-message-show-message (<= level 3))
1514 ((= level 2) "Warning: ")
1518 ;; Log only when there is a minimum level.
1519 (when (>= tramp-verbose 4)
1520 (when (and vec-or-proc
1521 (processp vec-or-proc)
1522 (buffer-name (process-buffer vec-or-proc)))
1523 (with-current-buffer (process-buffer vec-or-proc)
1524 ;; Translate proc to vec.
1525 (setq vec-or-proc (tramp-dissect-file-name default-directory))))
1526 (when (and vec-or-proc (vectorp vec-or-proc))
1527 (apply 'tramp-debug-message
1529 (concat (format "(%d) # " level) fmt-string)
1532 (defsubst tramp-backtrace (vec-or-proc)
1533 "Dump a backtrace into the debug buffer.
1534 This function is meant for debugging purposes."
1535 (tramp-message vec-or-proc 10 "\n%s" (with-output-to-string (backtrace))))
1537 (defsubst tramp-error (vec-or-proc signal fmt-string &rest args)
1539 VEC-OR-PROC identifies the connection to use, SIGNAL is the
1540 signal identifier to be raised, remaining args passed to
1541 `tramp-message'. Finally, signal SIGNAL is raised."
1542 (let (tramp-message-show-message)
1543 (tramp-backtrace vec-or-proc)
1546 (error-message-string
1548 (get signal 'error-message)
1549 (apply 'format fmt-string args))))
1550 (signal signal (list (apply 'format fmt-string args)))))
1552 (defsubst tramp-error-with-buffer
1553 (buffer vec-or-proc signal fmt-string &rest args)
1554 "Emit an error, and show BUFFER.
1555 If BUFFER is nil, show the connection buffer. Wait for 30\", or until
1556 an input event arrives. The other arguments are passed to `tramp-error'."
1557 (save-window-excursion
1558 (let* ((buf (or (and (bufferp buffer) buffer)
1559 (and (processp vec-or-proc) (process-buffer vec-or-proc))
1560 (and (vectorp vec-or-proc)
1561 (tramp-get-connection-buffer vec-or-proc))))
1562 (vec (or (and (vectorp vec-or-proc) vec-or-proc)
1563 (and buf (with-current-buffer buf
1564 (tramp-dissect-file-name default-directory))))))
1566 (apply 'tramp-error vec-or-proc signal fmt-string args)
1569 tramp-message-show-message
1570 (not (zerop tramp-verbose))
1571 (not (tramp-completion-mode-p)))
1572 (let ((enable-recursive-minibuffers t))
1573 ;; `tramp-error' does not show messages. So we must do it
1575 (message fmt-string args)
1580 ;; Reset timestamp. It would be wrong after waiting for a while.
1581 (when (equal (butlast (append vec nil) 2)
1582 (car tramp-current-connection))
1583 (setcdr tramp-current-connection (current-time)))))))
1585 (defmacro with-parsed-tramp-file-name (filename var &rest body)
1586 "Parse a Tramp filename and make components available in the body.
1588 First arg FILENAME is evaluated and dissected into its components.
1589 Second arg VAR is a symbol. It is used as a variable name to hold
1590 the filename structure. It is also used as a prefix for the variables
1591 holding the components. For example, if VAR is the symbol `foo', then
1592 `foo' will be bound to the whole structure, `foo-method' will be bound to
1593 the method component, and so on for `foo-user', `foo-host', `foo-localname',
1596 Remaining args are Lisp expressions to be evaluated (inside an implicit
1599 If VAR is nil, then we bind `v' to the structure and `method', `user',
1600 `host', `localname', `hop' to the components."
1601 `(let* ((,(or var 'v) (tramp-dissect-file-name ,filename))
1602 (,(if var (intern (concat (symbol-name var) "-method")) 'method)
1603 (tramp-file-name-method ,(or var 'v)))
1604 (,(if var (intern (concat (symbol-name var) "-user")) 'user)
1605 (tramp-file-name-user ,(or var 'v)))
1606 (,(if var (intern (concat (symbol-name var) "-host")) 'host)
1607 (tramp-file-name-host ,(or var 'v)))
1608 (,(if var (intern (concat (symbol-name var) "-localname")) 'localname)
1609 (tramp-file-name-localname ,(or var 'v)))
1610 (,(if var (intern (concat (symbol-name var) "-hop")) 'hop)
1611 (tramp-file-name-hop ,(or var 'v))))
1614 (put 'with-parsed-tramp-file-name 'lisp-indent-function 2)
1615 (put 'with-parsed-tramp-file-name 'edebug-form-spec '(form symbolp body))
1616 (tramp-compat-font-lock-add-keywords
1617 'emacs-lisp-mode '("\\<with-parsed-tramp-file-name\\>"))
1619 (defun tramp-progress-reporter-update (reporter &optional value)
1620 (let* ((parameters (cdr reporter))
1621 (message (aref parameters 3)))
1622 (when (string-match message (or (current-message) ""))
1623 (tramp-compat-funcall 'progress-reporter-update reporter value))))
1625 (defmacro with-tramp-progress-reporter (vec level message &rest body)
1626 "Executes BODY, spinning a progress reporter with MESSAGE.
1627 If LEVEL does not fit for visible messages, there are only traces
1628 without a visible progress reporter."
1629 (declare (indent 3) (debug t))
1630 `(let ((result "failed")
1632 (tramp-message ,vec ,level "%s..." ,message)
1633 ;; We start a pulsing progress reporter after 3 seconds. Feature
1634 ;; introduced in Emacs 24.1.
1635 (when (and tramp-message-show-message
1636 ;; Display only when there is a minimum level.
1637 (<= ,level (min tramp-verbose 3)))
1639 (setq pr (tramp-compat-funcall 'make-progress-reporter ,message)
1641 (run-at-time 3 0.1 'tramp-progress-reporter-update pr)))))
1643 ;; Execute the body.
1644 (prog1 (progn ,@body) (setq result "done"))
1645 ;; Stop progress reporter.
1646 (if tm (tramp-compat-funcall 'cancel-timer tm))
1647 (tramp-message ,vec ,level "%s...%s" ,message result))))
1649 (tramp-compat-font-lock-add-keywords
1650 'emacs-lisp-mode '("\\<with-tramp-progress-reporter\\>"))
1652 (defmacro with-tramp-file-property (vec file property &rest body)
1653 "Check in Tramp cache for PROPERTY, otherwise execute BODY and set cache.
1654 FILE must be a local file name on a connection identified via VEC."
1655 `(if (file-name-absolute-p ,file)
1656 (let ((value (tramp-get-file-property ,vec ,file ,property 'undef)))
1657 (when (eq value 'undef)
1658 ;; We cannot pass @body as parameter to
1659 ;; `tramp-set-file-property' because it mangles our
1661 (setq value (progn ,@body))
1662 (tramp-set-file-property ,vec ,file ,property value))
1666 (put 'with-tramp-file-property 'lisp-indent-function 3)
1667 (put 'with-tramp-file-property 'edebug-form-spec t)
1668 (tramp-compat-font-lock-add-keywords
1669 'emacs-lisp-mode '("\\<with-tramp-file-property\\>"))
1671 (defmacro with-tramp-connection-property (key property &rest body)
1672 "Check in Tramp for property PROPERTY, otherwise executes BODY and set."
1673 `(let ((value (tramp-get-connection-property ,key ,property 'undef)))
1674 (when (eq value 'undef)
1675 ;; We cannot pass ,@body as parameter to
1676 ;; `tramp-set-connection-property' because it mangles our debug
1678 (setq value (progn ,@body))
1679 (tramp-set-connection-property ,key ,property value))
1682 (put 'with-tramp-connection-property 'lisp-indent-function 2)
1683 (put 'with-tramp-connection-property 'edebug-form-spec t)
1684 (tramp-compat-font-lock-add-keywords
1685 'emacs-lisp-mode '("\\<with-tramp-connection-property\\>"))
1687 (defun tramp-drop-volume-letter (name)
1688 "Cut off unnecessary drive letter from file NAME.
1689 The functions `tramp-*-handle-expand-file-name' call `expand-file-name'
1690 locally on a remote file name. When the local system is a W32 system
1691 but the remote system is Unix, this introduces a superfluous drive
1692 letter into the file name. This function removes it."
1694 (if (string-match "\\`[a-zA-Z]:/" name)
1695 (replace-match "/" nil t name)
1698 (defun tramp-cleanup (vec)
1699 "Cleanup connection VEC, but keep the debug buffer."
1700 (with-current-buffer (tramp-get-debug-buffer vec)
1701 ;; Keep the debug buffer.
1703 (generate-new-buffer-name tramp-temp-buffer-name) 'unique)
1704 (tramp-cleanup-connection vec)
1705 (if (= (point-min) (point-max))
1707 (rename-buffer (tramp-debug-buffer-name vec) 'unique))
1708 ;; We call `tramp-get-buffer' in order to keep the debug buffer.
1709 (tramp-get-buffer vec)))
1711 ;;; Config Manipulation Functions:
1713 ;;;###tramp-autoload
1714 (defun tramp-set-completion-function (method function-list)
1715 "Sets the list of completion functions for METHOD.
1716 FUNCTION-LIST is a list of entries of the form (FUNCTION FILE).
1717 The FUNCTION is intended to parse FILE according its syntax.
1718 It might be a predefined FUNCTION, or a user defined FUNCTION.
1719 For the list of predefined FUNCTIONs see `tramp-completion-function-alist'.
1723 (tramp-set-completion-function
1725 '((tramp-parse-sconfig \"/etc/ssh_config\")
1726 (tramp-parse-sconfig \"~/.ssh/config\")))"
1728 (let ((r function-list)
1730 (setq tramp-completion-function-alist
1731 (delete (assoc method tramp-completion-function-alist)
1732 tramp-completion-function-alist))
1735 ;; Remove double entries.
1736 (when (member (car v) (cdr v))
1737 (setcdr v (delete (car v) (cdr v))))
1738 ;; Check for function and file or registry key.
1739 (unless (and (functionp (nth 0 (car v)))
1740 (if (string-match "^HKEY_CURRENT_USER" (nth 1 (car v)))
1741 ;; Windows registry.
1742 (and (memq system-type '(cygwin windows-nt))
1745 "reg" nil nil nil "query" (nth 1 (car v)))))
1746 ;; Configuration file.
1747 (file-exists-p (nth 1 (car v)))))
1748 (setq r (delete (car v) r)))
1752 (add-to-list 'tramp-completion-function-alist
1755 (defun tramp-get-completion-function (method)
1756 "Returns a list of completion functions for METHOD.
1757 For definition of that list see `tramp-set-completion-function'."
1759 ;; Hosts visited once shall be remembered.
1760 `(tramp-parse-connection-properties ,method)
1761 ;; The method related defaults.
1762 (cdr (assoc method tramp-completion-function-alist))))
1765 ;;; Fontification of `read-file-name':
1767 ;; rfn-eshadow.el is part of Emacs 22. It is autoloaded.
1768 (defvar tramp-rfn-eshadow-overlay)
1769 (make-variable-buffer-local 'tramp-rfn-eshadow-overlay)
1771 (defun tramp-rfn-eshadow-setup-minibuffer ()
1772 "Set up a minibuffer for `file-name-shadow-mode'.
1773 Adds another overlay hiding filename parts according to Tramp's
1774 special handling of `substitute-in-file-name'."
1775 (when (symbol-value 'minibuffer-completing-file-name)
1776 (setq tramp-rfn-eshadow-overlay
1777 (tramp-compat-funcall
1779 (tramp-compat-funcall 'minibuffer-prompt-end)
1780 (tramp-compat-funcall 'minibuffer-prompt-end)))
1781 ;; Copy rfn-eshadow-overlay properties.
1782 (let ((props (tramp-compat-funcall
1783 'overlay-properties (symbol-value 'rfn-eshadow-overlay))))
1785 ;; The `field' property prevents correct minibuffer
1786 ;; completion; we exclude it.
1787 (if (not (eq (car props) 'field))
1788 (tramp-compat-funcall
1789 'overlay-put tramp-rfn-eshadow-overlay (pop props) (pop props))
1790 (pop props) (pop props))))))
1792 (when (boundp 'rfn-eshadow-setup-minibuffer-hook)
1793 (add-hook 'rfn-eshadow-setup-minibuffer-hook
1794 'tramp-rfn-eshadow-setup-minibuffer)
1795 (add-hook 'tramp-unload-hook
1797 (remove-hook 'rfn-eshadow-setup-minibuffer-hook
1798 'tramp-rfn-eshadow-setup-minibuffer))))
1800 (defconst tramp-rfn-eshadow-update-overlay-regexp
1801 (format "[^%s/~]*\\(/\\|~\\)" tramp-postfix-host-format))
1803 (defun tramp-rfn-eshadow-update-overlay ()
1804 "Update `rfn-eshadow-overlay' to cover shadowed part of minibuffer input.
1805 This is intended to be used as a minibuffer `post-command-hook' for
1806 `file-name-shadow-mode'; the minibuffer should have already
1807 been set up by `rfn-eshadow-setup-minibuffer'."
1808 ;; In remote files name, there is a shadowing just for the local part.
1810 (let ((end (or (tramp-compat-funcall
1811 'overlay-end (symbol-value 'rfn-eshadow-overlay))
1812 (tramp-compat-funcall 'minibuffer-prompt-end)))
1813 ;; We do not want to send any remote command.
1817 (tramp-compat-funcall
1818 'buffer-substring-no-properties end (point-max)))
1822 (1+ (or (string-match
1823 tramp-rfn-eshadow-update-overlay-regexp
1824 (buffer-string) end)
1827 (let ((rfn-eshadow-overlay tramp-rfn-eshadow-overlay)
1828 (rfn-eshadow-update-overlay-hook nil)
1829 file-name-handler-alist)
1830 (tramp-compat-funcall
1831 'move-overlay rfn-eshadow-overlay (point-max) (point-max))
1832 (tramp-compat-funcall 'rfn-eshadow-update-overlay))))))))
1834 (when (boundp 'rfn-eshadow-update-overlay-hook)
1835 (add-hook 'rfn-eshadow-update-overlay-hook
1836 'tramp-rfn-eshadow-update-overlay)
1837 (add-hook 'tramp-unload-hook
1839 (remove-hook 'rfn-eshadow-update-overlay-hook
1840 'tramp-rfn-eshadow-update-overlay))))
1842 ;; Inodes don't exist for some file systems. Therefore we must
1843 ;; generate virtual ones. Used in `find-buffer-visiting'. The method
1844 ;; applied might be not so efficient (Ange-FTP uses hashes). But
1845 ;; performance isn't the major issue given that file transfer will
1847 (defvar tramp-inodes 0
1848 "Keeps virtual inodes numbers.")
1850 ;; Devices must distinguish physical file systems. The device numbers
1851 ;; provided by "lstat" aren't unique, because we operate on different hosts.
1852 ;; So we use virtual device numbers, generated by Tramp. Both Ange-FTP and
1853 ;; EFS use device number "-1". In order to be different, we use device number
1854 ;; (-1 . x), whereby "x" is unique for a given (method user host).
1855 (defvar tramp-devices 0
1856 "Keeps virtual device numbers.")
1858 (defun tramp-default-file-modes (filename)
1859 "Return file modes of FILENAME as integer.
1860 If the file modes of FILENAME cannot be determined, return the
1861 value of `default-file-modes', without execute permissions."
1862 (or (file-modes filename)
1863 (logand (default-file-modes) (tramp-compat-octal-to-decimal "0666"))))
1865 (defun tramp-replace-environment-variables (filename)
1866 "Replace environment variables in FILENAME.
1867 Return the string with the replaced variables."
1869 (tramp-compat-funcall 'substitute-env-vars filename 'only-defined))
1870 ;; We need an own implementation.
1872 (let ((idx (string-match "$\\(\\w+\\)" filename)))
1873 ;; `$' is coded as `$$'.
1875 (or (zerop idx) (not (eq ?$ (aref filename (1- idx)))))
1876 (getenv (match-string 1 filename)))
1879 (substitute-in-file-name (match-string 0 filename))
1883 ;; In XEmacs, electricity is implemented via a key map for ?/ and ?~,
1884 ;; which calls corresponding functions (see minibuf.el).
1885 (when (fboundp 'minibuffer-electric-separator)
1890 (around ,(intern (format "tramp-advice-%s" x)) activate)
1891 "Invoke `substitute-in-file-name' for Tramp files."
1892 (if (and (symbol-value 'minibuffer-electric-file-name-behavior)
1893 (tramp-tramp-file-p (buffer-substring)))
1894 ;; We don't need to handle `last-input-event', because
1895 ;; due to the key map we know it must be ?/ or ?~.
1896 (let ((s (concat (buffer-substring (point-min) (point))
1897 (string last-command-char))))
1898 (delete-region (point-min) (point))
1899 (insert (substitute-in-file-name s))
1900 (setq ad-return-value last-command-char))
1906 (ad-remove-advice ',x 'around ',(intern (format "tramp-advice-%s" x)))
1907 (ad-activate ',x)))))
1909 '(minibuffer-electric-separator
1910 minibuffer-electric-tilde)))
1912 (defun tramp-find-file-name-coding-system-alist (filename tmpname)
1913 "Like `find-operation-coding-system' for Tramp filenames.
1914 Tramp's `insert-file-contents' and `write-region' work over
1915 temporary file names. If `file-coding-system-alist' contains an
1916 expression, which matches more than the file name suffix, the
1917 coding system might not be determined. This function repairs it."
1919 (dolist (elt file-coding-system-alist result)
1920 (when (and (consp elt) (string-match (car elt) filename))
1921 ;; We found a matching entry in `file-coding-system-alist'.
1922 ;; So we add a similar entry, but with the temporary file name
1925 'result (cons (regexp-quote tmpname) (cdr elt)) 'append)))))
1928 (progn (defun tramp-run-real-handler (operation args)
1929 "Invoke normal file name handler for OPERATION.
1930 First arg specifies the OPERATION, second arg is a list of arguments to
1931 pass to the OPERATION."
1932 (let* ((inhibit-file-name-handlers
1933 `(tramp-file-name-handler
1934 tramp-vc-file-name-handler
1935 tramp-completion-file-name-handler
1936 cygwin-mount-name-hook-function
1937 cygwin-mount-map-drive-hook-function
1939 ,(and (eq inhibit-file-name-operation operation)
1940 inhibit-file-name-handlers)))
1941 (inhibit-file-name-operation operation))
1942 (apply operation args))))
1945 (progn (defun tramp-completion-run-real-handler (operation args)
1946 "Invoke `tramp-file-name-handler' for OPERATION.
1947 First arg specifies the OPERATION, second arg is a list of arguments to
1948 pass to the OPERATION."
1949 (let* ((inhibit-file-name-handlers
1950 `(tramp-completion-file-name-handler
1951 cygwin-mount-name-hook-function
1952 cygwin-mount-map-drive-hook-function
1954 ,(and (eq inhibit-file-name-operation operation)
1955 inhibit-file-name-handlers)))
1956 (inhibit-file-name-operation operation))
1957 (apply operation args))))
1959 ;; We handle here all file primitives. Most of them have the file
1960 ;; name as first parameter; nevertheless we check for them explicitly
1961 ;; in order to be signaled if a new primitive appears. This
1962 ;; scenario is needed because there isn't a way to decide by
1963 ;; syntactical means whether a foreign method must be called. It would
1964 ;; ease the life if `file-name-handler-alist' would support a decision
1965 ;; function as well but regexp only.
1966 (defun tramp-file-name-for-operation (operation &rest args)
1967 "Return file name related to OPERATION file primitive.
1968 ARGS are the arguments OPERATION has been called with."
1970 ;; FILE resp DIRECTORY.
1972 (list 'access-file 'byte-compiler-base-file-name 'delete-directory
1973 'delete-file 'diff-latest-backup-file 'directory-file-name
1974 'directory-files 'directory-files-and-attributes
1975 'dired-compress-file 'dired-uncache
1976 'file-accessible-directory-p 'file-attributes
1977 'file-directory-p 'file-executable-p 'file-exists-p
1978 'file-local-copy 'file-modes
1979 'file-name-as-directory 'file-name-directory
1980 'file-name-nondirectory 'file-name-sans-versions
1981 'file-ownership-preserved-p 'file-readable-p
1982 'file-regular-p 'file-remote-p 'file-symlink-p 'file-truename
1983 'file-writable-p 'find-backup-file-name 'find-file-noselect
1984 'get-file-buffer 'insert-directory 'insert-file-contents
1985 'load 'make-directory 'make-directory-internal
1986 'set-file-modes 'substitute-in-file-name
1987 'unhandled-file-name-directory 'vc-registered
1991 'file-acl 'file-notify-add-watch
1992 'file-selinux-context 'set-file-acl 'set-file-selinux-context
1994 'abbreviate-file-name 'create-file-buffer
1995 'dired-file-modtime 'dired-make-compressed-filename
1996 'dired-recursive-delete-directory 'dired-set-file-modtime
1997 'dired-shell-unhandle-file-name 'dired-uucode-file
1998 'insert-file-contents-literally 'make-temp-name 'recover-file
1999 'vm-imap-check-mail 'vm-pop-check-mail 'vm-spool-check-mail))
2000 (if (file-name-absolute-p (nth 0 args))
2002 (expand-file-name (nth 0 args))))
2003 ;; FILE DIRECTORY resp FILE1 FILE2.
2005 (list 'add-name-to-file 'copy-file 'expand-file-name
2006 'file-name-all-completions 'file-name-completion
2007 'file-newer-than-file-p 'make-symbolic-link 'rename-file
2011 'file-equal-p 'file-in-directory-p
2013 'dired-make-relative-symlink
2014 'vm-imap-move-mail 'vm-pop-move-mail 'vm-spool-move-mail))
2017 ((string-match tramp-file-name-regexp (nth 0 args)) (nth 0 args))
2018 ((string-match tramp-file-name-regexp (nth 1 args)) (nth 1 args))
2019 (t (buffer-file-name (current-buffer))))))
2021 ((eq operation 'write-region)
2025 (list 'set-visited-file-modtime 'verify-visited-file-modtime
2027 'make-auto-save-file-name
2031 (if (bufferp (nth 0 args)) (nth 0 args) (current-buffer))))
2034 (list ;; not in Emacs 23+.
2043 'dired-print-file 'dired-shell-call-process))
2046 ((eq operation 'file-notify-rm-watch)
2047 (when (processp (nth 0 args))
2048 (with-current-buffer (process-buffer (nth 0 args))
2049 default-directory)))
2050 ;; Unknown file primitive.
2051 (t (error "unknown file I/O primitive: %s" operation))))
2053 (defun tramp-find-foreign-file-name-handler (filename)
2054 "Return foreign file name handler if exists."
2055 (when (tramp-tramp-file-p filename)
2056 (let ((v (tramp-dissect-file-name filename t))
2057 (handler tramp-foreign-file-name-handler-alist)
2059 ;; When we are not fully sure that filename completion is safe,
2060 ;; we should not return a handler.
2061 (when (or (tramp-file-name-method v) (tramp-file-name-user v)
2062 (and (tramp-file-name-host v)
2063 (not (member (tramp-file-name-host v)
2064 (mapcar 'car tramp-methods))))
2065 (not (tramp-completion-mode-p)))
2067 (setq elt (car handler)
2068 handler (cdr handler))
2069 (when (funcall (car elt) filename)
2074 (defvar tramp-debug-on-error nil
2075 "Like `debug-on-error' but used Tramp internal.")
2077 (defmacro tramp-condition-case-unless-debug
2078 (var bodyform &rest handlers)
2079 "Like `condition-case-unless-debug' but `tramp-debug-on-error'."
2080 `(let ((debug-on-error tramp-debug-on-error))
2081 (tramp-compat-condition-case-unless-debug ,var ,bodyform ,@handlers)))
2085 (defun tramp-file-name-handler (operation &rest args)
2086 "Invoke Tramp file name handler.
2087 Falls back to normal file name handler if no Tramp file name handler exists."
2091 (tramp-replace-environment-variables
2092 (apply 'tramp-file-name-for-operation operation args)))
2093 (completion (tramp-completion-mode-p))
2094 (foreign (tramp-find-foreign-file-name-handler filename)))
2095 (with-parsed-tramp-file-name filename nil
2096 ;; Call the backend function.
2098 (tramp-condition-case-unless-debug err
2099 (let ((sf (symbol-function foreign))
2101 ;; Some packages set the default directory to a
2102 ;; remote path, before respective Tramp packages
2103 ;; are already loaded. This results in
2104 ;; recursive loading. Therefore, we load the
2105 ;; Tramp packages locally.
2106 (when (and (listp sf) (eq (car sf) 'autoload))
2107 (let ((default-directory
2108 (tramp-compat-temporary-file-directory)))
2109 (load (cadr sf) 'noerror 'nomessage)))
2110 ;; If `non-essential' is non-nil, Tramp shall
2111 ;; not open a new connection.
2112 ;; If Tramp detects that it shouldn't continue
2113 ;; to work, it throws the `suppress' event.
2114 ;; This could happen for example, when Tramp
2115 ;; tries to open the same connection twice in a
2116 ;; short time frame.
2117 ;; In both cases, we try the default handler then.
2119 (catch 'non-essential
2121 (apply foreign operation args))))
2123 ((eq result 'non-essential)
2125 v 5 "Non-essential received in operation %s"
2126 (append (list operation) args))
2127 (tramp-run-real-handler operation args))
2128 ((eq result 'suppress)
2129 (let (tramp-message-show-message)
2131 v 1 "Suppress received in operation %s"
2132 (append (list operation) args))
2134 (tramp-run-real-handler operation args)))
2137 ;; Trace that somebody has interrupted the operation.
2139 (let (tramp-message-show-message)
2141 v 1 "Interrupt received in operation %s"
2142 (append (list operation) args)))
2143 ;; Propagate the quit signal.
2144 (signal (car err) (cdr err)))
2146 ;; When we are in completion mode, some failed
2147 ;; operations shall return at least a default value
2148 ;; in order to give the user a chance to correct the
2149 ;; file name in the minibuffer.
2150 ;; In order to get a full backtrace, one could apply
2151 ;; (setq tramp-debug-on-error t)
2154 ((and completion (zerop (length localname))
2155 (memq operation '(file-exists-p file-directory-p)))
2157 ((and completion (zerop (length localname))
2159 '(expand-file-name file-name-as-directory)))
2161 ;; Propagate the error.
2162 (t (signal (car err) (cdr err))))))
2164 ;; Nothing to do for us.
2165 (tramp-run-real-handler operation args)))))
2167 ;; When `tramp-mode' is not enabled, we don't do anything.
2168 (tramp-run-real-handler operation args)))
2170 ;; In Emacs, there is some concurrency due to timers. If a timer
2171 ;; interrupts Tramp and wishes to use the same connection buffer as
2172 ;; the "main" Emacs, then garbage might occur in the connection
2173 ;; buffer. Therefore, we need to make sure that a timer does not use
2174 ;; the same connection buffer as the "main" Emacs. We implement a
2175 ;; cheap global lock, instead of locking each connection buffer
2176 ;; separately. The global lock is based on two variables,
2177 ;; `tramp-locked' and `tramp-locker'. `tramp-locked' is set to true
2178 ;; (with setq) to indicate a lock. But Tramp also calls itself during
2179 ;; processing of a single file operation, so we need to allow
2180 ;; recursive calls. That's where the `tramp-locker' variable comes in
2181 ;; -- it is let-bound to t during the execution of the current
2182 ;; handler. So if `tramp-locked' is t and `tramp-locker' is also t,
2183 ;; then we should just proceed because we have been called
2184 ;; recursively. But if `tramp-locker' is nil, then we are a timer
2185 ;; interrupting the "main" Emacs, and then we signal an error.
2187 (defvar tramp-locked nil
2188 "If non-nil, then Tramp is currently busy.
2189 Together with `tramp-locker', this implements a locking mechanism
2190 preventing reentrant calls of Tramp.")
2192 (defvar tramp-locker nil
2193 "If non-nil, then a caller has locked Tramp.
2194 Together with `tramp-locked', this implements a locking mechanism
2195 preventing reentrant calls of Tramp.")
2198 (progn (defun tramp-completion-file-name-handler (operation &rest args)
2199 "Invoke Tramp file name completion handler.
2200 Falls back to normal file name handler if no Tramp file name handler exists."
2201 ;; We bind `directory-sep-char' here for XEmacs on Windows, which
2202 ;; would otherwise use backslash.
2203 (let ((directory-sep-char ?/)
2204 (fn (assoc operation tramp-completion-file-name-handler-alist)))
2206 ;; When `tramp-mode' is not enabled, we don't do anything.
2208 ;; For other syntaxes than `sep', the regexp matches many common
2209 ;; situations where the user doesn't actually want to use Tramp.
2210 ;; So to avoid autoloading Tramp after typing just "/s", we
2211 ;; disable this part of the completion, unless the user implicitly
2212 ;; indicated his interest in using a fancier completion system.
2213 (or (eq tramp-syntax 'sep)
2214 (featurep 'tramp) ;; If it's loaded, we may as well use it.
2215 ;; `partial-completion-mode' does not exist in XEmacs.
2216 ;; It is obsoleted with Emacs 24.1.
2217 (and (boundp 'partial-completion-mode)
2218 (symbol-value 'partial-completion-mode))
2219 ;; FIXME: These may have been loaded even if the user never
2220 ;; intended to use them.
2222 (featurep 'icicles)))
2223 (save-match-data (apply (cdr fn) args))
2224 (tramp-completion-run-real-handler operation args)))))
2227 (progn (defun tramp-register-file-name-handlers ()
2228 "Add Tramp file name handlers to `file-name-handler-alist'."
2229 ;; Remove autoloaded handlers from file name handler alist. Useful,
2230 ;; if `tramp-syntax' has been changed.
2231 (let ((a1 (rassq 'tramp-file-name-handler file-name-handler-alist)))
2232 (setq file-name-handler-alist (delq a1 file-name-handler-alist)))
2234 'tramp-completion-file-name-handler file-name-handler-alist)))
2235 (setq file-name-handler-alist (delq a1 file-name-handler-alist)))
2236 ;; Add the handlers.
2237 (add-to-list 'file-name-handler-alist
2238 (cons tramp-file-name-regexp 'tramp-file-name-handler))
2239 (put 'tramp-file-name-handler 'safe-magic t)
2240 (add-to-list 'file-name-handler-alist
2241 (cons tramp-completion-file-name-regexp
2242 'tramp-completion-file-name-handler))
2243 (put 'tramp-completion-file-name-handler 'safe-magic t)
2244 ;; If jka-compr or epa-file are already loaded, move them to the
2245 ;; front of `file-name-handler-alist'.
2246 (dolist (fnh '(epa-file-handler jka-compr-handler))
2247 (let ((entry (rassoc fnh file-name-handler-alist)))
2249 (setq file-name-handler-alist
2250 (cons entry (delete entry file-name-handler-alist))))))))
2252 ;; `tramp-file-name-handler' must be registered before evaluation of
2253 ;; site-start and init files, because there might exist remote files
2254 ;; already, f.e. files kept via recentf-mode.
2256 (tramp-register-file-name-handlers)
2258 (defun tramp-exists-file-name-handler (operation &rest args)
2259 "Check, whether OPERATION runs a file name handler."
2260 ;; The file name handler is determined on base of either an
2261 ;; argument, `buffer-file-name', or `default-directory'.
2263 (let* ((buffer-file-name "/")
2264 (default-directory "/")
2265 (fnha file-name-handler-alist)
2266 (check-file-name-operation operation)
2267 (file-name-handler-alist
2270 (lambda (operation &rest args)
2271 "Returns OPERATION if it is the one to be checked."
2272 (if (equal check-file-name-operation operation)
2274 (let ((file-name-handler-alist fnha))
2275 (apply operation args))))))))
2276 (equal (apply operation args) operation))))
2279 (defun tramp-unload-file-name-handlers ()
2280 (setq file-name-handler-alist
2281 (delete (rassoc 'tramp-file-name-handler
2282 file-name-handler-alist)
2283 (delete (rassoc 'tramp-completion-file-name-handler
2284 file-name-handler-alist)
2285 file-name-handler-alist))))
2287 (add-hook 'tramp-unload-hook 'tramp-unload-file-name-handlers)
2289 ;;; File name handler functions for completion mode:
2291 (defvar tramp-completion-mode nil
2292 "If non-nil, external packages signal that they are in file name completion.
2294 This is necessary, because Tramp uses a heuristic depending on last
2295 input event. This fails when external packages use other characters
2296 but <TAB>, <SPACE> or ?\\? for file name completion. This variable
2297 should never be set globally, the intention is to let-bind it.")
2299 ;; Necessary because `tramp-file-name-regexp-unified' and
2300 ;; `tramp-completion-file-name-regexp-unified' aren't different. If
2301 ;; nil, `tramp-completion-run-real-handler' is called (i.e. forwarding
2302 ;; to `tramp-file-name-handler'). Otherwise, it takes
2303 ;; `tramp-run-real-handler'. Using `last-input-event' is a little bit
2304 ;; risky, because completing a file might require loading other files,
2305 ;; like "~/.netrc", and for them it shouldn't be decided based on that
2306 ;; variable. On the other hand, those files shouldn't have partial
2307 ;; Tramp file name syntax. Maybe another variable should be introduced
2308 ;; overwriting this check in such cases. Or we change Tramp file name
2309 ;; syntax in order to avoid ambiguities, like in XEmacs ...
2310 ;;;###tramp-autoload
2311 (defun tramp-completion-mode-p ()
2312 "Check, whether method / user name / host name completion is active."
2314 ;; Signal from outside. `non-essential' has been introduced in Emacs 24.
2315 (and (boundp 'non-essential) (symbol-value 'non-essential))
2316 tramp-completion-mode
2318 (equal last-input-event 'tab)
2319 (and (natnump last-input-event)
2321 ;; ?\t has event-modifier 'control.
2322 (equal last-input-event ?\t)
2323 (and (not (event-modifiers last-input-event))
2324 (or (equal last-input-event ?\?)
2325 (equal last-input-event ?\ )))))
2327 (and (featurep 'xemacs)
2328 ;; `last-input-event' might be nil.
2329 (not (null last-input-event))
2330 ;; `last-input-event' may have no character approximation.
2331 (tramp-compat-funcall 'event-to-character last-input-event)
2333 ;; ?\t has event-modifier 'control.
2335 (tramp-compat-funcall 'event-to-character last-input-event) ?\t)
2336 (and (not (event-modifiers last-input-event))
2338 (tramp-compat-funcall 'event-to-character last-input-event)
2341 (tramp-compat-funcall 'event-to-character last-input-event)
2344 (defun tramp-connectable-p (filename)
2345 "Check, whether it is possible to connect the remote host w/o side-effects.
2346 This is true, if either the remote host is already connected, or if we are
2347 not in completion mode."
2348 (and (tramp-tramp-file-p filename)
2349 (with-parsed-tramp-file-name filename nil
2350 (or (not (tramp-completion-mode-p))
2351 (let ((p (tramp-get-connection-process v)))
2352 (and p (processp p) (memq (process-status p) '(run open))))))))
2354 ;; Method, host name and user name completion.
2355 ;; `tramp-completion-dissect-file-name' returns a list of
2356 ;; tramp-file-name structures. For all of them we return possible completions.
2358 (defun tramp-completion-handle-file-name-all-completions (filename directory)
2359 "Like `file-name-all-completions' for partial Tramp files."
2362 (tramp-drop-volume-letter (expand-file-name filename directory)))
2365 ;; Suppress hop from completion.
2369 "\\(" "\\(" tramp-remote-file-name-spec-regexp
2370 tramp-postfix-hop-regexp
2373 (setq hop (match-string 1 fullname)
2374 fullname (replace-match "" nil nil fullname 1)))
2376 ;; Possible completion structures.
2377 (dolist (elt (tramp-completion-dissect-file-name fullname))
2378 (let* ((method (tramp-file-name-method elt))
2379 (user (tramp-file-name-user elt))
2380 (host (tramp-file-name-host elt))
2381 (localname (tramp-file-name-localname elt))
2382 (m (tramp-find-method method user host))
2383 (tramp-current-user user) ; see `tramp-parse-passwd'
2386 (unless localname ;; Nothing to complete.
2390 ;; Method dependent user / host combinations.
2394 (setq all-user-hosts
2395 (append all-user-hosts
2396 (funcall (nth 0 x) (nth 1 x)))))
2397 (tramp-get-completion-function m))
2403 (tramp-get-completion-user-host
2404 method user host (nth 0 x) (nth 1 x)))
2405 (delq nil all-user-hosts)))))
2407 ;; Possible methods.
2409 (append result (tramp-get-completion-methods m)))))))
2411 ;; Unify list, add hop, remove nil elements.
2412 (dolist (elt result)
2414 (string-match tramp-prefix-regexp elt)
2415 (setq elt (replace-match (concat tramp-prefix-format hop) nil nil elt))
2418 (substring elt (length (tramp-drop-volume-letter directory))))))
2420 ;; Complete local parts.
2424 (apply (if (tramp-connectable-p fullname)
2425 'tramp-completion-run-real-handler
2426 'tramp-run-real-handler)
2427 'file-name-all-completions (list (list filename directory)))))))
2429 ;; Method, host name and user name completion for a file.
2431 (defun tramp-completion-handle-file-name-completion
2432 (filename directory &optional predicate)
2433 "Like `file-name-completion' for Tramp files."
2436 (mapcar 'list (file-name-all-completions filename directory))
2437 (when (and predicate
2438 (tramp-connectable-p (expand-file-name filename directory)))
2439 (lambda (x) (funcall predicate (expand-file-name (car x) directory))))))
2441 ;; I misuse a little bit the tramp-file-name structure in order to handle
2442 ;; completion possibilities for partial methods / user names / host names.
2443 ;; Return value is a list of tramp-file-name structures according to possible
2444 ;; completions. If "localname" is non-nil it means there
2445 ;; shouldn't be a completion anymore.
2447 ;; Expected results:
2449 ;; "/x" "/[x" "/x@" "/[x@" "/x@y" "/[x@y"
2450 ;; [nil nil "x" nil] [nil "x" nil nil] [nil "x" "y" nil]
2451 ;; [nil "x" nil nil]
2452 ;; ["x" nil nil nil]
2454 ;; "/x:" "/x:y" "/x:y:"
2455 ;; [nil nil "x" ""] [nil nil "x" "y"] ["x" nil "y" ""]
2457 ;; ["x" nil "" nil] ["x" nil "y" nil]
2458 ;; ["x" "" nil nil] ["x" "y" nil nil]
2460 ;; "/x:y@" "/x:y@z" "/x:y@z:"
2461 ;; [nil nil "x" "y@"] [nil nil "x" "y@z"] ["x" "y" "z" ""]
2462 ;; "/[x/y@" "/[x/y@z"
2463 ;; ["x" nil "y" nil] ["x" "y" "z" nil]
2464 (defun tramp-completion-dissect-file-name (name)
2465 "Returns a list of `tramp-file-name' structures.
2466 They are collected by `tramp-completion-dissect-file-name1'."
2470 (tramp-completion-ipv6-regexp
2473 (if (zerop (length tramp-postfix-ipv6-format))
2474 tramp-postfix-host-format
2475 tramp-postfix-ipv6-format)))
2476 ;; "/method" "/[method"
2477 (tramp-completion-file-name-structure1
2478 (list (concat tramp-prefix-regexp "\\(" tramp-method-regexp x-nil "\\)$")
2481 (tramp-completion-file-name-structure2
2482 (list (concat tramp-prefix-regexp "\\(" tramp-user-regexp x-nil "\\)$")
2485 (tramp-completion-file-name-structure3
2486 (list (concat tramp-prefix-regexp "\\(" tramp-host-regexp x-nil "\\)$")
2488 ;; "/[ipv6" "/[ipv6"
2489 (tramp-completion-file-name-structure4
2490 (list (concat tramp-prefix-regexp
2491 tramp-prefix-ipv6-regexp
2492 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
2494 ;; "/user@host" "/[user@host"
2495 (tramp-completion-file-name-structure5
2496 (list (concat tramp-prefix-regexp
2497 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
2498 "\\(" tramp-host-regexp x-nil "\\)$")
2500 ;; "/user@[ipv6" "/[user@ipv6"
2501 (tramp-completion-file-name-structure6
2502 (list (concat tramp-prefix-regexp
2503 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
2504 tramp-prefix-ipv6-regexp
2505 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
2507 ;; "/method:user" "/[method/user" "/method://user"
2508 (tramp-completion-file-name-structure7
2509 (list (concat tramp-prefix-regexp
2510 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
2511 "\\(" tramp-user-regexp x-nil "\\)$")
2513 ;; "/method:host" "/[method/host" "/method://host"
2514 (tramp-completion-file-name-structure8
2515 (list (concat tramp-prefix-regexp
2516 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
2517 "\\(" tramp-host-regexp x-nil "\\)$")
2519 ;; "/method:[ipv6" "/[method/ipv6" "/method://[ipv6"
2520 (tramp-completion-file-name-structure9
2521 (list (concat tramp-prefix-regexp
2522 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
2523 tramp-prefix-ipv6-regexp
2524 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
2526 ;; "/method:user@host" "/[method/user@host" "/method://user@host"
2527 (tramp-completion-file-name-structure10
2528 (list (concat tramp-prefix-regexp
2529 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
2530 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
2531 "\\(" tramp-host-regexp x-nil "\\)$")
2533 ;; "/method:user@[ipv6" "/[method/user@ipv6" "/method://user@[ipv6"
2534 (tramp-completion-file-name-structure11
2535 (list (concat tramp-prefix-regexp
2536 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
2537 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
2538 tramp-prefix-ipv6-regexp
2539 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
2541 ;; "/method: "/method:/"
2542 (tramp-completion-file-name-structure12
2544 (if (equal tramp-syntax 'url)
2545 (concat tramp-prefix-regexp
2546 "\\(" tramp-method-regexp "\\)"
2547 "\\(" (substring tramp-postfix-method-regexp 0 1)
2548 "\\|" (substring tramp-postfix-method-regexp 1 2) "\\)"
2550 ;; Should not match if not URL syntax.
2551 (concat tramp-prefix-regexp "/$"))
2553 ;; "/method: "/method:/"
2554 (tramp-completion-file-name-structure13
2556 (if (equal tramp-syntax 'url)
2557 (concat tramp-prefix-regexp
2558 "\\(" tramp-method-regexp "\\)"
2559 "\\(" (substring tramp-postfix-method-regexp 0 1)
2560 "\\|" (substring tramp-postfix-method-regexp 1 2) "\\)"
2562 ;; Should not match if not URL syntax.
2563 (concat tramp-prefix-regexp "/$"))
2566 (mapc (lambda (structure)
2567 (add-to-list 'result
2568 (tramp-completion-dissect-file-name1 structure name)))
2570 tramp-completion-file-name-structure1
2571 tramp-completion-file-name-structure2
2572 tramp-completion-file-name-structure3
2573 tramp-completion-file-name-structure4
2574 tramp-completion-file-name-structure5
2575 tramp-completion-file-name-structure6
2576 tramp-completion-file-name-structure7
2577 tramp-completion-file-name-structure8
2578 tramp-completion-file-name-structure9
2579 tramp-completion-file-name-structure10
2580 tramp-completion-file-name-structure11
2581 tramp-completion-file-name-structure12
2582 tramp-completion-file-name-structure13
2583 tramp-file-name-structure))
2587 (defun tramp-completion-dissect-file-name1 (structure name)
2588 "Returns a `tramp-file-name' structure matching STRUCTURE.
2589 The structure consists of remote method, remote user,
2590 remote host and localname (filename on remote host)."
2593 (when (string-match (nth 0 structure) name)
2594 (let ((method (and (nth 1 structure)
2595 (match-string (nth 1 structure) name)))
2596 (user (and (nth 2 structure)
2597 (match-string (nth 2 structure) name)))
2598 (host (and (nth 3 structure)
2599 (match-string (nth 3 structure) name)))
2600 (localname (and (nth 4 structure)
2601 (match-string (nth 4 structure) name))))
2602 (vector method user host localname nil)))))
2604 ;; This function returns all possible method completions, adding the
2605 ;; trailing method delimiter.
2606 (defun tramp-get-completion-methods (partial-method)
2607 "Returns all method completions for PARTIAL-METHOD."
2611 (string-match (concat "^" (regexp-quote partial-method)) method)
2612 (tramp-completion-make-tramp-file-name method nil nil nil)))
2613 (mapcar 'car tramp-methods)))
2615 ;; Compares partial user and host names with possible completions.
2616 (defun tramp-get-completion-user-host
2617 (method partial-user partial-host user host)
2618 "Returns the most expanded string for user and host name completion.
2619 PARTIAL-USER must match USER, PARTIAL-HOST must match HOST."
2622 ((and partial-user partial-host)
2624 (string-match (concat "^" (regexp-quote partial-host)) host)
2625 (string-equal partial-user (or user partial-user)))
2626 (setq user partial-user)
2633 (and user (string-match (concat "^" (regexp-quote partial-user)) user))
2639 (and host (string-match (concat "^" (regexp-quote partial-host)) host))
2645 (unless (zerop (+ (length user) (length host)))
2646 (tramp-completion-make-tramp-file-name method user host nil)))
2648 ;; Generic function.
2649 (defun tramp-parse-group (regexp match-level skip-regexp)
2650 "Return a (user host) tuple allowed to access.
2651 User is always nil."
2653 (when (re-search-forward regexp (point-at-eol) t)
2654 (setq result (list nil (match-string match-level))))
2656 (> (skip-chars-forward skip-regexp) 0)
2660 ;; Generic function.
2661 (defun tramp-parse-file (filename function)
2662 "Return a list of (user host) tuples allowed to access.
2663 User is always nil."
2664 ;; On Windows, there are problems in completion when
2665 ;; `default-directory' is remote.
2666 (let ((default-directory (tramp-compat-temporary-file-directory)))
2667 (when (file-readable-p filename)
2669 (insert-file-contents filename)
2670 (goto-char (point-min))
2671 (loop while (not (eobp)) collect (funcall function))))))
2673 ;;;###tramp-autoload
2674 (defun tramp-parse-rhosts (filename)
2675 "Return a list of (user host) tuples allowed to access.
2676 Either user or host may be nil."
2677 (tramp-parse-file filename 'tramp-parse-rhosts-group))
2679 (defun tramp-parse-rhosts-group ()
2680 "Return a (user host) tuple allowed to access.
2681 Either user or host may be nil."
2685 "^\\(" tramp-host-regexp "\\)"
2686 "\\([ \t]+" "\\(" tramp-user-regexp "\\)" "\\)?")))
2687 (when (re-search-forward regexp (point-at-eol) t)
2688 (setq result (append (list (match-string 3) (match-string 1)))))
2692 ;;;###tramp-autoload
2693 (defun tramp-parse-shosts (filename)
2694 "Return a list of (user host) tuples allowed to access.
2695 User is always nil."
2696 (tramp-parse-file filename 'tramp-parse-shosts-group))
2698 (defun tramp-parse-shosts-group ()
2699 "Return a (user host) tuple allowed to access.
2700 User is always nil."
2701 (tramp-parse-group (concat "^\\(" tramp-host-regexp "\\)") 1 ","))
2703 ;;;###tramp-autoload
2704 (defun tramp-parse-sconfig (filename)
2705 "Return a list of (user host) tuples allowed to access.
2706 User is always nil."
2707 (tramp-parse-file filename 'tramp-parse-sconfig-group))
2709 (defun tramp-parse-sconfig-group ()
2710 "Return a (user host) tuple allowed to access.
2711 User is always nil."
2713 (concat "^[ \t]*Host[ \t]+" "\\(" tramp-host-regexp "\\)") 1 ","))
2715 ;; Generic function.
2716 (defun tramp-parse-shostkeys-sknownhosts (dirname regexp)
2717 "Return a list of (user host) tuples allowed to access.
2718 User is always nil."
2719 ;; On Windows, there are problems in completion when
2720 ;; `default-directory' is remote.
2721 (let* ((default-directory (tramp-compat-temporary-file-directory))
2722 (files (and (file-directory-p dirname) (directory-files dirname))))
2723 (loop for f in files
2724 when (and (not (string-match "^\\.\\.?$" f)) (string-match regexp f))
2725 collect (list nil (match-string 1 f)))))
2727 ;;;###tramp-autoload
2728 (defun tramp-parse-shostkeys (dirname)
2729 "Return a list of (user host) tuples allowed to access.
2730 User is always nil."
2731 (tramp-parse-shostkeys-sknownhosts
2732 dirname (concat "^key_[0-9]+_\\(" tramp-host-regexp "\\)\\.pub$")))
2734 ;;;###tramp-autoload
2735 (defun tramp-parse-sknownhosts (dirname)
2736 "Return a list of (user host) tuples allowed to access.
2737 User is always nil."
2738 (tramp-parse-shostkeys-sknownhosts
2740 (concat "^\\(" tramp-host-regexp "\\)\\.ssh-\\(dss\\|rsa\\)\\.pub$")))
2742 ;;;###tramp-autoload
2743 (defun tramp-parse-hosts (filename)
2744 "Return a list of (user host) tuples allowed to access.
2745 User is always nil."
2746 (tramp-parse-file filename 'tramp-parse-hosts-group))
2748 (defun tramp-parse-hosts-group ()
2749 "Return a (user host) tuple allowed to access.
2750 User is always nil."
2752 (concat "^\\(" tramp-ipv6-regexp "\\|" tramp-host-regexp "\\)") 1 " \t"))
2754 ;; For su-alike methods it would be desirable to return "root@localhost"
2755 ;; as default. Unfortunately, we have no information whether any user name
2756 ;; has been typed already. So we use `tramp-current-user' as indication,
2757 ;; assuming it is set in `tramp-completion-handle-file-name-all-completions'.
2758 ;;;###tramp-autoload
2759 (defun tramp-parse-passwd (filename)
2760 "Return a list of (user host) tuples allowed to access.
2761 Host is always \"localhost\"."
2762 (if (zerop (length tramp-current-user))
2764 (tramp-parse-file filename 'tramp-parse-passwd-group)))
2766 (defun tramp-parse-passwd-group ()
2767 "Return a (user host) tuple allowed to access.
2768 Host is always \"localhost\"."
2770 (regexp (concat "^\\(" tramp-user-regexp "\\):")))
2771 (when (re-search-forward regexp (point-at-eol) t)
2772 (setq result (list (match-string 1) "localhost")))
2776 ;;;###tramp-autoload
2777 (defun tramp-parse-netrc (filename)
2778 "Return a list of (user host) tuples allowed to access.
2780 (tramp-parse-file filename 'tramp-parse-netrc-group))
2782 (defun tramp-parse-netrc-group ()
2783 "Return a (user host) tuple allowed to access.
2788 "^[ \t]*machine[ \t]+" "\\(" tramp-host-regexp "\\)"
2789 "\\([ \t]+login[ \t]+" "\\(" tramp-user-regexp "\\)" "\\)?")))
2790 (when (re-search-forward regexp (point-at-eol) t)
2791 (setq result (list (match-string 3) (match-string 1))))
2795 ;;;###tramp-autoload
2796 (defun tramp-parse-putty (registry-or-dirname)
2797 "Return a list of (user host) tuples allowed to access.
2798 User is always nil."
2799 (if (memq system-type '(windows-nt))
2801 (when (zerop (tramp-call-process
2802 "reg" nil t nil "query" registry-or-dirname))
2803 (goto-char (point-min))
2804 (loop while (not (eobp)) collect
2805 (tramp-parse-putty-group registry-or-dirname))))
2807 (tramp-parse-shostkeys-sknownhosts
2808 registry-or-dirname (concat "^\\(" tramp-host-regexp "\\)$"))))
2810 (defun tramp-parse-putty-group (registry)
2811 "Return a (user host) tuple allowed to access.
2812 User is always nil."
2814 (regexp (concat (regexp-quote registry) "\\\\\\(.+\\)")))
2815 (when (re-search-forward regexp (point-at-eol) t)
2816 (setq result (list nil (match-string 1))))
2820 ;;; Common file name handler functions for different backends:
2822 (defvar tramp-handle-file-local-copy-hook nil
2823 "Normal hook to be run at the end of `tramp-*-handle-file-local-copy'.")
2825 (defvar tramp-handle-write-region-hook nil
2826 "Normal hook to be run at the end of `tramp-*-handle-write-region'.")
2828 (defun tramp-handle-directory-file-name (directory)
2829 "Like `directory-file-name' for Tramp files."
2830 ;; If localname component of filename is "/", leave it unchanged.
2831 ;; Otherwise, remove any trailing slash from localname component.
2832 ;; Method, host, etc, are unchanged. Does it make sense to try
2833 ;; to avoid parsing the filename?
2834 (with-parsed-tramp-file-name directory nil
2835 (if (and (not (zerop (length localname)))
2836 (eq (aref localname (1- (length localname))) ?/)
2837 (not (string= localname "/")))
2838 (substring directory 0 -1)
2841 (defun tramp-handle-directory-files
2842 (directory &optional full match nosort files-only)
2843 "Like `directory-files' for Tramp files."
2844 ;; FILES-ONLY is valid for XEmacs only.
2845 (when (file-directory-p directory)
2846 (setq directory (file-name-as-directory (expand-file-name directory)))
2847 (let ((temp (nreverse (file-name-all-completions "" directory)))
2851 (setq item (directory-file-name (pop temp)))
2852 (when (and (or (null match) (string-match match item))
2853 (or (null files-only)
2855 (and (equal files-only t) (file-regular-p item))
2856 ;; Directories only.
2857 (file-directory-p item)))
2858 (push (if full (concat directory item) item)
2860 (if nosort result (sort result 'string<)))))
2862 (defun tramp-handle-directory-files-and-attributes
2863 (directory &optional full match nosort id-format)
2864 "Like `directory-files-and-attributes' for Tramp files."
2867 (cons x (tramp-compat-file-attributes
2868 (if full x (expand-file-name x directory)) id-format)))
2869 (directory-files directory full match nosort)))
2871 (defun tramp-handle-dired-uncache (dir &optional dir-p)
2872 "Like `dired-uncache' for Tramp files."
2873 ;; DIR-P is valid for XEmacs only.
2874 (with-parsed-tramp-file-name
2875 (if (or dir-p (file-directory-p dir)) dir (file-name-directory dir)) nil
2876 (tramp-flush-directory-property v localname)))
2878 (defun tramp-handle-file-accessible-directory-p (filename)
2879 "Like `file-accessible-directory-p' for Tramp files."
2880 (and (file-directory-p filename)
2881 (file-executable-p filename)))
2883 (defun tramp-handle-file-exists-p (filename)
2884 "Like `file-exists-p' for Tramp files."
2885 (not (null (file-attributes filename))))
2887 (defun tramp-handle-file-modes (filename)
2888 "Like `file-modes' for Tramp files."
2889 (let ((truename (or (file-truename filename) filename)))
2890 (when (file-exists-p truename)
2891 (tramp-mode-string-to-int (nth 8 (file-attributes truename))))))
2893 ;; Localname manipulation functions that grok Tramp localnames...
2894 (defun tramp-handle-file-name-as-directory (file)
2895 "Like `file-name-as-directory' but aware of Tramp files."
2896 ;; `file-name-as-directory' would be sufficient except localname is
2897 ;; the empty string.
2898 (let ((v (tramp-dissect-file-name file t)))
2899 ;; Run the command on the localname portion only.
2900 (tramp-make-tramp-file-name
2901 (tramp-file-name-method v)
2902 (tramp-file-name-user v)
2903 (tramp-file-name-host v)
2904 (tramp-run-real-handler
2905 'file-name-as-directory (list (or (tramp-file-name-localname v) ""))))))
2907 (defun tramp-handle-file-name-completion
2908 (filename directory &optional predicate)
2909 "Like `file-name-completion' for Tramp files."
2910 (unless (tramp-tramp-file-p directory)
2912 "tramp-handle-file-name-completion invoked on non-tramp directory `%s'"
2916 (mapcar 'list (file-name-all-completions filename directory))
2918 (lambda (x) (funcall predicate (expand-file-name (car x) directory))))))
2920 (defun tramp-handle-file-name-directory (file)
2921 "Like `file-name-directory' but aware of Tramp files."
2922 ;; Everything except the last filename thing is the directory. We
2923 ;; cannot apply `with-parsed-tramp-file-name', because this expands
2924 ;; the remote file name parts. This is a problem when we are in
2925 ;; file name completion.
2926 (let ((v (tramp-dissect-file-name file t)))
2927 ;; Run the command on the localname portion only.
2928 (tramp-make-tramp-file-name
2929 (tramp-file-name-method v)
2930 (tramp-file-name-user v)
2931 (tramp-file-name-host v)
2932 (tramp-run-real-handler
2933 'file-name-directory (list (or (tramp-file-name-localname v) ""))))))
2935 (defun tramp-handle-file-name-nondirectory (file)
2936 "Like `file-name-nondirectory' but aware of Tramp files."
2937 (with-parsed-tramp-file-name file nil
2938 (tramp-run-real-handler 'file-name-nondirectory (list localname))))
2940 (defun tramp-handle-file-newer-than-file-p (file1 file2)
2941 "Like `file-newer-than-file-p' for Tramp files."
2943 ((not (file-exists-p file1)) nil)
2944 ((not (file-exists-p file2)) t)
2945 (t (tramp-time-less-p (nth 5 (file-attributes file2))
2946 (nth 5 (file-attributes file1))))))
2948 (defun tramp-handle-file-regular-p (filename)
2949 "Like `file-regular-p' for Tramp files."
2950 (and (file-exists-p filename)
2951 (eq ?- (aref (nth 8 (file-attributes filename)) 0))))
2953 (defun tramp-handle-file-remote-p (filename &optional identification connected)
2954 "Like `file-remote-p' for Tramp files."
2955 (let ((tramp-verbose 3))
2956 (when (tramp-tramp-file-p filename)
2957 (let* ((v (tramp-dissect-file-name filename))
2958 (p (tramp-get-connection-process v))
2959 (c (and p (processp p) (memq (process-status p) '(run open)))))
2960 ;; We expand the file name only, if there is already a connection.
2961 (with-parsed-tramp-file-name
2962 (if c (expand-file-name filename) filename) nil
2963 (and (or (not connected) c)
2965 ((eq identification 'method) method)
2966 ((eq identification 'user) user)
2967 ((eq identification 'host) host)
2968 ((eq identification 'localname) localname)
2969 (t (tramp-make-tramp-file-name method user host "")))))))))
2971 (defun tramp-handle-file-symlink-p (filename)
2972 "Like `file-symlink-p' for Tramp files."
2973 (with-parsed-tramp-file-name filename nil
2974 (let ((x (car (file-attributes filename))))
2976 ;; When Tramp is running on VMS, then `file-name-absolute-p'
2977 ;; might do weird things.
2978 (if (file-name-absolute-p x)
2979 (tramp-make-tramp-file-name method user host x)
2982 (defun tramp-handle-find-backup-file-name (filename)
2983 "Like `find-backup-file-name' for Tramp files."
2984 (with-parsed-tramp-file-name filename nil
2985 ;; We set both variables. It doesn't matter whether it is
2987 (let ((backup-directory-alist
2989 (when (boundp 'backup-directory-alist)
2990 (if (symbol-value 'tramp-backup-directory-alist)
2995 (if (and (stringp (cdr x))
2996 (file-name-absolute-p (cdr x))
2997 (not (tramp-file-name-p (cdr x))))
2998 (tramp-make-tramp-file-name method user host (cdr x))
3000 (symbol-value 'tramp-backup-directory-alist))
3001 (symbol-value 'backup-directory-alist))))
3003 (bkup-backup-directory-info
3005 (when (boundp 'bkup-backup-directory-info)
3006 (if (symbol-value 'tramp-bkup-backup-directory-info)
3012 (if (and (stringp (car (cdr x)))
3013 (file-name-absolute-p (car (cdr x)))
3014 (not (tramp-file-name-p (car (cdr x)))))
3015 (tramp-make-tramp-file-name
3016 method user host (car (cdr x)))
3019 (symbol-value 'tramp-bkup-backup-directory-info))
3020 (symbol-value 'bkup-backup-directory-info)))))
3022 (tramp-run-real-handler 'find-backup-file-name (list filename)))))
3024 (defun tramp-handle-insert-file-contents
3025 (filename &optional visit beg end replace)
3026 "Like `insert-file-contents' for Tramp files."
3027 (barf-if-buffer-read-only)
3028 (setq filename (expand-file-name filename))
3029 (let (result local-copy remote-copy)
3030 (with-parsed-tramp-file-name filename nil
3031 (with-tramp-progress-reporter
3032 v 3 (format "Inserting `%s'" filename)
3034 (if (not (file-exists-p filename))
3035 ;; We don't raise a Tramp error, because it might be
3036 ;; suppressed, like in `find-file-noselect-1'.
3038 (list "File not found on remote host" filename))
3040 (if (and (tramp-local-host-p v)
3041 (let (file-name-handler-alist)
3042 (file-readable-p localname)))
3043 ;; Short track: if we are on the local host, we can
3046 (tramp-run-real-handler
3047 'insert-file-contents
3048 (list localname visit beg end replace)))
3050 ;; When we shall insert only a part of the file, we
3053 (setq remote-copy (tramp-make-tramp-temp-file v))
3054 ;; This is defined in tramp-sh.el. Let's assume
3055 ;; this is loaded already.
3056 (tramp-compat-funcall
3061 (format "dd bs=1 skip=%d if=%s count=%d of=%s"
3062 beg (tramp-shell-quote-argument localname)
3063 (- end beg) remote-copy))
3065 (format "dd bs=1 skip=%d if=%s of=%s"
3066 beg (tramp-shell-quote-argument localname)
3069 (format "dd bs=1 count=%d if=%s of=%s"
3070 end (tramp-shell-quote-argument localname)
3073 ;; `insert-file-contents-literally' takes care to
3074 ;; avoid calling jka-compr. By let-binding
3075 ;; `inhibit-file-name-operation', we propagate that
3076 ;; care to the `file-local-copy' operation.
3078 (let ((inhibit-file-name-operation
3079 (when (eq inhibit-file-name-operation
3080 'insert-file-contents)
3083 ((stringp remote-copy)
3085 (tramp-make-tramp-file-name
3086 method user host remote-copy)))
3087 ((stringp tramp-temp-buffer-file-name)
3088 (copy-file filename tramp-temp-buffer-file-name 'ok)
3089 tramp-temp-buffer-file-name)
3090 (t (file-local-copy filename)))))
3092 ;; When the file is not readable for the owner, it
3093 ;; cannot be inserted, even if it is readable for the
3094 ;; group or for everybody.
3096 local-copy (tramp-compat-octal-to-decimal "0600"))
3098 (when (and (null remote-copy)
3099 (tramp-get-method-parameter
3100 method 'tramp-copy-keep-tmpfile))
3101 ;; We keep the local file for performance reasons,
3102 ;; useful for "rsync".
3103 (setq tramp-temp-buffer-file-name local-copy))
3105 ;; We must ensure that `file-coding-system-alist'
3106 ;; matches `local-copy'. We must also use `visit',
3107 ;; otherwise there might be an error in the
3108 ;; `revert-buffer' function under XEmacs.
3109 (let ((file-coding-system-alist
3110 (tramp-find-file-name-coding-system-alist
3111 filename local-copy)))
3113 (insert-file-contents
3114 local-copy visit nil nil replace)))))
3119 (setq buffer-file-name filename)
3120 (setq buffer-read-only (not (file-writable-p filename)))
3121 (set-visited-file-modtime)
3122 (set-buffer-modified-p nil))
3123 (when (and (stringp local-copy)
3124 (or remote-copy (null tramp-temp-buffer-file-name)))
3125 (delete-file local-copy))
3126 (when (stringp remote-copy)
3128 (tramp-make-tramp-file-name method user host remote-copy)))))))
3131 (list (expand-file-name filename)
3134 (defun tramp-handle-load (file &optional noerror nomessage nosuffix must-suffix)
3135 "Like `load' for Tramp files."
3136 (with-parsed-tramp-file-name (expand-file-name file) nil
3138 (cond ((file-exists-p (concat file ".elc"))
3139 (setq file (concat file ".elc")))
3140 ((file-exists-p (concat file ".el"))
3141 (setq file (concat file ".el")))))
3143 ;; The first condition is always true for absolute file names.
3144 ;; Included for safety's sake.
3145 (unless (or (file-name-directory file)
3146 (string-match "\\.elc?\\'" file))
3149 "File `%s' does not include a `.el' or `.elc' suffix" file)))
3151 (when (not (file-exists-p file))
3152 (tramp-error v 'file-error "Cannot load nonexistent file `%s'" file)))
3153 (if (not (file-exists-p file))
3155 (let ((tramp-message-show-message (not nomessage)))
3156 (with-tramp-progress-reporter v 0 (format "Loading %s" file)
3157 (let ((local-copy (file-local-copy file)))
3158 ;; MUST-SUFFIX doesn't exist on XEmacs, so let it default to nil.
3160 (load local-copy noerror t t)
3161 (delete-file local-copy)))))
3164 (defun tramp-handle-shell-command
3165 (command &optional output-buffer error-buffer)
3166 "Like `shell-command' for Tramp files."
3167 (let* ((asynchronous (string-match "[ \t]*&[ \t]*\\'" command))
3168 ;; We cannot use `shell-file-name' and `shell-command-switch',
3169 ;; they are variables of the local host.
3172 (tramp-get-method-parameter
3173 (tramp-file-name-method
3174 (tramp-dissect-file-name default-directory))
3175 'tramp-remote-shell)
3176 (tramp-get-method-parameter
3177 (tramp-file-name-method
3178 (tramp-dissect-file-name default-directory))
3179 'tramp-remote-shell-args))
3180 (list (substring command 0 asynchronous))))
3184 ((bufferp output-buffer) output-buffer)
3185 ((stringp output-buffer) (get-buffer-create output-buffer))
3187 (setq current-buffer-p t)
3189 (t (get-buffer-create
3191 "*Async Shell Command*"
3192 "*Shell Command Output*")))))
3195 ((bufferp error-buffer) error-buffer)
3196 ((stringp error-buffer) (get-buffer-create error-buffer))))
3198 (if (and (not asynchronous) error-buffer)
3199 (with-parsed-tramp-file-name default-directory nil
3200 (list output-buffer (tramp-make-tramp-temp-file v)))
3202 (p (get-buffer-process output-buffer)))
3204 ;; Check whether there is another process running. Tramp does not
3205 ;; support 2 (asynchronous) processes in parallel.
3207 (if (yes-or-no-p "A command is running. Kill it? ")
3208 (ignore-errors (kill-process p))
3209 (tramp-compat-user-error "Shell command in progress")))
3211 (if current-buffer-p
3213 (barf-if-buffer-read-only)
3215 (with-current-buffer output-buffer
3216 (setq buffer-read-only nil)
3219 (if (and (not current-buffer-p) (integerp asynchronous))
3222 (setq p (apply 'start-file-process "*Async Shell*" buffer args))
3224 (pop-to-buffer output-buffer)
3225 (setq mode-line-process '(":%s"))
3227 (set-process-sentinel p 'shell-command-sentinel)
3228 (set-process-filter p 'comint-output-filter))
3232 (apply 'process-file (car args) nil buffer nil (cdr args))
3233 ;; Insert error messages if they were separated.
3234 (when (listp buffer)
3235 (with-current-buffer error-buffer
3236 (insert-file-contents (cadr buffer)))
3237 (delete-file (cadr buffer)))
3238 (if current-buffer-p
3239 ;; This is like exchange-point-and-mark, but doesn't
3240 ;; activate the mark. It is cleaner to avoid activation,
3241 ;; even though the command loop would deactivate the mark
3242 ;; because we inserted text.
3243 (goto-char (prog1 (mark t)
3244 (set-marker (mark-marker) (point)
3246 ;; There's some output, display it.
3247 (when (with-current-buffer output-buffer (> (point-max) (point-min)))
3248 (if (functionp 'display-message-or-buffer)
3249 (tramp-compat-funcall 'display-message-or-buffer output-buffer)
3250 (pop-to-buffer output-buffer))))))))
3252 (defun tramp-handle-substitute-in-file-name (filename)
3253 "Like `substitute-in-file-name' for Tramp files.
3254 \"//\" and \"/~\" substitute only in the local filename part.
3255 If the URL Tramp syntax is chosen, \"//\" as method delimiter and \"/~\" at
3256 beginning of local filename are not substituted."
3257 ;; First, we must replace environment variables.
3258 (setq filename (tramp-replace-environment-variables filename))
3259 (with-parsed-tramp-file-name filename nil
3260 (if (equal tramp-syntax 'url)
3261 ;; We need to check localname only. The other parts cannot contain
3263 (if (and (> (length localname) 1)
3264 (or (string-match "//" localname)
3265 (string-match "/~" localname 1)))
3266 (tramp-run-real-handler 'substitute-in-file-name (list filename))
3267 (tramp-make-tramp-file-name
3268 (when method (substitute-in-file-name method))
3269 (when user (substitute-in-file-name user))
3270 (when host (substitute-in-file-name host))
3272 (tramp-run-real-handler
3273 'substitute-in-file-name (list localname)))))
3274 ;; Ignore in LOCALNAME everything before "//" or "/~".
3275 (when (and (stringp localname) (string-match ".+?/\\(/\\|~\\)" localname))
3277 (concat (file-remote-p filename)
3278 (replace-match "\\1" nil nil localname)))
3279 ;; "/m:h:~" does not work for completion. We use "/m:h:~/".
3280 (when (string-match "~$" filename)
3281 (setq filename (concat filename "/"))))
3282 (tramp-run-real-handler 'substitute-in-file-name (list filename)))))
3284 (defun tramp-handle-unhandled-file-name-directory (filename)
3285 "Like `unhandled-file-name-directory' for Tramp files."
3286 ;; With Emacs 23, we could simply return `nil'. But we must keep it
3287 ;; for backward compatibility.
3288 (expand-file-name "~/"))
3290 (defun tramp-handle-set-visited-file-modtime (&optional time-list)
3291 "Like `set-visited-file-modtime' for Tramp files."
3292 (unless (buffer-file-name)
3293 (error "Can't set-visited-file-modtime: buffer `%s' not visiting a file"
3296 (let ((remote-file-name-inhibit-cache t))
3297 ;; '(-1 65535) means file doesn't exists yet.
3299 (or (nth 5 (file-attributes (buffer-file-name))) '(-1 65535)))))
3300 ;; We use '(0 0) as a don't-know value.
3301 (unless (equal time-list '(0 0))
3302 (tramp-run-real-handler 'set-visited-file-modtime (list time-list))))
3304 (defun tramp-handle-verify-visited-file-modtime (&optional buf)
3305 "Like `verify-visited-file-modtime' for Tramp files.
3306 At the time `verify-visited-file-modtime' calls this function, we
3307 already know that the buffer is visiting a file and that
3308 `visited-file-modtime' does not return 0. Do not call this
3309 function directly, unless those two cases are already taken care
3311 (with-current-buffer (or buf (current-buffer))
3312 (let ((f (buffer-file-name)))
3313 ;; There is no file visiting the buffer, or the buffer has no
3314 ;; recorded last modification time, or there is no established
3317 (eq (visited-file-modtime) 0)
3318 (not (tramp-file-name-handler 'file-remote-p f nil 'connected)))
3320 (with-parsed-tramp-file-name f nil
3321 (let* ((remote-file-name-inhibit-cache t)
3322 (attr (file-attributes f))
3323 (modtime (nth 5 attr))
3324 (mt (visited-file-modtime)))
3327 ;; File exists, and has a known modtime.
3328 ((and attr (not (equal modtime '(0 0))))
3329 (< (abs (tramp-time-diff
3331 ;; For compatibility, deal with both the old
3332 ;; (HIGH . LOW) and the new (HIGH LOW) return
3333 ;; values of `visited-file-modtime'.
3335 (list (car mt) (cdr mt))
3338 ;; Modtime has the don't know value.
3340 ;; If file does not exist, say it is not modified if and
3341 ;; only if that agrees with the buffer's record.
3342 (t (equal mt '(-1 65535))))))))))
3344 (defun tramp-handle-file-notify-add-watch (filename flags callback)
3345 "Like `file-notify-add-watch' for Tramp files."
3346 ;; This is the default handler. tramp-gvfs.el and tramp-sh.el have
3348 (setq filename (expand-file-name filename))
3349 (with-parsed-tramp-file-name filename nil
3351 v 'file-notify-error "File notification not supported for `%s'" filename)))
3353 (defvar file-notify-descriptors)
3354 (defun tramp-handle-file-notify-rm-watch (proc)
3355 "Like `file-notify-rm-watch' for Tramp files."
3356 ;; The descriptor must be a process object.
3357 (unless (and (processp proc) (gethash proc file-notify-descriptors))
3358 (tramp-error proc 'file-notify-error "Not a valid descriptor %S" proc))
3359 (tramp-message proc 6 "Kill %S" proc)
3360 (kill-process proc))
3362 ;;; Functions for establishing connection:
3364 ;; The following functions are actions to be taken when seeing certain
3365 ;; prompts from the remote host. See the variable
3366 ;; `tramp-actions-before-shell' for usage of these functions.
3368 (defun tramp-action-login (proc vec)
3369 "Send the login name."
3370 (when (not (stringp tramp-current-user))
3371 (setq tramp-current-user
3372 (with-tramp-connection-property vec "login-as"
3373 (save-window-excursion
3374 (let ((enable-recursive-minibuffers t))
3375 (pop-to-buffer (tramp-get-connection-buffer vec))
3376 (read-string (match-string 0)))))))
3377 (with-current-buffer (tramp-get-connection-buffer vec)
3378 (tramp-message vec 6 "\n%s" (buffer-string)))
3379 (tramp-message vec 3 "Sending login name `%s'" tramp-current-user)
3380 (tramp-send-string vec (concat tramp-current-user tramp-local-end-of-line)))
3382 (defun tramp-action-password (proc vec)
3383 "Query the user for a password."
3384 (with-current-buffer (process-buffer proc)
3385 (let ((enable-recursive-minibuffers t))
3386 (tramp-check-for-regexp proc tramp-password-prompt-regexp)
3387 (tramp-message vec 3 "Sending %s" (match-string 1))
3388 ;; We don't call `tramp-send-string' in order to hide the
3389 ;; password from the debug buffer.
3390 (process-send-string
3391 proc (concat (tramp-read-passwd proc) tramp-local-end-of-line))
3392 ;; Hide password prompt.
3393 (narrow-to-region (point-max) (point-max)))))
3395 (defun tramp-action-succeed (proc vec)
3396 "Signal success in finding shell prompt."
3397 (throw 'tramp-action 'ok))
3399 (defun tramp-action-permission-denied (proc vec)
3400 "Signal permission denied."
3402 (throw 'tramp-action 'permission-denied))
3404 (defun tramp-action-yesno (proc vec)
3405 "Ask the user for confirmation using `yes-or-no-p'.
3406 Send \"yes\" to remote process on confirmation, abort otherwise.
3407 See also `tramp-action-yn'."
3408 (save-window-excursion
3409 (let ((enable-recursive-minibuffers t))
3410 (save-match-data (pop-to-buffer (tramp-get-connection-buffer vec)))
3411 (unless (yes-or-no-p (match-string 0))
3413 (throw 'tramp-action 'permission-denied))
3414 (with-current-buffer (tramp-get-connection-buffer vec)
3415 (tramp-message vec 6 "\n%s" (buffer-string)))
3416 (tramp-send-string vec (concat "yes" tramp-local-end-of-line)))))
3418 (defun tramp-action-yn (proc vec)
3419 "Ask the user for confirmation using `y-or-n-p'.
3420 Send \"y\" to remote process on confirmation, abort otherwise.
3421 See also `tramp-action-yesno'."
3422 (save-window-excursion
3423 (let ((enable-recursive-minibuffers t))
3424 (save-match-data (pop-to-buffer (tramp-get-connection-buffer vec)))
3425 (unless (y-or-n-p (match-string 0))
3427 (throw 'tramp-action 'permission-denied))
3428 (with-current-buffer (tramp-get-connection-buffer vec)
3429 (tramp-message vec 6 "\n%s" (buffer-string)))
3430 (tramp-send-string vec (concat "y" tramp-local-end-of-line)))))
3432 (defun tramp-action-terminal (proc vec)
3433 "Tell the remote host which terminal type to use.
3434 The terminal type can be configured with `tramp-terminal-type'."
3435 (tramp-message vec 5 "Setting `%s' as terminal type." tramp-terminal-type)
3436 (with-current-buffer (tramp-get-connection-buffer vec)
3437 (tramp-message vec 6 "\n%s" (buffer-string)))
3438 (tramp-send-string vec (concat tramp-terminal-type tramp-local-end-of-line)))
3440 (defun tramp-action-process-alive (proc vec)
3441 "Check, whether a process has finished."
3442 (unless (memq (process-status proc) '(run open))
3443 (throw 'tramp-action 'process-died)))
3445 (defun tramp-action-out-of-band (proc vec)
3446 "Check, whether an out-of-band copy has finished."
3447 (cond ((and (memq (process-status proc) '(stop exit))
3448 (zerop (process-exit-status proc)))
3449 (tramp-message vec 3 "Process has finished.")
3450 (throw 'tramp-action 'ok))
3451 ((or (and (memq (process-status proc) '(stop exit))
3452 (not (zerop (process-exit-status proc))))
3453 (memq (process-status proc) '(signal)))
3454 ;; `scp' could have copied correctly, but set modes could have failed.
3455 ;; This can be ignored.
3456 (with-current-buffer (process-buffer proc)
3457 (goto-char (point-min))
3458 (if (re-search-forward tramp-operation-not-permitted-regexp nil t)
3460 (tramp-message vec 5 "'set mode' error ignored.")
3461 (tramp-message vec 3 "Process has finished.")
3462 (throw 'tramp-action 'ok))
3463 (tramp-message vec 3 "Process has died.")
3464 (throw 'tramp-action 'process-died))))
3467 ;;; Functions for processing the actions:
3469 (defun tramp-process-one-action (proc vec actions)
3470 "Wait for output from the shell and perform one action."
3471 (let (found todo item pattern action)
3473 ;; Reread output once all actions have been performed.
3474 ;; Obviously, the output was not complete.
3475 (tramp-accept-process-output proc 1)
3478 (setq item (pop todo))
3479 (setq pattern (format "\\(%s\\)\\'" (symbol-value (nth 0 item))))
3480 (setq action (nth 1 item))
3482 vec 5 "Looking for regexp \"%s\" from remote shell" pattern)
3483 (when (tramp-check-for-regexp proc pattern)
3484 (tramp-message vec 5 "Call `%s'" (symbol-name action))
3485 (setq found (funcall action proc vec)))))
3488 (defun tramp-process-actions (proc vec pos actions &optional timeout)
3489 "Perform ACTIONS until success or TIMEOUT.
3490 PROC and VEC indicate the remote connection to be used. POS, if
3491 set, is the starting point of the region to be deleted in the
3493 ;; Enable `auth-source' and `password-cache'. We must use
3494 ;; tramp-current-* variables in case we have several hops.
3495 (tramp-set-connection-property
3496 (tramp-dissect-file-name
3497 (tramp-make-tramp-file-name
3498 tramp-current-method tramp-current-user tramp-current-host ""))
3499 "first-password-request" t)
3501 (with-tramp-progress-reporter
3502 proc 3 "Waiting for prompts from remote shell"
3505 (with-timeout (timeout (setq exit 'timeout))
3508 (catch 'tramp-action
3509 (tramp-process-one-action proc vec actions)))))
3512 (catch 'tramp-action
3513 (tramp-process-one-action proc vec actions)))))
3514 (with-current-buffer (tramp-get-connection-buffer vec)
3516 (tramp-message vec 6 "\n%s" (buffer-string)))
3517 (unless (eq exit 'ok)
3518 (tramp-clear-passwd vec)
3519 (delete-process proc)
3520 (tramp-error-with-buffer
3521 (tramp-get-connection-buffer vec) vec 'file-error
3523 ((eq exit 'permission-denied) "Permission denied")
3524 ((eq exit 'process-died)
3526 "Tramp failed to connect. If this happens repeatedly, try\n"
3527 " `M-x tramp-cleanup-this-connection'"))
3530 "Timeout reached, see buffer `%s' for details"
3531 (tramp-get-connection-buffer vec)))
3532 (t "Login failed")))))
3534 (with-current-buffer (tramp-get-connection-buffer vec)
3535 (let (buffer-read-only) (delete-region pos (point))))))))
3537 :;; Utility functions:
3539 (defun tramp-accept-process-output (&optional proc timeout timeout-msecs)
3540 "Like `accept-process-output' for Tramp processes.
3541 This is needed in order to hide `last-coding-system-used', which is set
3542 for process communication also."
3543 (with-current-buffer (process-buffer proc)
3544 (tramp-message proc 10 "%s %s" proc (process-status proc))
3545 (let (buffer-read-only last-coding-system-used)
3546 ;; Under Windows XP, accept-process-output doesn't return
3547 ;; sometimes. So we add an additional timeout.
3548 (with-timeout ((or timeout 1))
3549 (if (featurep 'xemacs)
3550 (accept-process-output proc timeout timeout-msecs)
3551 (accept-process-output proc timeout timeout-msecs (and proc t)))))
3552 (tramp-message proc 10 "\n%s" (buffer-string))))
3554 (defun tramp-check-for-regexp (proc regexp)
3555 "Check, whether REGEXP is contained in process buffer of PROC.
3556 Erase echoed commands if exists."
3557 (with-current-buffer (process-buffer proc)
3558 (goto-char (point-min))
3560 ;; Check whether we need to remove echo output.
3561 (when (and (tramp-get-connection-property proc "check-remote-echo" nil)
3562 (re-search-forward tramp-echoed-echo-mark-regexp nil t))
3563 (let ((begin (match-beginning 0)))
3564 (when (re-search-forward tramp-echoed-echo-mark-regexp nil t)
3565 ;; Discard echo from remote output.
3566 (tramp-set-connection-property proc "check-remote-echo" nil)
3567 (tramp-message proc 5 "echo-mark found")
3569 (delete-region begin (point))
3570 (goto-char (point-min)))))
3572 (when (or (not (tramp-get-connection-property proc "check-remote-echo" nil))
3573 ;; Sometimes, the echo string is suppressed on the remote side.
3575 (tramp-compat-funcall
3576 'substring-no-properties tramp-echo-mark-marker
3577 0 (min tramp-echo-mark-marker-length (1- (point-max))))
3578 (tramp-compat-funcall
3579 'buffer-substring-no-properties
3581 (min (+ (point-min) tramp-echo-mark-marker-length)
3583 ;; No echo to be handled, now we can look for the regexp.
3584 ;; Sometimes, lines are much to long, and we run into a "Stack
3585 ;; overflow in regexp matcher". For example, //DIRED// lines of
3586 ;; directory listings with some thousand files. Therefore, we
3587 ;; look from the end.
3588 (goto-char (point-max))
3589 (ignore-errors (re-search-backward regexp nil t)))))
3591 (defun tramp-wait-for-regexp (proc timeout regexp)
3592 "Wait for a REGEXP to appear from process PROC within TIMEOUT seconds.
3593 Expects the output of PROC to be sent to the current buffer. Returns
3594 the string that matched, or nil. Waits indefinitely if TIMEOUT is
3596 (with-current-buffer (process-buffer proc)
3597 (let ((found (tramp-check-for-regexp proc regexp))
3598 (start-time (current-time)))
3600 ;; Work around a bug in XEmacs 21, where the timeout
3601 ;; expires faster than it should. This degenerates
3602 ;; to polling for buggy XEmacsen, but oh, well.
3603 (while (and (not found)
3604 (< (tramp-time-diff (current-time) start-time)
3606 (with-timeout (timeout)
3608 (tramp-accept-process-output proc 1)
3609 (unless (memq (process-status proc) '(run open))
3610 (tramp-error-with-buffer
3611 nil proc 'file-error "Process has died"))
3612 (setq found (tramp-check-for-regexp proc regexp))))))
3615 (tramp-accept-process-output proc 1)
3616 (unless (memq (process-status proc) '(run open))
3617 (tramp-error-with-buffer
3618 nil proc 'file-error "Process has died"))
3619 (setq found (tramp-check-for-regexp proc regexp)))))
3620 (tramp-message proc 6 "\n%s" (buffer-string))
3624 proc 'file-error "[[Regexp `%s' not found in %d secs]]"
3626 (tramp-error proc 'file-error "[[Regexp `%s' not found]]" regexp)))
3629 ;; It seems that Tru64 Unix does not like it if long strings are sent
3630 ;; to it in one go. (This happens when sending the Perl
3631 ;; `file-attributes' implementation, for instance.) Therefore, we
3632 ;; have this function which sends the string in chunks.
3633 (defun tramp-send-string (vec string)
3634 "Send the STRING via connection VEC.
3636 The STRING is expected to use Unix line-endings, but the lines sent to
3637 the remote host use line-endings as defined in the variable
3638 `tramp-rsh-end-of-line'. The communication buffer is erased before sending."
3639 (let* ((p (tramp-get-connection-process vec))
3640 (chunksize (tramp-get-connection-property p "chunksize" nil)))
3643 vec 'file-error "Can't send string to remote host -- not logged in"))
3644 (tramp-set-connection-property p "last-cmd-time" (current-time))
3645 (tramp-message vec 10 "%s" string)
3646 (with-current-buffer (tramp-get-connection-buffer vec)
3647 ;; Clean up the buffer. We cannot call `erase-buffer' because
3648 ;; narrowing might be in effect.
3649 (let (buffer-read-only) (delete-region (point-min) (point-max)))
3650 ;; Replace "\n" by `tramp-rsh-end-of-line'.
3652 (mapconcat 'identity
3653 (tramp-compat-split-string string "\n")
3654 tramp-rsh-end-of-line))
3655 (unless (or (string= string "")
3656 (string-equal (substring string -1) tramp-rsh-end-of-line))
3657 (setq string (concat string tramp-rsh-end-of-line)))
3659 (if (and chunksize (not (zerop chunksize)))
3661 (end (length string)))
3664 vec 10 "Sending chunk from %s to %s"
3665 pos (min (+ pos chunksize) end))
3666 (process-send-string
3667 p (substring string pos (min (+ pos chunksize) end)))
3668 (setq pos (+ pos chunksize))))
3669 (process-send-string p string)))))
3671 (defun tramp-get-inode (vec)
3672 "Returns the virtual inode number.
3673 If it doesn't exist, generate a new one."
3674 (with-tramp-file-property vec (tramp-file-name-localname vec) "inode"
3675 (setq tramp-inodes (1+ tramp-inodes))))
3677 (defun tramp-get-device (vec)
3678 "Returns the virtual device number.
3679 If it doesn't exist, generate a new one."
3680 (with-tramp-connection-property (tramp-get-connection-process vec) "device"
3681 (cons -1 (setq tramp-devices (1+ tramp-devices)))))
3683 (defun tramp-equal-remote (file1 file2)
3684 "Check, whether the remote parts of FILE1 and FILE2 are identical.
3685 The check depends on method, user and host name of the files. If
3686 one of the components is missing, the default values are used.
3687 The local file name parts of FILE1 and FILE2 are not taken into
3692 (tramp-equal-remote \"/ssh::/etc\" \"/<your host name>:/home\")
3694 would yield `t'. On the other hand, the following check results in nil:
3696 (tramp-equal-remote \"/sudo::/etc\" \"/su::/etc\")"
3697 (and (stringp (file-remote-p file1))
3698 (stringp (file-remote-p file2))
3699 (string-equal (file-remote-p file1) (file-remote-p file2))))
3701 ;;;###tramp-autoload
3702 (defun tramp-mode-string-to-int (mode-string)
3703 "Converts a ten-letter `drwxrwxrwx'-style mode string into mode bits."
3704 (let* (case-fold-search
3705 (mode-chars (string-to-vector mode-string))
3706 (owner-read (aref mode-chars 1))
3707 (owner-write (aref mode-chars 2))
3708 (owner-execute-or-setid (aref mode-chars 3))
3709 (group-read (aref mode-chars 4))
3710 (group-write (aref mode-chars 5))
3711 (group-execute-or-setid (aref mode-chars 6))
3712 (other-read (aref mode-chars 7))
3713 (other-write (aref mode-chars 8))
3714 (other-execute-or-sticky (aref mode-chars 9)))
3718 ((char-equal owner-read ?r) (tramp-compat-octal-to-decimal "00400"))
3719 ((char-equal owner-read ?-) 0)
3720 (t (error "Second char `%c' must be one of `r-'" owner-read)))
3722 ((char-equal owner-write ?w) (tramp-compat-octal-to-decimal "00200"))
3723 ((char-equal owner-write ?-) 0)
3724 (t (error "Third char `%c' must be one of `w-'" owner-write)))
3726 ((char-equal owner-execute-or-setid ?x)
3727 (tramp-compat-octal-to-decimal "00100"))
3728 ((char-equal owner-execute-or-setid ?S)
3729 (tramp-compat-octal-to-decimal "04000"))
3730 ((char-equal owner-execute-or-setid ?s)
3731 (tramp-compat-octal-to-decimal "04100"))
3732 ((char-equal owner-execute-or-setid ?-) 0)
3733 (t (error "Fourth char `%c' must be one of `xsS-'"
3734 owner-execute-or-setid)))
3736 ((char-equal group-read ?r) (tramp-compat-octal-to-decimal "00040"))
3737 ((char-equal group-read ?-) 0)
3738 (t (error "Fifth char `%c' must be one of `r-'" group-read)))
3740 ((char-equal group-write ?w) (tramp-compat-octal-to-decimal "00020"))
3741 ((char-equal group-write ?-) 0)
3742 (t (error "Sixth char `%c' must be one of `w-'" group-write)))
3744 ((char-equal group-execute-or-setid ?x)
3745 (tramp-compat-octal-to-decimal "00010"))
3746 ((char-equal group-execute-or-setid ?S)
3747 (tramp-compat-octal-to-decimal "02000"))
3748 ((char-equal group-execute-or-setid ?s)
3749 (tramp-compat-octal-to-decimal "02010"))
3750 ((char-equal group-execute-or-setid ?-) 0)
3751 (t (error "Seventh char `%c' must be one of `xsS-'"
3752 group-execute-or-setid)))
3754 ((char-equal other-read ?r)
3755 (tramp-compat-octal-to-decimal "00004"))
3756 ((char-equal other-read ?-) 0)
3757 (t (error "Eighth char `%c' must be one of `r-'" other-read)))
3759 ((char-equal other-write ?w) (tramp-compat-octal-to-decimal "00002"))
3760 ((char-equal other-write ?-) 0)
3761 (t (error "Ninth char `%c' must be one of `w-'" other-write)))
3763 ((char-equal other-execute-or-sticky ?x)
3764 (tramp-compat-octal-to-decimal "00001"))
3765 ((char-equal other-execute-or-sticky ?T)
3766 (tramp-compat-octal-to-decimal "01000"))
3767 ((char-equal other-execute-or-sticky ?t)
3768 (tramp-compat-octal-to-decimal "01001"))
3769 ((char-equal other-execute-or-sticky ?-) 0)
3770 (t (error "Tenth char `%c' must be one of `xtT-'"
3771 other-execute-or-sticky)))))))
3773 (defconst tramp-file-mode-type-map
3774 '((0 . "-") ; Normal file (SVID-v2 and XPG2)
3776 (2 . "c") ; character device
3777 (3 . "m") ; multiplexed character device (v7)
3778 (4 . "d") ; directory
3779 (5 . "?") ; Named special file (XENIX)
3780 (6 . "b") ; block device
3781 (7 . "?") ; multiplexed block device (v7)
3782 (8 . "-") ; regular file
3783 (9 . "n") ; network special file (HP-UX)
3784 (10 . "l") ; symlink
3785 (11 . "?") ; ACL shadow inode (Solaris, not userspace)
3787 (13 . "D") ; door special (Solaris)
3788 (14 . "w")) ; whiteout (BSD)
3789 "A list of file types returned from the `stat' system call.
3790 This is used to map a mode number to a permission string.")
3792 ;;;###tramp-autoload
3793 (defun tramp-file-mode-from-int (mode)
3794 "Turn an integer representing a file mode into an ls(1)-like string."
3796 (assoc (logand (lsh mode -12) 15) tramp-file-mode-type-map)))
3797 (user (logand (lsh mode -6) 7))
3798 (group (logand (lsh mode -3) 7))
3799 (other (logand (lsh mode -0) 7))
3800 (suid (> (logand (lsh mode -9) 4) 0))
3801 (sgid (> (logand (lsh mode -9) 2) 0))
3802 (sticky (> (logand (lsh mode -9) 1) 0)))
3803 (setq user (tramp-file-mode-permissions user suid "s"))
3804 (setq group (tramp-file-mode-permissions group sgid "s"))
3805 (setq other (tramp-file-mode-permissions other sticky "t"))
3806 (concat type user group other)))
3808 (defun tramp-file-mode-permissions (perm suid suid-text)
3809 "Convert a permission bitset into a string.
3810 This is used internally by `tramp-file-mode-from-int'."
3811 (let ((r (> (logand perm 4) 0))
3812 (w (> (logand perm 2) 0))
3813 (x (> (logand perm 1) 0)))
3814 (concat (or (and r "r") "-")
3815 (or (and w "w") "-")
3816 (or (and suid x suid-text) ; suid, execute
3817 (and suid (upcase suid-text)) ; suid, !execute
3818 (and x "x") "-")))) ; !suid
3820 ;;;###tramp-autoload
3821 (defun tramp-get-local-uid (id-format)
3822 (if (equal id-format 'integer) (user-uid) (user-login-name)))
3824 ;;;###tramp-autoload
3825 (defun tramp-get-local-gid (id-format)
3826 (if (and (fboundp 'group-gid) (equal id-format 'integer))
3827 (tramp-compat-funcall 'group-gid)
3828 (nth 3 (tramp-compat-file-attributes "~/" id-format))))
3830 ;;;###tramp-autoload
3831 (defun tramp-check-cached-permissions (vec access)
3832 "Check `file-attributes' caches for VEC.
3833 Return t if according to the cache access type ACCESS is known to
3839 ((eq ?x access) 3))))
3840 (dolist (suffix '("string" "integer") result)
3846 (tramp-get-file-property
3847 vec (tramp-file-name-localname vec)
3848 (concat "file-attributes-" suffix) nil))
3850 (tramp-get-connection-property
3851 vec (concat "uid-" suffix) nil))
3853 (tramp-get-connection-property
3854 vec (concat "gid-" suffix) nil)))
3859 (eq t (car file-attr))
3860 (null (car file-attr)))
3862 ;; World accessible.
3863 (eq access (aref (nth 8 file-attr) (+ offset 6)))
3864 ;; User accessible and owned by user.
3866 (eq access (aref (nth 8 file-attr) offset))
3867 (equal remote-uid (nth 2 file-attr)))
3868 ;; Group accessible and owned by user's
3871 (eq access (aref (nth 8 file-attr) (+ offset 3)))
3872 (equal remote-gid (nth 3 file-attr)))))))))))
3874 ;;;###tramp-autoload
3875 (defun tramp-local-host-p (vec)
3876 "Return t if this points to the local host, nil otherwise."
3877 ;; We cannot use `tramp-file-name-real-host'. A port is an
3878 ;; indication for an ssh tunnel or alike.
3879 (let ((host (tramp-file-name-host vec)))
3882 (string-match tramp-local-host-regexp host)
3883 ;; The method shall be applied to one of the shell file name
3884 ;; handler. `tramp-local-host-p' is also called for "smb" and
3885 ;; alike, where it must fail.
3886 (tramp-get-method-parameter
3887 (tramp-file-name-method vec) 'tramp-login-program)
3888 ;; The local temp directory must be writable for the other user.
3890 (tramp-make-tramp-file-name
3891 (tramp-file-name-method vec)
3892 (tramp-file-name-user vec)
3894 (tramp-compat-temporary-file-directory)))
3895 ;; On some systems, chown runs only for root.
3896 (or (zerop (user-uid))
3897 ;; This is defined in tramp-sh.el. Let's assume this is
3899 (zerop (tramp-compat-funcall 'tramp-get-remote-uid vec 'integer))))))
3901 (defun tramp-get-remote-tmpdir (vec)
3902 "Return directory for temporary files on the remote host identified by VEC."
3903 (with-tramp-connection-property vec "tmpdir"
3904 (let ((dir (tramp-make-tramp-file-name
3905 (tramp-file-name-method vec)
3906 (tramp-file-name-user vec)
3907 (tramp-file-name-host vec)
3909 (tramp-get-method-parameter
3910 (tramp-file-name-method vec) 'tramp-tmpdir)
3912 (if (and (file-directory-p dir) (file-writable-p dir))
3914 (tramp-error vec 'file-error "Directory %s not accessible" dir)))))
3916 ;;;###tramp-autoload
3917 (defun tramp-make-tramp-temp-file (vec)
3918 "Create a temporary file on the remote host identified by VEC.
3919 Return the local name of the temporary file."
3920 (let ((prefix (expand-file-name
3921 tramp-temp-name-prefix (tramp-get-remote-tmpdir vec)))
3924 ;; `make-temp-file' would be the natural choice for
3925 ;; implementation. But it calls `write-region' internally,
3926 ;; which also needs a temporary file - we would end in an
3928 (setq result (make-temp-name prefix))
3929 (if (file-exists-p result)
3931 ;; This creates the file by side effect.
3932 (set-file-times result)
3933 (set-file-modes result (tramp-compat-octal-to-decimal "0700"))))
3935 ;; Return the local part.
3936 (with-parsed-tramp-file-name result nil localname)))
3938 (defun tramp-delete-temp-file-function ()
3939 "Remove temporary files related to current buffer."
3940 (when (stringp tramp-temp-buffer-file-name)
3941 (ignore-errors (delete-file tramp-temp-buffer-file-name))))
3943 (add-hook 'kill-buffer-hook 'tramp-delete-temp-file-function)
3944 (add-hook 'tramp-unload-hook
3946 (remove-hook 'kill-buffer-hook
3947 'tramp-delete-temp-file-function)))
3949 ;;; Auto saving to a special directory:
3951 (unless (tramp-exists-file-name-handler 'make-auto-save-file-name)
3952 (defadvice make-auto-save-file-name
3953 (around tramp-advice-make-auto-save-file-name () activate)
3954 "Invoke `tramp-*-handle-make-auto-save-file-name' for Tramp files."
3955 (if (tramp-tramp-file-p (buffer-file-name))
3956 ;; We cannot call `tramp-handle-make-auto-save-file-name'
3957 ;; directly, because this would bypass the locking mechanism.
3958 (setq ad-return-value
3959 (tramp-file-name-handler 'make-auto-save-file-name))
3965 'make-auto-save-file-name
3966 'around 'tramp-advice-make-auto-save-file-name)
3967 (ad-activate 'make-auto-save-file-name))))
3969 ;; In XEmacs < 21.5, autosaved remote files have permission 0666 minus
3970 ;; umask. This is a security threat.
3972 (defun tramp-set-auto-save-file-modes ()
3973 "Set permissions of autosaved remote files to the original permissions."
3974 (let ((bfn (buffer-file-name)))
3975 (when (and (tramp-tramp-file-p bfn)
3977 (stringp buffer-auto-save-file-name)
3978 (not (equal bfn buffer-auto-save-file-name)))
3979 (unless (file-exists-p buffer-auto-save-file-name)
3980 (write-region "" nil buffer-auto-save-file-name))
3981 ;; Permissions should be set always, because there might be an old
3982 ;; auto-saved file belonging to another original file. This could
3983 ;; be a security threat.
3985 buffer-auto-save-file-name
3986 (or (file-modes bfn) (tramp-compat-octal-to-decimal "0600"))))))
3988 (unless (and (featurep 'xemacs)
3989 (= emacs-major-version 21)
3990 (> emacs-minor-version 4))
3991 (add-hook 'auto-save-hook 'tramp-set-auto-save-file-modes)
3992 (add-hook 'tramp-unload-hook
3994 (remove-hook 'auto-save-hook 'tramp-set-auto-save-file-modes))))
3996 (defun tramp-subst-strs-in-string (alist string)
3997 "Replace all occurrences of the string FROM with TO in STRING.
3998 ALIST is of the form ((FROM . TO) ...)."
4001 (let* ((pr (car alist))
4004 (while (string-match (regexp-quote from) string)
4005 (setq string (replace-match to t t string)))
4006 (setq alist (cdr alist))))
4009 ;;; Compatibility functions section:
4011 (defun tramp-call-process
4012 (program &optional infile destination display &rest args)
4013 "Calls `call-process' on the local host.
4014 This is needed because for some Emacs flavors Tramp has
4015 defadvised `call-process' to behave like `process-file'. The
4016 Lisp error raised when PROGRAM is nil is trapped also, returning 1.
4017 Furthermore, traces are written with verbosity of 6."
4019 (vector tramp-current-method tramp-current-user tramp-current-host nil nil)
4020 6 "%s %s %s" program infile args)
4021 (if (executable-find program)
4022 (apply 'call-process program infile destination display args)
4025 ;;;###tramp-autoload
4026 (defun tramp-read-passwd (proc &optional prompt)
4027 "Read a password from user (compat function).
4028 Consults the auth-source package.
4029 Invokes `password-read' if available, `read-passwd' else."
4030 (let* ((key (tramp-make-tramp-file-name
4031 tramp-current-method tramp-current-user
4032 tramp-current-host ""))
4035 (with-current-buffer (process-buffer proc)
4036 (tramp-check-for-regexp proc tramp-password-prompt-regexp)
4037 (format "%s for %s " (capitalize (match-string 1)) key))))
4038 auth-info auth-passwd)
4039 (with-parsed-tramp-file-name key nil
4042 ;; See if auth-sources contains something useful, if it's
4043 ;; bound. `auth-source-user-or-password' is an obsoleted
4044 ;; function, it has been replaced by `auth-source-search'.
4045 (and (boundp 'auth-sources)
4046 (tramp-get-connection-property v "first-password-request" nil)
4047 ;; Try with Tramp's current method.
4048 (if (fboundp 'auth-source-search)
4050 (tramp-compat-funcall
4053 :user (or tramp-current-user t)
4054 :host tramp-current-host
4055 :port tramp-current-method)
4056 auth-passwd (plist-get (nth 0 auth-info) :secret)
4057 auth-passwd (if (functionp auth-passwd)
4058 (funcall auth-passwd)
4060 (tramp-compat-funcall
4061 'auth-source-user-or-password
4062 "password" tramp-current-host tramp-current-method)))
4063 ;; Try the password cache.
4064 (when (functionp 'password-read)
4065 (unless (tramp-get-connection-property
4066 v "first-password-request" nil)
4067 (tramp-compat-funcall 'password-cache-remove key))
4069 (tramp-compat-funcall 'password-read pw-prompt key)))
4070 (tramp-compat-funcall 'password-cache-add key password)
4072 ;; Else, get the password interactively.
4073 (read-passwd pw-prompt))
4074 (tramp-set-connection-property v "first-password-request" nil)))))
4076 ;;;###tramp-autoload
4077 (defun tramp-clear-passwd (vec)
4078 "Clear password cache for connection related to VEC."
4079 (tramp-compat-funcall
4080 'password-cache-remove
4081 (tramp-make-tramp-file-name
4082 (tramp-file-name-method vec)
4083 (tramp-file-name-user vec)
4084 (tramp-file-name-host vec)
4087 ;; Snarfed code from time-date.el and parse-time.el
4089 (defconst tramp-half-a-year '(241 17024)
4090 "Evaluated by \"(days-to-time 183)\".")
4092 (defconst tramp-parse-time-months
4093 '(("jan" . 1) ("feb" . 2) ("mar" . 3)
4094 ("apr" . 4) ("may" . 5) ("jun" . 6)
4095 ("jul" . 7) ("aug" . 8) ("sep" . 9)
4096 ("oct" . 10) ("nov" . 11) ("dec" . 12))
4097 "Alist mapping month names to integers.")
4099 ;; FIXME: Shouldn't this also look at any subseconds parts of T1 and T2?
4100 ;;;###tramp-autoload
4101 (defun tramp-time-less-p (t1 t2)
4102 "Say whether time value T1 is less than time value T2."
4103 (unless t1 (setq t1 '(0 0)))
4104 (unless t2 (setq t2 '(0 0)))
4105 (or (< (car t1) (car t2))
4106 (and (= (car t1) (car t2))
4107 (< (nth 1 t1) (nth 1 t2)))))
4109 ;; FIXME: Shouldn't this also look at any subseconds parts of T1 and T2?
4110 (defun tramp-time-subtract (t1 t2)
4111 "Subtract two time values.
4112 Return the difference in the format of a time value."
4113 (unless t1 (setq t1 '(0 0)))
4114 (unless t2 (setq t2 '(0 0)))
4115 (let ((borrow (< (cadr t1) (cadr t2))))
4116 (list (- (car t1) (car t2) (if borrow 1 0))
4117 (- (+ (if borrow 65536 0) (cadr t1)) (cadr t2)))))
4119 ;;;###tramp-autoload
4120 (defun tramp-time-diff (t1 t2)
4121 "Return the difference between the two times, in seconds.
4122 T1 and T2 are time values (as returned by `current-time' for example)."
4123 (cond ((and (fboundp 'subtract-time)
4124 (fboundp 'float-time))
4125 (tramp-compat-funcall
4126 'float-time (tramp-compat-funcall 'subtract-time t1 t2)))
4127 ((and (fboundp 'subtract-time)
4128 (fboundp 'time-to-seconds))
4129 (tramp-compat-funcall
4130 'time-to-seconds (tramp-compat-funcall 'subtract-time t1 t2)))
4131 ((fboundp 'itimer-time-difference)
4132 (tramp-compat-funcall
4133 'itimer-time-difference
4134 (if (< (length t1) 3) (append t1 '(0)) t1)
4135 (if (< (length t2) 3) (append t2 '(0)) t2)))
4137 (let ((time (tramp-time-subtract t1 t2)))
4138 (+ (* (car time) 65536.0)
4140 (/ (or (nth 2 time) 0) 1000000.0))))))
4142 ;; Currently (as of Emacs 20.5), the function `shell-quote-argument'
4143 ;; does not deal well with newline characters. Newline is replaced by
4144 ;; backslash newline. But if, say, the string `a backslash newline b'
4145 ;; is passed to a shell, the shell will expand this into "ab",
4146 ;; completely omitting the newline. This is not what was intended.
4147 ;; It does not appear to be possible to make the function
4148 ;; `shell-quote-argument' work with newlines without making it
4149 ;; dependent on the shell used. But within this package, we know that
4150 ;; we will always use a Bourne-like shell, so we use an approach which
4153 ;; The approach is simple: we call `shell-quote-argument', then
4154 ;; massage the newline part of the result.
4156 ;; This function should produce a string which is grokked by a Unix
4157 ;; shell, even if the Emacs is running on Windows. Since this is the
4158 ;; kludges section, we bind `system-type' in such a way that
4159 ;; `shell-quote-arguments' behaves as if on Unix.
4161 ;; Thanks to Mario DeWeerd for the hint that it is sufficient for this
4162 ;; function to work with Bourne-like shells.
4164 ;; CCC: This function should be rewritten so that
4165 ;; `shell-quote-argument' is not used. This way, we are safe from
4166 ;; changes in `shell-quote-argument'.
4167 ;;;###tramp-autoload
4168 (defun tramp-shell-quote-argument (s)
4169 "Similar to `shell-quote-argument', but groks newlines.
4170 Only works for Bourne-like shells."
4171 (let ((system-type 'not-windows))
4173 (let ((result (shell-quote-argument s))
4174 (nl (regexp-quote (format "\\%s" tramp-rsh-end-of-line))))
4175 (when (and (>= (length result) 2)
4176 (string= (substring result 0 2) "\\~"))
4177 (setq result (substring result 1)))
4178 (while (string-match nl result)
4179 (setq result (replace-match (format "'%s'" tramp-rsh-end-of-line)
4183 ;;; Integration of eshell.el:
4186 (defvar eshell-path-env))
4188 ;; eshell.el keeps the path in `eshell-path-env'. We must change it
4189 ;; when `default-directory' points to another host.
4190 (defun tramp-eshell-directory-change ()
4191 "Set `eshell-path-env' to $PATH of the host related to `default-directory'."
4192 (setq eshell-path-env
4193 (if (file-remote-p default-directory)
4194 (with-parsed-tramp-file-name default-directory nil
4198 ;; When `tramp-own-remote-path' is in `tramp-remote-path',
4199 ;; the remote path is only set in the session cache.
4200 (tramp-get-connection-property
4201 (tramp-get-connection-process v) "remote-path" nil)
4202 (tramp-get-connection-property v "remote-path" nil))
4206 (eval-after-load "esh-util"
4208 (tramp-eshell-directory-change)
4209 (add-hook 'eshell-directory-change-hook
4210 'tramp-eshell-directory-change)
4211 (add-hook 'tramp-unload-hook
4213 (remove-hook 'eshell-directory-change-hook
4214 'tramp-eshell-directory-change)))))
4216 ;; Checklist for `tramp-unload-hook'
4217 ;; - Unload all `tramp-*' packages
4218 ;; - Reset `file-name-handler-alist'
4219 ;; - Cleanup hooks where Tramp functions are in
4220 ;; - Cleanup advised functions
4221 ;; - Cleanup autoloads
4223 (defun tramp-unload-tramp ()
4224 "Discard Tramp from loading remote files."
4226 ;; ange-ftp settings must be enabled.
4227 (tramp-compat-funcall 'tramp-ftp-enable-ange-ftp)
4228 ;; Maybe it's not loaded yet.
4229 (ignore-errors (unload-feature 'tramp 'force)))
4235 ;; * Rewrite `tramp-shell-quote-argument' to abstain from using
4236 ;; `shell-quote-argument'.
4237 ;; * In Emacs 21, `insert-directory' shows total number of bytes used
4238 ;; by the files in that directory. Add this here.
4239 ;; * Avoid screen blanking when hitting `g' in dired. (Eli Tziperman)
4240 ;; * abbreviate-file-name
4241 ;; * Better error checking. At least whenever we see something
4242 ;; strange when doing zerop, we should kill the process and start
4243 ;; again. (Greg Stark)
4244 ;; * Username and hostname completion.
4245 ;; ** Try to avoid usage of `last-input-event' in `tramp-completion-mode-p'.
4246 ;; * Make `tramp-default-user' obsolete.
4247 ;; * Implement a general server-local-variable mechanism, as there are
4248 ;; probably other variables that need different values for different
4249 ;; servers too. The user could then configure a variable (such as
4250 ;; tramp-server-local-variable-alist) to define any such variables
4251 ;; that they need to, which would then be let bound as appropriate
4252 ;; in tramp functions. (Jason Rumney)
4253 ;; * IMHO, it's a drawback that currently Tramp doesn't support
4254 ;; Unicode in Dired file names by default. Is it possible to
4255 ;; improve Tramp to set LC_ALL to "C" only for commands where Tramp
4256 ;; expects English? Or just to set LC_MESSAGES to "C" if Tramp
4257 ;; expects only English messages? (Juri Linkov)
4258 ;; * Make shadowfile.el grok Tramp filenames. (Bug#4526, Bug#4846)
4259 ;; * I was wondering if it would be possible to use tramp even if I'm
4260 ;; actually using sshfs. But when I launch a command I would like
4261 ;; to get it executed on the remote machine where the files really
4262 ;; are. (Andrea Crotti)
4263 ;; * Run emerge on two remote files. Bug is described here:
4264 ;; <http://www.mail-archive.com/tramp-devel@nongnu.org/msg01041.html>.
4266 ;; * Use also port to distinguish connections. This is needed for
4267 ;; different hosts sitting behind a single router (distinguished by
4268 ;; different port numbers). (Tzvi Edelman)
4270 ;;; tramp.el ends here