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