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