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