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