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