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