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