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