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