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