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