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