1 ;;; tramp.el --- Transparent Remote Access, Multiple Protocol
3 ;; Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004,
4 ;; 2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
6 ;; Author: Kai Großjohann <kai.grossjohann@gmx.net>
7 ;; Michael Albinus <michael.albinus@gmx.de>
8 ;; Keywords: comm, processes
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
28 ;; This package provides remote file editing, similar to ange-ftp.
29 ;; The difference is that ange-ftp uses FTP to transfer files between
30 ;; the local and the remote host, whereas tramp.el uses a combination
31 ;; of rsh and rcp or other work-alike programs, such as ssh/scp.
33 ;; For more detailed instructions, please see the info file.
38 ;; This package only works for Emacs 22.1 and higher, and for XEmacs 21.4
39 ;; and higher. For XEmacs 21, you need the package `fsf-compat' for
40 ;; the `with-timeout' macro.
42 ;; Also see the todo list at the bottom of this file.
44 ;; The current version of Tramp can be retrieved from the following URL:
45 ;; http://ftp.gnu.org/gnu/tramp/
47 ;; There's a mailing list for this, as well. Its name is:
48 ;; tramp-devel@gnu.org
49 ;; You can use the Web to subscribe, under the following URL:
50 ;; http://lists.gnu.org/mailman/listinfo/tramp-devel
52 ;; For the adventurous, the current development sources are available
53 ;; via CVS. You can find instructions about this at the following URL:
54 ;; http://savannah.gnu.org/projects/tramp/
55 ;; Click on "CVS" in the navigation bar near the top.
57 ;; Don't forget to put on your asbestos longjohns, first!
61 (require 'tramp-compat)
63 ;;; User Customizable Internal Variables:
66 "Edit remote files with a combination of rsh and rcp or similar programs."
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 deocding, 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 Note that this variable is not used for remote commands. There are
164 mechanisms in tramp.el which automatically determine the right shell to
165 use for the remote host."
167 :type '(file :must-match t))
169 (defcustom tramp-encoding-command-switch
170 (if (string-match "cmd\\.exe" tramp-encoding-shell)
173 "*Use this switch together with `tramp-encoding-shell' for local commands.
174 See the variable `tramp-encoding-shell' for more information."
179 (defvar tramp-methods nil
180 "*Alist of methods for remote files.
181 This is a list of entries of the form (NAME PARAM1 PARAM2 ...).
182 Each NAME stands for a remote access method. Each PARAM is a
183 pair of the form (KEY VALUE). The following KEYs are defined:
185 This specifies the Bourne shell to use on the remote host. This
186 MUST be a Bourne-like shell. It is normally not necessary to set
187 this to any value other than \"/bin/sh\": Tramp wants to use a shell
188 which groks tilde expansion, but it can search for it. Also note
189 that \"/bin/sh\" exists on all Unixen, this might not be true for
190 the value that you decide to use. You Have Been Warned.
191 * `tramp-login-program'
192 This specifies the name of the program to use for logging in to the
193 remote host. This may be the name of rsh or a workalike program,
194 or the name of telnet or a workalike, or the name of su or a workalike.
196 This specifies the list of arguments to pass to the above
197 mentioned program. Please note that this is a list of list of arguments,
198 that is, normally you don't want to put \"-a -b\" or \"-f foo\"
199 here. Instead, you want a list (\"-a\" \"-b\"), or (\"-f\" \"foo\").
200 There are some patterns: \"%h\" in this list is replaced by the host
201 name, \"%u\" is replaced by the user name, \"%p\" is replaced by the
202 port number, and \"%%\" can be used to obtain a literal percent character.
203 If a list containing \"%h\", \"%u\" or \"%p\" is unchanged during
204 expansion (i.e. no host or no user specified), this list is not used as
205 argument. By this, arguments like (\"-l\" \"%u\") are optional.
206 \"%t\" is replaced by the temporary file name produced with
207 `tramp-make-tramp-temp-file'. \"%k\" indicates the keep-date
208 parameter of a program, if exists.
210 When an asynchronous process is started, we know already that
211 the connection works. Therefore, we can pass additional
212 parameters to suppress diagnostic messages, in order not to
213 tamper the process output.
214 * `tramp-copy-program'
215 This specifies the name of the program to use for remotely copying
216 the file; this might be the absolute filename of rcp or the name of
219 This specifies the list of parameters to pass to the above mentioned
220 program, the hints for `tramp-login-args' also apply here.
221 * `tramp-copy-keep-date'
222 This specifies whether the copying program when the preserves the
223 timestamp of the original file.
224 * `tramp-copy-keep-tmpfile'
225 This specifies whether a temporary local file shall be kept
226 for optimization reasons (useful for \"rsync\" methods).
227 * `tramp-copy-recursive'
228 Whether the operation copies directories recursively.
229 * `tramp-default-port'
230 The default port of a method is needed in case of gateway connections.
231 Additionally, it is used as indication which method is prepared for
234 As the attribute name says, additional arguments are specified here
235 when a method is applied via a gateway.
236 * `tramp-password-end-of-line'
237 This specifies the string to use for terminating the line after
238 submitting the password. If this method parameter is nil, then the
239 value of the normal variable `tramp-default-password-end-of-line'
240 is used. This parameter is necessary because the \"plink\" program
241 requires any two characters after sending the password. These do
242 not have to be newline or carriage return characters. Other login
243 programs are happy with just one character, the newline character.
244 We use \"xy\" as the value for methods using \"plink\".
246 What does all this mean? Well, you should specify `tramp-login-program'
247 for all methods; this program is used to log in to the remote site. Then,
248 there are two ways to actually transfer the files between the local and the
249 remote side. One way is using an additional rcp-like program. If you want
250 to do this, set `tramp-copy-program' in the method.
252 Another possibility for file transfer is inline transfer, i.e. the
253 file is passed through the same buffer used by `tramp-login-program'. In
254 this case, the file contents need to be protected since the
255 `tramp-login-program' might use escape codes or the connection might not
256 be eight-bit clean. Therefore, file contents are encoded for transit.
257 See the variables `tramp-local-coding-commands' and
258 `tramp-remote-coding-commands' for details.
260 So, to summarize: if the method is an out-of-band method, then you
261 must specify `tramp-copy-program' and `tramp-copy-args'. If it is an
262 inline method, then these two parameters should be nil. Methods which
263 are fit for gateways must have `tramp-default-port' at least.
267 When using `su' or `sudo' the phrase `open connection to a remote
268 host' sounds strange, but it is used nevertheless, for consistency.
269 No connection is opened to a remote host, but `su' or `sudo' is
270 started on the local host. You should specify a remote host
271 `localhost' or the name of the local host. Another host name is
272 useful only in combination with `tramp-default-proxies-alist'.")
274 (defun tramp-detect-ssh-controlmaster ()
275 "Call ssh to detect whether it supports the ControlMaster argument.
276 This function may return nil when the argument is supported, but
277 shouldn't return t when it isn't."
280 (call-process "ssh" nil t nil "-o" "ControlMaster")
281 (goto-char (point-min))
282 (search-forward-regexp "Missing ControlMaster argument" nil t))))
284 (defcustom tramp-default-method
285 ;; An external copy method seems to be preferred, because it is much
286 ;; more performant for large files, and it hasn't too serious delays
287 ;; for small files. But it must be ensured that there aren't
288 ;; permanent password queries. Either a password agent like
289 ;; "ssh-agent" or "Pageant" shall run, or the optional
290 ;; password-cache.el or auth-sources.el packages shall be active for
291 ;; password caching. "scpc" is chosen if we detect that the user is
292 ;; running OpenSSH 4.0 or newer.
294 ;; PuTTY is installed.
295 ((executable-find "pscp")
296 (if (or (fboundp 'password-read)
297 (fboundp 'auth-source-user-or-password)
298 ;; Pageant is running.
299 (tramp-compat-process-running-p "Pageant"))
302 ;; There is an ssh installation.
303 ((executable-find "scp")
305 ((tramp-detect-ssh-controlmaster) "scpc")
306 ((or (fboundp 'password-read)
307 (fboundp 'auth-source-user-or-password)
308 ;; ssh-agent is running.
309 (getenv "SSH_AUTH_SOCK")
310 (getenv "SSH_AGENT_PID"))
315 "*Default method to use for transferring files.
316 See `tramp-methods' for possibilities.
317 Also see `tramp-default-method-alist'."
321 (defcustom tramp-default-method-alist nil
322 "*Default method to use for specific host/user pairs.
323 This is an alist of items (HOST USER METHOD). The first matching item
324 specifies the method to use for a file name which does not specify a
325 method. HOST and USER are regular expressions or nil, which is
326 interpreted as a regular expression which always matches. If no entry
327 matches, the variable `tramp-default-method' takes effect.
329 If the file name does not specify the user, lookup is done using the
330 empty string for the user name.
332 See `tramp-methods' for a list of possibilities for METHOD."
334 :type '(repeat (list (choice :tag "Host regexp" regexp sexp)
335 (choice :tag "User regexp" regexp sexp)
336 (choice :tag "Method name" string (const nil)))))
338 (defcustom tramp-default-user nil
339 "*Default user to use for transferring files.
340 It is nil by default; otherwise settings in configuration files like
341 \"~/.ssh/config\" would be overwritten. Also see `tramp-default-user-alist'.
343 This variable is regarded as obsolete, and will be removed soon."
345 :type '(choice (const nil) string))
347 (defcustom tramp-default-user-alist nil
348 "*Default user to use for specific method/host pairs.
349 This is an alist of items (METHOD HOST USER). The first matching item
350 specifies the user to use for a file name which does not specify a
351 user. METHOD and USER are regular expressions or nil, which is
352 interpreted as a regular expression which always matches. If no entry
353 matches, the variable `tramp-default-user' takes effect.
355 If the file name does not specify the method, lookup is done using the
356 empty string for the method name."
358 :type '(repeat (list (choice :tag "Method regexp" regexp sexp)
359 (choice :tag " Host regexp" regexp sexp)
360 (choice :tag " User name" string (const nil)))))
362 (defcustom tramp-default-host (system-name)
363 "*Default host to use for transferring files.
364 Useful for su and sudo methods mostly."
368 (defcustom tramp-default-proxies-alist nil
369 "*Route to be followed for specific host/user pairs.
370 This is an alist of items (HOST USER PROXY). The first matching
371 item specifies the proxy to be passed for a file name located on
372 a remote target matching USER@HOST. HOST and USER are regular
373 expressions. PROXY must be a Tramp filename without a localname
374 part. Method and user name on PROXY are optional, which is
375 interpreted with the default values. PROXY can contain the
376 patterns %h and %u, which are replaced by the strings matching
377 HOST or USER, respectively.
379 HOST, USER or PROXY could also be Lisp forms, which will be
380 evaluated. The result must be a string or nil, which is
381 interpreted as a regular expression which always matches."
383 :type '(repeat (list (choice :tag "Host regexp" regexp sexp)
384 (choice :tag "User regexp" regexp sexp)
385 (choice :tag " Proxy name" string (const nil)))))
387 (defconst tramp-local-host-regexp
391 (list "localhost" "localhost6" (system-name) "127\.0\.0\.1" "::1") t)
393 "*Host names which are regarded as local host.")
395 (defvar tramp-completion-function-alist nil
396 "*Alist of methods for remote files.
397 This is a list of entries of the form \(NAME PAIR1 PAIR2 ...\).
398 Each NAME stands for a remote access method. Each PAIR is of the form
399 \(FUNCTION FILE\). FUNCTION is responsible to extract user names and host
400 names from FILE for completion. The following predefined FUNCTIONs exists:
402 * `tramp-parse-rhosts' for \"~/.rhosts\" like files,
403 * `tramp-parse-shosts' for \"~/.ssh/known_hosts\" like files,
404 * `tramp-parse-sconfig' for \"~/.ssh/config\" like files,
405 * `tramp-parse-shostkeys' for \"~/.ssh2/hostkeys/*\" like files,
406 * `tramp-parse-sknownhosts' for \"~/.ssh2/knownhosts/*\" like files,
407 * `tramp-parse-hosts' for \"/etc/hosts\" like files,
408 * `tramp-parse-passwd' for \"/etc/passwd\" like files.
409 * `tramp-parse-netrc' for \"~/.netrc\" like files.
410 * `tramp-parse-putty' for PuTTY registry keys.
412 FUNCTION can also be a customer defined function. For more details see
415 (defconst tramp-echo-mark-marker "_echo"
416 "String marker to surround echoed commands.")
418 (defconst tramp-echo-mark-marker-length (length tramp-echo-mark-marker)
419 "String length of `tramp-echo-mark-marker'.")
421 (defconst tramp-echo-mark
422 (concat tramp-echo-mark-marker
423 (make-string tramp-echo-mark-marker-length ?\b))
424 "String mark to be transmitted around shell commands.
425 Used to separate their echo from the output they produce. This
426 will only be used if we cannot disable remote echo via stty.
427 This string must have no effect on the remote shell except for
428 producing some echo which can later be detected by
429 `tramp-echoed-echo-mark-regexp'. Using `tramp-echo-mark-marker',
430 followed by an equal number of backspaces to erase them will
433 (defconst tramp-echoed-echo-mark-regexp
434 (format "%s\\(\b\\( \b\\)?\\)\\{%d\\}"
435 tramp-echo-mark-marker tramp-echo-mark-marker-length)
436 "Regexp which matches `tramp-echo-mark' as it gets echoed by
439 (defcustom tramp-rsh-end-of-line "\n"
440 "*String used for end of line in rsh connections.
441 I don't think this ever needs to be changed, so please tell me about it
442 if you need to change this.
443 Also see the method parameter `tramp-password-end-of-line' and the normal
444 variable `tramp-default-password-end-of-line'."
448 (defcustom tramp-default-password-end-of-line
449 tramp-rsh-end-of-line
450 "*String used for end of line after sending a password.
451 This variable provides the default value for the method parameter
452 `tramp-password-end-of-line', see `tramp-methods' for more details.
454 It seems that people using plink under Windows need to send
455 \"\\r\\n\" (carriage-return, then newline) after a password, but just
456 \"\\n\" after all other lines. This variable can be used for the
457 password, see `tramp-rsh-end-of-line' for the other cases.
459 The default value is to use the same value as `tramp-rsh-end-of-line'."
463 (defcustom tramp-login-prompt-regexp
464 ".*ogin\\( .*\\)?: *"
465 "*Regexp matching login-like prompts.
466 The regexp should match at end of buffer.
468 Sometimes the prompt is reported to look like \"login as:\"."
472 (defcustom tramp-shell-prompt-pattern
473 ;; Allow a prompt to start right after a ^M since it indeed would be
474 ;; displayed at the beginning of the line (and Zsh uses it). This
475 ;; regexp works only for GNU Emacs.
476 (concat (if (featurep 'xemacs) "" "\\(?:^\\|\r\\)")
477 "[^#$%>\n]*#?[#$%>] *\\(\e\\[[0-9;]*[a-zA-Z] *\\)*")
478 "Regexp to match prompts from remote shell.
479 Normally, Tramp expects you to configure `shell-prompt-pattern'
480 correctly, but sometimes it happens that you are connecting to a
481 remote host which sends a different kind of shell prompt. Therefore,
482 Tramp recognizes things matched by `shell-prompt-pattern' as prompt,
483 and also things matched by this variable. The default value of this
484 variable is similar to the default value of `shell-prompt-pattern',
485 which should work well in many cases.
487 This regexp must match both `tramp-initial-end-of-output' and
488 `tramp-end-of-output'."
492 (defcustom tramp-password-prompt-regexp
493 "^.*\\([pP]assword\\|[pP]assphrase\\).*:\^@? *"
494 "*Regexp matching password-like prompts.
495 The regexp should match at end of buffer.
497 The `sudo' program appears to insert a `^@' character into the prompt."
501 (defcustom tramp-wrong-passwd-regexp
503 ;; These strings should be on the last line
504 (regexp-opt '("Permission denied"
509 "Timeout, server not responding."
511 "Name or service not known"
512 "Host key verification failed."
513 "No supported authentication methods left to try!") t)
517 ;; Here comes a list of regexes, separated by \\|
518 "Received signal [0-9]+"
520 "*Regexp matching a `login failed' message.
521 The regexp should match at end of buffer."
525 (defcustom tramp-yesno-prompt-regexp
527 (regexp-opt '("Are you sure you want to continue connecting (yes/no)?") t)
529 "Regular expression matching all yes/no queries which need to be confirmed.
530 The confirmation should be done with yes or no.
531 The regexp should match at end of buffer.
532 See also `tramp-yn-prompt-regexp'."
536 (defcustom tramp-yn-prompt-regexp
538 (regexp-opt '("Store key in cache? (y/n)"
539 "Update cached key? (y/n, Return cancels connection)") t)
541 "Regular expression matching all y/n queries which need to be confirmed.
542 The confirmation should be done with y or n.
543 The regexp should match at end of buffer.
544 See also `tramp-yesno-prompt-regexp'."
548 (defcustom tramp-terminal-prompt-regexp
552 "Terminal type\\? \\[.*\\]"
554 "Regular expression matching all terminal setting prompts.
555 The regexp should match at end of buffer.
556 The answer will be provided by `tramp-action-terminal', which see."
560 (defcustom tramp-operation-not-permitted-regexp
561 (concat "\\(" "preserving times.*" "\\|" "set mode" "\\)" ":\\s-*"
562 (regexp-opt '("Operation not permitted") t))
563 "Regular expression matching keep-date problems in (s)cp operations.
564 Copying has been performed successfully already, so this message can
569 (defcustom tramp-copy-failed-regexp
571 (regexp-opt '("Permission denied"
574 "No such file or directory") t)
576 "Regular expression matching copy problems in (s)cp operations."
580 (defcustom tramp-process-alive-regexp
582 "Regular expression indicating a process has finished.
583 In fact this expression is empty by intention, it will be used only to
584 check regularly the status of the associated process.
585 The answer will be provided by `tramp-action-process-alive',
586 `tramp-action-out-of-band', which see."
590 (defconst tramp-temp-name-prefix "tramp."
591 "*Prefix to use for temporary files.
592 If this is a relative file name (such as \"tramp.\"), it is considered
593 relative to the directory name returned by the function
594 `tramp-compat-temporary-file-directory' (which see). It may also be an
595 absolute file name; don't forget to include a prefix for the filename
598 (defconst tramp-temp-buffer-name " *tramp temp*"
599 "Buffer name for a temporary buffer.
600 It shall be used in combination with `generate-new-buffer-name'.")
602 (defvar tramp-temp-buffer-file-name nil
603 "File name of a persistent local temporary file.
604 Useful for \"rsync\" like methods.")
605 (make-variable-buffer-local 'tramp-temp-buffer-file-name)
607 ;; XEmacs is distributed with few Lisp packages. Further packages are
608 ;; installed using EFS. If we use a unified filename format, then
609 ;; Tramp is required in addition to EFS. (But why can't Tramp just
610 ;; disable EFS when Tramp is loaded? Then XEmacs can ship with EFS
611 ;; just like before.) Another reason for using a separate filename
612 ;; syntax on XEmacs is that EFS hooks into XEmacs in many places, but
613 ;; Tramp only knows how to deal with `file-name-handler-alist', not
616 ;; Currently, we have the choice between 'ftp, 'sep, and 'url.
618 (defcustom tramp-syntax
619 (if (featurep 'xemacs) 'sep 'ftp)
620 "Tramp filename syntax to be used.
622 It can have the following values:
624 'ftp -- Ange-FTP respective EFS like syntax (GNU Emacs default)
625 'sep -- Syntax as defined for XEmacs (not available yet for GNU Emacs)
626 'url -- URL-like syntax."
628 :type (if (featurep 'xemacs)
629 '(choice (const :tag "EFS" ftp)
630 (const :tag "XEmacs" sep)
631 (const :tag "URL" url))
632 '(choice (const :tag "Ange-FTP" ftp)
633 (const :tag "URL" url))))
635 (defconst tramp-prefix-format
636 (cond ((equal tramp-syntax 'ftp) "/")
637 ((equal tramp-syntax 'sep) "/[")
638 ((equal tramp-syntax 'url) "/")
639 (t (error "Wrong `tramp-syntax' defined")))
640 "*String matching the very beginning of Tramp file names.
641 Used in `tramp-make-tramp-file-name'.")
643 (defconst tramp-prefix-regexp
644 (concat "^" (regexp-quote tramp-prefix-format))
645 "*Regexp matching the very beginning of Tramp file names.
646 Should always start with \"^\". Derived from `tramp-prefix-format'.")
648 (defconst tramp-method-regexp
650 "*Regexp matching methods identifiers.")
652 (defconst tramp-postfix-method-format
653 (cond ((equal tramp-syntax 'ftp) ":")
654 ((equal tramp-syntax 'sep) "/")
655 ((equal tramp-syntax 'url) "://")
656 (t (error "Wrong `tramp-syntax' defined")))
657 "*String matching delimeter between method and user or host names.
658 Used in `tramp-make-tramp-file-name'.")
660 (defconst tramp-postfix-method-regexp
661 (regexp-quote tramp-postfix-method-format)
662 "*Regexp matching delimeter between method and user or host names.
663 Derived from `tramp-postfix-method-format'.")
665 (defconst tramp-user-regexp "[^:/ \t]+"
666 "*Regexp matching user names.")
668 (defconst tramp-prefix-domain-format "%"
669 "*String matching delimeter between user and domain names.")
671 (defconst tramp-prefix-domain-regexp
672 (regexp-quote tramp-prefix-domain-format)
673 "*Regexp matching delimeter between user and domain names.
674 Derived from `tramp-prefix-domain-format'.")
676 (defconst tramp-domain-regexp "[-a-zA-Z0-9_.]+"
677 "*Regexp matching domain names.")
679 (defconst tramp-user-with-domain-regexp
680 (concat "\\(" tramp-user-regexp "\\)"
681 tramp-prefix-domain-regexp
682 "\\(" tramp-domain-regexp "\\)")
683 "*Regexp matching user names with domain names.")
685 (defconst tramp-postfix-user-format "@"
686 "*String matching delimeter between user and host names.
687 Used in `tramp-make-tramp-file-name'.")
689 (defconst tramp-postfix-user-regexp
690 (regexp-quote tramp-postfix-user-format)
691 "*Regexp matching delimeter between user and host names.
692 Derived from `tramp-postfix-user-format'.")
694 (defconst tramp-host-regexp "[a-zA-Z0-9_.-]+"
695 "*Regexp matching host names.")
697 (defconst tramp-prefix-ipv6-format
698 (cond ((equal tramp-syntax 'ftp) "[")
699 ((equal tramp-syntax 'sep) "")
700 ((equal tramp-syntax 'url) "[")
701 (t (error "Wrong `tramp-syntax' defined")))
702 "*String matching left hand side of IPv6 addresses.
703 Used in `tramp-make-tramp-file-name'.")
705 (defconst tramp-prefix-ipv6-regexp
706 (regexp-quote tramp-prefix-ipv6-format)
707 "*Regexp matching left hand side of IPv6 addresses.
708 Derived from `tramp-prefix-ipv6-format'.")
710 ;; The following regexp is a bit sloppy. But it shall serve our
711 ;; purposes. It covers also IPv4 mapped IPv6 addresses, like in
712 ;; "::ffff:192.168.0.1".
713 (defconst tramp-ipv6-regexp
714 "\\(?:\\(?:[a-zA-Z0-9]+\\)?:\\)+[a-zA-Z0-9.]+"
715 "*Regexp matching IPv6 addresses.")
717 (defconst tramp-postfix-ipv6-format
718 (cond ((equal tramp-syntax 'ftp) "]")
719 ((equal tramp-syntax 'sep) "")
720 ((equal tramp-syntax 'url) "]")
721 (t (error "Wrong `tramp-syntax' defined")))
722 "*String matching right hand side of IPv6 addresses.
723 Used in `tramp-make-tramp-file-name'.")
725 (defconst tramp-postfix-ipv6-regexp
726 (regexp-quote tramp-postfix-ipv6-format)
727 "*Regexp matching right hand side of IPv6 addresses.
728 Derived from `tramp-postfix-ipv6-format'.")
730 (defconst tramp-prefix-port-format
731 (cond ((equal tramp-syntax 'ftp) "#")
732 ((equal tramp-syntax 'sep) "#")
733 ((equal tramp-syntax 'url) ":")
734 (t (error "Wrong `tramp-syntax' defined")))
735 "*String matching delimeter between host names and port numbers.")
737 (defconst tramp-prefix-port-regexp
738 (regexp-quote tramp-prefix-port-format)
739 "*Regexp matching delimeter between host names and port numbers.
740 Derived from `tramp-prefix-port-format'.")
742 (defconst tramp-port-regexp "[0-9]+"
743 "*Regexp matching port numbers.")
745 (defconst tramp-host-with-port-regexp
746 (concat "\\(" tramp-host-regexp "\\)"
747 tramp-prefix-port-regexp
748 "\\(" tramp-port-regexp "\\)")
749 "*Regexp matching host names with port numbers.")
751 (defconst tramp-postfix-host-format
752 (cond ((equal tramp-syntax 'ftp) ":")
753 ((equal tramp-syntax 'sep) "]")
754 ((equal tramp-syntax 'url) "")
755 (t (error "Wrong `tramp-syntax' defined")))
756 "*String matching delimeter between host names and localnames.
757 Used in `tramp-make-tramp-file-name'.")
759 (defconst tramp-postfix-host-regexp
760 (regexp-quote tramp-postfix-host-format)
761 "*Regexp matching delimeter between host names and localnames.
762 Derived from `tramp-postfix-host-format'.")
764 (defconst tramp-localname-regexp ".*$"
765 "*Regexp matching localnames.")
767 ;;; File name format:
769 (defconst tramp-file-name-structure
773 "\\(" "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp "\\)?"
774 "\\(" "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp "\\)?"
775 "\\(" "\\(" tramp-host-regexp
777 tramp-prefix-ipv6-regexp tramp-ipv6-regexp
778 tramp-postfix-ipv6-regexp "\\)"
779 "\\(" tramp-prefix-port-regexp tramp-port-regexp "\\)?" "\\)?"
780 tramp-postfix-host-regexp
781 "\\(" tramp-localname-regexp "\\)")
784 "*List of five elements (REGEXP METHOD USER HOST FILE), detailing \
785 the Tramp file name structure.
787 The first element REGEXP is a regular expression matching a Tramp file
788 name. The regex should contain parentheses around the method name,
789 the user name, the host name, and the file name parts.
791 The second element METHOD is a number, saying which pair of
792 parentheses matches the method name. The third element USER is
793 similar, but for the user name. The fourth element HOST is similar,
794 but for the host name. The fifth element FILE is for the file name.
795 These numbers are passed directly to `match-string', which see. That
796 means the opening parentheses are counted to identify the pair.
798 See also `tramp-file-name-regexp'.")
801 (defconst tramp-file-name-regexp-unified
802 (if (memq system-type '(cygwin windows-nt))
803 "\\`/\\([^[/:]\\{2,\\}\\|[^/]\\{2,\\}]\\):"
804 "\\`/\\([^[/:]+\\|[^/]+]\\):")
805 "Value for `tramp-file-name-regexp' for unified remoting.
806 Emacs (not XEmacs) uses a unified filename syntax for Ange-FTP and
807 Tramp. See `tramp-file-name-structure' for more explanations.
809 On W32 systems, the volume letter must be ignored.")
812 (defconst tramp-file-name-regexp-separate "\\`/\\[.*\\]"
813 "Value for `tramp-file-name-regexp' for separate remoting.
814 XEmacs uses a separate filename syntax for Tramp and EFS.
815 See `tramp-file-name-structure' for more explanations.")
818 (defconst tramp-file-name-regexp-url "\\`/[^/:]+://"
819 "Value for `tramp-file-name-regexp' for URL-like remoting.
820 See `tramp-file-name-structure' for more explanations.")
823 (defconst tramp-file-name-regexp
824 (cond ((equal tramp-syntax 'ftp) tramp-file-name-regexp-unified)
825 ((equal tramp-syntax 'sep) tramp-file-name-regexp-separate)
826 ((equal tramp-syntax 'url) tramp-file-name-regexp-url)
827 (t (error "Wrong `tramp-syntax' defined")))
828 "*Regular expression matching file names handled by Tramp.
829 This regexp should match Tramp file names but no other file names.
830 When tramp.el is loaded, this regular expression is prepended to
831 `file-name-handler-alist', and that is searched sequentially. Thus,
832 if the Tramp entry appears rather early in the `file-name-handler-alist'
833 and is a bit too general, then some files might be considered Tramp
834 files which are not really Tramp files.
836 Please note that the entry in `file-name-handler-alist' is made when
837 this file \(tramp.el\) is loaded. This means that this variable must be set
838 before loading tramp.el. Alternatively, `file-name-handler-alist' can be
839 updated after changing this variable.
841 Also see `tramp-file-name-structure'.")
844 (defconst tramp-root-regexp
845 (if (memq system-type '(cygwin windows-nt))
846 "\\`\\([a-zA-Z]:\\)?/"
848 "Beginning of an incomplete Tramp file name.
849 Usually, it is just \"\\\\`/\". On W32 systems, there might be a
850 volume letter, which will be removed by `tramp-drop-volume-letter'.")
853 (defconst tramp-completion-file-name-regexp-unified
854 (if (memq system-type '(cygwin windows-nt))
855 (concat tramp-root-regexp "[^/]\\{2,\\}\\'")
856 (concat tramp-root-regexp "[^/]*\\'"))
857 "Value for `tramp-completion-file-name-regexp' for unified remoting.
858 GNU Emacs uses a unified filename syntax for Tramp and Ange-FTP.
859 See `tramp-file-name-structure' for more explanations.
861 On W32 systems, the volume letter must be ignored.")
864 (defconst tramp-completion-file-name-regexp-separate
865 (concat tramp-root-regexp "\\([[][^]]*\\)?\\'")
866 "Value for `tramp-completion-file-name-regexp' for separate remoting.
867 XEmacs uses a separate filename syntax for Tramp and EFS.
868 See `tramp-file-name-structure' for more explanations.")
871 (defconst tramp-completion-file-name-regexp-url
872 (concat tramp-root-regexp "[^/:]+\\(:\\(/\\(/[^/]*\\)?\\)?\\)?\\'")
873 "Value for `tramp-completion-file-name-regexp' for URL-like remoting.
874 See `tramp-file-name-structure' for more explanations.")
877 (defconst tramp-completion-file-name-regexp
878 (cond ((equal tramp-syntax 'ftp) tramp-completion-file-name-regexp-unified)
879 ((equal tramp-syntax 'sep) tramp-completion-file-name-regexp-separate)
880 ((equal tramp-syntax 'url) tramp-completion-file-name-regexp-url)
881 (t (error "Wrong `tramp-syntax' defined")))
882 "*Regular expression matching file names handled by Tramp completion.
883 This regexp should match partial Tramp file names only.
885 Please note that the entry in `file-name-handler-alist' is made when
886 this file (tramp.el) is loaded. This means that this variable must be set
887 before loading tramp.el. Alternatively, `file-name-handler-alist' can be
888 updated after changing this variable.
890 Also see `tramp-file-name-structure'.")
892 ;; Chunked sending kludge. We set this to 500 for black-listed constellations
893 ;; known to have a bug in `process-send-string'; some ssh connections appear
894 ;; to drop bytes when data is sent too quickly. There is also a connection
895 ;; buffer local variable, which is computed depending on remote host properties
896 ;; when `tramp-chunksize' is zero or nil.
897 (defcustom tramp-chunksize
898 (when (and (not (featurep 'xemacs))
899 (memq system-type '(hpux)))
901 ;; Parentheses in docstring starting at beginning of line are escaped.
902 ;; Fontification is messed up when
903 ;; `open-paren-in-column-0-is-defun-start' set to t.
904 "*If non-nil, chunksize for sending input to local process.
905 It is necessary only on systems which have a buggy `process-send-string'
906 implementation. The necessity, whether this variable must be set, can be
907 checked via the following code:
910 (let* ((user \"xxx\") (host \"yyy\")
912 (sent init) (received init))
913 (while (= sent received)
914 (setq sent (+ sent step))
916 (let ((proc (start-process (buffer-name) (current-buffer)
917 \"ssh\" \"-l\" user host \"wc\" \"-c\")))
918 (when (memq (process-status proc) '(run open))
919 (process-send-string proc (make-string sent ?\\ ))
920 (process-send-eof proc)
921 (process-send-eof proc))
922 (while (not (progn (goto-char (point-min))
923 (re-search-forward \"\\\\w+\" (point-max) t)))
924 (accept-process-output proc 1))
925 (when (memq (process-status proc) '(run open))
926 (setq received (string-to-number (match-string 0)))
927 (delete-process proc)
928 (message \"Bytes sent: %s\\tBytes received: %s\" sent received)
930 (if (> sent (+ init step))
931 (message \"You should set `tramp-chunksize' to a maximum of %s\"
933 (message \"Test does not work\")
934 (display-buffer (current-buffer))
937 In the Emacs normally running Tramp, evaluate the above code
938 \(replace \"xxx\" and \"yyy\" by the remote user and host name,
939 respectively\). You can do this, for example, by pasting it into
940 the `*scratch*' buffer and then hitting C-j with the cursor after the
941 last closing parenthesis. Note that it works only if you have configured
942 \"ssh\" to run without password query, see ssh-agent\(1\).
944 You will see the number of bytes sent successfully to the remote host.
945 If that number exceeds 1000, you can stop the execution by hitting
946 C-g, because your Emacs is likely clean.
948 When it is necessary to set `tramp-chunksize', you might consider to
949 use an out-of-the-band method \(like \"scp\"\) instead of an internal one
950 \(like \"ssh\"\), because setting `tramp-chunksize' to non-nil decreases
953 If your Emacs is buggy, the code stops and gives you an indication
954 about the value `tramp-chunksize' should be set. Maybe you could just
955 experiment a bit, e.g. changing the values of `init' and `step'
956 in the third line of the code.
958 Please raise a bug report via \"M-x tramp-bug\" if your system needs
959 this variable to be set as well."
961 :type '(choice (const nil) integer))
963 ;; Logging in to a remote host normally requires obtaining a pty. But
964 ;; Emacs on MacOS X has process-connection-type set to nil by default,
965 ;; so on those systems Tramp doesn't obtain a pty. Here, we allow
966 ;; for an override of the system default.
967 (defcustom tramp-process-connection-type t
968 "Overrides `process-connection-type' for connections from Tramp.
969 Tramp binds process-connection-type to the value given here before
970 opening a connection to a remote host."
972 :type '(choice (const nil) (const t) (const pty)))
974 (defcustom tramp-completion-reread-directory-timeout 10
975 "Defines seconds since last remote command before rereading a directory.
976 A remote directory might have changed its contents. In order to
977 make it visible during file name completion in the minibuffer,
978 Tramp flushes its cache and rereads the directory contents when
979 more than `tramp-completion-reread-directory-timeout' seconds
980 have been gone since last remote command execution. A value of `t'
981 would require an immediate reread during filename completion, `nil'
982 means to use always cached values for the directory contents."
984 :type '(choice (const nil) integer))
986 ;;; Internal Variables:
988 (defvar tramp-current-method nil
989 "Connection method for this *tramp* buffer.")
991 (defvar tramp-current-user nil
992 "Remote login name for this *tramp* buffer.")
994 (defvar tramp-current-host nil
995 "Remote host for this *tramp* buffer.")
998 (defconst tramp-completion-file-name-handler-alist
999 '((file-name-all-completions . tramp-completion-handle-file-name-all-completions)
1000 (file-name-completion . tramp-completion-handle-file-name-completion))
1001 "Alist of completion handler functions.
1002 Used for file names matching `tramp-file-name-regexp'. Operations
1003 not mentioned here will be handled by Tramp's file name handler
1004 functions, or the normal Emacs functions.")
1006 ;; Handlers for foreign methods, like FTP or SMB, shall be plugged here.
1007 ;;;###tramp-autoload
1008 (defvar tramp-foreign-file-name-handler-alist nil
1009 "Alist of elements (FUNCTION . HANDLER) for foreign methods handled specially.
1010 If (FUNCTION FILENAME) returns non-nil, then all I/O on that file is done by
1013 ;;; Internal functions which must come first:
1015 ;; Conversion functions between external representation and
1016 ;; internal data structure. Convenience functions for internal
1019 (defun tramp-file-name-p (vec)
1020 "Check, whether VEC is a Tramp object."
1021 (and (vectorp vec) (= 4 (length vec))))
1023 (defun tramp-file-name-method (vec)
1024 "Return method component of VEC."
1025 (and (tramp-file-name-p vec) (aref vec 0)))
1027 (defun tramp-file-name-user (vec)
1028 "Return user component of VEC."
1029 (and (tramp-file-name-p vec) (aref vec 1)))
1031 (defun tramp-file-name-host (vec)
1032 "Return host component of VEC."
1033 (and (tramp-file-name-p vec) (aref vec 2)))
1035 (defun tramp-file-name-localname (vec)
1036 "Return localname component of VEC."
1037 (and (tramp-file-name-p vec) (aref vec 3)))
1039 ;; The user part of a Tramp file name vector can be of kind
1040 ;; "user%domain". Sometimes, we must extract these parts.
1041 (defun tramp-file-name-real-user (vec)
1042 "Return the user name of VEC without domain."
1044 (let ((user (tramp-file-name-user vec)))
1045 (if (and (stringp user)
1046 (string-match tramp-user-with-domain-regexp user))
1047 (match-string 1 user)
1050 (defun tramp-file-name-domain (vec)
1051 "Return the domain name of VEC."
1053 (let ((user (tramp-file-name-user vec)))
1055 (string-match tramp-user-with-domain-regexp user)
1056 (match-string 2 user)))))
1058 ;; The host part of a Tramp file name vector can be of kind
1059 ;; "host#port". Sometimes, we must extract these parts.
1060 (defun tramp-file-name-real-host (vec)
1061 "Return the host name of VEC without port."
1063 (let ((host (tramp-file-name-host vec)))
1064 (if (and (stringp host)
1065 (string-match tramp-host-with-port-regexp host))
1066 (match-string 1 host)
1069 (defun tramp-file-name-port (vec)
1070 "Return the port number of VEC."
1072 (let ((method (tramp-file-name-method vec))
1073 (host (tramp-file-name-host vec)))
1074 (or (and (stringp host)
1075 (string-match tramp-host-with-port-regexp host)
1076 (string-to-number (match-string 2 host)))
1077 (tramp-get-method-parameter method 'tramp-default-port)))))
1079 ;;;###tramp-autoload
1080 (defun tramp-tramp-file-p (name)
1081 "Return t if NAME is a string with Tramp file name syntax."
1083 (and (stringp name) (string-match tramp-file-name-regexp name))))
1085 (defun tramp-find-method (method user host)
1086 "Return the right method string to use.
1087 This is METHOD, if non-nil. Otherwise, do a lookup in
1088 `tramp-default-method-alist'."
1090 (let ((choices tramp-default-method-alist)
1093 (setq item (pop choices))
1094 (when (and (string-match (or (nth 0 item) "") (or host ""))
1095 (string-match (or (nth 1 item) "") (or user "")))
1096 (setq lmethod (nth 2 item))
1097 (setq choices nil)))
1099 tramp-default-method))
1101 (defun tramp-find-user (method user host)
1102 "Return the right user string to use.
1103 This is USER, if non-nil. Otherwise, do a lookup in
1104 `tramp-default-user-alist'."
1106 (let ((choices tramp-default-user-alist)
1109 (setq item (pop choices))
1110 (when (and (string-match (or (nth 0 item) "") (or method ""))
1111 (string-match (or (nth 1 item) "") (or host "")))
1112 (setq luser (nth 2 item))
1113 (setq choices nil)))
1115 tramp-default-user))
1117 (defun tramp-find-host (method user host)
1118 "Return the right host string to use.
1119 This is HOST, if non-nil. Otherwise, it is `tramp-default-host'."
1120 (or (and (> (length host) 0) host)
1121 tramp-default-host))
1123 (defun tramp-dissect-file-name (name &optional nodefault)
1124 "Return a `tramp-file-name' structure.
1125 The structure consists of remote method, remote user, remote host
1126 and localname (file name on remote host). If NODEFAULT is
1127 non-nil, the file name parts are not expanded to their default
1130 (let ((match (string-match (nth 0 tramp-file-name-structure) name)))
1131 (unless match (error "Not a Tramp file name: %s" name))
1132 (let ((method (match-string (nth 1 tramp-file-name-structure) name))
1133 (user (match-string (nth 2 tramp-file-name-structure) name))
1134 (host (match-string (nth 3 tramp-file-name-structure) name))
1135 (localname (match-string (nth 4 tramp-file-name-structure) name)))
1137 (when (string-match tramp-prefix-ipv6-regexp host)
1138 (setq host (replace-match "" nil t host)))
1139 (when (string-match tramp-postfix-ipv6-regexp host)
1140 (setq host (replace-match "" nil t host))))
1142 (vector method user host localname)
1144 (tramp-find-method method user host)
1145 (tramp-find-user method user host)
1146 (tramp-find-host method user host)
1149 (defun tramp-buffer-name (vec)
1150 "A name for the connection buffer VEC."
1151 ;; We must use `tramp-file-name-real-host', because for gateway
1152 ;; methods the default port will be expanded later on, which would
1154 (let ((method (tramp-file-name-method vec))
1155 (user (tramp-file-name-user vec))
1156 (host (tramp-file-name-real-host vec)))
1157 (if (not (zerop (length user)))
1158 (format "*tramp/%s %s@%s*" method user host)
1159 (format "*tramp/%s %s*" method host))))
1161 (defun tramp-make-tramp-file-name (method user host localname)
1162 "Constructs a Tramp file name from METHOD, USER, HOST and LOCALNAME."
1163 (concat tramp-prefix-format
1164 (when (not (zerop (length method)))
1165 (concat method tramp-postfix-method-format))
1166 (when (not (zerop (length user)))
1167 (concat user tramp-postfix-user-format))
1169 (if (string-match tramp-ipv6-regexp host)
1170 (concat tramp-prefix-ipv6-format host tramp-postfix-ipv6-format)
1172 tramp-postfix-host-format
1173 (when localname localname)))
1175 (defun tramp-completion-make-tramp-file-name (method user host localname)
1176 "Constructs a Tramp file name from METHOD, USER, HOST and LOCALNAME.
1177 It must not be a complete Tramp file name, but as long as there are
1178 necessary only. This function will be used in file name completion."
1179 (concat tramp-prefix-format
1180 (when (not (zerop (length method)))
1181 (concat method tramp-postfix-method-format))
1182 (when (not (zerop (length user)))
1183 (concat user tramp-postfix-user-format))
1184 (when (not (zerop (length host)))
1186 (if (string-match tramp-ipv6-regexp host)
1188 tramp-prefix-ipv6-format host tramp-postfix-ipv6-format)
1190 tramp-postfix-host-format))
1191 (when localname localname)))
1193 (defun tramp-get-buffer (vec)
1194 "Get the connection buffer to be used for VEC."
1195 (or (get-buffer (tramp-buffer-name vec))
1196 (with-current-buffer (get-buffer-create (tramp-buffer-name vec))
1197 (setq buffer-undo-list t)
1198 (setq default-directory
1199 (tramp-make-tramp-file-name
1200 (tramp-file-name-method vec)
1201 (tramp-file-name-user vec)
1202 (tramp-file-name-host vec)
1206 (defun tramp-get-connection-buffer (vec)
1207 "Get the connection buffer to be used for VEC.
1208 In case a second asynchronous communication has been started, it is different
1209 from `tramp-get-buffer'."
1210 (or (tramp-get-connection-property vec "process-buffer" nil)
1211 (tramp-get-buffer vec)))
1213 (defun tramp-get-connection-name (vec)
1214 "Get the connection name to be used for VEC.
1215 In case a second asynchronous communication has been started, it is different
1216 from the default one."
1217 (or (tramp-get-connection-property vec "process-name" nil)
1218 (tramp-buffer-name vec)))
1220 (defun tramp-get-connection-process (vec)
1221 "Get the connection process to be used for VEC.
1222 In case a second asynchronous communication has been started, it is different
1223 from the default one."
1224 (get-process (tramp-get-connection-name vec)))
1226 (defun tramp-debug-buffer-name (vec)
1227 "A name for the debug buffer for VEC."
1228 ;; We must use `tramp-file-name-real-host', because for gateway
1229 ;; methods the default port will be expanded later on, which would
1231 (let ((method (tramp-file-name-method vec))
1232 (user (tramp-file-name-user vec))
1233 (host (tramp-file-name-real-host vec)))
1234 (if (not (zerop (length user)))
1235 (format "*debug tramp/%s %s@%s*" method user host)
1236 (format "*debug tramp/%s %s*" method host))))
1238 (defconst tramp-debug-outline-regexp
1239 "[0-9]+:[0-9]+:[0-9]+\\.[0-9]+ [a-z0-9-]+ (\\([0-9]+\\)) #"
1240 "Used for highlighting Tramp debug buffers in `outline-mode'.")
1242 (defun tramp-debug-outline-level ()
1243 "Return the depth to which a statement is nested in the outline.
1244 Point must be at the beginning of a header line.
1246 The outline level is equal to the verbosity of the Tramp message."
1247 (1+ (string-to-number (match-string 1))))
1249 (defun tramp-get-debug-buffer (vec)
1250 "Get the debug buffer for VEC."
1251 (with-current-buffer
1252 (get-buffer-create (tramp-debug-buffer-name vec))
1254 (setq buffer-undo-list t)
1255 ;; Activate `outline-mode'. This runs `text-mode-hook' and
1256 ;; `outline-mode-hook'. We must prevent that local processes
1257 ;; die. Yes: I've seen `flyspell-mode', which starts "ispell".
1258 ;; Furthermore, `outline-regexp' must have the correct value
1259 ;; already, because it is used by `font-lock-compile-keywords'.
1260 (let ((default-directory (tramp-compat-temporary-file-directory))
1261 (outline-regexp tramp-debug-outline-regexp))
1263 (set (make-local-variable 'outline-regexp) tramp-debug-outline-regexp)
1264 (set (make-local-variable 'outline-level) 'tramp-debug-outline-level))
1267 (defsubst tramp-debug-message (vec fmt-string &rest args)
1268 "Append message to debug buffer.
1269 Message is formatted with FMT-STRING as control string and the remaining
1270 ARGS to actually emit the message (if applicable)."
1271 (when (get-buffer (tramp-buffer-name vec))
1272 (with-current-buffer (tramp-get-debug-buffer vec)
1273 (goto-char (point-max))
1278 ";; %sEmacs: %s Tramp: %s -*- mode: outline; -*-"
1279 (if (featurep 'sxemacs) "SX" (if (featurep 'xemacs) "X" "GNU "))
1280 emacs-version tramp-version)))
1284 (let ((now (current-time)))
1285 (insert (format-time-string "%T." now))
1286 (insert (format "%06d " (nth 2 now))))
1287 ;; Calling function.
1288 (let ((btn 1) btf fn)
1290 (setq btf (nth 1 (backtrace-frame btn)))
1294 (setq fn (symbol-name btf))
1295 (unless (and (string-match "^tramp" fn)
1297 "^tramp\\(-debug\\)?\\(-message\\|-error\\|-compat\\(-funcall\\|-with-temp-message\\)\\)$"
1300 (setq btn (1+ btn))))
1301 ;; The following code inserts filename and line number.
1302 ;; Should be deactivated by default, because it is time
1304 ; (let ((ffn (find-function-noselect (intern fn))))
1308 ; (file-name-nondirectory (buffer-file-name (car ffn)))
1309 ; (with-current-buffer (car ffn)
1310 ; (1+ (count-lines (point-min) (cdr ffn)))))))
1311 (insert (format "%s " fn)))
1313 (insert (apply 'format fmt-string args)))))
1315 (defvar tramp-message-show-message t
1316 "Show Tramp message in the minibuffer.
1317 This variable is used to disable messages from `tramp-error'.
1318 The messages are visible anyway, because an error is raised.")
1320 (defsubst tramp-message (vec-or-proc level fmt-string &rest args)
1321 "Emit a message depending on verbosity level.
1322 VEC-OR-PROC identifies the Tramp buffer to use. It can be either a
1323 vector or a process. LEVEL says to be quiet if `tramp-verbose' is
1324 less than LEVEL. The message is emitted only if `tramp-verbose' is
1325 greater than or equal to LEVEL.
1327 The message is also logged into the debug buffer when `tramp-verbose'
1328 is greater than or equal 4.
1330 Calls functions `message' and `tramp-debug-message' with FMT-STRING as
1331 control string and the remaining ARGS to actually emit the message (if
1334 (when (<= level tramp-verbose)
1335 ;; Match data must be preserved!
1337 ;; Display only when there is a minimum level.
1338 (when (and tramp-message-show-message (<= level 3))
1344 ((= level 2) "Warning: ")
1348 ;; Log only when there is a minimum level.
1349 (when (>= tramp-verbose 4)
1350 (when (and vec-or-proc
1351 (processp vec-or-proc)
1352 (buffer-name (process-buffer vec-or-proc)))
1353 (with-current-buffer (process-buffer vec-or-proc)
1354 ;; Translate proc to vec.
1355 (setq vec-or-proc (tramp-dissect-file-name default-directory))))
1356 (when (and vec-or-proc (vectorp vec-or-proc))
1357 (apply 'tramp-debug-message
1359 (concat (format "(%d) # " level) fmt-string)
1362 (defsubst tramp-error (vec-or-proc signal fmt-string &rest args)
1364 VEC-OR-PROC identifies the connection to use, SIGNAL is the
1365 signal identifier to be raised, remaining args passed to
1366 `tramp-message'. Finally, signal SIGNAL is raised."
1367 (let (tramp-message-show-message)
1370 (error-message-string
1372 (get signal 'error-message)
1373 (apply 'format fmt-string args))))
1374 (signal signal (list (apply 'format fmt-string args)))))
1376 (defsubst tramp-error-with-buffer
1377 (buffer vec-or-proc signal fmt-string &rest args)
1378 "Emit an error, and show BUFFER.
1379 If BUFFER is nil, show the connection buffer. Wait for 30\", or until
1380 an input event arrives. The other arguments are passed to `tramp-error'."
1381 (save-window-excursion
1383 (apply 'tramp-error vec-or-proc signal fmt-string args)
1384 (when (and vec-or-proc
1385 (not (zerop tramp-verbose))
1386 (not (tramp-completion-mode-p)))
1387 (let ((enable-recursive-minibuffers t))
1389 (or (and (bufferp buffer) buffer)
1390 (and (processp vec-or-proc) (process-buffer vec-or-proc))
1391 (tramp-get-buffer vec-or-proc)))
1394 (defmacro with-parsed-tramp-file-name (filename var &rest body)
1395 "Parse a Tramp filename and make components available in the body.
1397 First arg FILENAME is evaluated and dissected into its components.
1398 Second arg VAR is a symbol. It is used as a variable name to hold
1399 the filename structure. It is also used as a prefix for the variables
1400 holding the components. For example, if VAR is the symbol `foo', then
1401 `foo' will be bound to the whole structure, `foo-method' will be bound to
1402 the method component, and so on for `foo-user', `foo-host', `foo-localname'.
1404 Remaining args are Lisp expressions to be evaluated (inside an implicit
1407 If VAR is nil, then we bind `v' to the structure and `method', `user',
1408 `host', `localname' to the components."
1409 `(let* ((,(or var 'v) (tramp-dissect-file-name ,filename))
1410 (,(if var (intern (concat (symbol-name var) "-method")) 'method)
1411 (tramp-file-name-method ,(or var 'v)))
1412 (,(if var (intern (concat (symbol-name var) "-user")) 'user)
1413 (tramp-file-name-user ,(or var 'v)))
1414 (,(if var (intern (concat (symbol-name var) "-host")) 'host)
1415 (tramp-file-name-host ,(or var 'v)))
1416 (,(if var (intern (concat (symbol-name var) "-localname")) 'localname)
1417 (tramp-file-name-localname ,(or var 'v))))
1420 (put 'with-parsed-tramp-file-name 'lisp-indent-function 2)
1421 (put 'with-parsed-tramp-file-name 'edebug-form-spec '(form symbolp body))
1422 (tramp-compat-font-lock-add-keywords
1423 'emacs-lisp-mode '("\\<with-parsed-tramp-file-name\\>"))
1425 (defun tramp-progress-reporter-update (reporter &optional value)
1426 (let* ((parameters (cdr reporter))
1427 (message (aref parameters 3)))
1428 (when (string-match message (or (current-message) ""))
1429 (tramp-compat-funcall 'progress-reporter-update reporter value))))
1431 (defmacro with-progress-reporter (vec level message &rest body)
1432 "Executes BODY, spinning a progress reporter with MESSAGE.
1433 If LEVEL does not fit for visible messages, or if this is a
1434 nested call of the macro, there are only traces without a visible
1437 (tramp-message ,vec ,level "%s..." ,message)
1438 ;; We start a pulsing progress reporter after 3 seconds. Feature
1439 ;; introduced in Emacs 24.1.
1440 (when (and tramp-message-show-message
1441 ;; Display only when there is a minimum level.
1442 (<= ,level (min tramp-verbose 3)))
1444 (setq pr (tramp-compat-funcall 'make-progress-reporter ,message)
1446 (run-at-time 3 0.1 'tramp-progress-reporter-update pr)))))
1448 ;; Execute the body. Unset `tramp-message-show-message' when
1449 ;; the timer object is created, in order to suppress
1450 ;; concurrent timers.
1451 (let ((tramp-message-show-message
1452 (and tramp-message-show-message (not tm))))
1454 ;; Stop progress reporter.
1455 (if tm (tramp-compat-funcall 'cancel-timer tm))
1456 (tramp-message ,vec ,level "%s...done" ,message))))
1458 (put 'with-progress-reporter 'lisp-indent-function 3)
1459 (put 'with-progress-reporter 'edebug-form-spec t)
1460 (tramp-compat-font-lock-add-keywords
1461 'emacs-lisp-mode '("\\<with-progress-reporter\\>"))
1463 (eval-and-compile ;; Silence compiler.
1464 (if (memq system-type '(cygwin windows-nt))
1465 (defun tramp-drop-volume-letter (name)
1466 "Cut off unnecessary drive letter from file NAME.
1467 The functions `tramp-*-handle-expand-file-name' call `expand-file-name'
1468 locally on a remote file name. When the local system is a W32 system
1469 but the remote system is Unix, this introduces a superfluous drive
1470 letter into the file name. This function removes it."
1472 (if (string-match tramp-root-regexp name)
1473 (replace-match "/" nil t name)
1476 (defalias 'tramp-drop-volume-letter 'identity)))
1478 ;;; Config Manipulation Functions:
1480 (defun tramp-set-completion-function (method function-list)
1481 "Sets the list of completion functions for METHOD.
1482 FUNCTION-LIST is a list of entries of the form (FUNCTION FILE).
1483 The FUNCTION is intended to parse FILE according its syntax.
1484 It might be a predefined FUNCTION, or a user defined FUNCTION.
1485 Predefined FUNCTIONs are `tramp-parse-rhosts', `tramp-parse-shosts',
1486 `tramp-parse-sconfig', `tramp-parse-hosts', `tramp-parse-passwd',
1487 and `tramp-parse-netrc'.
1491 (tramp-set-completion-function
1493 '((tramp-parse-sconfig \"/etc/ssh_config\")
1494 (tramp-parse-sconfig \"~/.ssh/config\")))"
1496 (let ((r function-list)
1498 (setq tramp-completion-function-alist
1499 (delete (assoc method tramp-completion-function-alist)
1500 tramp-completion-function-alist))
1503 ;; Remove double entries.
1504 (when (member (car v) (cdr v))
1505 (setcdr v (delete (car v) (cdr v))))
1506 ;; Check for function and file or registry key.
1507 (unless (and (functionp (nth 0 (car v)))
1508 (if (string-match "^HKEY_CURRENT_USER" (nth 1 (car v)))
1509 ;; Windows registry.
1510 (and (memq system-type '(cygwin windows-nt))
1512 (tramp-compat-call-process
1513 "reg" nil nil nil "query" (nth 1 (car v)))))
1514 ;; Configuration file.
1515 (file-exists-p (nth 1 (car v)))))
1516 (setq r (delete (car v) r)))
1520 (add-to-list 'tramp-completion-function-alist
1523 (defun tramp-get-completion-function (method)
1524 "Returns a list of completion functions for METHOD.
1525 For definition of that list see `tramp-set-completion-function'."
1527 ;; Hosts visited once shall be remembered.
1528 `(tramp-parse-connection-properties ,method)
1529 ;; The method related defaults.
1530 (cdr (assoc method tramp-completion-function-alist))))
1533 ;;; Fontification of `read-file-name':
1535 ;; rfn-eshadow.el is part of Emacs 22. It is autoloaded.
1536 (defvar tramp-rfn-eshadow-overlay)
1537 (make-variable-buffer-local 'tramp-rfn-eshadow-overlay)
1539 (defun tramp-rfn-eshadow-setup-minibuffer ()
1540 "Set up a minibuffer for `file-name-shadow-mode'.
1541 Adds another overlay hiding filename parts according to Tramp's
1542 special handling of `substitute-in-file-name'."
1543 (when (symbol-value 'minibuffer-completing-file-name)
1544 (setq tramp-rfn-eshadow-overlay
1545 (tramp-compat-funcall
1547 (tramp-compat-funcall 'minibuffer-prompt-end)
1548 (tramp-compat-funcall 'minibuffer-prompt-end)))
1549 ;; Copy rfn-eshadow-overlay properties.
1550 (let ((props (tramp-compat-funcall
1551 'overlay-properties (symbol-value 'rfn-eshadow-overlay))))
1553 (tramp-compat-funcall
1554 'overlay-put tramp-rfn-eshadow-overlay (pop props) (pop props))))))
1556 (when (boundp 'rfn-eshadow-setup-minibuffer-hook)
1557 (add-hook 'rfn-eshadow-setup-minibuffer-hook
1558 'tramp-rfn-eshadow-setup-minibuffer)
1559 (add-hook 'tramp-unload-hook
1561 (remove-hook 'rfn-eshadow-setup-minibuffer-hook
1562 'tramp-rfn-eshadow-setup-minibuffer))))
1564 (defconst tramp-rfn-eshadow-update-overlay-regexp
1565 (format "[^%s/~]*\\(/\\|~\\)" tramp-postfix-host-format))
1567 (defun tramp-rfn-eshadow-update-overlay ()
1568 "Update `rfn-eshadow-overlay' to cover shadowed part of minibuffer input.
1569 This is intended to be used as a minibuffer `post-command-hook' for
1570 `file-name-shadow-mode'; the minibuffer should have already
1571 been set up by `rfn-eshadow-setup-minibuffer'."
1572 ;; In remote files name, there is a shadowing just for the local part.
1573 (let ((end (or (tramp-compat-funcall
1574 'overlay-end (symbol-value 'rfn-eshadow-overlay))
1575 (tramp-compat-funcall 'minibuffer-prompt-end))))
1578 (tramp-compat-funcall 'buffer-substring-no-properties end (point-max)))
1582 (1+ (or (string-match
1583 tramp-rfn-eshadow-update-overlay-regexp (buffer-string) end)
1586 (let ((rfn-eshadow-overlay tramp-rfn-eshadow-overlay)
1587 (rfn-eshadow-update-overlay-hook nil))
1588 (tramp-compat-funcall
1589 'move-overlay rfn-eshadow-overlay (point-max) (point-max))
1590 (tramp-compat-funcall 'rfn-eshadow-update-overlay)))))))
1592 (when (boundp 'rfn-eshadow-update-overlay-hook)
1593 (add-hook 'rfn-eshadow-update-overlay-hook
1594 'tramp-rfn-eshadow-update-overlay)
1595 (add-hook 'tramp-unload-hook
1597 (remove-hook 'rfn-eshadow-update-overlay-hook
1598 'tramp-rfn-eshadow-update-overlay))))
1600 ;; Inodes don't exist for some file systems. Therefore we must
1601 ;; generate virtual ones. Used in `find-buffer-visiting'. The method
1602 ;; applied might be not so efficient (Ange-FTP uses hashes). But
1603 ;; performance isn't the major issue given that file transfer will
1605 (defvar tramp-inodes nil
1606 "Keeps virtual inodes numbers.")
1608 ;; Devices must distinguish physical file systems. The device numbers
1609 ;; provided by "lstat" aren't unique, because we operate on different hosts.
1610 ;; So we use virtual device numbers, generated by Tramp. Both Ange-FTP and
1611 ;; EFS use device number "-1". In order to be different, we use device number
1612 ;; (-1 . x), whereby "x" is unique for a given (method user host).
1613 (defvar tramp-devices nil
1614 "Keeps virtual device numbers.")
1616 (defun tramp-default-file-modes (filename)
1617 "Return file modes of FILENAME as integer.
1618 If the file modes of FILENAME cannot be determined, return the
1619 value of `default-file-modes', without execute permissions."
1620 (or (file-modes filename)
1621 (logand (default-file-modes) (tramp-compat-octal-to-decimal "0666"))))
1623 (defun tramp-replace-environment-variables (filename)
1624 "Replace environment variables in FILENAME.
1625 Return the string with the replaced variables."
1627 (let ((idx (string-match "$\\(\\w+\\)" filename)))
1628 ;; `$' is coded as `$$'.
1630 (or (zerop idx) (not (eq ?$ (aref filename (1- idx)))))
1631 (getenv (match-string 1 filename)))
1634 (substitute-in-file-name (match-string 0 filename))
1638 ;; In XEmacs, electricity is implemented via a key map for ?/ and ?~,
1639 ;; which calls corresponding functions (see minibuf.el).
1640 (when (fboundp 'minibuffer-electric-separator)
1645 (around ,(intern (format "tramp-advice-%s" x)) activate)
1646 "Invoke `substitute-in-file-name' for Tramp files."
1647 (if (and (symbol-value 'minibuffer-electric-file-name-behavior)
1648 (tramp-tramp-file-p (buffer-substring)))
1649 ;; We don't need to handle `last-input-event', because
1650 ;; due to the key map we know it must be ?/ or ?~.
1651 (let ((s (concat (buffer-substring (point-min) (point))
1652 (string last-command-char))))
1653 (delete-region (point-min) (point))
1654 (insert (substitute-in-file-name s))
1655 (setq ad-return-value last-command-char))
1661 (ad-remove-advice ',x 'around ',(intern (format "tramp-advice-%s" x)))
1662 (ad-activate ',x)))))
1664 '(minibuffer-electric-separator
1665 minibuffer-electric-tilde)))
1667 (defun tramp-find-file-name-coding-system-alist (filename tmpname)
1668 "Like `find-operation-coding-system' for Tramp filenames.
1669 Tramp's `insert-file-contents' and `write-region' work over
1670 temporary file names. If `file-coding-system-alist' contains an
1671 expression, which matches more than the file name suffix, the
1672 coding system might not be determined. This function repairs it."
1674 (dolist (elt file-coding-system-alist result)
1675 (when (and (consp elt) (string-match (car elt) filename))
1676 ;; We found a matching entry in `file-coding-system-alist'.
1677 ;; So we add a similar entry, but with the temporary file name
1680 'result (cons (regexp-quote tmpname) (cdr elt)) 'append)))))
1683 (progn (defun tramp-run-real-handler (operation args)
1684 "Invoke normal file name handler for OPERATION.
1685 First arg specifies the OPERATION, second arg is a list of arguments to
1686 pass to the OPERATION."
1687 (let* ((inhibit-file-name-handlers
1688 `(tramp-file-name-handler
1689 tramp-vc-file-name-handler
1690 tramp-completion-file-name-handler
1691 cygwin-mount-name-hook-function
1692 cygwin-mount-map-drive-hook-function
1694 ,(and (eq inhibit-file-name-operation operation)
1695 inhibit-file-name-handlers)))
1696 (inhibit-file-name-operation operation))
1697 (apply operation args))))
1700 (progn (defun tramp-completion-run-real-handler (operation args)
1701 "Invoke `tramp-file-name-handler' for OPERATION.
1702 First arg specifies the OPERATION, second arg is a list of arguments to
1703 pass to the OPERATION."
1704 (let* ((inhibit-file-name-handlers
1705 `(tramp-completion-file-name-handler
1706 cygwin-mount-name-hook-function
1707 cygwin-mount-map-drive-hook-function
1709 ,(and (eq inhibit-file-name-operation operation)
1710 inhibit-file-name-handlers)))
1711 (inhibit-file-name-operation operation))
1712 (apply operation args))))
1714 ;; We handle here all file primitives. Most of them have the file
1715 ;; name as first parameter; nevertheless we check for them explicitly
1716 ;; in order to be signaled if a new primitive appears. This
1717 ;; scenario is needed because there isn't a way to decide by
1718 ;; syntactical means whether a foreign method must be called. It would
1719 ;; ease the life if `file-name-handler-alist' would support a decision
1720 ;; function as well but regexp only.
1721 (defun tramp-file-name-for-operation (operation &rest args)
1722 "Return file name related to OPERATION file primitive.
1723 ARGS are the arguments OPERATION has been called with."
1725 ;; FILE resp DIRECTORY.
1727 (list 'access-file 'byte-compiler-base-file-name 'delete-directory
1728 'delete-file 'diff-latest-backup-file 'directory-file-name
1729 'directory-files 'directory-files-and-attributes
1730 'dired-compress-file 'dired-uncache
1731 'file-accessible-directory-p 'file-attributes
1732 'file-directory-p 'file-executable-p 'file-exists-p
1733 'file-local-copy 'file-remote-p 'file-modes
1734 'file-name-as-directory 'file-name-directory
1735 'file-name-nondirectory 'file-name-sans-versions
1736 'file-ownership-preserved-p 'file-readable-p
1737 'file-regular-p 'file-symlink-p 'file-truename
1738 'file-writable-p 'find-backup-file-name 'find-file-noselect
1739 'get-file-buffer 'insert-directory 'insert-file-contents
1740 'load 'make-directory 'make-directory-internal
1741 'set-file-modes 'substitute-in-file-name
1742 'unhandled-file-name-directory 'vc-registered
1746 'file-selinux-context 'set-file-selinux-context
1748 'abbreviate-file-name 'create-file-buffer
1749 'dired-file-modtime 'dired-make-compressed-filename
1750 'dired-recursive-delete-directory 'dired-set-file-modtime
1751 'dired-shell-unhandle-file-name 'dired-uucode-file
1752 'insert-file-contents-literally 'make-temp-name 'recover-file
1753 'vm-imap-check-mail 'vm-pop-check-mail 'vm-spool-check-mail))
1754 (if (file-name-absolute-p (nth 0 args))
1756 (expand-file-name (nth 0 args))))
1757 ;; FILE DIRECTORY resp FILE1 FILE2.
1759 (list 'add-name-to-file 'copy-file 'expand-file-name
1760 'file-name-all-completions 'file-name-completion
1761 'file-newer-than-file-p 'make-symbolic-link 'rename-file
1765 'dired-make-relative-symlink
1766 'vm-imap-move-mail 'vm-pop-move-mail 'vm-spool-move-mail))
1769 ((string-match tramp-file-name-regexp (nth 0 args)) (nth 0 args))
1770 ((string-match tramp-file-name-regexp (nth 1 args)) (nth 1 args))
1771 (t (buffer-file-name (current-buffer))))))
1773 ((eq operation 'write-region)
1777 (list 'set-visited-file-modtime 'verify-visited-file-modtime
1779 'make-auto-save-file-name
1783 (if (bufferp (nth 0 args)) (nth 0 args) (current-buffer))))
1786 (list ;; not in Emacs 23+.
1795 'dired-print-file 'dired-shell-call-process
1797 'executable-find 'start-process
1798 'call-process 'call-process-region))
1800 ;; Unknown file primitive.
1801 (t (error "unknown file I/O primitive: %s" operation))))
1803 (defun tramp-find-foreign-file-name-handler (filename)
1804 "Return foreign file name handler if exists."
1805 (when (tramp-tramp-file-p filename)
1806 (let ((v (tramp-dissect-file-name filename t))
1807 (handler tramp-foreign-file-name-handler-alist)
1809 ;; When we are not fully sure that filename completion is safe,
1810 ;; we should not return a handler.
1811 (when (or (tramp-file-name-method v) (tramp-file-name-user v)
1812 (and (tramp-file-name-host v)
1813 (not (member (tramp-file-name-host v)
1814 (mapcar 'car tramp-methods))))
1815 (not (tramp-completion-mode-p)))
1817 (setq elt (car handler)
1818 handler (cdr handler))
1819 (when (funcall (car elt) filename)
1826 (defun tramp-file-name-handler (operation &rest args)
1827 "Invoke Tramp file name handler.
1828 Falls back to normal file name handler if no Tramp file name handler exists."
1832 (tramp-replace-environment-variables
1833 (apply 'tramp-file-name-for-operation operation args)))
1834 (completion (tramp-completion-mode-p))
1835 (foreign (tramp-find-foreign-file-name-handler filename)))
1836 (with-parsed-tramp-file-name filename nil
1837 ;; Call the backend function.
1840 (apply foreign operation args)
1842 ;; Trace, that somebody has interrupted the operation.
1844 (let (tramp-message-show-message)
1846 v 1 "Interrupt received in operation %s"
1847 (append (list operation) args)))
1848 ;; Propagate the quit signal.
1849 (signal (car err) (cdr err)))
1851 ;; When we are in completion mode, some failed
1852 ;; operations shall return at least a default value
1853 ;; in order to give the user a chance to correct the
1854 ;; file name in the minibuffer.
1857 ((and completion (zerop (length localname))
1858 (memq operation '(file-exists-p file-directory-p)))
1860 ((and completion (zerop (length localname))
1862 '(expand-file-name file-name-as-directory)))
1864 ;; Propagate the error.
1865 (t (signal (car err) (cdr err))))))
1867 ;; Nothing to do for us.
1868 (tramp-run-real-handler operation args)))))
1870 ;; When `tramp-mode' is not enabled, we don't do anything.
1871 (tramp-run-real-handler operation args)))
1873 ;; In Emacs, there is some concurrency due to timers. If a timer
1874 ;; interrupts Tramp and wishes to use the same connection buffer as
1875 ;; the "main" Emacs, then garbage might occur in the connection
1876 ;; buffer. Therefore, we need to make sure that a timer does not use
1877 ;; the same connection buffer as the "main" Emacs. We implement a
1878 ;; cheap global lock, instead of locking each connection buffer
1879 ;; separately. The global lock is based on two variables,
1880 ;; `tramp-locked' and `tramp-locker'. `tramp-locked' is set to true
1881 ;; (with setq) to indicate a lock. But Tramp also calls itself during
1882 ;; processing of a single file operation, so we need to allow
1883 ;; recursive calls. That's where the `tramp-locker' variable comes in
1884 ;; -- it is let-bound to t during the execution of the current
1885 ;; handler. So if `tramp-locked' is t and `tramp-locker' is also t,
1886 ;; then we should just proceed because we have been called
1887 ;; recursively. But if `tramp-locker' is nil, then we are a timer
1888 ;; interrupting the "main" Emacs, and then we signal an error.
1890 (defvar tramp-locked nil
1891 "If non-nil, then Tramp is currently busy.
1892 Together with `tramp-locker', this implements a locking mechanism
1893 preventing reentrant calls of Tramp.")
1895 (defvar tramp-locker nil
1896 "If non-nil, then a caller has locked Tramp.
1897 Together with `tramp-locked', this implements a locking mechanism
1898 preventing reentrant calls of Tramp.")
1901 (progn (defun tramp-completion-file-name-handler (operation &rest args)
1902 "Invoke Tramp file name completion handler.
1903 Falls back to normal file name handler if no Tramp file name handler exists."
1904 ;; We bind `directory-sep-char' here for XEmacs on Windows, which
1905 ;; would otherwise use backslash.
1906 (let ((directory-sep-char ?/)
1907 (fn (assoc operation tramp-completion-file-name-handler-alist)))
1909 ;; When `tramp-mode' is not enabled, we don't do anything.
1911 ;; For other syntaxes than `sep', the regexp matches many common
1912 ;; situations where the user doesn't actually want to use Tramp.
1913 ;; So to avoid autoloading Tramp after typing just "/s", we
1914 ;; disable this part of the completion, unless the user implicitly
1915 ;; indicated his interest in using a fancier completion system.
1916 (or (eq tramp-syntax 'sep)
1917 (featurep 'tramp) ;; If it's loaded, we may as well use it.
1918 ;; `partial-completion-mode' does not exist in XEmacs.
1919 ;; It is obsoleted with Emacs 24.1.
1920 (and (boundp 'partial-completion-mode)
1921 (symbol-value 'partial-completion-mode))
1922 ;; FIXME: These may have been loaded even if the user never
1923 ;; intended to use them.
1925 (featurep 'icicles)))
1926 (save-match-data (apply (cdr fn) args))
1927 (tramp-completion-run-real-handler operation args)))))
1930 (progn (defun tramp-register-file-name-handlers ()
1931 "Add Tramp file name handlers to `file-name-handler-alist'."
1932 ;; Remove autoloaded handlers from file name handler alist. Useful,
1933 ;; if `tramp-syntax' has been changed.
1934 (let ((a1 (rassq 'tramp-file-name-handler file-name-handler-alist)))
1935 (setq file-name-handler-alist (delq a1 file-name-handler-alist)))
1937 'tramp-completion-file-name-handler file-name-handler-alist)))
1938 (setq file-name-handler-alist (delq a1 file-name-handler-alist)))
1939 ;; Add the handlers.
1940 (add-to-list 'file-name-handler-alist
1941 (cons tramp-file-name-regexp 'tramp-file-name-handler))
1942 (put 'tramp-file-name-handler 'safe-magic t)
1943 (add-to-list 'file-name-handler-alist
1944 (cons tramp-completion-file-name-regexp
1945 'tramp-completion-file-name-handler))
1946 (put 'tramp-completion-file-name-handler 'safe-magic t)
1947 ;; If jka-compr or epa-file are already loaded, move them to the
1948 ;; front of `file-name-handler-alist'.
1949 (dolist (fnh '(epa-file-handler jka-compr-handler))
1950 (let ((entry (rassoc fnh file-name-handler-alist)))
1952 (setq file-name-handler-alist
1953 (cons entry (delete entry file-name-handler-alist))))))))
1955 ;; `tramp-file-name-handler' must be registered before evaluation of
1956 ;; site-start and init files, because there might exist remote files
1957 ;; already, f.e. files kept via recentf-mode.
1959 (tramp-register-file-name-handlers)
1961 (defun tramp-exists-file-name-handler (operation &rest args)
1962 "Check, whether OPERATION runs a file name handler."
1963 ;; The file name handler is determined on base of either an
1964 ;; argument, `buffer-file-name', or `default-directory'.
1966 (let* ((buffer-file-name "/")
1967 (default-directory "/")
1968 (fnha file-name-handler-alist)
1969 (check-file-name-operation operation)
1970 (file-name-handler-alist
1973 (lambda (operation &rest args)
1974 "Returns OPERATION if it is the one to be checked."
1975 (if (equal check-file-name-operation operation)
1977 (let ((file-name-handler-alist fnha))
1978 (apply operation args))))))))
1979 (equal (apply operation args) operation))))
1982 (defun tramp-unload-file-name-handlers ()
1983 (setq file-name-handler-alist
1984 (delete (rassoc 'tramp-file-name-handler
1985 file-name-handler-alist)
1986 (delete (rassoc 'tramp-completion-file-name-handler
1987 file-name-handler-alist)
1988 file-name-handler-alist))))
1990 (add-hook 'tramp-unload-hook 'tramp-unload-file-name-handlers)
1992 ;;; File name handler functions for completion mode:
1994 (defvar tramp-completion-mode nil
1995 "If non-nil, external packages signal that they are in file name completion.
1997 This is necessary, because Tramp uses a heuristic depending on last
1998 input event. This fails when external packages use other characters
1999 but <TAB>, <SPACE> or ?\\? for file name completion. This variable
2000 should never be set globally, the intention is to let-bind it.")
2002 ;; Necessary because `tramp-file-name-regexp-unified' and
2003 ;; `tramp-completion-file-name-regexp-unified' aren't different. If
2004 ;; nil, `tramp-completion-run-real-handler' is called (i.e. forwarding
2005 ;; to `tramp-file-name-handler'). Otherwise, it takes
2006 ;; `tramp-run-real-handler'. Using `last-input-event' is a little bit
2007 ;; risky, because completing a file might require loading other files,
2008 ;; like "~/.netrc", and for them it shouldn't be decided based on that
2009 ;; variable. On the other hand, those files shouldn't have partial
2010 ;; Tramp file name syntax. Maybe another variable should be introduced
2011 ;; overwriting this check in such cases. Or we change Tramp file name
2012 ;; syntax in order to avoid ambiguities, like in XEmacs ...
2013 ;;;###tramp-autoload
2014 (defun tramp-completion-mode-p ()
2015 "Check, whether method / user name / host name completion is active."
2017 ;; Signal from outside. `non-essential' has been introduced in Emacs 24.
2018 (and (boundp 'non-essential) (symbol-value 'non-essential))
2019 tramp-completion-mode
2021 (equal last-input-event 'tab)
2022 (and (natnump last-input-event)
2024 ;; ?\t has event-modifier 'control.
2025 (equal last-input-event ?\t)
2026 (and (not (event-modifiers last-input-event))
2027 (or (equal last-input-event ?\?)
2028 (equal last-input-event ?\ )))))
2030 (and (featurep 'xemacs)
2031 ;; `last-input-event' might be nil.
2032 (not (null last-input-event))
2033 ;; `last-input-event' may have no character approximation.
2034 (tramp-compat-funcall 'event-to-character last-input-event)
2036 ;; ?\t has event-modifier 'control.
2038 (tramp-compat-funcall 'event-to-character last-input-event) ?\t)
2039 (and (not (event-modifiers last-input-event))
2041 (tramp-compat-funcall 'event-to-character last-input-event)
2044 (tramp-compat-funcall 'event-to-character last-input-event)
2047 (defun tramp-connectable-p (filename)
2048 "Check, whether it is possible to connect the remote host w/o side-effects.
2049 This is true, if either the remote host is already connected, or if we are
2050 not in completion mode."
2051 (and (tramp-tramp-file-p filename)
2052 (with-parsed-tramp-file-name filename nil
2053 (or (get-buffer (tramp-buffer-name v))
2054 (not (tramp-completion-mode-p))))))
2056 ;; Method, host name and user name completion.
2057 ;; `tramp-completion-dissect-file-name' returns a list of
2058 ;; tramp-file-name structures. For all of them we return possible completions.
2060 (defun tramp-completion-handle-file-name-all-completions (filename directory)
2061 "Like `file-name-all-completions' for partial Tramp files."
2063 (let* ((fullname (tramp-drop-volume-letter
2064 (expand-file-name filename directory)))
2065 ;; Possible completion structures.
2066 (v (tramp-completion-dissect-file-name fullname))
2070 (let* ((car (car v))
2071 (method (tramp-file-name-method car))
2072 (user (tramp-file-name-user car))
2073 (host (tramp-file-name-host car))
2074 (localname (tramp-file-name-localname car))
2075 (m (tramp-find-method method user host))
2076 (tramp-current-user user) ; see `tramp-parse-passwd'
2079 (unless localname ;; Nothing to complete.
2083 ;; Method dependent user / host combinations.
2087 (setq all-user-hosts
2088 (append all-user-hosts
2089 (funcall (nth 0 x) (nth 1 x)))))
2090 (tramp-get-completion-function m))
2096 (tramp-get-completion-user-host
2097 method user host (nth 0 x) (nth 1 x)))
2098 (delq nil all-user-hosts)))))
2100 ;; Possible methods.
2102 (append result (tramp-get-completion-methods m)))))
2106 ;; Unify list, remove nil elements.
2108 (let ((car (car result)))
2112 (substring car (length (tramp-drop-volume-letter directory)))))
2113 (setq result (cdr result))))
2115 ;; Complete local parts.
2119 (apply (if (tramp-connectable-p fullname)
2120 'tramp-completion-run-real-handler
2121 'tramp-run-real-handler)
2122 'file-name-all-completions (list (list filename directory)))))))
2124 ;; Method, host name and user name completion for a file.
2126 (defun tramp-completion-handle-file-name-completion
2127 (filename directory &optional predicate)
2128 "Like `file-name-completion' for Tramp files."
2131 (mapcar 'list (file-name-all-completions filename directory))
2132 (when (and predicate
2133 (tramp-connectable-p (expand-file-name filename directory)))
2134 (lambda (x) (funcall predicate (expand-file-name (car x) directory))))))
2136 ;; I misuse a little bit the tramp-file-name structure in order to handle
2137 ;; completion possibilities for partial methods / user names / host names.
2138 ;; Return value is a list of tramp-file-name structures according to possible
2139 ;; completions. If "localname" is non-nil it means there
2140 ;; shouldn't be a completion anymore.
2142 ;; Expected results:
2144 ;; "/x" "/[x" "/x@" "/[x@" "/x@y" "/[x@y"
2145 ;; [nil nil "x" nil] [nil "x" nil nil] [nil "x" "y" nil]
2146 ;; [nil "x" nil nil]
2147 ;; ["x" nil nil nil]
2149 ;; "/x:" "/x:y" "/x:y:"
2150 ;; [nil nil "x" ""] [nil nil "x" "y"] ["x" nil "y" ""]
2152 ;; ["x" nil "" nil] ["x" nil "y" nil]
2153 ;; ["x" "" nil nil] ["x" "y" nil nil]
2155 ;; "/x:y@" "/x:y@z" "/x:y@z:"
2156 ;; [nil nil "x" "y@"] [nil nil "x" "y@z"] ["x" "y" "z" ""]
2157 ;; "/[x/y@" "/[x/y@z"
2158 ;; ["x" nil "y" nil] ["x" "y" "z" nil]
2159 (defun tramp-completion-dissect-file-name (name)
2160 "Returns a list of `tramp-file-name' structures.
2161 They are collected by `tramp-completion-dissect-file-name1'."
2165 (tramp-completion-ipv6-regexp
2168 (if (zerop (length tramp-postfix-ipv6-format))
2169 tramp-postfix-host-format
2170 tramp-postfix-ipv6-format)))
2171 ;; "/method" "/[method"
2172 (tramp-completion-file-name-structure1
2173 (list (concat tramp-prefix-regexp "\\(" tramp-method-regexp x-nil "\\)$")
2176 (tramp-completion-file-name-structure2
2177 (list (concat tramp-prefix-regexp "\\(" tramp-user-regexp x-nil "\\)$")
2180 (tramp-completion-file-name-structure3
2181 (list (concat tramp-prefix-regexp "\\(" tramp-host-regexp x-nil "\\)$")
2183 ;; "/[ipv6" "/[ipv6"
2184 (tramp-completion-file-name-structure4
2185 (list (concat tramp-prefix-regexp
2186 tramp-prefix-ipv6-regexp
2187 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
2189 ;; "/user@host" "/[user@host"
2190 (tramp-completion-file-name-structure5
2191 (list (concat tramp-prefix-regexp
2192 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
2193 "\\(" tramp-host-regexp x-nil "\\)$")
2195 ;; "/user@[ipv6" "/[user@ipv6"
2196 (tramp-completion-file-name-structure6
2197 (list (concat tramp-prefix-regexp
2198 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
2199 tramp-prefix-ipv6-regexp
2200 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
2202 ;; "/method:user" "/[method/user" "/method://user"
2203 (tramp-completion-file-name-structure7
2204 (list (concat tramp-prefix-regexp
2205 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
2206 "\\(" tramp-user-regexp x-nil "\\)$")
2208 ;; "/method:host" "/[method/host" "/method://host"
2209 (tramp-completion-file-name-structure8
2210 (list (concat tramp-prefix-regexp
2211 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
2212 "\\(" tramp-host-regexp x-nil "\\)$")
2214 ;; "/method:[ipv6" "/[method/ipv6" "/method://[ipv6"
2215 (tramp-completion-file-name-structure9
2216 (list (concat tramp-prefix-regexp
2217 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
2218 tramp-prefix-ipv6-regexp
2219 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
2221 ;; "/method:user@host" "/[method/user@host" "/method://user@host"
2222 (tramp-completion-file-name-structure10
2223 (list (concat tramp-prefix-regexp
2224 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
2225 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
2226 "\\(" tramp-host-regexp x-nil "\\)$")
2228 ;; "/method:user@[ipv6" "/[method/user@ipv6" "/method://user@[ipv6"
2229 (tramp-completion-file-name-structure11
2230 (list (concat tramp-prefix-regexp
2231 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
2232 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
2233 tramp-prefix-ipv6-regexp
2234 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
2236 ;; "/method: "/method:/"
2237 (tramp-completion-file-name-structure12
2239 (if (equal tramp-syntax 'url)
2240 (concat tramp-prefix-regexp
2241 "\\(" tramp-method-regexp "\\)"
2242 "\\(" (substring tramp-postfix-method-regexp 0 1)
2243 "\\|" (substring tramp-postfix-method-regexp 1 2) "\\)"
2245 ;; Should not match if not URL syntax.
2246 (concat tramp-prefix-regexp "/$"))
2248 ;; "/method: "/method:/"
2249 (tramp-completion-file-name-structure13
2251 (if (equal tramp-syntax 'url)
2252 (concat tramp-prefix-regexp
2253 "\\(" tramp-method-regexp "\\)"
2254 "\\(" (substring tramp-postfix-method-regexp 0 1)
2255 "\\|" (substring tramp-postfix-method-regexp 1 2) "\\)"
2257 ;; Should not match if not URL syntax.
2258 (concat tramp-prefix-regexp "/$"))
2261 (mapc (lambda (regexp)
2262 (add-to-list 'result
2263 (tramp-completion-dissect-file-name1 regexp name)))
2265 tramp-completion-file-name-structure1
2266 tramp-completion-file-name-structure2
2267 tramp-completion-file-name-structure3
2268 tramp-completion-file-name-structure4
2269 tramp-completion-file-name-structure5
2270 tramp-completion-file-name-structure6
2271 tramp-completion-file-name-structure7
2272 tramp-completion-file-name-structure8
2273 tramp-completion-file-name-structure9
2274 tramp-completion-file-name-structure10
2275 tramp-completion-file-name-structure11
2276 tramp-completion-file-name-structure12
2277 tramp-completion-file-name-structure13
2278 tramp-file-name-structure))
2282 (defun tramp-completion-dissect-file-name1 (structure name)
2283 "Returns a `tramp-file-name' structure matching STRUCTURE.
2284 The structure consists of remote method, remote user,
2285 remote host and localname (filename on remote host)."
2288 (when (string-match (nth 0 structure) name)
2289 (let ((method (and (nth 1 structure)
2290 (match-string (nth 1 structure) name)))
2291 (user (and (nth 2 structure)
2292 (match-string (nth 2 structure) name)))
2293 (host (and (nth 3 structure)
2294 (match-string (nth 3 structure) name)))
2295 (localname (and (nth 4 structure)
2296 (match-string (nth 4 structure) name))))
2297 (vector method user host localname)))))
2299 ;; This function returns all possible method completions, adding the
2300 ;; trailing method delimeter.
2301 (defun tramp-get-completion-methods (partial-method)
2302 "Returns all method completions for PARTIAL-METHOD."
2306 (string-match (concat "^" (regexp-quote partial-method)) method)
2307 (tramp-completion-make-tramp-file-name method nil nil nil)))
2308 (mapcar 'car tramp-methods)))
2310 ;; Compares partial user and host names with possible completions.
2311 (defun tramp-get-completion-user-host (method partial-user partial-host user host)
2312 "Returns the most expanded string for user and host name completion.
2313 PARTIAL-USER must match USER, PARTIAL-HOST must match HOST."
2316 ((and partial-user partial-host)
2318 (string-match (concat "^" (regexp-quote partial-host)) host)
2319 (string-equal partial-user (or user partial-user)))
2320 (setq user partial-user)
2327 (and user (string-match (concat "^" (regexp-quote partial-user)) user))
2333 (and host (string-match (concat "^" (regexp-quote partial-host)) host))
2339 (unless (zerop (+ (length user) (length host)))
2340 (tramp-completion-make-tramp-file-name method user host nil)))
2342 (defun tramp-parse-rhosts (filename)
2343 "Return a list of (user host) tuples allowed to access.
2344 Either user or host may be nil."
2345 ;; On Windows, there are problems in completion when
2346 ;; `default-directory' is remote.
2347 (let ((default-directory (tramp-compat-temporary-file-directory))
2349 (when (file-readable-p filename)
2351 (insert-file-contents filename)
2352 (goto-char (point-min))
2354 (push (tramp-parse-rhosts-group) res))))
2357 (defun tramp-parse-rhosts-group ()
2358 "Return a (user host) tuple allowed to access.
2359 Either user or host may be nil."
2363 "^\\(" tramp-host-regexp "\\)"
2364 "\\([ \t]+" "\\(" tramp-user-regexp "\\)" "\\)?")))
2365 (narrow-to-region (point) (point-at-eol))
2366 (when (re-search-forward regexp nil t)
2367 (setq result (append (list (match-string 3) (match-string 1)))))
2372 (defun tramp-parse-shosts (filename)
2373 "Return a list of (user host) tuples allowed to access.
2374 User is always nil."
2375 ;; On Windows, there are problems in completion when
2376 ;; `default-directory' is remote.
2377 (let ((default-directory (tramp-compat-temporary-file-directory))
2379 (when (file-readable-p filename)
2381 (insert-file-contents filename)
2382 (goto-char (point-min))
2384 (push (tramp-parse-shosts-group) res))))
2387 (defun tramp-parse-shosts-group ()
2388 "Return a (user host) tuple allowed to access.
2389 User is always nil."
2391 (regexp (concat "^\\(" tramp-host-regexp "\\)")))
2392 (narrow-to-region (point) (point-at-eol))
2393 (when (re-search-forward regexp nil t)
2394 (setq result (list nil (match-string 1))))
2397 (> (skip-chars-forward ",") 0)
2401 (defun tramp-parse-sconfig (filename)
2402 "Return a list of (user host) tuples allowed to access.
2403 User is always nil."
2404 ;; On Windows, there are problems in completion when
2405 ;; `default-directory' is remote.
2406 (let ((default-directory (tramp-compat-temporary-file-directory))
2408 (when (file-readable-p filename)
2410 (insert-file-contents filename)
2411 (goto-char (point-min))
2413 (push (tramp-parse-sconfig-group) res))))
2416 (defun tramp-parse-sconfig-group ()
2417 "Return a (user host) tuple allowed to access.
2418 User is always nil."
2420 (regexp (concat "^[ \t]*Host[ \t]+" "\\(" tramp-host-regexp "\\)")))
2421 (narrow-to-region (point) (point-at-eol))
2422 (when (re-search-forward regexp nil t)
2423 (setq result (list nil (match-string 1))))
2426 (> (skip-chars-forward ",") 0)
2430 (defun tramp-parse-shostkeys (dirname)
2431 "Return a list of (user host) tuples allowed to access.
2432 User is always nil."
2433 ;; On Windows, there are problems in completion when
2434 ;; `default-directory' is remote.
2435 (let* ((default-directory (tramp-compat-temporary-file-directory))
2436 (regexp (concat "^key_[0-9]+_\\(" tramp-host-regexp "\\)\\.pub$"))
2437 (files (when (file-directory-p dirname) (directory-files dirname)))
2440 (when (string-match regexp (car files))
2441 (push (list nil (match-string 1 (car files))) result))
2442 (setq files (cdr files)))
2445 (defun tramp-parse-sknownhosts (dirname)
2446 "Return a list of (user host) tuples allowed to access.
2447 User is always nil."
2448 ;; On Windows, there are problems in completion when
2449 ;; `default-directory' is remote.
2450 (let* ((default-directory (tramp-compat-temporary-file-directory))
2451 (regexp (concat "^\\(" tramp-host-regexp
2452 "\\)\\.ssh-\\(dss\\|rsa\\)\\.pub$"))
2453 (files (when (file-directory-p dirname) (directory-files dirname)))
2456 (when (string-match regexp (car files))
2457 (push (list nil (match-string 1 (car files))) result))
2458 (setq files (cdr files)))
2461 (defun tramp-parse-hosts (filename)
2462 "Return a list of (user host) tuples allowed to access.
2463 User is always nil."
2464 ;; On Windows, there are problems in completion when
2465 ;; `default-directory' is remote.
2466 (let ((default-directory (tramp-compat-temporary-file-directory))
2468 (when (file-readable-p filename)
2470 (insert-file-contents filename)
2471 (goto-char (point-min))
2473 (push (tramp-parse-hosts-group) res))))
2476 (defun tramp-parse-hosts-group ()
2477 "Return a (user host) tuple allowed to access.
2478 User is always nil."
2481 (concat "^\\(" tramp-ipv6-regexp "\\|" tramp-host-regexp "\\)")))
2482 (narrow-to-region (point) (point-at-eol))
2483 (when (re-search-forward regexp nil t)
2484 (setq result (list nil (match-string 1))))
2487 (> (skip-chars-forward " \t") 0)
2491 ;; For su-alike methods it would be desirable to return "root@localhost"
2492 ;; as default. Unfortunately, we have no information whether any user name
2493 ;; has been typed already. So we use `tramp-current-user' as indication,
2494 ;; assuming it is set in `tramp-completion-handle-file-name-all-completions'.
2495 (defun tramp-parse-passwd (filename)
2496 "Return a list of (user host) tuples allowed to access.
2497 Host is always \"localhost\"."
2498 ;; On Windows, there are problems in completion when
2499 ;; `default-directory' is remote.
2500 (let ((default-directory (tramp-compat-temporary-file-directory))
2502 (if (zerop (length tramp-current-user))
2504 (when (file-readable-p filename)
2506 (insert-file-contents filename)
2507 (goto-char (point-min))
2509 (push (tramp-parse-passwd-group) res))))
2512 (defun tramp-parse-passwd-group ()
2513 "Return a (user host) tuple allowed to access.
2514 Host is always \"localhost\"."
2516 (regexp (concat "^\\(" tramp-user-regexp "\\):")))
2517 (narrow-to-region (point) (point-at-eol))
2518 (when (re-search-forward regexp nil t)
2519 (setq result (list (match-string 1) "localhost")))
2524 (defun tramp-parse-netrc (filename)
2525 "Return a list of (user host) tuples allowed to access.
2527 ;; On Windows, there are problems in completion when
2528 ;; `default-directory' is remote.
2529 (let ((default-directory (tramp-compat-temporary-file-directory))
2531 (when (file-readable-p filename)
2533 (insert-file-contents filename)
2534 (goto-char (point-min))
2536 (push (tramp-parse-netrc-group) res))))
2539 (defun tramp-parse-netrc-group ()
2540 "Return a (user host) tuple allowed to access.
2545 "^[ \t]*machine[ \t]+" "\\(" tramp-host-regexp "\\)"
2546 "\\([ \t]+login[ \t]+" "\\(" tramp-user-regexp "\\)" "\\)?")))
2547 (narrow-to-region (point) (point-at-eol))
2548 (when (re-search-forward regexp nil t)
2549 (setq result (list (match-string 3) (match-string 1))))
2554 (defun tramp-parse-putty (registry)
2555 "Return a list of (user host) tuples allowed to access.
2556 User is always nil."
2557 ;; On Windows, there are problems in completion when
2558 ;; `default-directory' is remote.
2559 (let ((default-directory (tramp-compat-temporary-file-directory))
2562 (when (zerop (tramp-compat-call-process "reg" nil t nil "query" registry))
2563 (goto-char (point-min))
2565 (push (tramp-parse-putty-group registry) res))))
2568 (defun tramp-parse-putty-group (registry)
2569 "Return a (user host) tuple allowed to access.
2570 User is always nil."
2572 (regexp (concat (regexp-quote registry) "\\\\\\(.+\\)")))
2573 (narrow-to-region (point) (point-at-eol))
2574 (when (re-search-forward regexp nil t)
2575 (setq result (list nil (match-string 1))))
2580 ;;; Common file name handler functions for different backends:
2582 (defvar tramp-handle-file-local-copy-hook nil
2583 "Normal hook to be run at the end of `tramp-*-handle-file-local-copy'.")
2585 (defvar tramp-handle-write-region-hook nil
2586 "Normal hook to be run at the end of `tramp-*-handle-write-region'.")
2588 (defun tramp-handle-directory-file-name (directory)
2589 "Like `directory-file-name' for Tramp files."
2590 ;; If localname component of filename is "/", leave it unchanged.
2591 ;; Otherwise, remove any trailing slash from localname component.
2592 ;; Method, host, etc, are unchanged. Does it make sense to try
2593 ;; to avoid parsing the filename?
2594 (with-parsed-tramp-file-name directory nil
2595 (if (and (not (zerop (length localname)))
2596 (eq (aref localname (1- (length localname))) ?/)
2597 (not (string= localname "/")))
2598 (substring directory 0 -1)
2601 (defun tramp-handle-directory-files
2602 (directory &optional full match nosort files-only)
2603 "Like `directory-files' for Tramp files."
2604 ;; FILES-ONLY is valid for XEmacs only.
2605 (when (file-directory-p directory)
2606 (setq directory (file-name-as-directory (expand-file-name directory)))
2607 (let ((temp (nreverse (file-name-all-completions "" directory)))
2611 (setq item (directory-file-name (pop temp)))
2612 (when (and (or (null match) (string-match match item))
2613 (or (null files-only)
2615 (and (equal files-only t) (file-regular-p item))
2616 ;; Directories only.
2617 (file-directory-p item)))
2618 (push (if full (concat directory item) item)
2620 (if nosort result (sort result 'string<)))))
2622 (defun tramp-handle-directory-files-and-attributes
2623 (directory &optional full match nosort id-format)
2624 "Like `directory-files-and-attributes' for Tramp files."
2627 (cons x (tramp-compat-file-attributes
2628 (if full x (expand-file-name x directory)) id-format)))
2629 (directory-files directory full match nosort)))
2631 (defun tramp-handle-dired-uncache (dir &optional dir-p)
2632 "Like `dired-uncache' for Tramp files."
2633 ;; DIR-P is valid for XEmacs only.
2634 (with-parsed-tramp-file-name
2635 (if (or dir-p (file-directory-p dir)) dir (file-name-directory dir)) nil
2636 (tramp-flush-directory-property v localname)))
2638 (defun tramp-handle-file-exists-p (filename)
2639 "Like `file-exists-p' for Tramp files."
2640 (not (null (file-attributes filename))))
2642 (defun tramp-handle-file-modes (filename)
2643 "Like `file-modes' for Tramp files."
2644 (let ((truename (or (file-truename filename) filename)))
2645 (when (file-exists-p truename)
2646 (tramp-mode-string-to-int (nth 8 (file-attributes truename))))))
2648 ;; Localname manipulation functions that grok Tramp localnames...
2649 (defun tramp-handle-file-name-as-directory (file)
2650 "Like `file-name-as-directory' but aware of Tramp files."
2651 ;; `file-name-as-directory' would be sufficient except localname is
2652 ;; the empty string.
2653 (let ((v (tramp-dissect-file-name file t)))
2654 ;; Run the command on the localname portion only.
2655 (tramp-make-tramp-file-name
2656 (tramp-file-name-method v)
2657 (tramp-file-name-user v)
2658 (tramp-file-name-host v)
2659 (tramp-run-real-handler
2660 'file-name-as-directory (list (or (tramp-file-name-localname v) ""))))))
2662 (defun tramp-handle-file-name-completion
2663 (filename directory &optional predicate)
2664 "Like `file-name-completion' for Tramp files."
2665 (unless (tramp-tramp-file-p directory)
2667 "tramp-handle-file-name-completion invoked on non-tramp directory `%s'"
2671 (mapcar 'list (file-name-all-completions filename directory))
2673 (lambda (x) (funcall predicate (expand-file-name (car x) directory))))))
2675 (defun tramp-handle-file-name-directory (file)
2676 "Like `file-name-directory' but aware of Tramp files."
2677 ;; Everything except the last filename thing is the directory. We
2678 ;; cannot apply `with-parsed-tramp-file-name', because this expands
2679 ;; the remote file name parts. This is a problem when we are in
2680 ;; file name completion.
2681 (let ((v (tramp-dissect-file-name file t)))
2682 ;; Run the command on the localname portion only.
2683 (tramp-make-tramp-file-name
2684 (tramp-file-name-method v)
2685 (tramp-file-name-user v)
2686 (tramp-file-name-host v)
2687 (tramp-run-real-handler
2688 'file-name-directory (list (or (tramp-file-name-localname v) ""))))))
2690 (defun tramp-handle-file-name-nondirectory (file)
2691 "Like `file-name-nondirectory' but aware of Tramp files."
2692 (with-parsed-tramp-file-name file nil
2693 (tramp-run-real-handler 'file-name-nondirectory (list localname))))
2695 (defun tramp-handle-file-newer-than-file-p (file1 file2)
2696 "Like `file-newer-than-file-p' for Tramp files."
2698 ((not (file-exists-p file1)) nil)
2699 ((not (file-exists-p file2)) t)
2700 (t (tramp-time-less-p (nth 5 (file-attributes file2))
2701 (nth 5 (file-attributes file1))))))
2703 (defun tramp-handle-file-regular-p (filename)
2704 "Like `file-regular-p' for Tramp files."
2705 (and (file-exists-p filename)
2706 (eq ?- (aref (nth 8 (file-attributes filename)) 0))))
2708 (defun tramp-handle-file-remote-p (filename &optional identification connected)
2709 "Like `file-remote-p' for Tramp files."
2710 (let ((tramp-verbose 3))
2711 (when (tramp-tramp-file-p filename)
2712 (let* ((v (tramp-dissect-file-name filename))
2713 (p (tramp-get-connection-process v))
2714 (c (and p (processp p) (memq (process-status p) '(run open)))))
2715 ;; We expand the file name only, if there is already a connection.
2716 (with-parsed-tramp-file-name
2717 (if c (expand-file-name filename) filename) nil
2718 (and (or (not connected) c)
2720 ((eq identification 'method) method)
2721 ((eq identification 'user) user)
2722 ((eq identification 'host) host)
2723 ((eq identification 'localname) localname)
2724 (t (tramp-make-tramp-file-name method user host "")))))))))
2726 (defun tramp-handle-file-symlink-p (filename)
2727 "Like `file-symlink-p' for Tramp files."
2728 (with-parsed-tramp-file-name filename nil
2729 (let ((x (car (file-attributes filename))))
2731 ;; When Tramp is running on VMS, then `file-name-absolute-p'
2732 ;; might do weird things.
2733 (if (file-name-absolute-p x)
2734 (tramp-make-tramp-file-name method user host x)
2737 (defun tramp-handle-find-backup-file-name (filename)
2738 "Like `find-backup-file-name' for Tramp files."
2739 (with-parsed-tramp-file-name filename nil
2740 ;; We set both variables. It doesn't matter whether it is
2742 (let ((backup-directory-alist
2744 (when (boundp 'backup-directory-alist)
2745 (if (symbol-value 'tramp-backup-directory-alist)
2750 (if (and (stringp (cdr x))
2751 (file-name-absolute-p (cdr x))
2752 (not (tramp-file-name-p (cdr x))))
2753 (tramp-make-tramp-file-name method user host (cdr x))
2755 (symbol-value 'tramp-backup-directory-alist))
2756 (symbol-value 'backup-directory-alist))))
2758 (bkup-backup-directory-info
2760 (when (boundp 'bkup-backup-directory-info)
2761 (if (symbol-value 'tramp-bkup-backup-directory-info)
2767 (if (and (stringp (car (cdr x)))
2768 (file-name-absolute-p (car (cdr x)))
2769 (not (tramp-file-name-p (car (cdr x)))))
2770 (tramp-make-tramp-file-name
2771 method user host (car (cdr x)))
2774 (symbol-value 'tramp-bkup-backup-directory-info))
2775 (symbol-value 'bkup-backup-directory-info)))))
2777 (tramp-run-real-handler 'find-backup-file-name (list filename)))))
2779 (defun tramp-handle-insert-file-contents
2780 (filename &optional visit beg end replace)
2781 "Like `insert-file-contents' for Tramp files."
2782 (barf-if-buffer-read-only)
2783 (setq filename (expand-file-name filename))
2784 (let (result local-copy remote-copy)
2785 (with-parsed-tramp-file-name filename nil
2787 (if (not (file-exists-p filename))
2788 ;; We don't raise a Tramp error, because it might be
2789 ;; suppressed, like in `find-file-noselect-1'.
2791 (list "File not found on remote host" filename))
2793 (if (and (tramp-local-host-p v)
2794 (let (file-name-handler-alist)
2795 (file-readable-p localname)))
2796 ;; Short track: if we are on the local host, we can
2799 (tramp-run-real-handler
2800 'insert-file-contents
2801 (list localname visit beg end replace)))
2803 ;; When we shall insert only a part of the file, we copy
2806 (setq remote-copy (tramp-make-tramp-temp-file v))
2807 ;; This is defined in tramp-sh.el. Let's assume this
2808 ;; is loaded already.
2809 (tramp-compat-funcall 'tramp-send-command
2813 (format "tail -c +%d %s | head -c +%d >%s"
2814 (1+ beg) (tramp-shell-quote-argument localname)
2815 (- end beg) remote-copy))
2817 (format "tail -c +%d %s >%s"
2818 (1+ beg) (tramp-shell-quote-argument localname)
2821 (format "head -c +%d %s >%s"
2822 (1+ end) (tramp-shell-quote-argument localname)
2825 ;; `insert-file-contents-literally' takes care to avoid
2826 ;; calling jka-compr. By let-binding
2827 ;; `inhibit-file-name-operation', we propagate that care
2828 ;; to the `file-local-copy' operation.
2830 (let ((inhibit-file-name-operation
2831 (when (eq inhibit-file-name-operation
2832 'insert-file-contents)
2835 ((stringp remote-copy)
2837 (tramp-make-tramp-file-name
2838 method user host remote-copy)))
2839 ((stringp tramp-temp-buffer-file-name)
2840 (copy-file filename tramp-temp-buffer-file-name 'ok)
2841 tramp-temp-buffer-file-name)
2842 (t (file-local-copy filename)))))
2844 ;; When the file is not readable for the owner, it
2845 ;; cannot be inserted, even it is redable for the group
2846 ;; or for everybody.
2847 (set-file-modes local-copy (tramp-compat-octal-to-decimal "0600"))
2849 (when (and (null remote-copy)
2850 (tramp-get-method-parameter
2851 method 'tramp-copy-keep-tmpfile))
2852 ;; We keep the local file for performance reasons,
2853 ;; useful for "rsync".
2854 (setq tramp-temp-buffer-file-name local-copy)
2855 (put 'tramp-temp-buffer-file-name 'permanent-local t))
2857 (with-progress-reporter
2858 v 3 (format "Inserting local temp file `%s'" local-copy)
2859 ;; We must ensure that `file-coding-system-alist'
2860 ;; matches `local-copy'.
2861 (let ((file-coding-system-alist
2862 (tramp-find-file-name-coding-system-alist
2863 filename local-copy)))
2865 (insert-file-contents
2866 local-copy nil nil nil replace))))))
2871 (setq buffer-file-name filename)
2872 (setq buffer-read-only (not (file-writable-p filename)))
2873 (set-visited-file-modtime)
2874 (set-buffer-modified-p nil))
2875 (when (and (stringp local-copy)
2876 (or remote-copy (null tramp-temp-buffer-file-name)))
2877 (delete-file local-copy))
2878 (when (stringp remote-copy)
2880 (tramp-make-tramp-file-name method user host remote-copy))))))
2883 (list (expand-file-name filename)
2886 (defun tramp-handle-load (file &optional noerror nomessage nosuffix must-suffix)
2887 "Like `load' for Tramp files."
2888 (with-parsed-tramp-file-name (expand-file-name file) nil
2890 (cond ((file-exists-p (concat file ".elc"))
2891 (setq file (concat file ".elc")))
2892 ((file-exists-p (concat file ".el"))
2893 (setq file (concat file ".el")))))
2895 ;; The first condition is always true for absolute file names.
2896 ;; Included for safety's sake.
2897 (unless (or (file-name-directory file)
2898 (string-match "\\.elc?\\'" file))
2901 "File `%s' does not include a `.el' or `.elc' suffix" file)))
2903 (when (not (file-exists-p file))
2904 (tramp-error v 'file-error "Cannot load nonexistent file `%s'" file)))
2905 (if (not (file-exists-p file))
2907 (let ((tramp-message-show-message (not nomessage)))
2908 (with-progress-reporter v 0 (format "Loading %s" file)
2909 (let ((local-copy (file-local-copy file)))
2910 ;; MUST-SUFFIX doesn't exist on XEmacs, so let it default to nil.
2912 (load local-copy noerror t t)
2913 (delete-file local-copy)))))
2916 (defun tramp-handle-substitute-in-file-name (filename)
2917 "Like `substitute-in-file-name' for Tramp files.
2918 \"//\" and \"/~\" substitute only in the local filename part.
2919 If the URL Tramp syntax is chosen, \"//\" as method delimeter and \"/~\" at
2920 beginning of local filename are not substituted."
2921 ;; First, we must replace environment variables.
2922 (setq filename (tramp-replace-environment-variables filename))
2923 (with-parsed-tramp-file-name filename nil
2924 (if (equal tramp-syntax 'url)
2925 ;; We need to check localname only. The other parts cannot contain
2927 (if (and (> (length localname) 1)
2928 (or (string-match "//" localname)
2929 (string-match "/~" localname 1)))
2930 (tramp-run-real-handler 'substitute-in-file-name (list filename))
2931 (tramp-make-tramp-file-name
2932 (when method (substitute-in-file-name method))
2933 (when user (substitute-in-file-name user))
2934 (when host (substitute-in-file-name host))
2936 (tramp-run-real-handler
2937 'substitute-in-file-name (list localname)))))
2938 ;; Ignore in LOCALNAME everything before "//" or "/~".
2939 (when (and (stringp localname) (string-match ".+?/\\(/\\|~\\)" localname))
2941 (concat (file-remote-p filename)
2942 (replace-match "\\1" nil nil localname)))
2943 ;; "/m:h:~" does not work for completion. We use "/m:h:~/".
2944 (when (string-match "~$" filename)
2945 (setq filename (concat filename "/"))))
2946 (tramp-run-real-handler 'substitute-in-file-name (list filename)))))
2948 (defun tramp-handle-unhandled-file-name-directory (filename)
2949 "Like `unhandled-file-name-directory' for Tramp files."
2950 ;; With Emacs 23, we could simply return `nil'. But we must keep it
2951 ;; for backward compatibility.
2952 (expand-file-name "~/"))
2954 ;;; Functions for establishing connection:
2956 ;; The following functions are actions to be taken when seeing certain
2957 ;; prompts from the remote host. See the variable
2958 ;; `tramp-actions-before-shell' for usage of these functions.
2960 (defun tramp-action-login (proc vec)
2961 "Send the login name."
2962 (when (not (stringp tramp-current-user))
2963 (save-window-excursion
2964 (let ((enable-recursive-minibuffers t))
2965 (pop-to-buffer (tramp-get-connection-buffer vec))
2966 (setq tramp-current-user (read-string (match-string 0))))))
2967 (tramp-message vec 3 "Sending login name `%s'" tramp-current-user)
2968 (with-current-buffer (tramp-get-connection-buffer vec)
2969 (tramp-message vec 6 "\n%s" (buffer-string)))
2970 (tramp-send-string vec tramp-current-user))
2972 (defun tramp-action-password (proc vec)
2973 "Query the user for a password."
2974 (with-current-buffer (process-buffer proc)
2975 (tramp-check-for-regexp proc tramp-password-prompt-regexp)
2976 (tramp-message vec 3 "Sending %s" (match-string 1))
2977 (tramp-enter-password proc)
2978 ;; Hide password prompt.
2979 (narrow-to-region (point-max) (point-max))))
2981 (defun tramp-action-succeed (proc vec)
2982 "Signal success in finding shell prompt."
2983 (throw 'tramp-action 'ok))
2985 (defun tramp-action-permission-denied (proc vec)
2986 "Signal permission denied."
2988 (throw 'tramp-action 'permission-denied))
2990 (defun tramp-action-yesno (proc vec)
2991 "Ask the user for confirmation using `yes-or-no-p'.
2992 Send \"yes\" to remote process on confirmation, abort otherwise.
2993 See also `tramp-action-yn'."
2994 (save-window-excursion
2995 (let ((enable-recursive-minibuffers t))
2996 (save-match-data (pop-to-buffer (tramp-get-connection-buffer vec)))
2997 (unless (yes-or-no-p (match-string 0))
2999 (throw 'tramp-action 'permission-denied))
3000 (with-current-buffer (tramp-get-connection-buffer vec)
3001 (tramp-message vec 6 "\n%s" (buffer-string)))
3002 (tramp-send-string vec "yes"))))
3004 (defun tramp-action-yn (proc vec)
3005 "Ask the user for confirmation using `y-or-n-p'.
3006 Send \"y\" to remote process on confirmation, abort otherwise.
3007 See also `tramp-action-yesno'."
3008 (save-window-excursion
3009 (let ((enable-recursive-minibuffers t))
3010 (save-match-data (pop-to-buffer (tramp-get-connection-buffer vec)))
3011 (unless (y-or-n-p (match-string 0))
3013 (throw 'tramp-action 'permission-denied))
3014 (with-current-buffer (tramp-get-connection-buffer vec)
3015 (tramp-message vec 6 "\n%s" (buffer-string)))
3016 (tramp-send-string vec "y"))))
3018 (defun tramp-action-terminal (proc vec)
3019 "Tell the remote host which terminal type to use.
3020 The terminal type can be configured with `tramp-terminal-type'."
3021 (tramp-message vec 5 "Setting `%s' as terminal type." tramp-terminal-type)
3022 (with-current-buffer (tramp-get-connection-buffer vec)
3023 (tramp-message vec 6 "\n%s" (buffer-string)))
3024 (tramp-send-string vec tramp-terminal-type))
3026 (defun tramp-action-process-alive (proc vec)
3027 "Check, whether a process has finished."
3028 (unless (memq (process-status proc) '(run open))
3029 (throw 'tramp-action 'process-died)))
3031 (defun tramp-action-out-of-band (proc vec)
3032 "Check, whether an out-of-band copy has finished."
3033 (cond ((and (memq (process-status proc) '(stop exit))
3034 (zerop (process-exit-status proc)))
3035 (tramp-message vec 3 "Process has finished.")
3036 (throw 'tramp-action 'ok))
3037 ((or (and (memq (process-status proc) '(stop exit))
3038 (not (zerop (process-exit-status proc))))
3039 (memq (process-status proc) '(signal)))
3040 ;; `scp' could have copied correctly, but set modes could have failed.
3041 ;; This can be ignored.
3042 (with-current-buffer (process-buffer proc)
3043 (goto-char (point-min))
3044 (if (re-search-forward tramp-operation-not-permitted-regexp nil t)
3046 (tramp-message vec 5 "'set mode' error ignored.")
3047 (tramp-message vec 3 "Process has finished.")
3048 (throw 'tramp-action 'ok))
3049 (tramp-message vec 3 "Process has died.")
3050 (throw 'tramp-action 'process-died))))
3053 ;;; Functions for processing the actions:
3055 (defun tramp-process-one-action (proc vec actions)
3056 "Wait for output from the shell and perform one action."
3057 (let (found todo item pattern action)
3059 ;; Reread output once all actions have been performed.
3060 ;; Obviously, the output was not complete.
3061 (tramp-accept-process-output proc 1)
3064 (setq item (pop todo))
3065 (setq pattern (format "\\(%s\\)\\'" (symbol-value (nth 0 item))))
3066 (setq action (nth 1 item))
3068 vec 5 "Looking for regexp \"%s\" from remote shell" pattern)
3069 (when (tramp-check-for-regexp proc pattern)
3070 (tramp-message vec 5 "Call `%s'" (symbol-name action))
3071 (setq found (funcall action proc vec)))))
3074 (defun tramp-process-actions (proc vec actions &optional timeout)
3075 "Perform actions until success or TIMEOUT."
3076 ;; Preserve message for `progress-reporter'.
3077 (tramp-compat-with-temp-message ""
3078 ;; Enable auth-source and password-cache.
3079 (tramp-set-connection-property vec "first-password-request" t)
3083 (tramp-message proc 3 "Waiting for prompts from remote shell")
3085 (catch 'tramp-action
3087 (with-timeout (timeout)
3088 (tramp-process-one-action proc vec actions))
3089 (tramp-process-one-action proc vec actions)))))
3090 (with-current-buffer (tramp-get-connection-buffer vec)
3092 (tramp-message vec 6 "\n%s" (buffer-string)))
3093 (unless (eq exit 'ok)
3094 (tramp-clear-passwd vec)
3095 (tramp-error-with-buffer
3098 ((eq exit 'permission-denied) "Permission denied")
3099 ((eq exit 'process-died) "Process died")
3100 (t "Login failed"))))))))
3102 :;; Utility functions:
3104 (defun tramp-accept-process-output (&optional proc timeout timeout-msecs)
3105 "Like `accept-process-output' for Tramp processes.
3106 This is needed in order to hide `last-coding-system-used', which is set
3107 for process communication also."
3108 (with-current-buffer (process-buffer proc)
3109 (tramp-message proc 10 "%s %s" proc (process-status proc))
3110 (let (buffer-read-only last-coding-system-used)
3111 ;; Under Windows XP, accept-process-output doesn't return
3112 ;; sometimes. So we add an additional timeout.
3113 (with-timeout ((or timeout 1))
3114 (accept-process-output proc timeout timeout-msecs)))
3115 (tramp-message proc 10 "\n%s" (buffer-string))))
3117 (defun tramp-check-for-regexp (proc regexp)
3118 "Check, whether REGEXP is contained in process buffer of PROC.
3119 Erase echoed commands if exists."
3120 (with-current-buffer (process-buffer proc)
3121 (goto-char (point-min))
3123 ;; Check whether we need to remove echo output.
3124 (when (and (tramp-get-connection-property proc "check-remote-echo" nil)
3125 (re-search-forward tramp-echoed-echo-mark-regexp nil t))
3126 (let ((begin (match-beginning 0)))
3127 (when (re-search-forward tramp-echoed-echo-mark-regexp nil t)
3128 ;; Discard echo from remote output.
3129 (tramp-set-connection-property proc "check-remote-echo" nil)
3130 (tramp-message proc 5 "echo-mark found")
3132 (delete-region begin (point))
3133 (goto-char (point-min)))))
3135 (when (or (not (tramp-get-connection-property proc "check-remote-echo" nil))
3136 ;; Sometimes, the echo string is suppressed on the remote side.
3138 (tramp-compat-funcall
3139 'substring-no-properties tramp-echo-mark-marker
3140 0 (min tramp-echo-mark-marker-length (1- (point-max))))
3141 (tramp-compat-funcall
3142 'buffer-substring-no-properties
3143 1 (min (1+ tramp-echo-mark-marker-length) (point-max))))))
3144 ;; No echo to be handled, now we can look for the regexp.
3145 (goto-char (point-min))
3146 (re-search-forward regexp nil t))))
3148 (defun tramp-wait-for-regexp (proc timeout regexp)
3149 "Wait for a REGEXP to appear from process PROC within TIMEOUT seconds.
3150 Expects the output of PROC to be sent to the current buffer. Returns
3151 the string that matched, or nil. Waits indefinitely if TIMEOUT is
3153 (with-current-buffer (process-buffer proc)
3154 (let ((found (tramp-check-for-regexp proc regexp))
3155 (start-time (current-time)))
3157 ;; Work around a bug in XEmacs 21, where the timeout
3158 ;; expires faster than it should. This degenerates
3159 ;; to polling for buggy XEmacsen, but oh, well.
3160 (while (and (not found)
3161 (< (tramp-time-diff (current-time) start-time)
3163 (with-timeout (timeout)
3165 (tramp-accept-process-output proc 1)
3166 (unless (memq (process-status proc) '(run open))
3167 (tramp-error-with-buffer
3168 nil proc 'file-error "Process has died"))
3169 (setq found (tramp-check-for-regexp proc regexp))))))
3172 (tramp-accept-process-output proc 1)
3173 (unless (memq (process-status proc) '(run open))
3174 (tramp-error-with-buffer
3175 nil proc 'file-error "Process has died"))
3176 (setq found (tramp-check-for-regexp proc regexp)))))
3177 (tramp-message proc 6 "\n%s" (buffer-string))
3181 proc 'file-error "[[Regexp `%s' not found in %d secs]]"
3183 (tramp-error proc 'file-error "[[Regexp `%s' not found]]" regexp)))
3186 ;; We don't call `tramp-send-string' in order to hide the password
3187 ;; from the debug buffer, and because end-of-line handling of the
3189 (defun tramp-enter-password (proc)
3190 "Prompt for a password and send it to the remote end."
3191 (process-send-string
3192 proc (concat (tramp-read-passwd proc)
3193 (or (tramp-get-method-parameter
3194 tramp-current-method
3195 'tramp-password-end-of-line)
3196 tramp-default-password-end-of-line))))
3198 ;; It seems that Tru64 Unix does not like it if long strings are sent
3199 ;; to it in one go. (This happens when sending the Perl
3200 ;; `file-attributes' implementation, for instance.) Therefore, we
3201 ;; have this function which sends the string in chunks.
3202 (defun tramp-send-string (vec string)
3203 "Send the STRING via connection VEC.
3205 The STRING is expected to use Unix line-endings, but the lines sent to
3206 the remote host use line-endings as defined in the variable
3207 `tramp-rsh-end-of-line'. The communication buffer is erased before sending."
3208 (let* ((p (tramp-get-connection-process vec))
3209 (chunksize (tramp-get-connection-property p "chunksize" nil)))
3212 vec 'file-error "Can't send string to remote host -- not logged in"))
3213 (tramp-set-connection-property p "last-cmd-time" (current-time))
3214 (tramp-message vec 10 "%s" string)
3215 (with-current-buffer (tramp-get-connection-buffer vec)
3216 ;; Clean up the buffer. We cannot call `erase-buffer' because
3217 ;; narrowing might be in effect.
3218 (let (buffer-read-only) (delete-region (point-min) (point-max)))
3219 ;; Replace "\n" by `tramp-rsh-end-of-line'.
3221 (mapconcat 'identity
3222 (tramp-compat-split-string string "\n")
3223 tramp-rsh-end-of-line))
3224 (unless (or (string= string "")
3225 (string-equal (substring string -1) tramp-rsh-end-of-line))
3226 (setq string (concat string tramp-rsh-end-of-line)))
3228 (if (and chunksize (not (zerop chunksize)))
3230 (end (length string)))
3233 vec 10 "Sending chunk from %s to %s"
3234 pos (min (+ pos chunksize) end))
3235 (process-send-string
3236 p (substring string pos (min (+ pos chunksize) end)))
3237 (setq pos (+ pos chunksize))))
3238 (process-send-string p string)))))
3240 (defun tramp-get-inode (vec)
3241 "Returns the virtual inode number.
3242 If it doesn't exist, generate a new one."
3243 (let ((string (tramp-make-tramp-file-name
3244 (tramp-file-name-method vec)
3245 (tramp-file-name-user vec)
3246 (tramp-file-name-host vec)
3248 (unless (assoc string tramp-inodes)
3249 (add-to-list 'tramp-inodes
3250 (list string (length tramp-inodes))))
3251 (nth 1 (assoc string tramp-inodes))))
3253 (defun tramp-get-device (vec)
3254 "Returns the virtual device number.
3255 If it doesn't exist, generate a new one."
3256 (let ((string (tramp-make-tramp-file-name
3257 (tramp-file-name-method vec)
3258 (tramp-file-name-user vec)
3259 (tramp-file-name-host vec)
3261 (unless (assoc string tramp-devices)
3262 (add-to-list 'tramp-devices
3263 (list string (length tramp-devices))))
3264 (cons -1 (nth 1 (assoc string tramp-devices)))))
3266 (defun tramp-equal-remote (file1 file2)
3267 "Check, whether the remote parts of FILE1 and FILE2 are identical.
3268 The check depends on method, user and host name of the files. If
3269 one of the components is missing, the default values are used.
3270 The local file name parts of FILE1 and FILE2 are not taken into
3275 (tramp-equal-remote \"/ssh::/etc\" \"/<your host name>:/home\")
3277 would yield `t'. On the other hand, the following check results in nil:
3279 (tramp-equal-remote \"/sudo::/etc\" \"/su::/etc\")"
3280 (and (stringp (file-remote-p file1))
3281 (stringp (file-remote-p file2))
3282 (string-equal (file-remote-p file1) (file-remote-p file2))))
3284 (defun tramp-get-method-parameter (method param)
3285 "Return the method parameter PARAM.
3286 If the `tramp-methods' entry does not exist, return nil."
3287 (let ((entry (assoc param (assoc method tramp-methods))))
3288 (when entry (cadr entry))))
3290 (defun tramp-mode-string-to-int (mode-string)
3291 "Converts a ten-letter `drwxrwxrwx'-style mode string into mode bits."
3292 (let* (case-fold-search
3293 (mode-chars (string-to-vector mode-string))
3294 (owner-read (aref mode-chars 1))
3295 (owner-write (aref mode-chars 2))
3296 (owner-execute-or-setid (aref mode-chars 3))
3297 (group-read (aref mode-chars 4))
3298 (group-write (aref mode-chars 5))
3299 (group-execute-or-setid (aref mode-chars 6))
3300 (other-read (aref mode-chars 7))
3301 (other-write (aref mode-chars 8))
3302 (other-execute-or-sticky (aref mode-chars 9)))
3306 ((char-equal owner-read ?r) (tramp-compat-octal-to-decimal "00400"))
3307 ((char-equal owner-read ?-) 0)
3308 (t (error "Second char `%c' must be one of `r-'" owner-read)))
3310 ((char-equal owner-write ?w) (tramp-compat-octal-to-decimal "00200"))
3311 ((char-equal owner-write ?-) 0)
3312 (t (error "Third char `%c' must be one of `w-'" owner-write)))
3314 ((char-equal owner-execute-or-setid ?x)
3315 (tramp-compat-octal-to-decimal "00100"))
3316 ((char-equal owner-execute-or-setid ?S)
3317 (tramp-compat-octal-to-decimal "04000"))
3318 ((char-equal owner-execute-or-setid ?s)
3319 (tramp-compat-octal-to-decimal "04100"))
3320 ((char-equal owner-execute-or-setid ?-) 0)
3321 (t (error "Fourth char `%c' must be one of `xsS-'"
3322 owner-execute-or-setid)))
3324 ((char-equal group-read ?r) (tramp-compat-octal-to-decimal "00040"))
3325 ((char-equal group-read ?-) 0)
3326 (t (error "Fifth char `%c' must be one of `r-'" group-read)))
3328 ((char-equal group-write ?w) (tramp-compat-octal-to-decimal "00020"))
3329 ((char-equal group-write ?-) 0)
3330 (t (error "Sixth char `%c' must be one of `w-'" group-write)))
3332 ((char-equal group-execute-or-setid ?x)
3333 (tramp-compat-octal-to-decimal "00010"))
3334 ((char-equal group-execute-or-setid ?S)
3335 (tramp-compat-octal-to-decimal "02000"))
3336 ((char-equal group-execute-or-setid ?s)
3337 (tramp-compat-octal-to-decimal "02010"))
3338 ((char-equal group-execute-or-setid ?-) 0)
3339 (t (error "Seventh char `%c' must be one of `xsS-'"
3340 group-execute-or-setid)))
3342 ((char-equal other-read ?r)
3343 (tramp-compat-octal-to-decimal "00004"))
3344 ((char-equal other-read ?-) 0)
3345 (t (error "Eighth char `%c' must be one of `r-'" other-read)))
3347 ((char-equal other-write ?w) (tramp-compat-octal-to-decimal "00002"))
3348 ((char-equal other-write ?-) 0)
3349 (t (error "Nineth char `%c' must be one of `w-'" other-write)))
3351 ((char-equal other-execute-or-sticky ?x)
3352 (tramp-compat-octal-to-decimal "00001"))
3353 ((char-equal other-execute-or-sticky ?T)
3354 (tramp-compat-octal-to-decimal "01000"))
3355 ((char-equal other-execute-or-sticky ?t)
3356 (tramp-compat-octal-to-decimal "01001"))
3357 ((char-equal other-execute-or-sticky ?-) 0)
3358 (t (error "Tenth char `%c' must be one of `xtT-'"
3359 other-execute-or-sticky)))))))
3361 (defun tramp-local-host-p (vec)
3362 "Return t if this points to the local host, nil otherwise."
3363 ;; We cannot use `tramp-file-name-real-host'. A port is an
3364 ;; indication for an ssh tunnel or alike.
3365 (let ((host (tramp-file-name-host vec)))
3368 (string-match tramp-local-host-regexp host)
3369 ;; The method shall be applied to one of the shell file name
3370 ;; handler. `tramp-local-host-p' is also called for "smb" and
3371 ;; alike, where it must fail.
3372 (tramp-get-method-parameter
3373 (tramp-file-name-method vec) 'tramp-login-program)
3374 ;; The local temp directory must be writable for the other user.
3376 (tramp-make-tramp-file-name
3377 (tramp-file-name-method vec)
3378 (tramp-file-name-user vec)
3380 (tramp-compat-temporary-file-directory)))
3381 ;; On some systems, chown runs only for root.
3382 (or (zerop (user-uid))
3383 ;; This is defined in tramp-sh.el. Let's assume this is
3385 (zerop (tramp-compat-funcall 'tramp-get-remote-uid vec 'integer))))))
3387 (defun tramp-make-tramp-temp-file (vec)
3388 "Create a temporary file on the remote host identified by VEC.
3389 Return the local name of the temporary file."
3391 (tramp-make-tramp-file-name
3392 (tramp-file-name-method vec)
3393 (tramp-file-name-user vec)
3394 (tramp-file-name-host vec)
3395 (tramp-drop-volume-letter
3397 tramp-temp-name-prefix
3398 ;; This is defined in tramp-sh.el. Let's assume this is
3400 (tramp-compat-funcall 'tramp-get-remote-tmpdir vec)))))
3403 ;; `make-temp-file' would be the natural choice for
3404 ;; implementation. But it calls `write-region' internally,
3405 ;; which also needs a temporary file - we would end in an
3407 (setq result (make-temp-name prefix))
3408 (if (file-exists-p result)
3410 ;; This creates the file by side effect.
3411 (set-file-times result)
3412 (set-file-modes result (tramp-compat-octal-to-decimal "0700"))))
3414 ;; Return the local part.
3415 (with-parsed-tramp-file-name result nil localname)))
3417 (defun tramp-delete-temp-file-function ()
3418 "Remove temporary files related to current buffer."
3419 (when (stringp tramp-temp-buffer-file-name)
3420 (ignore-errors (delete-file tramp-temp-buffer-file-name))))
3422 (add-hook 'kill-buffer-hook 'tramp-delete-temp-file-function)
3423 (add-hook 'tramp-cache-unload-hook
3425 (remove-hook 'kill-buffer-hook
3426 'tramp-delete-temp-file-function)))
3428 ;;; Auto saving to a special directory:
3430 (unless (tramp-exists-file-name-handler 'make-auto-save-file-name)
3431 (defadvice make-auto-save-file-name
3432 (around tramp-advice-make-auto-save-file-name () activate)
3433 "Invoke `tramp-*-handle-make-auto-save-file-name' for Tramp files."
3434 (if (tramp-tramp-file-p (buffer-file-name))
3435 ;; We cannot call `tramp-handle-make-auto-save-file-name'
3436 ;; directly, because this would bypass the locking mechanism.
3437 (setq ad-return-value
3438 (tramp-file-name-handler 'make-auto-save-file-name))
3444 'make-auto-save-file-name
3445 'around 'tramp-advice-make-auto-save-file-name)
3446 (ad-activate 'make-auto-save-file-name))))
3448 ;; In XEmacs < 21.5, autosaved remote files have permission 0666 minus
3449 ;; umask. This is a security threat.
3451 (defun tramp-set-auto-save-file-modes ()
3452 "Set permissions of autosaved remote files to the original permissions."
3453 (let ((bfn (buffer-file-name)))
3454 (when (and (tramp-tramp-file-p bfn)
3456 (stringp buffer-auto-save-file-name)
3457 (not (equal bfn buffer-auto-save-file-name)))
3458 (unless (file-exists-p buffer-auto-save-file-name)
3459 (write-region "" nil buffer-auto-save-file-name))
3460 ;; Permissions should be set always, because there might be an old
3461 ;; auto-saved file belonging to another original file. This could
3462 ;; be a security threat.
3464 buffer-auto-save-file-name
3465 (or (file-modes bfn) (tramp-compat-octal-to-decimal "0600"))))))
3467 (unless (and (featurep 'xemacs)
3468 (= emacs-major-version 21)
3469 (> emacs-minor-version 4))
3470 (add-hook 'auto-save-hook 'tramp-set-auto-save-file-modes)
3471 (add-hook 'tramp-unload-hook
3473 (remove-hook 'auto-save-hook 'tramp-set-auto-save-file-modes))))
3475 (defun tramp-subst-strs-in-string (alist string)
3476 "Replace all occurrences of the string FROM with TO in STRING.
3477 ALIST is of the form ((FROM . TO) ...)."
3480 (let* ((pr (car alist))
3483 (while (string-match (regexp-quote from) string)
3484 (setq string (replace-match to t t string)))
3485 (setq alist (cdr alist))))
3488 ;;; Compatibility functions section:
3490 (defun tramp-read-passwd (proc &optional prompt)
3491 "Read a password from user (compat function).
3492 Consults the auth-source package.
3493 Invokes `password-read' if available, `read-passwd' else."
3494 (let* ((key (tramp-make-tramp-file-name
3495 tramp-current-method tramp-current-user
3496 tramp-current-host ""))
3499 (with-current-buffer (process-buffer proc)
3500 (tramp-check-for-regexp proc tramp-password-prompt-regexp)
3501 (format "%s for %s " (capitalize (match-string 1)) key)))))
3502 (with-parsed-tramp-file-name key nil
3505 ;; See if auth-sources contains something useful, if it's bound.
3506 (and (boundp 'auth-sources)
3507 (tramp-get-connection-property v "first-password-request" nil)
3508 ;; Try with Tramp's current method.
3509 (tramp-compat-funcall
3510 'auth-source-user-or-password
3511 "password" tramp-current-host tramp-current-method))
3512 ;; Try the password cache.
3513 (when (functionp 'password-read)
3514 (unless (tramp-get-connection-property
3515 v "first-password-request" nil)
3516 (tramp-compat-funcall 'password-cache-remove key))
3518 (tramp-compat-funcall 'password-read pw-prompt key)))
3519 (tramp-compat-funcall 'password-cache-add key password)
3521 ;; Else, get the password interactively.
3522 (read-passwd pw-prompt))
3523 (tramp-set-connection-property v "first-password-request" nil)))))
3525 (defun tramp-clear-passwd (vec)
3526 "Clear password cache for connection related to VEC."
3527 (tramp-compat-funcall
3528 'password-cache-remove
3529 (tramp-make-tramp-file-name
3530 (tramp-file-name-method vec)
3531 (tramp-file-name-user vec)
3532 (tramp-file-name-host vec)
3535 ;; Snarfed code from time-date.el and parse-time.el
3537 (defconst tramp-half-a-year '(241 17024)
3538 "Evaluated by \"(days-to-time 183)\".")
3540 (defconst tramp-parse-time-months
3541 '(("jan" . 1) ("feb" . 2) ("mar" . 3)
3542 ("apr" . 4) ("may" . 5) ("jun" . 6)
3543 ("jul" . 7) ("aug" . 8) ("sep" . 9)
3544 ("oct" . 10) ("nov" . 11) ("dec" . 12))
3545 "Alist mapping month names to integers.")
3547 (defun tramp-time-less-p (t1 t2)
3548 "Say whether time value T1 is less than time value T2."
3549 (unless t1 (setq t1 '(0 0)))
3550 (unless t2 (setq t2 '(0 0)))
3551 (or (< (car t1) (car t2))
3552 (and (= (car t1) (car t2))
3553 (< (nth 1 t1) (nth 1 t2)))))
3555 (defun tramp-time-subtract (t1 t2)
3556 "Subtract two time values.
3557 Return the difference in the format of a time value."
3558 (unless t1 (setq t1 '(0 0)))
3559 (unless t2 (setq t2 '(0 0)))
3560 (let ((borrow (< (cadr t1) (cadr t2))))
3561 (list (- (car t1) (car t2) (if borrow 1 0))
3562 (- (+ (if borrow 65536 0) (cadr t1)) (cadr t2)))))
3564 (defun tramp-time-diff (t1 t2)
3565 "Return the difference between the two times, in seconds.
3566 T1 and T2 are time values (as returned by `current-time' for example)."
3567 (cond ((and (fboundp 'subtract-time)
3568 (fboundp 'float-time))
3569 (tramp-compat-funcall
3570 'float-time (tramp-compat-funcall 'subtract-time t1 t2)))
3571 ((and (fboundp 'subtract-time)
3572 (fboundp 'time-to-seconds))
3573 (tramp-compat-funcall
3574 'time-to-seconds (tramp-compat-funcall 'subtract-time t1 t2)))
3575 ((fboundp 'itimer-time-difference)
3576 (tramp-compat-funcall
3577 'itimer-time-difference
3578 (if (< (length t1) 3) (append t1 '(0)) t1)
3579 (if (< (length t2) 3) (append t2 '(0)) t2)))
3581 (let ((time (tramp-time-subtract t1 t2)))
3582 (+ (* (car time) 65536.0)
3584 (/ (or (nth 2 time) 0) 1000000.0))))))
3586 ;; Currently (as of Emacs 20.5), the function `shell-quote-argument'
3587 ;; does not deal well with newline characters. Newline is replaced by
3588 ;; backslash newline. But if, say, the string `a backslash newline b'
3589 ;; is passed to a shell, the shell will expand this into "ab",
3590 ;; completely omitting the newline. This is not what was intended.
3591 ;; It does not appear to be possible to make the function
3592 ;; `shell-quote-argument' work with newlines without making it
3593 ;; dependent on the shell used. But within this package, we know that
3594 ;; we will always use a Bourne-like shell, so we use an approach which
3597 ;; The approach is simple: we call `shell-quote-argument', then
3598 ;; massage the newline part of the result.
3600 ;; This function should produce a string which is grokked by a Unix
3601 ;; shell, even if the Emacs is running on Windows. Since this is the
3602 ;; kludges section, we bind `system-type' in such a way that
3603 ;; `shell-quote-arguments' behaves as if on Unix.
3605 ;; Thanks to Mario DeWeerd for the hint that it is sufficient for this
3606 ;; function to work with Bourne-like shells.
3608 ;; CCC: This function should be rewritten so that
3609 ;; `shell-quote-argument' is not used. This way, we are safe from
3610 ;; changes in `shell-quote-argument'.
3611 ;;;###tramp-autoload
3612 (defun tramp-shell-quote-argument (s)
3613 "Similar to `shell-quote-argument', but groks newlines.
3614 Only works for Bourne-like shells."
3615 (let ((system-type 'not-windows))
3617 (let ((result (shell-quote-argument s))
3618 (nl (regexp-quote (format "\\%s" tramp-rsh-end-of-line))))
3619 (when (and (>= (length result) 2)
3620 (string= (substring result 0 2) "\\~"))
3621 (setq result (substring result 1)))
3622 (while (string-match nl result)
3623 (setq result (replace-match (format "'%s'" tramp-rsh-end-of-line)
3627 ;; Checklist for `tramp-unload-hook'
3628 ;; - Unload all `tramp-*' packages
3629 ;; - Reset `file-name-handler-alist'
3630 ;; - Cleanup hooks where Tramp functions are in
3631 ;; - Cleanup advised functions
3632 ;; - Cleanup autoloads
3634 (defun tramp-unload-tramp ()
3635 "Discard Tramp from loading remote files."
3637 ;; ange-ftp settings must be enabled.
3638 (tramp-compat-funcall 'tramp-ftp-enable-ange-ftp)
3639 ;; Maybe it's not loaded yet.
3640 (ignore-errors (unload-feature 'tramp 'force)))
3646 ;; * Rewrite `tramp-shell-quote-argument' to abstain from using
3647 ;; `shell-quote-argument'.
3648 ;; * In Emacs 21, `insert-directory' shows total number of bytes used
3649 ;; by the files in that directory. Add this here.
3650 ;; * Avoid screen blanking when hitting `g' in dired. (Eli Tziperman)
3651 ;; * Make ffap.el grok Tramp filenames. (Eli Tziperman)
3652 ;; * abbreviate-file-name
3653 ;; * Better error checking. At least whenever we see something
3654 ;; strange when doing zerop, we should kill the process and start
3655 ;; again. (Greg Stark)
3656 ;; * Username and hostname completion.
3657 ;; ** Try to avoid usage of `last-input-event' in `tramp-completion-mode-p'.
3658 ;; ** Unify `tramp-parse-{rhosts,shosts,sconfig,hosts,passwd,netrc}'.
3659 ;; Code is nearly identical.
3660 ;; * Make `tramp-default-user' obsolete.
3661 ;; * Implement a general server-local-variable mechanism, as there are
3662 ;; probably other variables that need different values for different
3663 ;; servers too. The user could then configure a variable (such as
3664 ;; tramp-server-local-variable-alist) to define any such variables
3665 ;; that they need to, which would then be let bound as appropriate
3666 ;; in tramp functions. (Jason Rumney)
3667 ;; * IMHO, it's a drawback that currently Tramp doesn't support
3668 ;; Unicode in Dired file names by default. Is it possible to
3669 ;; improve Tramp to set LC_ALL to "C" only for commands where Tramp
3670 ;; expects English? Or just to set LC_MESSAGES to "C" if Tramp
3671 ;; expects only English messages? (Juri Linkov)
3672 ;; * Make shadowfile.el grok Tramp filenames. (Bug#4526, Bug#4846)
3673 ;; * I was wondering it it would be possible to use tramp even if I'm
3674 ;; actually using sshfs. But when I launch a command I would like
3675 ;; to get it executed on the remote machine where the files really
3676 ;; are. (Andrea Crotti)
3677 ;; * Run emerge on two remote files. Bug is described here:
3678 ;; <http://www.mail-archive.com/tramp-devel@nongnu.org/msg01041.html>.
3681 ;; Functions for file-name-handler-alist:
3682 ;; diff-latest-backup-file -- in diff.el
3684 ;;; tramp.el ends here