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