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