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