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