Merge from emacs-23
[emacs.git] / lisp / net / tramp.el
blobe5ebe81ce292b5e1b3410987bc83cbe3f85152e4
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
9 ;; Package: tramp
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/>.
26 ;;; Commentary:
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.
35 ;; Notes:
36 ;; -----
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!
59 ;;; Code:
61 (require 'tramp-compat)
63 ;;; User Customizable Internal Variables:
65 (defgroup tramp nil
66 "Edit remote files with a combination of rsh and rcp or similar programs."
67 :group 'files
68 :group 'comm
69 :version "22.1")
71 ;; Maybe we need once a real Tramp mode, with key bindings etc.
72 ;;;###autoload
73 (defcustom tramp-mode t
74 "*Whether Tramp is enabled.
75 If it is set to nil, all remote file names are used literally."
76 :group 'tramp
77 :type 'boolean)
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)
84 1 errors
85 2 warnings
86 3 connection to remote hosts (default level)
87 4 activities
88 5 internal
89 6 sent and received strings
90 7 file caching
91 8 connection properties
92 9 test commands
93 10 traces (huge)."
94 :group 'tramp
95 :type 'integer)
97 ;; Emacs case.
98 (eval-and-compile
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."
111 :group 'tramp
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.
117 (eval-and-compile
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."
130 :type '(repeat
131 (list (regexp :tag "File regexp")
132 (string :tag "Backup Dir")
133 (set :inline t
134 (const ok-create)
135 (const full-path)
136 (const prepend-name)
137 (const search-upward))))
138 :group 'tramp)))
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."
143 :group 'tramp
144 :type '(choice (const nil) string))
146 (defcustom tramp-encoding-shell
147 (if (memq system-type '(windows-nt))
148 (getenv "COMSPEC")
149 "/bin/sh")
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."
166 :group 'tramp
167 :type '(file :must-match t))
169 (defcustom tramp-encoding-command-switch
170 (if (string-match "cmd\\.exe" tramp-encoding-shell)
171 "/c"
172 "-c")
173 "*Use this switch together with `tramp-encoding-shell' for local commands.
174 See the variable `tramp-encoding-shell' for more information."
175 :group 'tramp
176 :type 'string)
178 ;;;###tramp-autoload
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:
184 * `tramp-remote-sh'
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.
195 * `tramp-login-args'
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.
209 * `tramp-async-args'
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
217 a workalike program.
218 * `tramp-copy-args'
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
232 passing gateways.
233 * `tramp-gw-args'
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.
265 Notes:
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."
278 (ignore-errors
279 (with-temp-buffer
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.
293 (cond
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"))
300 "pscp"
301 "plink"))
302 ;; There is an ssh installation.
303 ((executable-find "scp")
304 (cond
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"))
311 "scp")
312 (t "ssh")))
313 ;; Fallback.
314 (t "ftp"))
315 "*Default method to use for transferring files.
316 See `tramp-methods' for possibilities.
317 Also see `tramp-default-method-alist'."
318 :group 'tramp
319 :type 'string)
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."
333 :group 'tramp
334 :type '(repeat (list (regexp :tag "Host regexp")
335 (regexp :tag "User regexp")
336 (string :tag "Method"))))
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."
344 :group 'tramp
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."
357 :group 'tramp
358 :type '(repeat (list (regexp :tag "Method regexp")
359 (regexp :tag "Host regexp")
360 (string :tag "User"))))
362 (defcustom tramp-default-host (system-name)
363 "*Default host to use for transferring files.
364 Useful for su and sudo methods mostly."
365 :group 'tramp
366 :type 'string)
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."
382 :group 'tramp
383 :type '(repeat (list (choice :tag "Host regexp" regexp sexp)
384 (choice :tag "User regexp" regexp sexp)
385 (choice :tag "Proxy remote name" string (const nil)))))
387 (defconst tramp-local-host-regexp
388 (concat
389 "^" (regexp-opt (list "localhost" (system-name) "127\.0\.0\.1" "::1") t) "$")
390 "*Host names which are regarded as local host.")
392 (defvar tramp-completion-function-alist nil
393 "*Alist of methods for remote files.
394 This is a list of entries of the form \(NAME PAIR1 PAIR2 ...\).
395 Each NAME stands for a remote access method. Each PAIR is of the form
396 \(FUNCTION FILE\). FUNCTION is responsible to extract user names and host
397 names from FILE for completion. The following predefined FUNCTIONs exists:
399 * `tramp-parse-rhosts' for \"~/.rhosts\" like files,
400 * `tramp-parse-shosts' for \"~/.ssh/known_hosts\" like files,
401 * `tramp-parse-sconfig' for \"~/.ssh/config\" like files,
402 * `tramp-parse-shostkeys' for \"~/.ssh2/hostkeys/*\" like files,
403 * `tramp-parse-sknownhosts' for \"~/.ssh2/knownhosts/*\" like files,
404 * `tramp-parse-hosts' for \"/etc/hosts\" like files,
405 * `tramp-parse-passwd' for \"/etc/passwd\" like files.
406 * `tramp-parse-netrc' for \"~/.netrc\" like files.
407 * `tramp-parse-putty' for PuTTY registry keys.
409 FUNCTION can also be a customer defined function. For more details see
410 the info pages.")
412 (defconst tramp-echo-mark-marker "_echo"
413 "String marker to surround echoed commands.")
415 (defconst tramp-echo-mark-marker-length (length tramp-echo-mark-marker)
416 "String length of `tramp-echo-mark-marker'.")
418 (defconst tramp-echo-mark
419 (concat tramp-echo-mark-marker
420 (make-string tramp-echo-mark-marker-length ?\b))
421 "String mark to be transmitted around shell commands.
422 Used to separate their echo from the output they produce. This
423 will only be used if we cannot disable remote echo via stty.
424 This string must have no effect on the remote shell except for
425 producing some echo which can later be detected by
426 `tramp-echoed-echo-mark-regexp'. Using `tramp-echo-mark-marker',
427 followed by an equal number of backspaces to erase them will
428 usually suffice.")
430 (defconst tramp-echoed-echo-mark-regexp
431 (format "%s\\(\b\\( \b\\)?\\)\\{%d\\}"
432 tramp-echo-mark-marker tramp-echo-mark-marker-length)
433 "Regexp which matches `tramp-echo-mark' as it gets echoed by
434 the remote shell.")
436 (defcustom tramp-rsh-end-of-line "\n"
437 "*String used for end of line in rsh connections.
438 I don't think this ever needs to be changed, so please tell me about it
439 if you need to change this.
440 Also see the method parameter `tramp-password-end-of-line' and the normal
441 variable `tramp-default-password-end-of-line'."
442 :group 'tramp
443 :type 'string)
445 (defcustom tramp-default-password-end-of-line
446 tramp-rsh-end-of-line
447 "*String used for end of line after sending a password.
448 This variable provides the default value for the method parameter
449 `tramp-password-end-of-line', see `tramp-methods' for more details.
451 It seems that people using plink under Windows need to send
452 \"\\r\\n\" (carriage-return, then newline) after a password, but just
453 \"\\n\" after all other lines. This variable can be used for the
454 password, see `tramp-rsh-end-of-line' for the other cases.
456 The default value is to use the same value as `tramp-rsh-end-of-line'."
457 :group 'tramp
458 :type 'string)
460 (defcustom tramp-login-prompt-regexp
461 ".*ogin\\( .*\\)?: *"
462 "*Regexp matching login-like prompts.
463 The regexp should match at end of buffer.
465 Sometimes the prompt is reported to look like \"login as:\"."
466 :group 'tramp
467 :type 'regexp)
469 (defcustom tramp-shell-prompt-pattern
470 ;; Allow a prompt to start right after a ^M since it indeed would be
471 ;; displayed at the beginning of the line (and Zsh uses it). This
472 ;; regexp works only for GNU Emacs.
473 (concat (if (featurep 'xemacs) "" "\\(?:^\\|\r\\)")
474 "[^#$%>\n]*#?[#$%>] *\\(\e\\[[0-9;]*[a-zA-Z] *\\)*")
475 "Regexp to match prompts from remote shell.
476 Normally, Tramp expects you to configure `shell-prompt-pattern'
477 correctly, but sometimes it happens that you are connecting to a
478 remote host which sends a different kind of shell prompt. Therefore,
479 Tramp recognizes things matched by `shell-prompt-pattern' as prompt,
480 and also things matched by this variable. The default value of this
481 variable is similar to the default value of `shell-prompt-pattern',
482 which should work well in many cases.
484 This regexp must match both `tramp-initial-end-of-output' and
485 `tramp-end-of-output'."
486 :group 'tramp
487 :type 'regexp)
489 (defcustom tramp-password-prompt-regexp
490 "^.*\\([pP]assword\\|[pP]assphrase\\).*:\^@? *"
491 "*Regexp matching password-like prompts.
492 The regexp should match at end of buffer.
494 The `sudo' program appears to insert a `^@' character into the prompt."
495 :group 'tramp
496 :type 'regexp)
498 (defcustom tramp-wrong-passwd-regexp
499 (concat "^.*"
500 ;; These strings should be on the last line
501 (regexp-opt '("Permission denied"
502 "Login incorrect"
503 "Login Incorrect"
504 "Connection refused"
505 "Connection closed"
506 "Timeout, server not responding."
507 "Sorry, try again."
508 "Name or service not known"
509 "Host key verification failed."
510 "No supported authentication methods left to try!") t)
511 ".*"
512 "\\|"
513 "^.*\\("
514 ;; Here comes a list of regexes, separated by \\|
515 "Received signal [0-9]+"
516 "\\).*")
517 "*Regexp matching a `login failed' message.
518 The regexp should match at end of buffer."
519 :group 'tramp
520 :type 'regexp)
522 (defcustom tramp-yesno-prompt-regexp
523 (concat
524 (regexp-opt '("Are you sure you want to continue connecting (yes/no)?") t)
525 "\\s-*")
526 "Regular expression matching all yes/no queries which need to be confirmed.
527 The confirmation should be done with yes or no.
528 The regexp should match at end of buffer.
529 See also `tramp-yn-prompt-regexp'."
530 :group 'tramp
531 :type 'regexp)
533 (defcustom tramp-yn-prompt-regexp
534 (concat
535 (regexp-opt '("Store key in cache? (y/n)"
536 "Update cached key? (y/n, Return cancels connection)") t)
537 "\\s-*")
538 "Regular expression matching all y/n queries which need to be confirmed.
539 The confirmation should be done with y or n.
540 The regexp should match at end of buffer.
541 See also `tramp-yesno-prompt-regexp'."
542 :group 'tramp
543 :type 'regexp)
545 (defcustom tramp-terminal-prompt-regexp
546 (concat "\\("
547 "TERM = (.*)"
548 "\\|"
549 "Terminal type\\? \\[.*\\]"
550 "\\)\\s-*")
551 "Regular expression matching all terminal setting prompts.
552 The regexp should match at end of buffer.
553 The answer will be provided by `tramp-action-terminal', which see."
554 :group 'tramp
555 :type 'regexp)
557 (defcustom tramp-operation-not-permitted-regexp
558 (concat "\\(" "preserving times.*" "\\|" "set mode" "\\)" ":\\s-*"
559 (regexp-opt '("Operation not permitted") t))
560 "Regular expression matching keep-date problems in (s)cp operations.
561 Copying has been performed successfully already, so this message can
562 be ignored safely."
563 :group 'tramp
564 :type 'regexp)
566 (defcustom tramp-copy-failed-regexp
567 (concat "\\(.+: "
568 (regexp-opt '("Permission denied"
569 "not a regular file"
570 "is a directory"
571 "No such file or directory") t)
572 "\\)\\s-*")
573 "Regular expression matching copy problems in (s)cp operations."
574 :group 'tramp
575 :type 'regexp)
577 (defcustom tramp-process-alive-regexp
579 "Regular expression indicating a process has finished.
580 In fact this expression is empty by intention, it will be used only to
581 check regularly the status of the associated process.
582 The answer will be provided by `tramp-action-process-alive',
583 `tramp-action-out-of-band', which see."
584 :group 'tramp
585 :type 'regexp)
587 (defconst tramp-temp-name-prefix "tramp."
588 "*Prefix to use for temporary files.
589 If this is a relative file name (such as \"tramp.\"), it is considered
590 relative to the directory name returned by the function
591 `tramp-compat-temporary-file-directory' (which see). It may also be an
592 absolute file name; don't forget to include a prefix for the filename
593 part, though.")
595 (defconst tramp-temp-buffer-name " *tramp temp*"
596 "Buffer name for a temporary buffer.
597 It shall be used in combination with `generate-new-buffer-name'.")
599 (defvar tramp-temp-buffer-file-name nil
600 "File name of a persistent local temporary file.
601 Useful for \"rsync\" like methods.")
602 (make-variable-buffer-local 'tramp-temp-buffer-file-name)
604 ;; XEmacs is distributed with few Lisp packages. Further packages are
605 ;; installed using EFS. If we use a unified filename format, then
606 ;; Tramp is required in addition to EFS. (But why can't Tramp just
607 ;; disable EFS when Tramp is loaded? Then XEmacs can ship with EFS
608 ;; just like before.) Another reason for using a separate filename
609 ;; syntax on XEmacs is that EFS hooks into XEmacs in many places, but
610 ;; Tramp only knows how to deal with `file-name-handler-alist', not
611 ;; the other places.
613 ;; Currently, we have the choice between 'ftp, 'sep, and 'url.
614 ;;;###autoload
615 (defcustom tramp-syntax
616 (if (featurep 'xemacs) 'sep 'ftp)
617 "Tramp filename syntax to be used.
619 It can have the following values:
621 'ftp -- Ange-FTP respective EFS like syntax (GNU Emacs default)
622 'sep -- Syntax as defined for XEmacs (not available yet for GNU Emacs)
623 'url -- URL-like syntax."
624 :group 'tramp
625 :type (if (featurep 'xemacs)
626 '(choice (const :tag "EFS" ftp)
627 (const :tag "XEmacs" sep)
628 (const :tag "URL" url))
629 '(choice (const :tag "Ange-FTP" ftp)
630 (const :tag "URL" url))))
632 (defconst tramp-prefix-format
633 (cond ((equal tramp-syntax 'ftp) "/")
634 ((equal tramp-syntax 'sep) "/[")
635 ((equal tramp-syntax 'url) "/")
636 (t (error "Wrong `tramp-syntax' defined")))
637 "*String matching the very beginning of Tramp file names.
638 Used in `tramp-make-tramp-file-name'.")
640 (defconst tramp-prefix-regexp
641 (concat "^" (regexp-quote tramp-prefix-format))
642 "*Regexp matching the very beginning of Tramp file names.
643 Should always start with \"^\". Derived from `tramp-prefix-format'.")
645 (defconst tramp-method-regexp
646 "[a-zA-Z_0-9-]+"
647 "*Regexp matching methods identifiers.")
649 (defconst tramp-postfix-method-format
650 (cond ((equal tramp-syntax 'ftp) ":")
651 ((equal tramp-syntax 'sep) "/")
652 ((equal tramp-syntax 'url) "://")
653 (t (error "Wrong `tramp-syntax' defined")))
654 "*String matching delimeter between method and user or host names.
655 Used in `tramp-make-tramp-file-name'.")
657 (defconst tramp-postfix-method-regexp
658 (regexp-quote tramp-postfix-method-format)
659 "*Regexp matching delimeter between method and user or host names.
660 Derived from `tramp-postfix-method-format'.")
662 (defconst tramp-user-regexp "[^:/ \t]+"
663 "*Regexp matching user names.")
665 (defconst tramp-prefix-domain-format "%"
666 "*String matching delimeter between user and domain names.")
668 (defconst tramp-prefix-domain-regexp
669 (regexp-quote tramp-prefix-domain-format)
670 "*Regexp matching delimeter between user and domain names.
671 Derived from `tramp-prefix-domain-format'.")
673 (defconst tramp-domain-regexp "[-a-zA-Z0-9_.]+"
674 "*Regexp matching domain names.")
676 (defconst tramp-user-with-domain-regexp
677 (concat "\\(" tramp-user-regexp "\\)"
678 tramp-prefix-domain-regexp
679 "\\(" tramp-domain-regexp "\\)")
680 "*Regexp matching user names with domain names.")
682 (defconst tramp-postfix-user-format "@"
683 "*String matching delimeter between user and host names.
684 Used in `tramp-make-tramp-file-name'.")
686 (defconst tramp-postfix-user-regexp
687 (regexp-quote tramp-postfix-user-format)
688 "*Regexp matching delimeter between user and host names.
689 Derived from `tramp-postfix-user-format'.")
691 (defconst tramp-host-regexp "[a-zA-Z0-9_.-]+"
692 "*Regexp matching host names.")
694 (defconst tramp-prefix-ipv6-format
695 (cond ((equal tramp-syntax 'ftp) "[")
696 ((equal tramp-syntax 'sep) "")
697 ((equal tramp-syntax 'url) "[")
698 (t (error "Wrong `tramp-syntax' defined")))
699 "*String matching left hand side of IPv6 addresses.
700 Used in `tramp-make-tramp-file-name'.")
702 (defconst tramp-prefix-ipv6-regexp
703 (regexp-quote tramp-prefix-ipv6-format)
704 "*Regexp matching left hand side of IPv6 addresses.
705 Derived from `tramp-prefix-ipv6-format'.")
707 ;; The following regexp is a bit sloppy. But it shall serve our
708 ;; purposes. It covers also IPv4 mapped IPv6 addresses, like in
709 ;; "::ffff:192.168.0.1".
710 (defconst tramp-ipv6-regexp
711 "\\(?:\\(?:[a-zA-Z0-9]+\\)?:\\)+[a-zA-Z0-9.]+"
712 "*Regexp matching IPv6 addresses.")
714 (defconst tramp-postfix-ipv6-format
715 (cond ((equal tramp-syntax 'ftp) "]")
716 ((equal tramp-syntax 'sep) "")
717 ((equal tramp-syntax 'url) "]")
718 (t (error "Wrong `tramp-syntax' defined")))
719 "*String matching right hand side of IPv6 addresses.
720 Used in `tramp-make-tramp-file-name'.")
722 (defconst tramp-postfix-ipv6-regexp
723 (regexp-quote tramp-postfix-ipv6-format)
724 "*Regexp matching right hand side of IPv6 addresses.
725 Derived from `tramp-postfix-ipv6-format'.")
727 (defconst tramp-prefix-port-format
728 (cond ((equal tramp-syntax 'ftp) "#")
729 ((equal tramp-syntax 'sep) "#")
730 ((equal tramp-syntax 'url) ":")
731 (t (error "Wrong `tramp-syntax' defined")))
732 "*String matching delimeter between host names and port numbers.")
734 (defconst tramp-prefix-port-regexp
735 (regexp-quote tramp-prefix-port-format)
736 "*Regexp matching delimeter between host names and port numbers.
737 Derived from `tramp-prefix-port-format'.")
739 (defconst tramp-port-regexp "[0-9]+"
740 "*Regexp matching port numbers.")
742 (defconst tramp-host-with-port-regexp
743 (concat "\\(" tramp-host-regexp "\\)"
744 tramp-prefix-port-regexp
745 "\\(" tramp-port-regexp "\\)")
746 "*Regexp matching host names with port numbers.")
748 (defconst tramp-postfix-host-format
749 (cond ((equal tramp-syntax 'ftp) ":")
750 ((equal tramp-syntax 'sep) "]")
751 ((equal tramp-syntax 'url) "")
752 (t (error "Wrong `tramp-syntax' defined")))
753 "*String matching delimeter between host names and localnames.
754 Used in `tramp-make-tramp-file-name'.")
756 (defconst tramp-postfix-host-regexp
757 (regexp-quote tramp-postfix-host-format)
758 "*Regexp matching delimeter between host names and localnames.
759 Derived from `tramp-postfix-host-format'.")
761 (defconst tramp-localname-regexp ".*$"
762 "*Regexp matching localnames.")
764 ;;; File name format:
766 (defconst tramp-file-name-structure
767 (list
768 (concat
769 tramp-prefix-regexp
770 "\\(" "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp "\\)?"
771 "\\(" "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp "\\)?"
772 "\\(" "\\(" tramp-host-regexp
773 "\\|"
774 tramp-prefix-ipv6-regexp tramp-ipv6-regexp
775 tramp-postfix-ipv6-regexp "\\)"
776 "\\(" tramp-prefix-port-regexp tramp-port-regexp "\\)?" "\\)?"
777 tramp-postfix-host-regexp
778 "\\(" tramp-localname-regexp "\\)")
779 2 4 5 8)
781 "*List of five elements (REGEXP METHOD USER HOST FILE), detailing \
782 the Tramp file name structure.
784 The first element REGEXP is a regular expression matching a Tramp file
785 name. The regex should contain parentheses around the method name,
786 the user name, the host name, and the file name parts.
788 The second element METHOD is a number, saying which pair of
789 parentheses matches the method name. The third element USER is
790 similar, but for the user name. The fourth element HOST is similar,
791 but for the host name. The fifth element FILE is for the file name.
792 These numbers are passed directly to `match-string', which see. That
793 means the opening parentheses are counted to identify the pair.
795 See also `tramp-file-name-regexp'.")
797 ;;;###autoload
798 (defconst tramp-file-name-regexp-unified
799 (if (memq system-type '(cygwin windows-nt))
800 "\\`/\\([^[/:]\\{2,\\}\\|[^/]\\{2,\\}]\\):"
801 "\\`/\\([^[/:]+\\|[^/]+]\\):")
802 "Value for `tramp-file-name-regexp' for unified remoting.
803 Emacs (not XEmacs) uses a unified filename syntax for Ange-FTP and
804 Tramp. See `tramp-file-name-structure' for more explanations.
806 On W32 systems, the volume letter must be ignored.")
808 ;;;###autoload
809 (defconst tramp-file-name-regexp-separate "\\`/\\[.*\\]"
810 "Value for `tramp-file-name-regexp' for separate remoting.
811 XEmacs uses a separate filename syntax for Tramp and EFS.
812 See `tramp-file-name-structure' for more explanations.")
814 ;;;###autoload
815 (defconst tramp-file-name-regexp-url "\\`/[^/:]+://"
816 "Value for `tramp-file-name-regexp' for URL-like remoting.
817 See `tramp-file-name-structure' for more explanations.")
819 ;;;###autoload
820 (defconst tramp-file-name-regexp
821 (cond ((equal tramp-syntax 'ftp) tramp-file-name-regexp-unified)
822 ((equal tramp-syntax 'sep) tramp-file-name-regexp-separate)
823 ((equal tramp-syntax 'url) tramp-file-name-regexp-url)
824 (t (error "Wrong `tramp-syntax' defined")))
825 "*Regular expression matching file names handled by Tramp.
826 This regexp should match Tramp file names but no other file names.
827 When tramp.el is loaded, this regular expression is prepended to
828 `file-name-handler-alist', and that is searched sequentially. Thus,
829 if the Tramp entry appears rather early in the `file-name-handler-alist'
830 and is a bit too general, then some files might be considered Tramp
831 files which are not really Tramp files.
833 Please note that the entry in `file-name-handler-alist' is made when
834 this file \(tramp.el\) is loaded. This means that this variable must be set
835 before loading tramp.el. Alternatively, `file-name-handler-alist' can be
836 updated after changing this variable.
838 Also see `tramp-file-name-structure'.")
840 ;;;###autoload
841 (defconst tramp-root-regexp
842 (if (memq system-type '(cygwin windows-nt))
843 "\\`\\([a-zA-Z]:\\)?/"
844 "\\`/")
845 "Beginning of an incomplete Tramp file name.
846 Usually, it is just \"\\\\`/\". On W32 systems, there might be a
847 volume letter, which will be removed by `tramp-drop-volume-letter'.")
849 ;;;###autoload
850 (defconst tramp-completion-file-name-regexp-unified
851 (if (memq system-type '(cygwin windows-nt))
852 (concat tramp-root-regexp "[^/]\\{2,\\}\\'")
853 (concat tramp-root-regexp "[^/]*\\'"))
854 "Value for `tramp-completion-file-name-regexp' for unified remoting.
855 GNU Emacs uses a unified filename syntax for Tramp and Ange-FTP.
856 See `tramp-file-name-structure' for more explanations.
858 On W32 systems, the volume letter must be ignored.")
860 ;;;###autoload
861 (defconst tramp-completion-file-name-regexp-separate
862 (concat tramp-root-regexp "\\([[][^]]*\\)?\\'")
863 "Value for `tramp-completion-file-name-regexp' for separate remoting.
864 XEmacs uses a separate filename syntax for Tramp and EFS.
865 See `tramp-file-name-structure' for more explanations.")
867 ;;;###autoload
868 (defconst tramp-completion-file-name-regexp-url
869 (concat tramp-root-regexp "[^/:]+\\(:\\(/\\(/[^/]*\\)?\\)?\\)?\\'")
870 "Value for `tramp-completion-file-name-regexp' for URL-like remoting.
871 See `tramp-file-name-structure' for more explanations.")
873 ;;;###autoload
874 (defconst tramp-completion-file-name-regexp
875 (cond ((equal tramp-syntax 'ftp) tramp-completion-file-name-regexp-unified)
876 ((equal tramp-syntax 'sep) tramp-completion-file-name-regexp-separate)
877 ((equal tramp-syntax 'url) tramp-completion-file-name-regexp-url)
878 (t (error "Wrong `tramp-syntax' defined")))
879 "*Regular expression matching file names handled by Tramp completion.
880 This regexp should match partial Tramp file names only.
882 Please note that the entry in `file-name-handler-alist' is made when
883 this file (tramp.el) is loaded. This means that this variable must be set
884 before loading tramp.el. Alternatively, `file-name-handler-alist' can be
885 updated after changing this variable.
887 Also see `tramp-file-name-structure'.")
889 ;; Chunked sending kludge. We set this to 500 for black-listed constellations
890 ;; known to have a bug in `process-send-string'; some ssh connections appear
891 ;; to drop bytes when data is sent too quickly. There is also a connection
892 ;; buffer local variable, which is computed depending on remote host properties
893 ;; when `tramp-chunksize' is zero or nil.
894 (defcustom tramp-chunksize
895 (when (and (not (featurep 'xemacs))
896 (memq system-type '(hpux)))
897 500)
898 ;; Parentheses in docstring starting at beginning of line are escaped.
899 ;; Fontification is messed up when
900 ;; `open-paren-in-column-0-is-defun-start' set to t.
901 "*If non-nil, chunksize for sending input to local process.
902 It is necessary only on systems which have a buggy `process-send-string'
903 implementation. The necessity, whether this variable must be set, can be
904 checked via the following code:
906 (with-temp-buffer
907 (let* ((user \"xxx\") (host \"yyy\")
908 (init 0) (step 50)
909 (sent init) (received init))
910 (while (= sent received)
911 (setq sent (+ sent step))
912 (erase-buffer)
913 (let ((proc (start-process (buffer-name) (current-buffer)
914 \"ssh\" \"-l\" user host \"wc\" \"-c\")))
915 (when (memq (process-status proc) '(run open))
916 (process-send-string proc (make-string sent ?\\ ))
917 (process-send-eof proc)
918 (process-send-eof proc))
919 (while (not (progn (goto-char (point-min))
920 (re-search-forward \"\\\\w+\" (point-max) t)))
921 (accept-process-output proc 1))
922 (when (memq (process-status proc) '(run open))
923 (setq received (string-to-number (match-string 0)))
924 (delete-process proc)
925 (message \"Bytes sent: %s\\tBytes received: %s\" sent received)
926 (sit-for 0))))
927 (if (> sent (+ init step))
928 (message \"You should set `tramp-chunksize' to a maximum of %s\"
929 (- sent step))
930 (message \"Test does not work\")
931 (display-buffer (current-buffer))
932 (sit-for 30))))
934 In the Emacs normally running Tramp, evaluate the above code
935 \(replace \"xxx\" and \"yyy\" by the remote user and host name,
936 respectively\). You can do this, for example, by pasting it into
937 the `*scratch*' buffer and then hitting C-j with the cursor after the
938 last closing parenthesis. Note that it works only if you have configured
939 \"ssh\" to run without password query, see ssh-agent\(1\).
941 You will see the number of bytes sent successfully to the remote host.
942 If that number exceeds 1000, you can stop the execution by hitting
943 C-g, because your Emacs is likely clean.
945 When it is necessary to set `tramp-chunksize', you might consider to
946 use an out-of-the-band method \(like \"scp\"\) instead of an internal one
947 \(like \"ssh\"\), because setting `tramp-chunksize' to non-nil decreases
948 performance.
950 If your Emacs is buggy, the code stops and gives you an indication
951 about the value `tramp-chunksize' should be set. Maybe you could just
952 experiment a bit, e.g. changing the values of `init' and `step'
953 in the third line of the code.
955 Please raise a bug report via \"M-x tramp-bug\" if your system needs
956 this variable to be set as well."
957 :group 'tramp
958 :type '(choice (const nil) integer))
960 ;; Logging in to a remote host normally requires obtaining a pty. But
961 ;; Emacs on MacOS X has process-connection-type set to nil by default,
962 ;; so on those systems Tramp doesn't obtain a pty. Here, we allow
963 ;; for an override of the system default.
964 (defcustom tramp-process-connection-type t
965 "Overrides `process-connection-type' for connections from Tramp.
966 Tramp binds process-connection-type to the value given here before
967 opening a connection to a remote host."
968 :group 'tramp
969 :type '(choice (const nil) (const t) (const pty)))
971 (defcustom tramp-completion-reread-directory-timeout 10
972 "Defines seconds since last remote command before rereading a directory.
973 A remote directory might have changed its contents. In order to
974 make it visible during file name completion in the minibuffer,
975 Tramp flushes its cache and rereads the directory contents when
976 more than `tramp-completion-reread-directory-timeout' seconds
977 have been gone since last remote command execution. A value of `t'
978 would require an immediate reread during filename completion, `nil'
979 means to use always cached values for the directory contents."
980 :group 'tramp
981 :type '(choice (const nil) integer))
983 ;;; Internal Variables:
985 (defvar tramp-current-method nil
986 "Connection method for this *tramp* buffer.")
988 (defvar tramp-current-user nil
989 "Remote login name for this *tramp* buffer.")
991 (defvar tramp-current-host nil
992 "Remote host for this *tramp* buffer.")
994 ;;;###autoload
995 (defconst tramp-completion-file-name-handler-alist
996 '((file-name-all-completions . tramp-completion-handle-file-name-all-completions)
997 (file-name-completion . tramp-completion-handle-file-name-completion))
998 "Alist of completion handler functions.
999 Used for file names matching `tramp-file-name-regexp'. Operations
1000 not mentioned here will be handled by Tramp's file name handler
1001 functions, or the normal Emacs functions.")
1003 ;; Handlers for foreign methods, like FTP or SMB, shall be plugged here.
1004 ;;;###tramp-autoload
1005 (defvar tramp-foreign-file-name-handler-alist nil
1006 "Alist of elements (FUNCTION . HANDLER) for foreign methods handled specially.
1007 If (FUNCTION FILENAME) returns non-nil, then all I/O on that file is done by
1008 calling HANDLER.")
1010 ;;; Internal functions which must come first:
1012 ;; Conversion functions between external representation and
1013 ;; internal data structure. Convenience functions for internal
1014 ;; data structure.
1016 (defun tramp-file-name-p (vec)
1017 "Check, whether VEC is a Tramp object."
1018 (and (vectorp vec) (= 4 (length vec))))
1020 (defun tramp-file-name-method (vec)
1021 "Return method component of VEC."
1022 (and (tramp-file-name-p vec) (aref vec 0)))
1024 (defun tramp-file-name-user (vec)
1025 "Return user component of VEC."
1026 (and (tramp-file-name-p vec) (aref vec 1)))
1028 (defun tramp-file-name-host (vec)
1029 "Return host component of VEC."
1030 (and (tramp-file-name-p vec) (aref vec 2)))
1032 (defun tramp-file-name-localname (vec)
1033 "Return localname component of VEC."
1034 (and (tramp-file-name-p vec) (aref vec 3)))
1036 ;; The user part of a Tramp file name vector can be of kind
1037 ;; "user%domain". Sometimes, we must extract these parts.
1038 (defun tramp-file-name-real-user (vec)
1039 "Return the user name of VEC without domain."
1040 (save-match-data
1041 (let ((user (tramp-file-name-user vec)))
1042 (if (and (stringp user)
1043 (string-match tramp-user-with-domain-regexp user))
1044 (match-string 1 user)
1045 user))))
1047 (defun tramp-file-name-domain (vec)
1048 "Return the domain name of VEC."
1049 (save-match-data
1050 (let ((user (tramp-file-name-user vec)))
1051 (and (stringp user)
1052 (string-match tramp-user-with-domain-regexp user)
1053 (match-string 2 user)))))
1055 ;; The host part of a Tramp file name vector can be of kind
1056 ;; "host#port". Sometimes, we must extract these parts.
1057 (defun tramp-file-name-real-host (vec)
1058 "Return the host name of VEC without port."
1059 (save-match-data
1060 (let ((host (tramp-file-name-host vec)))
1061 (if (and (stringp host)
1062 (string-match tramp-host-with-port-regexp host))
1063 (match-string 1 host)
1064 host))))
1066 (defun tramp-file-name-port (vec)
1067 "Return the port number of VEC."
1068 (save-match-data
1069 (let ((host (tramp-file-name-host vec)))
1070 (and (stringp host)
1071 (string-match tramp-host-with-port-regexp host)
1072 (string-to-number (match-string 2 host))))))
1074 ;;;###tramp-autoload
1075 (defun tramp-tramp-file-p (name)
1076 "Return t if NAME is a string with Tramp file name syntax."
1077 (save-match-data
1078 (and (stringp name) (string-match tramp-file-name-regexp name))))
1080 (defun tramp-find-method (method user host)
1081 "Return the right method string to use.
1082 This is METHOD, if non-nil. Otherwise, do a lookup in
1083 `tramp-default-method-alist'."
1084 (or method
1085 (let ((choices tramp-default-method-alist)
1086 lmethod item)
1087 (while choices
1088 (setq item (pop choices))
1089 (when (and (string-match (or (nth 0 item) "") (or host ""))
1090 (string-match (or (nth 1 item) "") (or user "")))
1091 (setq lmethod (nth 2 item))
1092 (setq choices nil)))
1093 lmethod)
1094 tramp-default-method))
1096 (defun tramp-find-user (method user host)
1097 "Return the right user string to use.
1098 This is USER, if non-nil. Otherwise, do a lookup in
1099 `tramp-default-user-alist'."
1100 (or user
1101 (let ((choices tramp-default-user-alist)
1102 luser item)
1103 (while choices
1104 (setq item (pop choices))
1105 (when (and (string-match (or (nth 0 item) "") (or method ""))
1106 (string-match (or (nth 1 item) "") (or host "")))
1107 (setq luser (nth 2 item))
1108 (setq choices nil)))
1109 luser)
1110 tramp-default-user))
1112 (defun tramp-find-host (method user host)
1113 "Return the right host string to use.
1114 This is HOST, if non-nil. Otherwise, it is `tramp-default-host'."
1115 (or (and (> (length host) 0) host)
1116 tramp-default-host))
1118 (defun tramp-dissect-file-name (name &optional nodefault)
1119 "Return a `tramp-file-name' structure.
1120 The structure consists of remote method, remote user, remote host
1121 and localname (file name on remote host). If NODEFAULT is
1122 non-nil, the file name parts are not expanded to their default
1123 values."
1124 (save-match-data
1125 (let ((match (string-match (nth 0 tramp-file-name-structure) name)))
1126 (unless match (error "Not a Tramp file name: %s" name))
1127 (let ((method (match-string (nth 1 tramp-file-name-structure) name))
1128 (user (match-string (nth 2 tramp-file-name-structure) name))
1129 (host (match-string (nth 3 tramp-file-name-structure) name))
1130 (localname (match-string (nth 4 tramp-file-name-structure) name)))
1131 (when host
1132 (when (string-match tramp-prefix-ipv6-regexp host)
1133 (setq host (replace-match "" nil t host)))
1134 (when (string-match tramp-postfix-ipv6-regexp host)
1135 (setq host (replace-match "" nil t host))))
1136 (if nodefault
1137 (vector method user host localname)
1138 (vector
1139 (tramp-find-method method user host)
1140 (tramp-find-user method user host)
1141 (tramp-find-host method user host)
1142 localname))))))
1144 (defun tramp-buffer-name (vec)
1145 "A name for the connection buffer VEC."
1146 ;; We must use `tramp-file-name-real-host', because for gateway
1147 ;; methods the default port will be expanded later on, which would
1148 ;; tamper the name.
1149 (let ((method (tramp-file-name-method vec))
1150 (user (tramp-file-name-user vec))
1151 (host (tramp-file-name-real-host vec)))
1152 (if (not (zerop (length user)))
1153 (format "*tramp/%s %s@%s*" method user host)
1154 (format "*tramp/%s %s*" method host))))
1156 (defun tramp-make-tramp-file-name (method user host localname)
1157 "Constructs a Tramp file name from METHOD, USER, HOST and LOCALNAME."
1158 (concat tramp-prefix-format
1159 (when (not (zerop (length method)))
1160 (concat method tramp-postfix-method-format))
1161 (when (not (zerop (length user)))
1162 (concat user tramp-postfix-user-format))
1163 (when host
1164 (if (string-match tramp-ipv6-regexp host)
1165 (concat tramp-prefix-ipv6-format host tramp-postfix-ipv6-format)
1166 host))
1167 tramp-postfix-host-format
1168 (when localname localname)))
1170 (defun tramp-completion-make-tramp-file-name (method user host localname)
1171 "Constructs a Tramp file name from METHOD, USER, HOST and LOCALNAME.
1172 It must not be a complete Tramp file name, but as long as there are
1173 necessary only. This function will be used in file name completion."
1174 (concat tramp-prefix-format
1175 (when (not (zerop (length method)))
1176 (concat method tramp-postfix-method-format))
1177 (when (not (zerop (length user)))
1178 (concat user tramp-postfix-user-format))
1179 (when (not (zerop (length host)))
1180 (concat
1181 (if (string-match tramp-ipv6-regexp host)
1182 (concat
1183 tramp-prefix-ipv6-format host tramp-postfix-ipv6-format)
1184 host)
1185 tramp-postfix-host-format))
1186 (when localname localname)))
1188 (defun tramp-get-buffer (vec)
1189 "Get the connection buffer to be used for VEC."
1190 (or (get-buffer (tramp-buffer-name vec))
1191 (with-current-buffer (get-buffer-create (tramp-buffer-name vec))
1192 (setq buffer-undo-list t)
1193 (setq default-directory
1194 (tramp-make-tramp-file-name
1195 (tramp-file-name-method vec)
1196 (tramp-file-name-user vec)
1197 (tramp-file-name-host vec)
1198 "/"))
1199 (current-buffer))))
1201 (defun tramp-get-connection-buffer (vec)
1202 "Get the connection buffer to be used for VEC.
1203 In case a second asynchronous communication has been started, it is different
1204 from `tramp-get-buffer'."
1205 (or (tramp-get-connection-property vec "process-buffer" nil)
1206 (tramp-get-buffer vec)))
1208 (defun tramp-get-connection-process (vec)
1209 "Get the connection process to be used for VEC.
1210 In case a second asynchronous communication has been started, it is different
1211 from the default one."
1212 (get-process
1213 (or (tramp-get-connection-property vec "process-name" nil)
1214 (tramp-buffer-name vec))))
1216 (defun tramp-debug-buffer-name (vec)
1217 "A name for the debug buffer for VEC."
1218 ;; We must use `tramp-file-name-real-host', because for gateway
1219 ;; methods the default port will be expanded later on, which would
1220 ;; tamper the name.
1221 (let ((method (tramp-file-name-method vec))
1222 (user (tramp-file-name-user vec))
1223 (host (tramp-file-name-real-host vec)))
1224 (if (not (zerop (length user)))
1225 (format "*debug tramp/%s %s@%s*" method user host)
1226 (format "*debug tramp/%s %s*" method host))))
1228 (defconst tramp-debug-outline-regexp
1229 "[0-9]+:[0-9]+:[0-9]+\\.[0-9]+ [a-z0-9-]+ (\\([0-9]+\\)) #"
1230 "Used for highlighting Tramp debug buffers in `outline-mode'.")
1232 (defun tramp-debug-outline-level ()
1233 "Return the depth to which a statement is nested in the outline.
1234 Point must be at the beginning of a header line.
1236 The outline level is equal to the verbosity of the Tramp message."
1237 (1+ (string-to-number (match-string 1))))
1239 (defun tramp-get-debug-buffer (vec)
1240 "Get the debug buffer for VEC."
1241 (with-current-buffer
1242 (get-buffer-create (tramp-debug-buffer-name vec))
1243 (when (bobp)
1244 (setq buffer-undo-list t)
1245 ;; Activate `outline-mode'. This runs `text-mode-hook' and
1246 ;; `outline-mode-hook'. We must prevent that local processes
1247 ;; die. Yes: I've seen `flyspell-mode', which starts "ispell".
1248 ;; Furthermore, `outline-regexp' must have the correct value
1249 ;; already, because it is used by `font-lock-compile-keywords'.
1250 (let ((default-directory (tramp-compat-temporary-file-directory))
1251 (outline-regexp tramp-debug-outline-regexp))
1252 (outline-mode))
1253 (set (make-local-variable 'outline-regexp) tramp-debug-outline-regexp)
1254 (set (make-local-variable 'outline-level) 'tramp-debug-outline-level))
1255 (current-buffer)))
1257 (defsubst tramp-debug-message (vec fmt-string &rest args)
1258 "Append message to debug buffer.
1259 Message is formatted with FMT-STRING as control string and the remaining
1260 ARGS to actually emit the message (if applicable)."
1261 (when (get-buffer (tramp-buffer-name vec))
1262 (with-current-buffer (tramp-get-debug-buffer vec)
1263 (goto-char (point-max))
1264 ;; Headline.
1265 (when (bobp)
1266 (insert
1267 (format
1268 ";; %sEmacs: %s Tramp: %s -*- mode: outline; -*-"
1269 (if (featurep 'sxemacs) "SX" (if (featurep 'xemacs) "X" "GNU "))
1270 emacs-version tramp-version)))
1271 (unless (bolp)
1272 (insert "\n"))
1273 ;; Timestamp.
1274 (let ((now (current-time)))
1275 (insert (format-time-string "%T." now))
1276 (insert (format "%06d " (nth 2 now))))
1277 ;; Calling function.
1278 (let ((btn 1) btf fn)
1279 (while (not fn)
1280 (setq btf (nth 1 (backtrace-frame btn)))
1281 (if (not btf)
1282 (setq fn "")
1283 (when (symbolp btf)
1284 (setq fn (symbol-name btf))
1285 (unless (and (string-match "^tramp" fn)
1286 (not (string-match
1287 "^tramp\\(-debug\\)?\\(-message\\|-error\\|-compat-funcall\\)$"
1288 fn)))
1289 (setq fn nil)))
1290 (setq btn (1+ btn))))
1291 ;; The following code inserts filename and line number.
1292 ;; Should be deactivated by default, because it is time
1293 ;; consuming.
1294 ; (let ((ffn (find-function-noselect (intern fn))))
1295 ; (insert
1296 ; (format
1297 ; "%s:%d: "
1298 ; (file-name-nondirectory (buffer-file-name (car ffn)))
1299 ; (with-current-buffer (car ffn)
1300 ; (1+ (count-lines (point-min) (cdr ffn)))))))
1301 (insert (format "%s " fn)))
1302 ;; The message.
1303 (insert (apply 'format fmt-string args)))))
1305 (defvar tramp-message-show-message t
1306 "Show Tramp message in the minibuffer.
1307 This variable is used to disable messages from `tramp-error'.
1308 The messages are visible anyway, because an error is raised.")
1310 (defsubst tramp-message (vec-or-proc level fmt-string &rest args)
1311 "Emit a message depending on verbosity level.
1312 VEC-OR-PROC identifies the Tramp buffer to use. It can be either a
1313 vector or a process. LEVEL says to be quiet if `tramp-verbose' is
1314 less than LEVEL. The message is emitted only if `tramp-verbose' is
1315 greater than or equal to LEVEL.
1317 The message is also logged into the debug buffer when `tramp-verbose'
1318 is greater than or equal 4.
1320 Calls functions `message' and `tramp-debug-message' with FMT-STRING as
1321 control string and the remaining ARGS to actually emit the message (if
1322 applicable)."
1323 (ignore-errors
1324 (when (<= level tramp-verbose)
1325 ;; Match data must be preserved!
1326 (save-match-data
1327 ;; Display only when there is a minimum level.
1328 (when (and tramp-message-show-message (<= level 3))
1329 (apply 'message
1330 (concat
1331 (cond
1332 ((= level 0) "")
1333 ((= level 1) "")
1334 ((= level 2) "Warning: ")
1335 (t "Tramp: "))
1336 fmt-string)
1337 args))
1338 ;; Log only when there is a minimum level.
1339 (when (>= tramp-verbose 4)
1340 (when (and vec-or-proc
1341 (processp vec-or-proc)
1342 (buffer-name (process-buffer vec-or-proc)))
1343 (with-current-buffer (process-buffer vec-or-proc)
1344 ;; Translate proc to vec.
1345 (setq vec-or-proc (tramp-dissect-file-name default-directory))))
1346 (when (and vec-or-proc (vectorp vec-or-proc))
1347 (apply 'tramp-debug-message
1348 vec-or-proc
1349 (concat (format "(%d) # " level) fmt-string)
1350 args)))))))
1352 (defsubst tramp-error (vec-or-proc signal fmt-string &rest args)
1353 "Emit an error.
1354 VEC-OR-PROC identifies the connection to use, SIGNAL is the
1355 signal identifier to be raised, remaining args passed to
1356 `tramp-message'. Finally, signal SIGNAL is raised."
1357 (let (tramp-message-show-message)
1358 (tramp-message
1359 vec-or-proc 1 "%s"
1360 (error-message-string
1361 (list signal
1362 (get signal 'error-message)
1363 (apply 'format fmt-string args))))
1364 (signal signal (list (apply 'format fmt-string args)))))
1366 (defsubst tramp-error-with-buffer
1367 (buffer vec-or-proc signal fmt-string &rest args)
1368 "Emit an error, and show BUFFER.
1369 If BUFFER is nil, show the connection buffer. Wait for 30\", or until
1370 an input event arrives. The other arguments are passed to `tramp-error'."
1371 (save-window-excursion
1372 (unwind-protect
1373 (apply 'tramp-error vec-or-proc signal fmt-string args)
1374 (when (and vec-or-proc
1375 (not (zerop tramp-verbose))
1376 (not (tramp-completion-mode-p)))
1377 (let ((enable-recursive-minibuffers t))
1378 (pop-to-buffer
1379 (or (and (bufferp buffer) buffer)
1380 (and (processp vec-or-proc) (process-buffer vec-or-proc))
1381 (tramp-get-buffer vec-or-proc)))
1382 (sit-for 30))))))
1384 (defmacro with-parsed-tramp-file-name (filename var &rest body)
1385 "Parse a Tramp filename and make components available in the body.
1387 First arg FILENAME is evaluated and dissected into its components.
1388 Second arg VAR is a symbol. It is used as a variable name to hold
1389 the filename structure. It is also used as a prefix for the variables
1390 holding the components. For example, if VAR is the symbol `foo', then
1391 `foo' will be bound to the whole structure, `foo-method' will be bound to
1392 the method component, and so on for `foo-user', `foo-host', `foo-localname'.
1394 Remaining args are Lisp expressions to be evaluated (inside an implicit
1395 `progn').
1397 If VAR is nil, then we bind `v' to the structure and `method', `user',
1398 `host', `localname' to the components."
1399 `(let* ((,(or var 'v) (tramp-dissect-file-name ,filename))
1400 (,(if var (intern (concat (symbol-name var) "-method")) 'method)
1401 (tramp-file-name-method ,(or var 'v)))
1402 (,(if var (intern (concat (symbol-name var) "-user")) 'user)
1403 (tramp-file-name-user ,(or var 'v)))
1404 (,(if var (intern (concat (symbol-name var) "-host")) 'host)
1405 (tramp-file-name-host ,(or var 'v)))
1406 (,(if var (intern (concat (symbol-name var) "-localname")) 'localname)
1407 (tramp-file-name-localname ,(or var 'v))))
1408 ,@body))
1410 (put 'with-parsed-tramp-file-name 'lisp-indent-function 2)
1411 (put 'with-parsed-tramp-file-name 'edebug-form-spec '(form symbolp body))
1412 (tramp-compat-font-lock-add-keywords
1413 'emacs-lisp-mode '("\\<with-parsed-tramp-file-name\\>"))
1415 (defun tramp-progress-reporter-update (reporter &optional value)
1416 (let* ((parameters (cdr reporter))
1417 (message (aref parameters 3)))
1418 (when (string-match message (or (current-message) ""))
1419 (tramp-compat-funcall 'progress-reporter-update reporter value))))
1421 (defmacro with-progress-reporter (vec level message &rest body)
1422 "Executes BODY, spinning a progress reporter with MESSAGE.
1423 If LEVEL does not fit for visible messages, or if this is a
1424 nested call of the macro, there are only traces without a visible
1425 progress reporter."
1426 `(let (pr tm)
1427 (tramp-message ,vec ,level "%s..." ,message)
1428 ;; We start a pulsing progress reporter after 3 seconds. Feature
1429 ;; introduced in Emacs 24.1.
1430 (when (and tramp-message-show-message
1431 ;; Display only when there is a minimum level.
1432 (<= ,level (min tramp-verbose 3)))
1433 (ignore-errors
1434 (setq pr (tramp-compat-funcall 'make-progress-reporter ,message)
1435 tm (when pr
1436 (run-at-time 3 0.1 'tramp-progress-reporter-update pr)))))
1437 (unwind-protect
1438 ;; Execute the body. Unset `tramp-message-show-message' when
1439 ;; the timer object is created, in order to suppress
1440 ;; concurrent timers.
1441 (let ((tramp-message-show-message
1442 (and tramp-message-show-message (not tm))))
1443 ,@body)
1444 ;; Stop progress reporter.
1445 (if tm (tramp-compat-funcall 'cancel-timer tm))
1446 (tramp-message ,vec ,level "%s...done" ,message))))
1448 (put 'with-progress-reporter 'lisp-indent-function 3)
1449 (put 'with-progress-reporter 'edebug-form-spec t)
1450 (tramp-compat-font-lock-add-keywords
1451 'emacs-lisp-mode '("\\<with-progress-reporter\\>"))
1453 (eval-and-compile ;; Silence compiler.
1454 (if (memq system-type '(cygwin windows-nt))
1455 (defun tramp-drop-volume-letter (name)
1456 "Cut off unnecessary drive letter from file NAME.
1457 The function `tramp-handle-expand-file-name' calls `expand-file-name'
1458 locally on a remote file name. When the local system is a W32 system
1459 but the remote system is Unix, this introduces a superfluous drive
1460 letter into the file name. This function removes it."
1461 (save-match-data
1462 (if (string-match tramp-root-regexp name)
1463 (replace-match "/" nil t name)
1464 name)))
1466 (defalias 'tramp-drop-volume-letter 'identity)))
1468 ;;; Config Manipulation Functions:
1470 (defun tramp-set-completion-function (method function-list)
1471 "Sets the list of completion functions for METHOD.
1472 FUNCTION-LIST is a list of entries of the form (FUNCTION FILE).
1473 The FUNCTION is intended to parse FILE according its syntax.
1474 It might be a predefined FUNCTION, or a user defined FUNCTION.
1475 Predefined FUNCTIONs are `tramp-parse-rhosts', `tramp-parse-shosts',
1476 `tramp-parse-sconfig', `tramp-parse-hosts', `tramp-parse-passwd',
1477 and `tramp-parse-netrc'.
1479 Example:
1481 (tramp-set-completion-function
1482 \"ssh\"
1483 '((tramp-parse-sconfig \"/etc/ssh_config\")
1484 (tramp-parse-sconfig \"~/.ssh/config\")))"
1486 (let ((r function-list)
1487 (v function-list))
1488 (setq tramp-completion-function-alist
1489 (delete (assoc method tramp-completion-function-alist)
1490 tramp-completion-function-alist))
1492 (while v
1493 ;; Remove double entries.
1494 (when (member (car v) (cdr v))
1495 (setcdr v (delete (car v) (cdr v))))
1496 ;; Check for function and file or registry key.
1497 (unless (and (functionp (nth 0 (car v)))
1498 (if (string-match "^HKEY_CURRENT_USER" (nth 1 (car v)))
1499 ;; Windows registry.
1500 (and (memq system-type '(cygwin windows-nt))
1501 (zerop
1502 (tramp-compat-call-process
1503 "reg" nil nil nil "query" (nth 1 (car v)))))
1504 ;; Configuration file.
1505 (file-exists-p (nth 1 (car v)))))
1506 (setq r (delete (car v) r)))
1507 (setq v (cdr v)))
1509 (when r
1510 (add-to-list 'tramp-completion-function-alist
1511 (cons method r)))))
1513 (defun tramp-get-completion-function (method)
1514 "Returns a list of completion functions for METHOD.
1515 For definition of that list see `tramp-set-completion-function'."
1516 (cons
1517 ;; Hosts visited once shall be remembered.
1518 `(tramp-parse-connection-properties ,method)
1519 ;; The method related defaults.
1520 (cdr (assoc method tramp-completion-function-alist))))
1523 ;;; Fontification of `read-file-name':
1525 ;; rfn-eshadow.el is part of Emacs 22. It is autoloaded.
1526 (defvar tramp-rfn-eshadow-overlay)
1527 (make-variable-buffer-local 'tramp-rfn-eshadow-overlay)
1529 (defun tramp-rfn-eshadow-setup-minibuffer ()
1530 "Set up a minibuffer for `file-name-shadow-mode'.
1531 Adds another overlay hiding filename parts according to Tramp's
1532 special handling of `substitute-in-file-name'."
1533 (when (symbol-value 'minibuffer-completing-file-name)
1534 (setq tramp-rfn-eshadow-overlay
1535 (tramp-compat-funcall
1536 'make-overlay
1537 (tramp-compat-funcall 'minibuffer-prompt-end)
1538 (tramp-compat-funcall 'minibuffer-prompt-end)))
1539 ;; Copy rfn-eshadow-overlay properties.
1540 (let ((props (tramp-compat-funcall
1541 'overlay-properties (symbol-value 'rfn-eshadow-overlay))))
1542 (while props
1543 (tramp-compat-funcall
1544 'overlay-put tramp-rfn-eshadow-overlay (pop props) (pop props))))))
1546 (when (boundp 'rfn-eshadow-setup-minibuffer-hook)
1547 (add-hook 'rfn-eshadow-setup-minibuffer-hook
1548 'tramp-rfn-eshadow-setup-minibuffer)
1549 (add-hook 'tramp-unload-hook
1550 (lambda ()
1551 (remove-hook 'rfn-eshadow-setup-minibuffer-hook
1552 'tramp-rfn-eshadow-setup-minibuffer))))
1554 (defconst tramp-rfn-eshadow-update-overlay-regexp
1555 (format "[^%s/~]*\\(/\\|~\\)" tramp-postfix-host-format))
1557 (defun tramp-rfn-eshadow-update-overlay ()
1558 "Update `rfn-eshadow-overlay' to cover shadowed part of minibuffer input.
1559 This is intended to be used as a minibuffer `post-command-hook' for
1560 `file-name-shadow-mode'; the minibuffer should have already
1561 been set up by `rfn-eshadow-setup-minibuffer'."
1562 ;; In remote files name, there is a shadowing just for the local part.
1563 (let ((end (or (tramp-compat-funcall
1564 'overlay-end (symbol-value 'rfn-eshadow-overlay))
1565 (tramp-compat-funcall 'minibuffer-prompt-end))))
1566 (when
1567 (file-remote-p
1568 (tramp-compat-funcall 'buffer-substring-no-properties end (point-max)))
1569 (save-excursion
1570 (save-restriction
1571 (narrow-to-region
1572 (1+ (or (string-match
1573 tramp-rfn-eshadow-update-overlay-regexp (buffer-string) end)
1574 end))
1575 (point-max))
1576 (let ((rfn-eshadow-overlay tramp-rfn-eshadow-overlay)
1577 (rfn-eshadow-update-overlay-hook nil))
1578 (tramp-compat-funcall
1579 'move-overlay rfn-eshadow-overlay (point-max) (point-max))
1580 (tramp-compat-funcall 'rfn-eshadow-update-overlay)))))))
1582 (when (boundp 'rfn-eshadow-update-overlay-hook)
1583 (add-hook 'rfn-eshadow-update-overlay-hook
1584 'tramp-rfn-eshadow-update-overlay)
1585 (add-hook 'tramp-unload-hook
1586 (lambda ()
1587 (remove-hook 'rfn-eshadow-update-overlay-hook
1588 'tramp-rfn-eshadow-update-overlay))))
1590 ;; Inodes don't exist for some file systems. Therefore we must
1591 ;; generate virtual ones. Used in `find-buffer-visiting'. The method
1592 ;; applied might be not so efficient (Ange-FTP uses hashes). But
1593 ;; performance isn't the major issue given that file transfer will
1594 ;; take time.
1595 (defvar tramp-inodes nil
1596 "Keeps virtual inodes numbers.")
1598 ;; Devices must distinguish physical file systems. The device numbers
1599 ;; provided by "lstat" aren't unique, because we operate on different hosts.
1600 ;; So we use virtual device numbers, generated by Tramp. Both Ange-FTP and
1601 ;; EFS use device number "-1". In order to be different, we use device number
1602 ;; (-1 . x), whereby "x" is unique for a given (method user host).
1603 (defvar tramp-devices nil
1604 "Keeps virtual device numbers.")
1606 (defun tramp-default-file-modes (filename)
1607 "Return file modes of FILENAME as integer.
1608 If the file modes of FILENAME cannot be determined, return the
1609 value of `default-file-modes', without execute permissions."
1610 (or (file-modes filename)
1611 (logand (default-file-modes) (tramp-compat-octal-to-decimal "0666"))))
1613 (defun tramp-replace-environment-variables (filename)
1614 "Replace environment variables in FILENAME.
1615 Return the string with the replaced variables."
1616 (save-match-data
1617 (let ((idx (string-match "$\\(\\w+\\)" filename)))
1618 ;; `$' is coded as `$$'.
1619 (when (and idx
1620 (or (zerop idx) (not (eq ?$ (aref filename (1- idx)))))
1621 (getenv (match-string 1 filename)))
1622 (setq filename
1623 (replace-match
1624 (substitute-in-file-name (match-string 0 filename))
1625 t nil filename)))
1626 filename)))
1628 ;; In XEmacs, electricity is implemented via a key map for ?/ and ?~,
1629 ;; which calls corresponding functions (see minibuf.el).
1630 (when (fboundp 'minibuffer-electric-separator)
1631 (mapc
1632 (lambda (x)
1633 (eval
1634 `(defadvice ,x
1635 (around ,(intern (format "tramp-advice-%s" x)) activate)
1636 "Invoke `substitute-in-file-name' for Tramp files."
1637 (if (and (symbol-value 'minibuffer-electric-file-name-behavior)
1638 (tramp-tramp-file-p (buffer-substring)))
1639 ;; We don't need to handle `last-input-event', because
1640 ;; due to the key map we know it must be ?/ or ?~.
1641 (let ((s (concat (buffer-substring (point-min) (point))
1642 (string last-command-char))))
1643 (delete-region (point-min) (point))
1644 (insert (substitute-in-file-name s))
1645 (setq ad-return-value last-command-char))
1646 ad-do-it)))
1647 (eval
1648 `(add-hook
1649 'tramp-unload-hook
1650 (lambda ()
1651 (ad-remove-advice ',x 'around ',(intern (format "tramp-advice-%s" x)))
1652 (ad-activate ',x)))))
1654 '(minibuffer-electric-separator
1655 minibuffer-electric-tilde)))
1657 (defun tramp-find-file-name-coding-system-alist (filename tmpname)
1658 "Like `find-operation-coding-system' for Tramp filenames.
1659 Tramp's `insert-file-contents' and `write-region' work over
1660 temporary file names. If `file-coding-system-alist' contains an
1661 expression, which matches more than the file name suffix, the
1662 coding system might not be determined. This function repairs it."
1663 (let (result)
1664 (dolist (elt file-coding-system-alist result)
1665 (when (and (consp elt) (string-match (car elt) filename))
1666 ;; We found a matching entry in `file-coding-system-alist'.
1667 ;; So we add a similar entry, but with the temporary file name
1668 ;; as regexp.
1669 (add-to-list
1670 'result (cons (regexp-quote tmpname) (cdr elt)) 'append)))))
1672 ;;;###autoload
1673 (progn (defun tramp-run-real-handler (operation args)
1674 "Invoke normal file name handler for OPERATION.
1675 First arg specifies the OPERATION, second arg is a list of arguments to
1676 pass to the OPERATION."
1677 (let* ((inhibit-file-name-handlers
1678 `(tramp-file-name-handler
1679 tramp-vc-file-name-handler
1680 tramp-completion-file-name-handler
1681 cygwin-mount-name-hook-function
1682 cygwin-mount-map-drive-hook-function
1684 ,(and (eq inhibit-file-name-operation operation)
1685 inhibit-file-name-handlers)))
1686 (inhibit-file-name-operation operation))
1687 (apply operation args))))
1689 ;;;###autoload
1690 (progn (defun tramp-completion-run-real-handler (operation args)
1691 "Invoke `tramp-file-name-handler' for OPERATION.
1692 First arg specifies the OPERATION, second arg is a list of arguments to
1693 pass to the OPERATION."
1694 (let* ((inhibit-file-name-handlers
1695 `(tramp-completion-file-name-handler
1696 cygwin-mount-name-hook-function
1697 cygwin-mount-map-drive-hook-function
1699 ,(and (eq inhibit-file-name-operation operation)
1700 inhibit-file-name-handlers)))
1701 (inhibit-file-name-operation operation))
1702 (apply operation args))))
1704 ;; We handle here all file primitives. Most of them have the file
1705 ;; name as first parameter; nevertheless we check for them explicitly
1706 ;; in order to be signaled if a new primitive appears. This
1707 ;; scenario is needed because there isn't a way to decide by
1708 ;; syntactical means whether a foreign method must be called. It would
1709 ;; ease the life if `file-name-handler-alist' would support a decision
1710 ;; function as well but regexp only.
1711 (defun tramp-file-name-for-operation (operation &rest args)
1712 "Return file name related to OPERATION file primitive.
1713 ARGS are the arguments OPERATION has been called with."
1714 (cond
1715 ;; FILE resp DIRECTORY.
1716 ((member operation
1717 (list 'access-file 'byte-compiler-base-file-name 'delete-directory
1718 'delete-file 'diff-latest-backup-file 'directory-file-name
1719 'directory-files 'directory-files-and-attributes
1720 'dired-compress-file 'dired-uncache
1721 'file-accessible-directory-p 'file-attributes
1722 'file-directory-p 'file-executable-p 'file-exists-p
1723 'file-local-copy 'file-remote-p 'file-modes
1724 'file-name-as-directory 'file-name-directory
1725 'file-name-nondirectory 'file-name-sans-versions
1726 'file-ownership-preserved-p 'file-readable-p
1727 'file-regular-p 'file-symlink-p 'file-truename
1728 'file-writable-p 'find-backup-file-name 'find-file-noselect
1729 'get-file-buffer 'insert-directory 'insert-file-contents
1730 'load 'make-directory 'make-directory-internal
1731 'set-file-modes 'substitute-in-file-name
1732 'unhandled-file-name-directory 'vc-registered
1733 ;; Emacs 22+ only.
1734 'set-file-times
1735 ;; Emacs 24+ only.
1736 'file-selinux-context 'set-file-selinux-context
1737 ;; XEmacs only.
1738 'abbreviate-file-name 'create-file-buffer
1739 'dired-file-modtime 'dired-make-compressed-filename
1740 'dired-recursive-delete-directory 'dired-set-file-modtime
1741 'dired-shell-unhandle-file-name 'dired-uucode-file
1742 'insert-file-contents-literally 'make-temp-name 'recover-file
1743 'vm-imap-check-mail 'vm-pop-check-mail 'vm-spool-check-mail))
1744 (if (file-name-absolute-p (nth 0 args))
1745 (nth 0 args)
1746 (expand-file-name (nth 0 args))))
1747 ;; FILE DIRECTORY resp FILE1 FILE2.
1748 ((member operation
1749 (list 'add-name-to-file 'copy-file 'expand-file-name
1750 'file-name-all-completions 'file-name-completion
1751 'file-newer-than-file-p 'make-symbolic-link 'rename-file
1752 ;; Emacs 23+ only.
1753 'copy-directory
1754 ;; XEmacs only.
1755 'dired-make-relative-symlink
1756 'vm-imap-move-mail 'vm-pop-move-mail 'vm-spool-move-mail))
1757 (save-match-data
1758 (cond
1759 ((string-match tramp-file-name-regexp (nth 0 args)) (nth 0 args))
1760 ((string-match tramp-file-name-regexp (nth 1 args)) (nth 1 args))
1761 (t (buffer-file-name (current-buffer))))))
1762 ;; START END FILE.
1763 ((eq operation 'write-region)
1764 (nth 2 args))
1765 ;; BUFFER.
1766 ((member operation
1767 (list 'set-visited-file-modtime 'verify-visited-file-modtime
1768 ;; Emacs 22+ only.
1769 'make-auto-save-file-name
1770 ;; XEmacs only.
1771 'backup-buffer))
1772 (buffer-file-name
1773 (if (bufferp (nth 0 args)) (nth 0 args) (current-buffer))))
1774 ;; COMMAND.
1775 ((member operation
1776 (list ;; not in Emacs 23+.
1777 'dired-call-process
1778 ;; Emacs only.
1779 'shell-command
1780 ;; Emacs 22+ only.
1781 'process-file
1782 ;; Emacs 23+ only.
1783 'start-file-process
1784 ;; XEmacs only.
1785 'dired-print-file 'dired-shell-call-process
1786 ;; nowhere yet.
1787 'executable-find 'start-process
1788 'call-process 'call-process-region))
1789 default-directory)
1790 ;; Unknown file primitive.
1791 (t (error "unknown file I/O primitive: %s" operation))))
1793 (defun tramp-find-foreign-file-name-handler (filename)
1794 "Return foreign file name handler if exists."
1795 (when (tramp-tramp-file-p filename)
1796 (let ((v (tramp-dissect-file-name filename t))
1797 (handler tramp-foreign-file-name-handler-alist)
1798 elt res)
1799 ;; When we are not fully sure that filename completion is safe,
1800 ;; we should not return a handler.
1801 (when (or (tramp-file-name-method v) (tramp-file-name-user v)
1802 (and (tramp-file-name-host v)
1803 (not (member (tramp-file-name-host v)
1804 (mapcar 'car tramp-methods))))
1805 (not (tramp-completion-mode-p)))
1806 (while handler
1807 (setq elt (car handler)
1808 handler (cdr handler))
1809 (when (funcall (car elt) filename)
1810 (setq handler nil
1811 res (cdr elt))))
1812 res))))
1814 ;; Main function.
1815 ;;;###autoload
1816 (defun tramp-file-name-handler (operation &rest args)
1817 "Invoke Tramp file name handler.
1818 Falls back to normal file name handler if no Tramp file name handler exists."
1819 (if tramp-mode
1820 (save-match-data
1821 (let* ((filename
1822 (tramp-replace-environment-variables
1823 (apply 'tramp-file-name-for-operation operation args)))
1824 (completion (tramp-completion-mode-p))
1825 (foreign (tramp-find-foreign-file-name-handler filename)))
1826 (with-parsed-tramp-file-name filename nil
1827 ;; Call the backend function.
1828 (if foreign
1829 (condition-case err
1830 (apply foreign operation args)
1832 ;; Trace, that somebody has interrupted the operation.
1833 (quit
1834 (let (tramp-message-show-message)
1835 (tramp-message
1836 v 1 "Interrupt received in operation %s"
1837 (append (list operation) args)))
1838 ;; Propagate the quit signal.
1839 (signal (car err) (cdr err)))
1841 ;; When we are in completion mode, some failed
1842 ;; operations shall return at least a default value
1843 ;; in order to give the user a chance to correct the
1844 ;; file name in the minibuffer.
1845 (error
1846 (cond
1847 ((and completion (zerop (length localname))
1848 (memq operation '(file-exists-p file-directory-p)))
1850 ((and completion (zerop (length localname))
1851 (memq operation
1852 '(expand-file-name file-name-as-directory)))
1853 filename)
1854 ;; Propagate the error.
1855 (t (signal (car err) (cdr err))))))
1857 ;; Nothing to do for us.
1858 (tramp-run-real-handler operation args)))))
1860 ;; When `tramp-mode' is not enabled, we don't do anything.
1861 (tramp-run-real-handler operation args)))
1863 ;; In Emacs, there is some concurrency due to timers. If a timer
1864 ;; interrupts Tramp and wishes to use the same connection buffer as
1865 ;; the "main" Emacs, then garbage might occur in the connection
1866 ;; buffer. Therefore, we need to make sure that a timer does not use
1867 ;; the same connection buffer as the "main" Emacs. We implement a
1868 ;; cheap global lock, instead of locking each connection buffer
1869 ;; separately. The global lock is based on two variables,
1870 ;; `tramp-locked' and `tramp-locker'. `tramp-locked' is set to true
1871 ;; (with setq) to indicate a lock. But Tramp also calls itself during
1872 ;; processing of a single file operation, so we need to allow
1873 ;; recursive calls. That's where the `tramp-locker' variable comes in
1874 ;; -- it is let-bound to t during the execution of the current
1875 ;; handler. So if `tramp-locked' is t and `tramp-locker' is also t,
1876 ;; then we should just proceed because we have been called
1877 ;; recursively. But if `tramp-locker' is nil, then we are a timer
1878 ;; interrupting the "main" Emacs, and then we signal an error.
1880 (defvar tramp-locked nil
1881 "If non-nil, then Tramp is currently busy.
1882 Together with `tramp-locker', this implements a locking mechanism
1883 preventing reentrant calls of Tramp.")
1885 (defvar tramp-locker nil
1886 "If non-nil, then a caller has locked Tramp.
1887 Together with `tramp-locked', this implements a locking mechanism
1888 preventing reentrant calls of Tramp.")
1890 ;;;###autoload
1891 (progn (defun tramp-completion-file-name-handler (operation &rest args)
1892 "Invoke Tramp file name completion handler.
1893 Falls back to normal file name handler if no Tramp file name handler exists."
1894 ;; We bind `directory-sep-char' here for XEmacs on Windows, which
1895 ;; would otherwise use backslash.
1896 (let ((directory-sep-char ?/)
1897 (fn (assoc operation tramp-completion-file-name-handler-alist)))
1898 (if (and
1899 ;; When `tramp-mode' is not enabled, we don't do anything.
1900 fn tramp-mode
1901 ;; For other syntaxes than `sep', the regexp matches many common
1902 ;; situations where the user doesn't actually want to use Tramp.
1903 ;; So to avoid autoloading Tramp after typing just "/s", we
1904 ;; disable this part of the completion, unless the user implicitly
1905 ;; indicated his interest in using a fancier completion system.
1906 (or (eq tramp-syntax 'sep)
1907 (featurep 'tramp) ;; If it's loaded, we may as well use it.
1908 ;; `partial-completion-mode' does not exist in XEmacs.
1909 ;; It is obsoleted with Emacs 24.1.
1910 (and (boundp 'partial-completion-mode)
1911 (symbol-value 'partial-completion-mode))
1912 ;; FIXME: These may have been loaded even if the user never
1913 ;; intended to use them.
1914 (featurep 'ido)
1915 (featurep 'icicles)))
1916 (save-match-data (apply (cdr fn) args))
1917 (tramp-completion-run-real-handler operation args)))))
1919 ;;;###autoload
1920 (progn (defun tramp-register-file-name-handlers ()
1921 "Add Tramp file name handlers to `file-name-handler-alist'."
1922 ;; Remove autoloaded handlers from file name handler alist. Useful,
1923 ;; if `tramp-syntax' has been changed.
1924 (let ((a1 (rassq 'tramp-file-name-handler file-name-handler-alist)))
1925 (setq file-name-handler-alist (delq a1 file-name-handler-alist)))
1926 (let ((a1 (rassq
1927 'tramp-completion-file-name-handler file-name-handler-alist)))
1928 (setq file-name-handler-alist (delq a1 file-name-handler-alist)))
1929 ;; Add the handlers.
1930 (add-to-list 'file-name-handler-alist
1931 (cons tramp-file-name-regexp 'tramp-file-name-handler))
1932 (put 'tramp-file-name-handler 'safe-magic t)
1933 (add-to-list 'file-name-handler-alist
1934 (cons tramp-completion-file-name-regexp
1935 'tramp-completion-file-name-handler))
1936 (put 'tramp-completion-file-name-handler 'safe-magic t)
1937 ;; If jka-compr or epa-file are already loaded, move them to the
1938 ;; front of `file-name-handler-alist'.
1939 (dolist (fnh '(epa-file-handler jka-compr-handler))
1940 (let ((entry (rassoc fnh file-name-handler-alist)))
1941 (when entry
1942 (setq file-name-handler-alist
1943 (cons entry (delete entry file-name-handler-alist))))))))
1945 ;; `tramp-file-name-handler' must be registered before evaluation of
1946 ;; site-start and init files, because there might exist remote files
1947 ;; already, f.e. files kept via recentf-mode.
1948 ;;;###autoload
1949 (tramp-register-file-name-handlers)
1951 (defun tramp-exists-file-name-handler (operation &rest args)
1952 "Check, whether OPERATION runs a file name handler."
1953 ;; The file name handler is determined on base of either an
1954 ;; argument, `buffer-file-name', or `default-directory'.
1955 (ignore-errors
1956 (let* ((buffer-file-name "/")
1957 (default-directory "/")
1958 (fnha file-name-handler-alist)
1959 (check-file-name-operation operation)
1960 (file-name-handler-alist
1961 (list
1962 (cons "/"
1963 (lambda (operation &rest args)
1964 "Returns OPERATION if it is the one to be checked."
1965 (if (equal check-file-name-operation operation)
1966 operation
1967 (let ((file-name-handler-alist fnha))
1968 (apply operation args))))))))
1969 (equal (apply operation args) operation))))
1971 ;;;###autoload
1972 (defun tramp-unload-file-name-handlers ()
1973 (setq file-name-handler-alist
1974 (delete (rassoc 'tramp-file-name-handler
1975 file-name-handler-alist)
1976 (delete (rassoc 'tramp-completion-file-name-handler
1977 file-name-handler-alist)
1978 file-name-handler-alist))))
1980 (add-hook 'tramp-unload-hook 'tramp-unload-file-name-handlers)
1982 ;;; File name handler functions for completion mode:
1984 (defvar tramp-completion-mode nil
1985 "If non-nil, external packages signal that they are in file name completion.
1987 This is necessary, because Tramp uses a heuristic depending on last
1988 input event. This fails when external packages use other characters
1989 but <TAB>, <SPACE> or ?\\? for file name completion. This variable
1990 should never be set globally, the intention is to let-bind it.")
1992 ;; Necessary because `tramp-file-name-regexp-unified' and
1993 ;; `tramp-completion-file-name-regexp-unified' aren't different. If
1994 ;; nil, `tramp-completion-run-real-handler' is called (i.e. forwarding
1995 ;; to `tramp-file-name-handler'). Otherwise, it takes
1996 ;; `tramp-run-real-handler'. Using `last-input-event' is a little bit
1997 ;; risky, because completing a file might require loading other files,
1998 ;; like "~/.netrc", and for them it shouldn't be decided based on that
1999 ;; variable. On the other hand, those files shouldn't have partial
2000 ;; Tramp file name syntax. Maybe another variable should be introduced
2001 ;; overwriting this check in such cases. Or we change Tramp file name
2002 ;; syntax in order to avoid ambiguities, like in XEmacs ...
2003 ;;;###tramp-autoload
2004 (defun tramp-completion-mode-p ()
2005 "Check, whether method / user name / host name completion is active."
2007 ;; Signal from outside. `non-essential' has been introduced in Emacs 24.
2008 (and (boundp 'non-essential) (symbol-value 'non-essential))
2009 tramp-completion-mode
2010 ;; Emacs.
2011 (equal last-input-event 'tab)
2012 (and (natnump last-input-event)
2014 ;; ?\t has event-modifier 'control.
2015 (equal last-input-event ?\t)
2016 (and (not (event-modifiers last-input-event))
2017 (or (equal last-input-event ?\?)
2018 (equal last-input-event ?\ )))))
2019 ;; XEmacs.
2020 (and (featurep 'xemacs)
2021 ;; `last-input-event' might be nil.
2022 (not (null last-input-event))
2023 ;; `last-input-event' may have no character approximation.
2024 (tramp-compat-funcall 'event-to-character last-input-event)
2026 ;; ?\t has event-modifier 'control.
2027 (equal
2028 (tramp-compat-funcall 'event-to-character last-input-event) ?\t)
2029 (and (not (event-modifiers last-input-event))
2030 (or (equal
2031 (tramp-compat-funcall 'event-to-character last-input-event)
2032 ?\?)
2033 (equal
2034 (tramp-compat-funcall 'event-to-character last-input-event)
2035 ?\ )))))))
2037 (defun tramp-connectable-p (filename)
2038 "Check, whether it is possible to connect the remote host w/o side-effects.
2039 This is true, if either the remote host is already connected, or if we are
2040 not in completion mode."
2041 (and (tramp-tramp-file-p filename)
2042 (with-parsed-tramp-file-name filename nil
2043 (or (get-buffer (tramp-buffer-name v))
2044 (not (tramp-completion-mode-p))))))
2046 ;; Method, host name and user name completion.
2047 ;; `tramp-completion-dissect-file-name' returns a list of
2048 ;; tramp-file-name structures. For all of them we return possible completions.
2049 ;;;###autoload
2050 (defun tramp-completion-handle-file-name-all-completions (filename directory)
2051 "Like `file-name-all-completions' for partial Tramp files."
2053 (let* ((fullname (tramp-drop-volume-letter
2054 (expand-file-name filename directory)))
2055 ;; Possible completion structures.
2056 (v (tramp-completion-dissect-file-name fullname))
2057 result result1)
2059 (while v
2060 (let* ((car (car v))
2061 (method (tramp-file-name-method car))
2062 (user (tramp-file-name-user car))
2063 (host (tramp-file-name-host car))
2064 (localname (tramp-file-name-localname car))
2065 (m (tramp-find-method method user host))
2066 (tramp-current-user user) ; see `tramp-parse-passwd'
2067 all-user-hosts)
2069 (unless localname ;; Nothing to complete.
2071 (if (or user host)
2073 ;; Method dependent user / host combinations.
2074 (progn
2075 (mapc
2076 (lambda (x)
2077 (setq all-user-hosts
2078 (append all-user-hosts
2079 (funcall (nth 0 x) (nth 1 x)))))
2080 (tramp-get-completion-function m))
2082 (setq result
2083 (append result
2084 (mapcar
2085 (lambda (x)
2086 (tramp-get-completion-user-host
2087 method user host (nth 0 x) (nth 1 x)))
2088 (delq nil all-user-hosts)))))
2090 ;; Possible methods.
2091 (setq result
2092 (append result (tramp-get-completion-methods m)))))
2094 (setq v (cdr v))))
2096 ;; Unify list, remove nil elements.
2097 (while result
2098 (let ((car (car result)))
2099 (when car
2100 (add-to-list
2101 'result1
2102 (substring car (length (tramp-drop-volume-letter directory)))))
2103 (setq result (cdr result))))
2105 ;; Complete local parts.
2106 (append
2107 result1
2108 (ignore-errors
2109 (apply (if (tramp-connectable-p fullname)
2110 'tramp-completion-run-real-handler
2111 'tramp-run-real-handler)
2112 'file-name-all-completions (list (list filename directory)))))))
2114 ;; Method, host name and user name completion for a file.
2115 ;;;###autoload
2116 (defun tramp-completion-handle-file-name-completion
2117 (filename directory &optional predicate)
2118 "Like `file-name-completion' for Tramp files."
2119 (try-completion
2120 filename
2121 (mapcar 'list (file-name-all-completions filename directory))
2122 (when (and predicate
2123 (tramp-connectable-p (expand-file-name filename directory)))
2124 (lambda (x) (funcall predicate (expand-file-name (car x) directory))))))
2126 ;; I misuse a little bit the tramp-file-name structure in order to handle
2127 ;; completion possibilities for partial methods / user names / host names.
2128 ;; Return value is a list of tramp-file-name structures according to possible
2129 ;; completions. If "localname" is non-nil it means there
2130 ;; shouldn't be a completion anymore.
2132 ;; Expected results:
2134 ;; "/x" "/[x" "/x@" "/[x@" "/x@y" "/[x@y"
2135 ;; [nil nil "x" nil] [nil "x" nil nil] [nil "x" "y" nil]
2136 ;; [nil "x" nil nil]
2137 ;; ["x" nil nil nil]
2139 ;; "/x:" "/x:y" "/x:y:"
2140 ;; [nil nil "x" ""] [nil nil "x" "y"] ["x" nil "y" ""]
2141 ;; "/[x/" "/[x/y"
2142 ;; ["x" nil "" nil] ["x" nil "y" nil]
2143 ;; ["x" "" nil nil] ["x" "y" nil nil]
2145 ;; "/x:y@" "/x:y@z" "/x:y@z:"
2146 ;; [nil nil "x" "y@"] [nil nil "x" "y@z"] ["x" "y" "z" ""]
2147 ;; "/[x/y@" "/[x/y@z"
2148 ;; ["x" nil "y" nil] ["x" "y" "z" nil]
2149 (defun tramp-completion-dissect-file-name (name)
2150 "Returns a list of `tramp-file-name' structures.
2151 They are collected by `tramp-completion-dissect-file-name1'."
2153 (let* ((result)
2154 (x-nil "\\|\\(\\)")
2155 (tramp-completion-ipv6-regexp
2156 (format
2157 "[^%s]*"
2158 (if (zerop (length tramp-postfix-ipv6-format))
2159 tramp-postfix-host-format
2160 tramp-postfix-ipv6-format)))
2161 ;; "/method" "/[method"
2162 (tramp-completion-file-name-structure1
2163 (list (concat tramp-prefix-regexp "\\(" tramp-method-regexp x-nil "\\)$")
2164 1 nil nil nil))
2165 ;; "/user" "/[user"
2166 (tramp-completion-file-name-structure2
2167 (list (concat tramp-prefix-regexp "\\(" tramp-user-regexp x-nil "\\)$")
2168 nil 1 nil nil))
2169 ;; "/host" "/[host"
2170 (tramp-completion-file-name-structure3
2171 (list (concat tramp-prefix-regexp "\\(" tramp-host-regexp x-nil "\\)$")
2172 nil nil 1 nil))
2173 ;; "/[ipv6" "/[ipv6"
2174 (tramp-completion-file-name-structure4
2175 (list (concat tramp-prefix-regexp
2176 tramp-prefix-ipv6-regexp
2177 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
2178 nil nil 1 nil))
2179 ;; "/user@host" "/[user@host"
2180 (tramp-completion-file-name-structure5
2181 (list (concat tramp-prefix-regexp
2182 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
2183 "\\(" tramp-host-regexp x-nil "\\)$")
2184 nil 1 2 nil))
2185 ;; "/user@[ipv6" "/[user@ipv6"
2186 (tramp-completion-file-name-structure6
2187 (list (concat tramp-prefix-regexp
2188 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
2189 tramp-prefix-ipv6-regexp
2190 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
2191 nil 1 2 nil))
2192 ;; "/method:user" "/[method/user" "/method://user"
2193 (tramp-completion-file-name-structure7
2194 (list (concat tramp-prefix-regexp
2195 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
2196 "\\(" tramp-user-regexp x-nil "\\)$")
2197 1 2 nil nil))
2198 ;; "/method:host" "/[method/host" "/method://host"
2199 (tramp-completion-file-name-structure8
2200 (list (concat tramp-prefix-regexp
2201 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
2202 "\\(" tramp-host-regexp x-nil "\\)$")
2203 1 nil 2 nil))
2204 ;; "/method:[ipv6" "/[method/ipv6" "/method://[ipv6"
2205 (tramp-completion-file-name-structure9
2206 (list (concat tramp-prefix-regexp
2207 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
2208 tramp-prefix-ipv6-regexp
2209 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
2210 1 nil 2 nil))
2211 ;; "/method:user@host" "/[method/user@host" "/method://user@host"
2212 (tramp-completion-file-name-structure10
2213 (list (concat tramp-prefix-regexp
2214 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
2215 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
2216 "\\(" tramp-host-regexp x-nil "\\)$")
2217 1 2 3 nil))
2218 ;; "/method:user@[ipv6" "/[method/user@ipv6" "/method://user@[ipv6"
2219 (tramp-completion-file-name-structure11
2220 (list (concat tramp-prefix-regexp
2221 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
2222 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
2223 tramp-prefix-ipv6-regexp
2224 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
2225 1 2 3 nil))
2226 ;; "/method: "/method:/"
2227 (tramp-completion-file-name-structure12
2228 (list
2229 (if (equal tramp-syntax 'url)
2230 (concat tramp-prefix-regexp
2231 "\\(" tramp-method-regexp "\\)"
2232 "\\(" (substring tramp-postfix-method-regexp 0 1)
2233 "\\|" (substring tramp-postfix-method-regexp 1 2) "\\)"
2234 "\\(" "\\)$")
2235 ;; Should not match if not URL syntax.
2236 (concat tramp-prefix-regexp "/$"))
2237 1 3 nil nil))
2238 ;; "/method: "/method:/"
2239 (tramp-completion-file-name-structure13
2240 (list
2241 (if (equal tramp-syntax 'url)
2242 (concat tramp-prefix-regexp
2243 "\\(" tramp-method-regexp "\\)"
2244 "\\(" (substring tramp-postfix-method-regexp 0 1)
2245 "\\|" (substring tramp-postfix-method-regexp 1 2) "\\)"
2246 "\\(" "\\)$")
2247 ;; Should not match if not URL syntax.
2248 (concat tramp-prefix-regexp "/$"))
2249 1 nil 3 nil)))
2251 (mapc (lambda (regexp)
2252 (add-to-list 'result
2253 (tramp-completion-dissect-file-name1 regexp name)))
2254 (list
2255 tramp-completion-file-name-structure1
2256 tramp-completion-file-name-structure2
2257 tramp-completion-file-name-structure3
2258 tramp-completion-file-name-structure4
2259 tramp-completion-file-name-structure5
2260 tramp-completion-file-name-structure6
2261 tramp-completion-file-name-structure7
2262 tramp-completion-file-name-structure8
2263 tramp-completion-file-name-structure9
2264 tramp-completion-file-name-structure10
2265 tramp-completion-file-name-structure11
2266 tramp-completion-file-name-structure12
2267 tramp-completion-file-name-structure13
2268 tramp-file-name-structure))
2270 (delq nil result)))
2272 (defun tramp-completion-dissect-file-name1 (structure name)
2273 "Returns a `tramp-file-name' structure matching STRUCTURE.
2274 The structure consists of remote method, remote user,
2275 remote host and localname (filename on remote host)."
2277 (save-match-data
2278 (when (string-match (nth 0 structure) name)
2279 (let ((method (and (nth 1 structure)
2280 (match-string (nth 1 structure) name)))
2281 (user (and (nth 2 structure)
2282 (match-string (nth 2 structure) name)))
2283 (host (and (nth 3 structure)
2284 (match-string (nth 3 structure) name)))
2285 (localname (and (nth 4 structure)
2286 (match-string (nth 4 structure) name))))
2287 (vector method user host localname)))))
2289 ;; This function returns all possible method completions, adding the
2290 ;; trailing method delimeter.
2291 (defun tramp-get-completion-methods (partial-method)
2292 "Returns all method completions for PARTIAL-METHOD."
2293 (mapcar
2294 (lambda (method)
2295 (and method
2296 (string-match (concat "^" (regexp-quote partial-method)) method)
2297 (tramp-completion-make-tramp-file-name method nil nil nil)))
2298 (mapcar 'car tramp-methods)))
2300 ;; Compares partial user and host names with possible completions.
2301 (defun tramp-get-completion-user-host (method partial-user partial-host user host)
2302 "Returns the most expanded string for user and host name completion.
2303 PARTIAL-USER must match USER, PARTIAL-HOST must match HOST."
2304 (cond
2306 ((and partial-user partial-host)
2307 (if (and host
2308 (string-match (concat "^" (regexp-quote partial-host)) host)
2309 (string-equal partial-user (or user partial-user)))
2310 (setq user partial-user)
2311 (setq user nil
2312 host nil)))
2314 (partial-user
2315 (setq host nil)
2316 (unless
2317 (and user (string-match (concat "^" (regexp-quote partial-user)) user))
2318 (setq user nil)))
2320 (partial-host
2321 (setq user nil)
2322 (unless
2323 (and host (string-match (concat "^" (regexp-quote partial-host)) host))
2324 (setq host nil)))
2326 (t (setq user nil
2327 host nil)))
2329 (unless (zerop (+ (length user) (length host)))
2330 (tramp-completion-make-tramp-file-name method user host nil)))
2332 (defun tramp-parse-rhosts (filename)
2333 "Return a list of (user host) tuples allowed to access.
2334 Either user or host may be nil."
2335 ;; On Windows, there are problems in completion when
2336 ;; `default-directory' is remote.
2337 (let ((default-directory (tramp-compat-temporary-file-directory))
2338 res)
2339 (when (file-readable-p filename)
2340 (with-temp-buffer
2341 (insert-file-contents filename)
2342 (goto-char (point-min))
2343 (while (not (eobp))
2344 (push (tramp-parse-rhosts-group) res))))
2345 res))
2347 (defun tramp-parse-rhosts-group ()
2348 "Return a (user host) tuple allowed to access.
2349 Either user or host may be nil."
2350 (let ((result)
2351 (regexp
2352 (concat
2353 "^\\(" tramp-host-regexp "\\)"
2354 "\\([ \t]+" "\\(" tramp-user-regexp "\\)" "\\)?")))
2355 (narrow-to-region (point) (tramp-compat-line-end-position))
2356 (when (re-search-forward regexp nil t)
2357 (setq result (append (list (match-string 3) (match-string 1)))))
2358 (widen)
2359 (forward-line 1)
2360 result))
2362 (defun tramp-parse-shosts (filename)
2363 "Return a list of (user host) tuples allowed to access.
2364 User is always nil."
2365 ;; On Windows, there are problems in completion when
2366 ;; `default-directory' is remote.
2367 (let ((default-directory (tramp-compat-temporary-file-directory))
2368 res)
2369 (when (file-readable-p filename)
2370 (with-temp-buffer
2371 (insert-file-contents filename)
2372 (goto-char (point-min))
2373 (while (not (eobp))
2374 (push (tramp-parse-shosts-group) res))))
2375 res))
2377 (defun tramp-parse-shosts-group ()
2378 "Return a (user host) tuple allowed to access.
2379 User is always nil."
2380 (let ((result)
2381 (regexp (concat "^\\(" tramp-host-regexp "\\)")))
2382 (narrow-to-region (point) (tramp-compat-line-end-position))
2383 (when (re-search-forward regexp nil t)
2384 (setq result (list nil (match-string 1))))
2385 (widen)
2387 (> (skip-chars-forward ",") 0)
2388 (forward-line 1))
2389 result))
2391 (defun tramp-parse-sconfig (filename)
2392 "Return a list of (user host) tuples allowed to access.
2393 User is always nil."
2394 ;; On Windows, there are problems in completion when
2395 ;; `default-directory' is remote.
2396 (let ((default-directory (tramp-compat-temporary-file-directory))
2397 res)
2398 (when (file-readable-p filename)
2399 (with-temp-buffer
2400 (insert-file-contents filename)
2401 (goto-char (point-min))
2402 (while (not (eobp))
2403 (push (tramp-parse-sconfig-group) res))))
2404 res))
2406 (defun tramp-parse-sconfig-group ()
2407 "Return a (user host) tuple allowed to access.
2408 User is always nil."
2409 (let ((result)
2410 (regexp (concat "^[ \t]*Host[ \t]+" "\\(" tramp-host-regexp "\\)")))
2411 (narrow-to-region (point) (tramp-compat-line-end-position))
2412 (when (re-search-forward regexp nil t)
2413 (setq result (list nil (match-string 1))))
2414 (widen)
2416 (> (skip-chars-forward ",") 0)
2417 (forward-line 1))
2418 result))
2420 (defun tramp-parse-shostkeys (dirname)
2421 "Return a list of (user host) tuples allowed to access.
2422 User is always nil."
2423 ;; On Windows, there are problems in completion when
2424 ;; `default-directory' is remote.
2425 (let* ((default-directory (tramp-compat-temporary-file-directory))
2426 (regexp (concat "^key_[0-9]+_\\(" tramp-host-regexp "\\)\\.pub$"))
2427 (files (when (file-directory-p dirname) (directory-files dirname)))
2428 result)
2429 (while files
2430 (when (string-match regexp (car files))
2431 (push (list nil (match-string 1 (car files))) result))
2432 (setq files (cdr files)))
2433 result))
2435 (defun tramp-parse-sknownhosts (dirname)
2436 "Return a list of (user host) tuples allowed to access.
2437 User is always nil."
2438 ;; On Windows, there are problems in completion when
2439 ;; `default-directory' is remote.
2440 (let* ((default-directory (tramp-compat-temporary-file-directory))
2441 (regexp (concat "^\\(" tramp-host-regexp
2442 "\\)\\.ssh-\\(dss\\|rsa\\)\\.pub$"))
2443 (files (when (file-directory-p dirname) (directory-files dirname)))
2444 result)
2445 (while files
2446 (when (string-match regexp (car files))
2447 (push (list nil (match-string 1 (car files))) result))
2448 (setq files (cdr files)))
2449 result))
2451 (defun tramp-parse-hosts (filename)
2452 "Return a list of (user host) tuples allowed to access.
2453 User is always nil."
2454 ;; On Windows, there are problems in completion when
2455 ;; `default-directory' is remote.
2456 (let ((default-directory (tramp-compat-temporary-file-directory))
2457 res)
2458 (when (file-readable-p filename)
2459 (with-temp-buffer
2460 (insert-file-contents filename)
2461 (goto-char (point-min))
2462 (while (not (eobp))
2463 (push (tramp-parse-hosts-group) res))))
2464 res))
2466 (defun tramp-parse-hosts-group ()
2467 "Return a (user host) tuple allowed to access.
2468 User is always nil."
2469 (let ((result)
2470 (regexp
2471 (concat "^\\(" tramp-ipv6-regexp "\\|" tramp-host-regexp "\\)")))
2472 (narrow-to-region (point) (tramp-compat-line-end-position))
2473 (when (re-search-forward regexp nil t)
2474 (setq result (list nil (match-string 1))))
2475 (widen)
2477 (> (skip-chars-forward " \t") 0)
2478 (forward-line 1))
2479 result))
2481 ;; For su-alike methods it would be desirable to return "root@localhost"
2482 ;; as default. Unfortunately, we have no information whether any user name
2483 ;; has been typed already. So we use `tramp-current-user' as indication,
2484 ;; assuming it is set in `tramp-completion-handle-file-name-all-completions'.
2485 (defun tramp-parse-passwd (filename)
2486 "Return a list of (user host) tuples allowed to access.
2487 Host is always \"localhost\"."
2488 ;; On Windows, there are problems in completion when
2489 ;; `default-directory' is remote.
2490 (let ((default-directory (tramp-compat-temporary-file-directory))
2491 res)
2492 (if (zerop (length tramp-current-user))
2493 '(("root" nil))
2494 (when (file-readable-p filename)
2495 (with-temp-buffer
2496 (insert-file-contents filename)
2497 (goto-char (point-min))
2498 (while (not (eobp))
2499 (push (tramp-parse-passwd-group) res))))
2500 res)))
2502 (defun tramp-parse-passwd-group ()
2503 "Return a (user host) tuple allowed to access.
2504 Host is always \"localhost\"."
2505 (let ((result)
2506 (regexp (concat "^\\(" tramp-user-regexp "\\):")))
2507 (narrow-to-region (point) (tramp-compat-line-end-position))
2508 (when (re-search-forward regexp nil t)
2509 (setq result (list (match-string 1) "localhost")))
2510 (widen)
2511 (forward-line 1)
2512 result))
2514 (defun tramp-parse-netrc (filename)
2515 "Return a list of (user host) tuples allowed to access.
2516 User may be nil."
2517 ;; On Windows, there are problems in completion when
2518 ;; `default-directory' is remote.
2519 (let ((default-directory (tramp-compat-temporary-file-directory))
2520 res)
2521 (when (file-readable-p filename)
2522 (with-temp-buffer
2523 (insert-file-contents filename)
2524 (goto-char (point-min))
2525 (while (not (eobp))
2526 (push (tramp-parse-netrc-group) res))))
2527 res))
2529 (defun tramp-parse-netrc-group ()
2530 "Return a (user host) tuple allowed to access.
2531 User may be nil."
2532 (let ((result)
2533 (regexp
2534 (concat
2535 "^[ \t]*machine[ \t]+" "\\(" tramp-host-regexp "\\)"
2536 "\\([ \t]+login[ \t]+" "\\(" tramp-user-regexp "\\)" "\\)?")))
2537 (narrow-to-region (point) (tramp-compat-line-end-position))
2538 (when (re-search-forward regexp nil t)
2539 (setq result (list (match-string 3) (match-string 1))))
2540 (widen)
2541 (forward-line 1)
2542 result))
2544 (defun tramp-parse-putty (registry)
2545 "Return a list of (user host) tuples allowed to access.
2546 User is always nil."
2547 ;; On Windows, there are problems in completion when
2548 ;; `default-directory' is remote.
2549 (let ((default-directory (tramp-compat-temporary-file-directory))
2550 res)
2551 (with-temp-buffer
2552 (when (zerop (tramp-compat-call-process "reg" nil t nil "query" registry))
2553 (goto-char (point-min))
2554 (while (not (eobp))
2555 (push (tramp-parse-putty-group registry) res))))
2556 res))
2558 (defun tramp-parse-putty-group (registry)
2559 "Return a (user host) tuple allowed to access.
2560 User is always nil."
2561 (let ((result)
2562 (regexp (concat (regexp-quote registry) "\\\\\\(.+\\)")))
2563 (narrow-to-region (point) (tramp-compat-line-end-position))
2564 (when (re-search-forward regexp nil t)
2565 (setq result (list nil (match-string 1))))
2566 (widen)
2567 (forward-line 1)
2568 result))
2570 ;;; Common file name handler functions for different backends:
2572 (defvar tramp-handle-file-local-copy-hook nil
2573 "Normal hook to be run at the end of `tramp-*-handle-file-local-copy'.")
2575 (defvar tramp-handle-write-region-hook nil
2576 "Normal hook to be run at the end of `tramp-*-handle-write-region'.")
2578 (defun tramp-handle-directory-file-name (directory)
2579 "Like `directory-file-name' for Tramp files."
2580 ;; If localname component of filename is "/", leave it unchanged.
2581 ;; Otherwise, remove any trailing slash from localname component.
2582 ;; Method, host, etc, are unchanged. Does it make sense to try
2583 ;; to avoid parsing the filename?
2584 (with-parsed-tramp-file-name directory nil
2585 (if (and (not (zerop (length localname)))
2586 (eq (aref localname (1- (length localname))) ?/)
2587 (not (string= localname "/")))
2588 (substring directory 0 -1)
2589 directory)))
2591 (defun tramp-handle-directory-files
2592 (directory &optional full match nosort files-only)
2593 "Like `directory-files' for Tramp files."
2594 ;; FILES-ONLY is valid for XEmacs only.
2595 (when (file-directory-p directory)
2596 (setq directory (file-name-as-directory (expand-file-name directory)))
2597 (let ((temp (nreverse (file-name-all-completions "" directory)))
2598 result item)
2600 (while temp
2601 (setq item (directory-file-name (pop temp)))
2602 (when (and (or (null match) (string-match match item))
2603 (or (null files-only)
2604 ;; Files only.
2605 (and (equal files-only t) (file-regular-p item))
2606 ;; Directories only.
2607 (file-directory-p item)))
2608 (push (if full (concat directory item) item)
2609 result)))
2610 (if nosort result (sort result 'string<)))))
2612 (defun tramp-handle-directory-files-and-attributes
2613 (directory &optional full match nosort id-format)
2614 "Like `directory-files-and-attributes' for Tramp files."
2615 (mapcar
2616 (lambda (x)
2617 (cons x (tramp-compat-file-attributes
2618 (if full x (expand-file-name x directory)) id-format)))
2619 (directory-files directory full match nosort)))
2621 (defun tramp-handle-dired-uncache (dir &optional dir-p)
2622 "Like `dired-uncache' for Tramp files."
2623 ;; DIR-P is valid for XEmacs only.
2624 (with-parsed-tramp-file-name
2625 (if (or dir-p (file-directory-p dir)) dir (file-name-directory dir)) nil
2626 (tramp-flush-directory-property v localname)))
2628 (defun tramp-handle-file-exists-p (filename)
2629 "Like `file-exists-p' for Tramp files."
2630 (not (null (file-attributes filename))))
2632 (defun tramp-handle-file-modes (filename)
2633 "Like `file-modes' for Tramp files."
2634 (let ((truename (or (file-truename filename) filename)))
2635 (when (file-exists-p truename)
2636 (tramp-mode-string-to-int (nth 8 (file-attributes truename))))))
2638 ;; Localname manipulation functions that grok Tramp localnames...
2639 (defun tramp-handle-file-name-as-directory (file)
2640 "Like `file-name-as-directory' but aware of Tramp files."
2641 ;; `file-name-as-directory' would be sufficient except localname is
2642 ;; the empty string.
2643 (let ((v (tramp-dissect-file-name file t)))
2644 ;; Run the command on the localname portion only.
2645 (tramp-make-tramp-file-name
2646 (tramp-file-name-method v)
2647 (tramp-file-name-user v)
2648 (tramp-file-name-host v)
2649 (tramp-run-real-handler
2650 'file-name-as-directory (list (or (tramp-file-name-localname v) ""))))))
2652 (defun tramp-handle-file-name-completion
2653 (filename directory &optional predicate)
2654 "Like `file-name-completion' for Tramp files."
2655 (unless (tramp-tramp-file-p directory)
2656 (error
2657 "tramp-handle-file-name-completion invoked on non-tramp directory `%s'"
2658 directory))
2659 (try-completion
2660 filename
2661 (mapcar 'list (file-name-all-completions filename directory))
2662 (when predicate
2663 (lambda (x) (funcall predicate (expand-file-name (car x) directory))))))
2665 (defun tramp-handle-file-name-directory (file)
2666 "Like `file-name-directory' but aware of Tramp files."
2667 ;; Everything except the last filename thing is the directory. We
2668 ;; cannot apply `with-parsed-tramp-file-name', because this expands
2669 ;; the remote file name parts. This is a problem when we are in
2670 ;; file name completion.
2671 (let ((v (tramp-dissect-file-name file t)))
2672 ;; Run the command on the localname portion only.
2673 (tramp-make-tramp-file-name
2674 (tramp-file-name-method v)
2675 (tramp-file-name-user v)
2676 (tramp-file-name-host v)
2677 (tramp-run-real-handler
2678 'file-name-directory (list (or (tramp-file-name-localname v) ""))))))
2680 (defun tramp-handle-file-name-nondirectory (file)
2681 "Like `file-name-nondirectory' but aware of Tramp files."
2682 (with-parsed-tramp-file-name file nil
2683 (tramp-run-real-handler 'file-name-nondirectory (list localname))))
2685 (defun tramp-handle-file-newer-than-file-p (file1 file2)
2686 "Like `file-newer-than-file-p' for Tramp files."
2687 (cond
2688 ((not (file-exists-p file1)) nil)
2689 ((not (file-exists-p file2)) t)
2690 (t (tramp-time-less-p (nth 5 (file-attributes file2))
2691 (nth 5 (file-attributes file1))))))
2693 (defun tramp-handle-file-regular-p (filename)
2694 "Like `file-regular-p' for Tramp files."
2695 (and (file-exists-p filename)
2696 (eq ?- (aref (nth 8 (file-attributes filename)) 0))))
2698 (defun tramp-handle-file-remote-p (filename &optional identification connected)
2699 "Like `file-remote-p' for Tramp files."
2700 (let ((tramp-verbose 3))
2701 (when (tramp-tramp-file-p filename)
2702 (let* ((v (tramp-dissect-file-name filename))
2703 (p (tramp-get-connection-process v))
2704 (c (and p (processp p) (memq (process-status p) '(run open)))))
2705 ;; We expand the file name only, if there is already a connection.
2706 (with-parsed-tramp-file-name
2707 (if c (expand-file-name filename) filename) nil
2708 (and (or (not connected) c)
2709 (cond
2710 ((eq identification 'method) method)
2711 ((eq identification 'user) user)
2712 ((eq identification 'host) host)
2713 ((eq identification 'localname) localname)
2714 (t (tramp-make-tramp-file-name method user host "")))))))))
2716 (defun tramp-handle-file-symlink-p (filename)
2717 "Like `file-symlink-p' for Tramp files."
2718 (with-parsed-tramp-file-name filename nil
2719 (let ((x (car (file-attributes filename))))
2720 (when (stringp x)
2721 ;; When Tramp is running on VMS, then `file-name-absolute-p'
2722 ;; might do weird things.
2723 (if (file-name-absolute-p x)
2724 (tramp-make-tramp-file-name method user host x)
2725 x)))))
2727 (defun tramp-handle-find-backup-file-name (filename)
2728 "Like `find-backup-file-name' for Tramp files."
2729 (with-parsed-tramp-file-name filename nil
2730 ;; We set both variables. It doesn't matter whether it is
2731 ;; Emacs or XEmacs.
2732 (let ((backup-directory-alist
2733 ;; Emacs case.
2734 (when (boundp 'backup-directory-alist)
2735 (if (symbol-value 'tramp-backup-directory-alist)
2736 (mapcar
2737 (lambda (x)
2738 (cons
2739 (car x)
2740 (if (and (stringp (cdr x))
2741 (file-name-absolute-p (cdr x))
2742 (not (tramp-file-name-p (cdr x))))
2743 (tramp-make-tramp-file-name method user host (cdr x))
2744 (cdr x))))
2745 (symbol-value 'tramp-backup-directory-alist))
2746 (symbol-value 'backup-directory-alist))))
2748 (bkup-backup-directory-info
2749 ;; XEmacs case.
2750 (when (boundp 'bkup-backup-directory-info)
2751 (if (symbol-value 'tramp-bkup-backup-directory-info)
2752 (mapcar
2753 (lambda (x)
2754 (nconc
2755 (list (car x))
2756 (list
2757 (if (and (stringp (car (cdr x)))
2758 (file-name-absolute-p (car (cdr x)))
2759 (not (tramp-file-name-p (car (cdr x)))))
2760 (tramp-make-tramp-file-name
2761 method user host (car (cdr x)))
2762 (car (cdr x))))
2763 (cdr (cdr x))))
2764 (symbol-value 'tramp-bkup-backup-directory-info))
2765 (symbol-value 'bkup-backup-directory-info)))))
2767 (tramp-run-real-handler 'find-backup-file-name (list filename)))))
2769 (defun tramp-handle-insert-file-contents
2770 (filename &optional visit beg end replace)
2771 "Like `insert-file-contents' for Tramp files."
2772 (barf-if-buffer-read-only)
2773 (setq filename (expand-file-name filename))
2774 (let (result local-copy remote-copy)
2775 (with-parsed-tramp-file-name filename nil
2776 (unwind-protect
2777 (if (not (file-exists-p filename))
2778 ;; We don't raise a Tramp error, because it might be
2779 ;; suppressed, like in `find-file-noselect-1'.
2780 (signal 'file-error
2781 (list "File not found on remote host" filename))
2783 (if (and (tramp-local-host-p v)
2784 (let (file-name-handler-alist)
2785 (file-readable-p localname)))
2786 ;; Short track: if we are on the local host, we can
2787 ;; run directly.
2788 (setq result
2789 (tramp-run-real-handler
2790 'insert-file-contents
2791 (list localname visit beg end replace)))
2793 ;; When we shall insert only a part of the file, we copy
2794 ;; this part.
2795 (when (or beg end)
2796 (setq remote-copy (tramp-make-tramp-temp-file v))
2797 ;; This is defined in tramp-sh.el. Let's assume this
2798 ;; is loaded already.
2799 (tramp-compat-funcall 'tramp-send-command
2801 (cond
2802 ((and beg end)
2803 (format "tail -c +%d %s | head -c +%d >%s"
2804 (1+ beg) (tramp-shell-quote-argument localname)
2805 (- end beg) remote-copy))
2806 (beg
2807 (format "tail -c +%d %s >%s"
2808 (1+ beg) (tramp-shell-quote-argument localname)
2809 remote-copy))
2810 (end
2811 (format "head -c +%d %s >%s"
2812 (1+ end) (tramp-shell-quote-argument localname)
2813 remote-copy)))))
2815 ;; `insert-file-contents-literally' takes care to avoid
2816 ;; calling jka-compr. By let-binding
2817 ;; `inhibit-file-name-operation', we propagate that care
2818 ;; to the `file-local-copy' operation.
2819 (setq local-copy
2820 (let ((inhibit-file-name-operation
2821 (when (eq inhibit-file-name-operation
2822 'insert-file-contents)
2823 'file-local-copy)))
2824 (cond
2825 ((stringp remote-copy)
2826 (file-local-copy
2827 (tramp-make-tramp-file-name
2828 method user host remote-copy)))
2829 ((stringp tramp-temp-buffer-file-name)
2830 (copy-file filename tramp-temp-buffer-file-name 'ok)
2831 tramp-temp-buffer-file-name)
2832 (t (file-local-copy filename)))))
2834 ;; When the file is not readable for the owner, it
2835 ;; cannot be inserted, even it is redable for the group
2836 ;; or for everybody.
2837 (set-file-modes local-copy (tramp-compat-octal-to-decimal "0600"))
2839 (when (and (null remote-copy)
2840 (tramp-get-method-parameter
2841 method 'tramp-copy-keep-tmpfile))
2842 ;; We keep the local file for performance reasons,
2843 ;; useful for "rsync".
2844 (setq tramp-temp-buffer-file-name local-copy)
2845 (put 'tramp-temp-buffer-file-name 'permanent-local t))
2847 (with-progress-reporter
2848 v 3 (format "Inserting local temp file `%s'" local-copy)
2849 ;; We must ensure that `file-coding-system-alist'
2850 ;; matches `local-copy'.
2851 (let ((file-coding-system-alist
2852 (tramp-find-file-name-coding-system-alist
2853 filename local-copy)))
2854 (setq result
2855 (insert-file-contents
2856 local-copy nil nil nil replace))))))
2858 ;; Save exit.
2859 (progn
2860 (when visit
2861 (setq buffer-file-name filename)
2862 (setq buffer-read-only (not (file-writable-p filename)))
2863 (set-visited-file-modtime)
2864 (set-buffer-modified-p nil)
2865 ;; For root, preserve owner and group when editing files.
2866 (when (string-equal (file-remote-p filename 'user) "root")
2867 (set (make-local-variable 'backup-by-copying-when-mismatch) t)))
2868 (when (and (stringp local-copy)
2869 (or remote-copy (null tramp-temp-buffer-file-name)))
2870 (delete-file local-copy))
2871 (when (stringp remote-copy)
2872 (delete-file
2873 (tramp-make-tramp-file-name method user host remote-copy))))))
2875 ;; Result.
2876 (list (expand-file-name filename)
2877 (cadr result))))
2879 (defun tramp-handle-load (file &optional noerror nomessage nosuffix must-suffix)
2880 "Like `load' for Tramp files."
2881 (with-parsed-tramp-file-name (expand-file-name file) nil
2882 (unless nosuffix
2883 (cond ((file-exists-p (concat file ".elc"))
2884 (setq file (concat file ".elc")))
2885 ((file-exists-p (concat file ".el"))
2886 (setq file (concat file ".el")))))
2887 (when must-suffix
2888 ;; The first condition is always true for absolute file names.
2889 ;; Included for safety's sake.
2890 (unless (or (file-name-directory file)
2891 (string-match "\\.elc?\\'" file))
2892 (tramp-error
2893 v 'file-error
2894 "File `%s' does not include a `.el' or `.elc' suffix" file)))
2895 (unless noerror
2896 (when (not (file-exists-p file))
2897 (tramp-error v 'file-error "Cannot load nonexistent file `%s'" file)))
2898 (if (not (file-exists-p file))
2900 (let ((tramp-message-show-message (not nomessage)))
2901 (with-progress-reporter v 0 (format "Loading %s" file)
2902 (let ((local-copy (file-local-copy file)))
2903 ;; MUST-SUFFIX doesn't exist on XEmacs, so let it default to nil.
2904 (unwind-protect
2905 (load local-copy noerror t t)
2906 (delete-file local-copy)))))
2907 t)))
2909 (defun tramp-handle-substitute-in-file-name (filename)
2910 "Like `substitute-in-file-name' for Tramp files.
2911 \"//\" and \"/~\" substitute only in the local filename part.
2912 If the URL Tramp syntax is chosen, \"//\" as method delimeter and \"/~\" at
2913 beginning of local filename are not substituted."
2914 ;; First, we must replace environment variables.
2915 (setq filename (tramp-replace-environment-variables filename))
2916 (with-parsed-tramp-file-name filename nil
2917 (if (equal tramp-syntax 'url)
2918 ;; We need to check localname only. The other parts cannot contain
2919 ;; "//" or "/~".
2920 (if (and (> (length localname) 1)
2921 (or (string-match "//" localname)
2922 (string-match "/~" localname 1)))
2923 (tramp-run-real-handler 'substitute-in-file-name (list filename))
2924 (tramp-make-tramp-file-name
2925 (when method (substitute-in-file-name method))
2926 (when user (substitute-in-file-name user))
2927 (when host (substitute-in-file-name host))
2928 (when localname
2929 (tramp-run-real-handler
2930 'substitute-in-file-name (list localname)))))
2931 ;; Ignore in LOCALNAME everything before "//" or "/~".
2932 (when (and (stringp localname) (string-match ".+?/\\(/\\|~\\)" localname))
2933 (setq filename
2934 (concat (file-remote-p filename)
2935 (replace-match "\\1" nil nil localname)))
2936 ;; "/m:h:~" does not work for completion. We use "/m:h:~/".
2937 (when (string-match "~$" filename)
2938 (setq filename (concat filename "/"))))
2939 (tramp-run-real-handler 'substitute-in-file-name (list filename)))))
2941 (defun tramp-handle-unhandled-file-name-directory (filename)
2942 "Like `unhandled-file-name-directory' for Tramp files."
2943 ;; With Emacs 23, we could simply return `nil'. But we must keep it
2944 ;; for backward compatibility.
2945 (expand-file-name "~/"))
2947 ;;; Functions for establishing connection:
2949 ;; The following functions are actions to be taken when seeing certain
2950 ;; prompts from the remote host. See the variable
2951 ;; `tramp-actions-before-shell' for usage of these functions.
2953 (defun tramp-action-login (proc vec)
2954 "Send the login name."
2955 (when (not (stringp tramp-current-user))
2956 (save-window-excursion
2957 (let ((enable-recursive-minibuffers t))
2958 (pop-to-buffer (tramp-get-connection-buffer vec))
2959 (setq tramp-current-user (read-string (match-string 0))))))
2960 (tramp-message vec 3 "Sending login name `%s'" tramp-current-user)
2961 (with-current-buffer (tramp-get-connection-buffer vec)
2962 (tramp-message vec 6 "\n%s" (buffer-string)))
2963 (tramp-send-string vec tramp-current-user))
2965 (defun tramp-action-password (proc vec)
2966 "Query the user for a password."
2967 (with-current-buffer (process-buffer proc)
2968 (tramp-check-for-regexp proc tramp-password-prompt-regexp)
2969 (tramp-message vec 3 "Sending %s" (match-string 1))
2970 (tramp-enter-password proc)
2971 ;; Hide password prompt.
2972 (narrow-to-region (point-max) (point-max))))
2974 (defun tramp-action-succeed (proc vec)
2975 "Signal success in finding shell prompt."
2976 (throw 'tramp-action 'ok))
2978 (defun tramp-action-permission-denied (proc vec)
2979 "Signal permission denied."
2980 (kill-process proc)
2981 (throw 'tramp-action 'permission-denied))
2983 (defun tramp-action-yesno (proc vec)
2984 "Ask the user for confirmation using `yes-or-no-p'.
2985 Send \"yes\" to remote process on confirmation, abort otherwise.
2986 See also `tramp-action-yn'."
2987 (save-window-excursion
2988 (let ((enable-recursive-minibuffers t))
2989 (save-match-data (pop-to-buffer (tramp-get-connection-buffer vec)))
2990 (unless (yes-or-no-p (match-string 0))
2991 (kill-process proc)
2992 (throw 'tramp-action 'permission-denied))
2993 (with-current-buffer (tramp-get-connection-buffer vec)
2994 (tramp-message vec 6 "\n%s" (buffer-string)))
2995 (tramp-send-string vec "yes"))))
2997 (defun tramp-action-yn (proc vec)
2998 "Ask the user for confirmation using `y-or-n-p'.
2999 Send \"y\" to remote process on confirmation, abort otherwise.
3000 See also `tramp-action-yesno'."
3001 (save-window-excursion
3002 (let ((enable-recursive-minibuffers t))
3003 (save-match-data (pop-to-buffer (tramp-get-connection-buffer vec)))
3004 (unless (y-or-n-p (match-string 0))
3005 (kill-process proc)
3006 (throw 'tramp-action 'permission-denied))
3007 (with-current-buffer (tramp-get-connection-buffer vec)
3008 (tramp-message vec 6 "\n%s" (buffer-string)))
3009 (tramp-send-string vec "y"))))
3011 (defun tramp-action-terminal (proc vec)
3012 "Tell the remote host which terminal type to use.
3013 The terminal type can be configured with `tramp-terminal-type'."
3014 (tramp-message vec 5 "Setting `%s' as terminal type." tramp-terminal-type)
3015 (with-current-buffer (tramp-get-connection-buffer vec)
3016 (tramp-message vec 6 "\n%s" (buffer-string)))
3017 (tramp-send-string vec tramp-terminal-type))
3019 (defun tramp-action-process-alive (proc vec)
3020 "Check, whether a process has finished."
3021 (unless (memq (process-status proc) '(run open))
3022 (throw 'tramp-action 'process-died)))
3024 (defun tramp-action-out-of-band (proc vec)
3025 "Check, whether an out-of-band copy has finished."
3026 (cond ((and (memq (process-status proc) '(stop exit))
3027 (zerop (process-exit-status proc)))
3028 (tramp-message vec 3 "Process has finished.")
3029 (throw 'tramp-action 'ok))
3030 ((or (and (memq (process-status proc) '(stop exit))
3031 (not (zerop (process-exit-status proc))))
3032 (memq (process-status proc) '(signal)))
3033 ;; `scp' could have copied correctly, but set modes could have failed.
3034 ;; This can be ignored.
3035 (with-current-buffer (process-buffer proc)
3036 (goto-char (point-min))
3037 (if (re-search-forward tramp-operation-not-permitted-regexp nil t)
3038 (progn
3039 (tramp-message vec 5 "'set mode' error ignored.")
3040 (tramp-message vec 3 "Process has finished.")
3041 (throw 'tramp-action 'ok))
3042 (tramp-message vec 3 "Process has died.")
3043 (throw 'tramp-action 'process-died))))
3044 (t nil)))
3046 ;;; Functions for processing the actions:
3048 (defun tramp-process-one-action (proc vec actions)
3049 "Wait for output from the shell and perform one action."
3050 (let (found todo item pattern action)
3051 (while (not found)
3052 ;; Reread output once all actions have been performed.
3053 ;; Obviously, the output was not complete.
3054 (tramp-accept-process-output proc 1)
3055 (setq todo actions)
3056 (while todo
3057 (setq item (pop todo))
3058 (setq pattern (format "\\(%s\\)\\'" (symbol-value (nth 0 item))))
3059 (setq action (nth 1 item))
3060 (tramp-message
3061 vec 5 "Looking for regexp \"%s\" from remote shell" pattern)
3062 (when (tramp-check-for-regexp proc pattern)
3063 (tramp-message vec 5 "Call `%s'" (symbol-name action))
3064 (setq found (funcall action proc vec)))))
3065 found))
3067 (defun tramp-process-actions (proc vec actions &optional timeout)
3068 "Perform actions until success or TIMEOUT."
3069 ;; Preserve message for `progress-reporter'.
3070 (tramp-compat-with-temp-message ""
3071 ;; Enable auth-source and password-cache.
3072 (tramp-set-connection-property vec "first-password-request" t)
3073 (let (exit)
3074 (while (not exit)
3075 (tramp-message proc 3 "Waiting for prompts from remote shell")
3076 (setq exit
3077 (catch 'tramp-action
3078 (if timeout
3079 (with-timeout (timeout)
3080 (tramp-process-one-action proc vec actions))
3081 (tramp-process-one-action proc vec actions)))))
3082 (with-current-buffer (tramp-get-connection-buffer vec)
3083 (widen)
3084 (tramp-message vec 6 "\n%s" (buffer-string)))
3085 (unless (eq exit 'ok)
3086 (tramp-clear-passwd vec)
3087 (tramp-error-with-buffer
3088 nil vec 'file-error
3089 (cond
3090 ((eq exit 'permission-denied) "Permission denied")
3091 ((eq exit 'process-died) "Process died")
3092 (t "Login failed")))))))
3094 :;; Utility functions:
3096 (defun tramp-accept-process-output (&optional proc timeout timeout-msecs)
3097 "Like `accept-process-output' for Tramp processes.
3098 This is needed in order to hide `last-coding-system-used', which is set
3099 for process communication also."
3100 (with-current-buffer (process-buffer proc)
3101 (tramp-message proc 10 "%s %s" proc (process-status proc))
3102 (let (buffer-read-only last-coding-system-used)
3103 ;; Under Windows XP, accept-process-output doesn't return
3104 ;; sometimes. So we add an additional timeout.
3105 (with-timeout ((or timeout 1))
3106 (accept-process-output proc timeout timeout-msecs)))
3107 (tramp-message proc 10 "\n%s" (buffer-string))))
3109 (defun tramp-check-for-regexp (proc regexp)
3110 "Check, whether REGEXP is contained in process buffer of PROC.
3111 Erase echoed commands if exists."
3112 (with-current-buffer (process-buffer proc)
3113 (goto-char (point-min))
3115 ;; Check whether we need to remove echo output.
3116 (when (and (tramp-get-connection-property proc "check-remote-echo" nil)
3117 (re-search-forward tramp-echoed-echo-mark-regexp nil t))
3118 (let ((begin (match-beginning 0)))
3119 (when (re-search-forward tramp-echoed-echo-mark-regexp nil t)
3120 ;; Discard echo from remote output.
3121 (tramp-set-connection-property proc "check-remote-echo" nil)
3122 (tramp-message proc 5 "echo-mark found")
3123 (forward-line 1)
3124 (delete-region begin (point))
3125 (goto-char (point-min)))))
3127 (when (or (not (tramp-get-connection-property proc "check-remote-echo" nil))
3128 ;; Sometimes, the echo string is suppressed on the remote side.
3129 (not (string-equal
3130 (tramp-compat-funcall
3131 'substring-no-properties tramp-echo-mark-marker
3132 0 (min tramp-echo-mark-marker-length (1- (point-max))))
3133 (tramp-compat-funcall
3134 'buffer-substring-no-properties
3135 1 (min (1+ tramp-echo-mark-marker-length) (point-max))))))
3136 ;; No echo to be handled, now we can look for the regexp.
3137 (goto-char (point-min))
3138 (re-search-forward regexp nil t))))
3140 (defun tramp-wait-for-regexp (proc timeout regexp)
3141 "Wait for a REGEXP to appear from process PROC within TIMEOUT seconds.
3142 Expects the output of PROC to be sent to the current buffer. Returns
3143 the string that matched, or nil. Waits indefinitely if TIMEOUT is
3144 nil."
3145 (with-current-buffer (process-buffer proc)
3146 (let ((found (tramp-check-for-regexp proc regexp))
3147 (start-time (current-time)))
3148 (cond (timeout
3149 ;; Work around a bug in XEmacs 21, where the timeout
3150 ;; expires faster than it should. This degenerates
3151 ;; to polling for buggy XEmacsen, but oh, well.
3152 (while (and (not found)
3153 (< (tramp-time-diff (current-time) start-time)
3154 timeout))
3155 (with-timeout (timeout)
3156 (while (not found)
3157 (tramp-accept-process-output proc 1)
3158 (unless (memq (process-status proc) '(run open))
3159 (tramp-error-with-buffer
3160 nil proc 'file-error "Process has died"))
3161 (setq found (tramp-check-for-regexp proc regexp))))))
3163 (while (not found)
3164 (tramp-accept-process-output proc 1)
3165 (unless (memq (process-status proc) '(run open))
3166 (tramp-error-with-buffer
3167 nil proc 'file-error "Process has died"))
3168 (setq found (tramp-check-for-regexp proc regexp)))))
3169 (tramp-message proc 6 "\n%s" (buffer-string))
3170 (when (not found)
3171 (if timeout
3172 (tramp-error
3173 proc 'file-error "[[Regexp `%s' not found in %d secs]]"
3174 regexp timeout)
3175 (tramp-error proc 'file-error "[[Regexp `%s' not found]]" regexp)))
3176 found)))
3178 ;; We don't call `tramp-send-string' in order to hide the password
3179 ;; from the debug buffer, and because end-of-line handling of the
3180 ;; string.
3181 (defun tramp-enter-password (proc)
3182 "Prompt for a password and send it to the remote end."
3183 (process-send-string
3184 proc (concat (tramp-read-passwd proc)
3185 (or (tramp-get-method-parameter
3186 tramp-current-method
3187 'tramp-password-end-of-line)
3188 tramp-default-password-end-of-line))))
3190 ;; It seems that Tru64 Unix does not like it if long strings are sent
3191 ;; to it in one go. (This happens when sending the Perl
3192 ;; `file-attributes' implementation, for instance.) Therefore, we
3193 ;; have this function which sends the string in chunks.
3194 (defun tramp-send-string (vec string)
3195 "Send the STRING via connection VEC.
3197 The STRING is expected to use Unix line-endings, but the lines sent to
3198 the remote host use line-endings as defined in the variable
3199 `tramp-rsh-end-of-line'. The communication buffer is erased before sending."
3200 (let* ((p (tramp-get-connection-process vec))
3201 (chunksize (tramp-get-connection-property p "chunksize" nil)))
3202 (unless p
3203 (tramp-error
3204 vec 'file-error "Can't send string to remote host -- not logged in"))
3205 (tramp-set-connection-property p "last-cmd-time" (current-time))
3206 (tramp-message vec 10 "%s" string)
3207 (with-current-buffer (tramp-get-connection-buffer vec)
3208 ;; Clean up the buffer. We cannot call `erase-buffer' because
3209 ;; narrowing might be in effect.
3210 (let (buffer-read-only) (delete-region (point-min) (point-max)))
3211 ;; Replace "\n" by `tramp-rsh-end-of-line'.
3212 (setq string
3213 (mapconcat 'identity
3214 (tramp-compat-split-string string "\n")
3215 tramp-rsh-end-of-line))
3216 (unless (or (string= string "")
3217 (string-equal (substring string -1) tramp-rsh-end-of-line))
3218 (setq string (concat string tramp-rsh-end-of-line)))
3219 ;; Send the string.
3220 (if (and chunksize (not (zerop chunksize)))
3221 (let ((pos 0)
3222 (end (length string)))
3223 (while (< pos end)
3224 (tramp-message
3225 vec 10 "Sending chunk from %s to %s"
3226 pos (min (+ pos chunksize) end))
3227 (process-send-string
3228 p (substring string pos (min (+ pos chunksize) end)))
3229 (setq pos (+ pos chunksize))))
3230 (process-send-string p string)))))
3232 (defun tramp-get-inode (vec)
3233 "Returns the virtual inode number.
3234 If it doesn't exist, generate a new one."
3235 (let ((string (tramp-make-tramp-file-name
3236 (tramp-file-name-method vec)
3237 (tramp-file-name-user vec)
3238 (tramp-file-name-host vec)
3239 "")))
3240 (unless (assoc string tramp-inodes)
3241 (add-to-list 'tramp-inodes
3242 (list string (length tramp-inodes))))
3243 (nth 1 (assoc string tramp-inodes))))
3245 (defun tramp-get-device (vec)
3246 "Returns the virtual device number.
3247 If it doesn't exist, generate a new one."
3248 (let ((string (tramp-make-tramp-file-name
3249 (tramp-file-name-method vec)
3250 (tramp-file-name-user vec)
3251 (tramp-file-name-host vec)
3252 "")))
3253 (unless (assoc string tramp-devices)
3254 (add-to-list 'tramp-devices
3255 (list string (length tramp-devices))))
3256 (cons -1 (nth 1 (assoc string tramp-devices)))))
3258 (defun tramp-equal-remote (file1 file2)
3259 "Check, whether the remote parts of FILE1 and FILE2 are identical.
3260 The check depends on method, user and host name of the files. If
3261 one of the components is missing, the default values are used.
3262 The local file name parts of FILE1 and FILE2 are not taken into
3263 account.
3265 Example:
3267 (tramp-equal-remote \"/ssh::/etc\" \"/<your host name>:/home\")
3269 would yield `t'. On the other hand, the following check results in nil:
3271 (tramp-equal-remote \"/sudo::/etc\" \"/su::/etc\")"
3272 (and (stringp (file-remote-p file1))
3273 (stringp (file-remote-p file2))
3274 (string-equal (file-remote-p file1) (file-remote-p file2))))
3276 (defun tramp-get-method-parameter (method param)
3277 "Return the method parameter PARAM.
3278 If the `tramp-methods' entry does not exist, return nil."
3279 (let ((entry (assoc param (assoc method tramp-methods))))
3280 (when entry (cadr entry))))
3282 (defun tramp-mode-string-to-int (mode-string)
3283 "Converts a ten-letter `drwxrwxrwx'-style mode string into mode bits."
3284 (let* (case-fold-search
3285 (mode-chars (string-to-vector mode-string))
3286 (owner-read (aref mode-chars 1))
3287 (owner-write (aref mode-chars 2))
3288 (owner-execute-or-setid (aref mode-chars 3))
3289 (group-read (aref mode-chars 4))
3290 (group-write (aref mode-chars 5))
3291 (group-execute-or-setid (aref mode-chars 6))
3292 (other-read (aref mode-chars 7))
3293 (other-write (aref mode-chars 8))
3294 (other-execute-or-sticky (aref mode-chars 9)))
3295 (save-match-data
3296 (logior
3297 (cond
3298 ((char-equal owner-read ?r) (tramp-compat-octal-to-decimal "00400"))
3299 ((char-equal owner-read ?-) 0)
3300 (t (error "Second char `%c' must be one of `r-'" owner-read)))
3301 (cond
3302 ((char-equal owner-write ?w) (tramp-compat-octal-to-decimal "00200"))
3303 ((char-equal owner-write ?-) 0)
3304 (t (error "Third char `%c' must be one of `w-'" owner-write)))
3305 (cond
3306 ((char-equal owner-execute-or-setid ?x)
3307 (tramp-compat-octal-to-decimal "00100"))
3308 ((char-equal owner-execute-or-setid ?S)
3309 (tramp-compat-octal-to-decimal "04000"))
3310 ((char-equal owner-execute-or-setid ?s)
3311 (tramp-compat-octal-to-decimal "04100"))
3312 ((char-equal owner-execute-or-setid ?-) 0)
3313 (t (error "Fourth char `%c' must be one of `xsS-'"
3314 owner-execute-or-setid)))
3315 (cond
3316 ((char-equal group-read ?r) (tramp-compat-octal-to-decimal "00040"))
3317 ((char-equal group-read ?-) 0)
3318 (t (error "Fifth char `%c' must be one of `r-'" group-read)))
3319 (cond
3320 ((char-equal group-write ?w) (tramp-compat-octal-to-decimal "00020"))
3321 ((char-equal group-write ?-) 0)
3322 (t (error "Sixth char `%c' must be one of `w-'" group-write)))
3323 (cond
3324 ((char-equal group-execute-or-setid ?x)
3325 (tramp-compat-octal-to-decimal "00010"))
3326 ((char-equal group-execute-or-setid ?S)
3327 (tramp-compat-octal-to-decimal "02000"))
3328 ((char-equal group-execute-or-setid ?s)
3329 (tramp-compat-octal-to-decimal "02010"))
3330 ((char-equal group-execute-or-setid ?-) 0)
3331 (t (error "Seventh char `%c' must be one of `xsS-'"
3332 group-execute-or-setid)))
3333 (cond
3334 ((char-equal other-read ?r)
3335 (tramp-compat-octal-to-decimal "00004"))
3336 ((char-equal other-read ?-) 0)
3337 (t (error "Eighth char `%c' must be one of `r-'" other-read)))
3338 (cond
3339 ((char-equal other-write ?w) (tramp-compat-octal-to-decimal "00002"))
3340 ((char-equal other-write ?-) 0)
3341 (t (error "Nineth char `%c' must be one of `w-'" other-write)))
3342 (cond
3343 ((char-equal other-execute-or-sticky ?x)
3344 (tramp-compat-octal-to-decimal "00001"))
3345 ((char-equal other-execute-or-sticky ?T)
3346 (tramp-compat-octal-to-decimal "01000"))
3347 ((char-equal other-execute-or-sticky ?t)
3348 (tramp-compat-octal-to-decimal "01001"))
3349 ((char-equal other-execute-or-sticky ?-) 0)
3350 (t (error "Tenth char `%c' must be one of `xtT-'"
3351 other-execute-or-sticky)))))))
3353 (defun tramp-local-host-p (vec)
3354 "Return t if this points to the local host, nil otherwise."
3355 ;; We cannot use `tramp-file-name-real-host'. A port is an
3356 ;; indication for an ssh tunnel or alike.
3357 (let ((host (tramp-file-name-host vec)))
3358 (and
3359 (stringp host)
3360 (string-match tramp-local-host-regexp host)
3361 ;; The method shall be applied to one of the shell file name
3362 ;; handler. `tramp-local-host-p' is also called for "smb" and
3363 ;; alike, where it must fail.
3364 (tramp-get-method-parameter
3365 (tramp-file-name-method vec) 'tramp-login-program)
3366 ;; The local temp directory must be writable for the other user.
3367 (file-writable-p
3368 (tramp-make-tramp-file-name
3369 (tramp-file-name-method vec)
3370 (tramp-file-name-user vec)
3371 host
3372 (tramp-compat-temporary-file-directory)))
3373 ;; On some systems, chown runs only for root.
3374 (or (zerop (user-uid))
3375 ;; This is defined in tramp-sh.el. Let's assume this is
3376 ;; loaded already.
3377 (zerop (tramp-compat-funcall 'tramp-get-remote-uid vec 'integer))))))
3379 (defun tramp-make-tramp-temp-file (vec)
3380 "Create a temporary file on the remote host identified by VEC.
3381 Return the local name of the temporary file."
3382 (let ((prefix
3383 (tramp-make-tramp-file-name
3384 (tramp-file-name-method vec)
3385 (tramp-file-name-user vec)
3386 (tramp-file-name-host vec)
3387 (tramp-drop-volume-letter
3388 (expand-file-name
3389 tramp-temp-name-prefix
3390 ;; This is defined in tramp-sh.el. Let's assume this is
3391 ;; loaded already.
3392 (tramp-compat-funcall 'tramp-get-remote-tmpdir vec)))))
3393 result)
3394 (while (not result)
3395 ;; `make-temp-file' would be the natural choice for
3396 ;; implementation. But it calls `write-region' internally,
3397 ;; which also needs a temporary file - we would end in an
3398 ;; infinite loop.
3399 (setq result (make-temp-name prefix))
3400 (if (file-exists-p result)
3401 (setq result nil)
3402 ;; This creates the file by side effect.
3403 (set-file-times result)
3404 (set-file-modes result (tramp-compat-octal-to-decimal "0700"))))
3406 ;; Return the local part.
3407 (with-parsed-tramp-file-name result nil localname)))
3409 (defun tramp-delete-temp-file-function ()
3410 "Remove temporary files related to current buffer."
3411 (when (stringp tramp-temp-buffer-file-name)
3412 (ignore-errors (delete-file tramp-temp-buffer-file-name))))
3414 (add-hook 'kill-buffer-hook 'tramp-delete-temp-file-function)
3415 (add-hook 'tramp-cache-unload-hook
3416 (lambda ()
3417 (remove-hook 'kill-buffer-hook
3418 'tramp-delete-temp-file-function)))
3420 ;;; Auto saving to a special directory:
3422 (unless (tramp-exists-file-name-handler 'make-auto-save-file-name)
3423 (defadvice make-auto-save-file-name
3424 (around tramp-advice-make-auto-save-file-name () activate)
3425 "Invoke `tramp-*-handle-make-auto-save-file-name' for Tramp files."
3426 (if (tramp-tramp-file-p (buffer-file-name))
3427 ;; We cannot call `tramp-handle-make-auto-save-file-name'
3428 ;; directly, because this would bypass the locking mechanism.
3429 (setq ad-return-value
3430 (tramp-file-name-handler 'make-auto-save-file-name))
3431 ad-do-it))
3432 (add-hook
3433 'tramp-unload-hook
3434 (lambda ()
3435 (ad-remove-advice
3436 'make-auto-save-file-name
3437 'around 'tramp-advice-make-auto-save-file-name)
3438 (ad-activate 'make-auto-save-file-name))))
3440 ;; In XEmacs < 21.5, autosaved remote files have permission 0666 minus
3441 ;; umask. This is a security threat.
3443 (defun tramp-set-auto-save-file-modes ()
3444 "Set permissions of autosaved remote files to the original permissions."
3445 (let ((bfn (buffer-file-name)))
3446 (when (and (tramp-tramp-file-p bfn)
3447 (buffer-modified-p)
3448 (stringp buffer-auto-save-file-name)
3449 (not (equal bfn buffer-auto-save-file-name)))
3450 (unless (file-exists-p buffer-auto-save-file-name)
3451 (write-region "" nil buffer-auto-save-file-name))
3452 ;; Permissions should be set always, because there might be an old
3453 ;; auto-saved file belonging to another original file. This could
3454 ;; be a security threat.
3455 (set-file-modes
3456 buffer-auto-save-file-name
3457 (or (file-modes bfn) (tramp-compat-octal-to-decimal "0600"))))))
3459 (unless (and (featurep 'xemacs)
3460 (= emacs-major-version 21)
3461 (> emacs-minor-version 4))
3462 (add-hook 'auto-save-hook 'tramp-set-auto-save-file-modes)
3463 (add-hook 'tramp-unload-hook
3464 (lambda ()
3465 (remove-hook 'auto-save-hook 'tramp-set-auto-save-file-modes))))
3467 (defun tramp-subst-strs-in-string (alist string)
3468 "Replace all occurrences of the string FROM with TO in STRING.
3469 ALIST is of the form ((FROM . TO) ...)."
3470 (save-match-data
3471 (while alist
3472 (let* ((pr (car alist))
3473 (from (car pr))
3474 (to (cdr pr)))
3475 (while (string-match (regexp-quote from) string)
3476 (setq string (replace-match to t t string)))
3477 (setq alist (cdr alist))))
3478 string))
3480 ;;; Compatibility functions section:
3482 (defun tramp-read-passwd (proc &optional prompt)
3483 "Read a password from user (compat function).
3484 Consults the auth-source package.
3485 Invokes `password-read' if available, `read-passwd' else."
3486 (let* ((key (tramp-make-tramp-file-name
3487 tramp-current-method tramp-current-user
3488 tramp-current-host ""))
3489 (pw-prompt
3490 (or prompt
3491 (with-current-buffer (process-buffer proc)
3492 (tramp-check-for-regexp proc tramp-password-prompt-regexp)
3493 (format "%s for %s " (capitalize (match-string 1)) key)))))
3494 (with-parsed-tramp-file-name key nil
3495 (prog1
3497 ;; See if auth-sources contains something useful, if it's bound.
3498 (and (boundp 'auth-sources)
3499 (tramp-get-connection-property v "first-password-request" nil)
3500 ;; Try with Tramp's current method.
3501 (tramp-compat-funcall
3502 'auth-source-user-or-password
3503 "password" tramp-current-host tramp-current-method))
3504 ;; Try the password cache.
3505 (when (functionp 'password-read)
3506 (unless (tramp-get-connection-property
3507 v "first-password-request" nil)
3508 (tramp-compat-funcall 'password-cache-remove key))
3509 (let ((password
3510 (tramp-compat-funcall 'password-read pw-prompt key)))
3511 (tramp-compat-funcall 'password-cache-add key password)
3512 password))
3513 ;; Else, get the password interactively.
3514 (read-passwd pw-prompt))
3515 (tramp-set-connection-property v "first-password-request" nil)))))
3517 (defun tramp-clear-passwd (vec)
3518 "Clear password cache for connection related to VEC."
3519 (tramp-compat-funcall
3520 'password-cache-remove
3521 (tramp-make-tramp-file-name
3522 (tramp-file-name-method vec)
3523 (tramp-file-name-user vec)
3524 (tramp-file-name-host vec)
3525 "")))
3527 ;; Snarfed code from time-date.el and parse-time.el
3529 (defconst tramp-half-a-year '(241 17024)
3530 "Evaluated by \"(days-to-time 183)\".")
3532 (defconst tramp-parse-time-months
3533 '(("jan" . 1) ("feb" . 2) ("mar" . 3)
3534 ("apr" . 4) ("may" . 5) ("jun" . 6)
3535 ("jul" . 7) ("aug" . 8) ("sep" . 9)
3536 ("oct" . 10) ("nov" . 11) ("dec" . 12))
3537 "Alist mapping month names to integers.")
3539 (defun tramp-time-less-p (t1 t2)
3540 "Say whether time value T1 is less than time value T2."
3541 (unless t1 (setq t1 '(0 0)))
3542 (unless t2 (setq t2 '(0 0)))
3543 (or (< (car t1) (car t2))
3544 (and (= (car t1) (car t2))
3545 (< (nth 1 t1) (nth 1 t2)))))
3547 (defun tramp-time-subtract (t1 t2)
3548 "Subtract two time values.
3549 Return the difference in the format of a time value."
3550 (unless t1 (setq t1 '(0 0)))
3551 (unless t2 (setq t2 '(0 0)))
3552 (let ((borrow (< (cadr t1) (cadr t2))))
3553 (list (- (car t1) (car t2) (if borrow 1 0))
3554 (- (+ (if borrow 65536 0) (cadr t1)) (cadr t2)))))
3556 (defun tramp-time-diff (t1 t2)
3557 "Return the difference between the two times, in seconds.
3558 T1 and T2 are time values (as returned by `current-time' for example)."
3559 (cond ((and (fboundp 'subtract-time)
3560 (fboundp 'float-time))
3561 (tramp-compat-funcall
3562 'float-time (tramp-compat-funcall 'subtract-time t1 t2)))
3563 ((and (fboundp 'subtract-time)
3564 (fboundp 'time-to-seconds))
3565 (tramp-compat-funcall
3566 'time-to-seconds (tramp-compat-funcall 'subtract-time t1 t2)))
3567 ((fboundp 'itimer-time-difference)
3568 (tramp-compat-funcall
3569 'itimer-time-difference
3570 (if (< (length t1) 3) (append t1 '(0)) t1)
3571 (if (< (length t2) 3) (append t2 '(0)) t2)))
3573 (let ((time (tramp-time-subtract t1 t2)))
3574 (+ (* (car time) 65536.0)
3575 (cadr time)
3576 (/ (or (nth 2 time) 0) 1000000.0))))))
3578 ;; Currently (as of Emacs 20.5), the function `shell-quote-argument'
3579 ;; does not deal well with newline characters. Newline is replaced by
3580 ;; backslash newline. But if, say, the string `a backslash newline b'
3581 ;; is passed to a shell, the shell will expand this into "ab",
3582 ;; completely omitting the newline. This is not what was intended.
3583 ;; It does not appear to be possible to make the function
3584 ;; `shell-quote-argument' work with newlines without making it
3585 ;; dependent on the shell used. But within this package, we know that
3586 ;; we will always use a Bourne-like shell, so we use an approach which
3587 ;; groks newlines.
3589 ;; The approach is simple: we call `shell-quote-argument', then
3590 ;; massage the newline part of the result.
3592 ;; This function should produce a string which is grokked by a Unix
3593 ;; shell, even if the Emacs is running on Windows. Since this is the
3594 ;; kludges section, we bind `system-type' in such a way that
3595 ;; `shell-quote-arguments' behaves as if on Unix.
3597 ;; Thanks to Mario DeWeerd for the hint that it is sufficient for this
3598 ;; function to work with Bourne-like shells.
3600 ;; CCC: This function should be rewritten so that
3601 ;; `shell-quote-argument' is not used. This way, we are safe from
3602 ;; changes in `shell-quote-argument'.
3603 ;;;###tramp-autoload
3604 (defun tramp-shell-quote-argument (s)
3605 "Similar to `shell-quote-argument', but groks newlines.
3606 Only works for Bourne-like shells."
3607 (let ((system-type 'not-windows))
3608 (save-match-data
3609 (let ((result (shell-quote-argument s))
3610 (nl (regexp-quote (format "\\%s" tramp-rsh-end-of-line))))
3611 (when (and (>= (length result) 2)
3612 (string= (substring result 0 2) "\\~"))
3613 (setq result (substring result 1)))
3614 (while (string-match nl result)
3615 (setq result (replace-match (format "'%s'" tramp-rsh-end-of-line)
3616 t t result)))
3617 result))))
3619 ;; Checklist for `tramp-unload-hook'
3620 ;; - Unload all `tramp-*' packages
3621 ;; - Reset `file-name-handler-alist'
3622 ;; - Cleanup hooks where Tramp functions are in
3623 ;; - Cleanup advised functions
3624 ;; - Cleanup autoloads
3625 ;;;###autoload
3626 (defun tramp-unload-tramp ()
3627 "Discard Tramp from loading remote files."
3628 (interactive)
3629 ;; ange-ftp settings must be enabled.
3630 (tramp-compat-funcall 'tramp-ftp-enable-ange-ftp)
3631 ;; Maybe it's not loaded yet.
3632 (ignore-errors (unload-feature 'tramp 'force)))
3634 (provide 'tramp)
3636 ;;; TODO:
3638 ;; * Rewrite `tramp-shell-quote-argument' to abstain from using
3639 ;; `shell-quote-argument'.
3640 ;; * In Emacs 21, `insert-directory' shows total number of bytes used
3641 ;; by the files in that directory. Add this here.
3642 ;; * Avoid screen blanking when hitting `g' in dired. (Eli Tziperman)
3643 ;; * Make ffap.el grok Tramp filenames. (Eli Tziperman)
3644 ;; * abbreviate-file-name
3645 ;; * Better error checking. At least whenever we see something
3646 ;; strange when doing zerop, we should kill the process and start
3647 ;; again. (Greg Stark)
3648 ;; * Username and hostname completion.
3649 ;; ** Try to avoid usage of `last-input-event' in `tramp-completion-mode-p'.
3650 ;; ** Unify `tramp-parse-{rhosts,shosts,sconfig,hosts,passwd,netrc}'.
3651 ;; Code is nearly identical.
3652 ;; * Make `tramp-default-user' obsolete.
3653 ;; * Implement a general server-local-variable mechanism, as there are
3654 ;; probably other variables that need different values for different
3655 ;; servers too. The user could then configure a variable (such as
3656 ;; tramp-server-local-variable-alist) to define any such variables
3657 ;; that they need to, which would then be let bound as appropriate
3658 ;; in tramp functions. (Jason Rumney)
3659 ;; * IMHO, it's a drawback that currently Tramp doesn't support
3660 ;; Unicode in Dired file names by default. Is it possible to
3661 ;; improve Tramp to set LC_ALL to "C" only for commands where Tramp
3662 ;; expects English? Or just to set LC_MESSAGES to "C" if Tramp
3663 ;; expects only English messages? (Juri Linkov)
3664 ;; * Make shadowfile.el grok Tramp filenames. (Bug#4526, Bug#4846)
3665 ;; * Load ~/.emacs_SHELLNAME on the remote host for `shell'.
3666 ;; * I was wondering it it would be possible to use tramp even if I'm
3667 ;; actually using sshfs. But when I launch a command I would like
3668 ;; to get it executed on the remote machine where the files really
3669 ;; are. (Andrea Crotti)
3670 ;; * Run emerge on two remote files. Bug is described here:
3671 ;; <http://www.mail-archive.com/tramp-devel@nongnu.org/msg01041.html>.
3672 ;; (Bug#6850)
3674 ;; Functions for file-name-handler-alist:
3675 ;; diff-latest-backup-file -- in diff.el
3677 ;; arch-tag: 3a21a994-182b-48fa-b0cd-c1d9fede424a
3678 ;;; tramp.el ends here
3680 ;; Local Variables:
3681 ;; mode: Emacs-Lisp
3682 ;; coding: utf-8
3683 ;; End: