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