(gdb-use-separate-io-buffer): Remove
[bpt/emacs.git] / lisp / net / tramp.el
CommitLineData
b1a2b924 1;;; tramp.el --- Transparent Remote Access, Multiple Protocol
fb7933a3 2
5fd6d89f 3;; Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004,
b96e6899 4;; 2005, 2006, 2007, 2008, 2009 Free Software Foundation, Inc.
fb7933a3 5
cbd12ed7
GM
6;; (copyright statements below in code to be updated with the above notice)
7
cdd44874 8;; Author: Kai Großjohann <kai.grossjohann@gmx.net>
d2a2c17f 9;; Michael Albinus <michael.albinus@gmx.de>
fb7933a3
KG
10;; Keywords: comm, processes
11
12;; This file is part of GNU Emacs.
13
874a927a 14;; GNU Emacs is free software: you can redistribute it and/or modify
fb7933a3 15;; it under the terms of the GNU General Public License as published by
874a927a
GM
16;; the Free Software Foundation, either version 3 of the License, or
17;; (at your option) any later version.
fb7933a3
KG
18
19;; GNU Emacs is distributed in the hope that it will be useful,
20;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22;; GNU General Public License for more details.
23
24;; You should have received a copy of the GNU General Public License
874a927a 25;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
fb7933a3
KG
26
27;;; Commentary:
28
29;; This package provides remote file editing, similar to ange-ftp.
30;; The difference is that ange-ftp uses FTP to transfer files between
31;; the local and the remote host, whereas tramp.el uses a combination
32;; of rsh and rcp or other work-alike programs, such as ssh/scp.
33;;
b1a2b924 34;; For more detailed instructions, please see the info file.
fb7933a3
KG
35;;
36;; Notes:
37;; -----
bf247b6e 38;;
00d6fd04
MA
39;; This package only works for Emacs 21.1 and higher, and for XEmacs 21.4
40;; and higher. For XEmacs 21, you need the package `fsf-compat' for
41;; the `with-timeout' macro.)
fb7933a3 42;;
fb7933a3
KG
43;; Also see the todo list at the bottom of this file.
44;;
b1a2b924 45;; The current version of Tramp can be retrieved from the following URL:
340b8d4f 46;; http://ftp.gnu.org/gnu/tramp/
fb7933a3
KG
47;;
48;; There's a mailing list for this, as well. Its name is:
340b8d4f
MA
49;; tramp-devel@gnu.org
50;; You can use the Web to subscribe, under the following URL:
51;; http://lists.gnu.org/mailman/listinfo/tramp-devel
fb7933a3
KG
52;;
53;; For the adventurous, the current development sources are available
54;; via CVS. You can find instructions about this at the following URL:
c62c9d08 55;; http://savannah.gnu.org/projects/tramp/
fb7933a3
KG
56;; Click on "CVS" in the navigation bar near the top.
57;;
58;; Don't forget to put on your asbestos longjohns, first!
59
60;;; Code:
61
ccb4a481
MA
62;; Since Emacs 23.1, loading messages have been disabled during
63;; autoload. However, loading Tramp takes a while, and it could
64;; happen while typing a filename in the minibuffer. Therefore, Tramp
65;; shall inform about.
66(when (and load-in-progress (null (current-message)))
67 (message "Loading tramp..."))
68
b1a2b924
KG
69;; The Tramp version number and bug report address, as prepared by configure.
70(require 'trampver)
a69c01a0
MA
71(add-hook 'tramp-unload-hook
72 '(lambda ()
73 (when (featurep 'trampver)
74 (unload-feature 'trampver 'force))))
75
9e6ab520 76(require 'tramp-compat)
94be87e8
MA
77(add-hook 'tramp-unload-hook
78 '(lambda ()
79 (when (featurep 'tramp-compat)
80 (unload-feature 'tramp-compat 'force))))
fb7933a3 81
9fa0d3aa 82(require 'format-spec) ; from Gnus 5.8, also in tar ball
5ec2cc41
KG
83;; As long as password.el is not part of (X)Emacs, it shouldn't
84;; be mandatory
85(if (featurep 'xemacs)
86 (load "password" 'noerror)
fd48cd18
GM
87 (or (require 'password-cache nil 'noerror)
88 (require 'password nil 'noerror))) ; from No Gnus, also in tar ball
5ec2cc41 89
fb7933a3
KG
90(require 'shell)
91(require 'advice)
92
bcb04d98
GM
93(eval-and-compile
94 (if (featurep 'xemacs)
95 (load "auth-source" 'noerror)
96 (require 'auth-source nil 'noerror)))
5615d63f 97
00d6fd04
MA
98;; Requiring 'tramp-cache results in an endless loop.
99(autoload 'tramp-get-file-property "tramp-cache")
100(autoload 'tramp-set-file-property "tramp-cache")
101(autoload 'tramp-flush-file-property "tramp-cache")
102(autoload 'tramp-flush-directory-property "tramp-cache")
00d6fd04
MA
103(autoload 'tramp-get-connection-property "tramp-cache")
104(autoload 'tramp-set-connection-property "tramp-cache")
105(autoload 'tramp-flush-connection-property "tramp-cache")
106(autoload 'tramp-parse-connection-properties "tramp-cache")
107(add-hook 'tramp-unload-hook
108 '(lambda ()
109 (when (featurep 'tramp-cache)
110 (unload-feature 'tramp-cache 'force))))
111
16674e4f
KG
112(autoload 'tramp-uuencode-region "tramp-uu"
113 "Implementation of `uuencode' in Lisp.")
a69c01a0
MA
114(add-hook 'tramp-unload-hook
115 '(lambda ()
116 (when (featurep 'tramp-uu)
117 (unload-feature 'tramp-uu 'force))))
16674e4f 118
00d6fd04 119(autoload 'uudecode-decode-region "uudecode")
16674e4f 120
0664ff72
MA
121;; The following Tramp packages must be loaded after tramp.el, because
122;; they require it as well.
00d6fd04 123(eval-after-load "tramp"
9c13938d
MA
124 '(dolist
125 (feature
126 (list
127
0664ff72 128 ;; Tramp interactive commands.
9c13938d
MA
129 'tramp-cmds
130
131 ;; Load foreign FTP method.
132 (if (featurep 'xemacs) 'tramp-efs 'tramp-ftp)
133
134 ;; tramp-smb uses "smbclient" from Samba. Not available
135 ;; under Cygwin and Windows, because they don't offer
136 ;; "smbclient". And even not necessary there, because Emacs
137 ;; supports UNC file names like "//host/share/localname".
138 (unless (memq system-type '(cygwin windows-nt)) 'tramp-smb)
139
140 ;; Load foreign FISH method.
141 'tramp-fish
00d6fd04 142
70c11b0b 143 ;; tramp-gvfs needs D-Bus messages. Available since Emacs 23
8e754ea2
MA
144 ;; on some system types. We don't call `dbus-ping', because
145 ;; this would load dbus.el.
70c11b0b 146 (when (and (featurep 'dbusbind)
2ac33804
MA
147 (condition-case nil
148 (funcall 'dbus-get-unique-name :session)
149 (error nil))
70c11b0b
MA
150 (tramp-compat-process-running-p "gvfs-fuse-daemon"))
151 'tramp-gvfs)
152
9c13938d
MA
153 ;; Load gateways. It needs `make-network-process' from Emacs 22.
154 (when (functionp 'make-network-process) 'tramp-gw)))
155
156 (when feature
70c11b0b
MA
157 ;; We have used just some basic tests, whether a package shall
158 ;; be added. There might still be other errors during loading,
159 ;; which we will catch here.
160 (catch 'tramp-loading
161 (require feature)
162 (add-hook 'tramp-unload-hook
163 `(lambda ()
164 (when (featurep (quote ,feature))
165 (unload-feature (quote ,feature) 'force)))))
166 (unless (featurep feature)
167 (message "Loading %s failed, ignoring this package" feature)))))
fb7933a3
KG
168
169;;; User Customizable Internal Variables:
170
171(defgroup tramp nil
172 "Edit remote files with a combination of rsh and rcp or similar programs."
589d30dd 173 :group 'files
bf247b6e 174 :version "22.1")
fb7933a3 175
2e271195
MA
176;; Maybe we need once a real Tramp mode, with key bindings etc.
177;;;###autoload
178(defcustom tramp-mode t
179 "*Whether Tramp is enabled.
180If it is set to nil, all remote file names are used literally."
181 :group 'tramp
182 :type 'boolean)
183
00d6fd04 184(defcustom tramp-verbose 3
94be87e8 185 "*Verbosity level for Tramp.
00d6fd04
MA
186Any level x includes messages for all levels 1 .. x-1. The levels are
187
188 0 silent (no tramp messages at all)
189 1 errors
190 2 warnings
191 3 connection to remote hosts (default level)
192 4 activities
193 5 internal
194 6 sent and received strings
195 7 file caching
196 8 connection properties
19710 traces (huge)."
fb7933a3
KG
198 :group 'tramp
199 :type 'integer)
200
38c65fca
KG
201;; Emacs case
202(eval-and-compile
203 (when (boundp 'backup-directory-alist)
204 (defcustom tramp-backup-directory-alist nil
205 "Alist of filename patterns and backup directory names.
206Each element looks like (REGEXP . DIRECTORY), with the same meaning like
207in `backup-directory-alist'. If a Tramp file is backed up, and DIRECTORY
208is a local file name, the backup directory is prepended with Tramp file
00d6fd04 209name prefix \(method, user, host\) of file.
38c65fca
KG
210
211\(setq tramp-backup-directory-alist backup-directory-alist\)
212
213gives the same backup policy for Tramp files on their hosts like the
214policy for local files."
215 :group 'tramp
216 :type '(repeat (cons (regexp :tag "Regexp matching filename")
217 (directory :tag "Backup directory name"))))))
218
219;; XEmacs case. We cannot check for `bkup-backup-directory-info', because
220;; the package "backup-dir" might not be loaded yet.
221(eval-and-compile
222 (when (featurep 'xemacs)
223 (defcustom tramp-bkup-backup-directory-info nil
224 "*Alist of (FILE-REGEXP BACKUP-DIR OPTIONS ...))
225It has the same meaning like `bkup-backup-directory-info' from package
226`backup-dir'. If a Tramp file is backed up, and BACKUP-DIR is a local
227file name, the backup directory is prepended with Tramp file name prefix
00d6fd04 228\(method, user, host\) of file.
38c65fca
KG
229
230\(setq tramp-bkup-backup-directory-info bkup-backup-directory-info\)
231
232gives the same backup policy for Tramp files on their hosts like the
233policy for local files."
bf247b6e 234 :type '(repeat
38c65fca
KG
235 (list (regexp :tag "File regexp")
236 (string :tag "Backup Dir")
237 (set :inline t
238 (const ok-create)
239 (const full-path)
240 (const prepend-name)
241 (const search-upward))))
242 :group 'tramp)))
243
fb7933a3
KG
244(defcustom tramp-auto-save-directory nil
245 "*Put auto-save files in this directory, if set.
246The idea is to use a local directory so that auto-saving is faster."
247 :group 'tramp
00d6fd04 248 :type '(choice (const nil) string))
fb7933a3 249
16674e4f
KG
250(defcustom tramp-encoding-shell
251 (if (memq system-type '(windows-nt))
252 (getenv "COMSPEC")
253 "/bin/sh")
254 "*Use this program for encoding and decoding commands on the local host.
255This shell is used to execute the encoding and decoding command on the
256local host, so if you want to use `~' in those commands, you should
257choose a shell here which groks tilde expansion. `/bin/sh' normally
258does not understand tilde expansion.
259
260For encoding and deocding, commands like the following are executed:
261
262 /bin/sh -c COMMAND < INPUT > OUTPUT
263
264This variable can be used to change the \"/bin/sh\" part. See the
00d6fd04 265variable `tramp-encoding-command-switch' for the \"-c\" part.
fb7933a3
KG
266
267Note that this variable is not used for remote commands. There are
268mechanisms in tramp.el which automatically determine the right shell to
269use for the remote host."
270 :group 'tramp
271 :type '(file :must-match t))
272
16674e4f
KG
273(defcustom tramp-encoding-command-switch
274 (if (string-match "cmd\\.exe" tramp-encoding-shell)
275 "/c"
276 "-c")
277 "*Use this switch together with `tramp-encoding-shell' for local commands.
278See the variable `tramp-encoding-shell' for more information."
279 :group 'tramp
280 :type 'string)
281
00d6fd04
MA
282(defcustom tramp-copy-size-limit 10240
283 "*The maximum file size where inline copying is preferred over an out-of-the-band copy."
16674e4f 284 :group 'tramp
00d6fd04 285 :type 'integer)
90dc758d 286
00d6fd04
MA
287(defcustom tramp-terminal-type "dumb"
288 "*Value of TERM environment variable for logging in to remote host.
289Because Tramp wants to parse the output of the remote shell, it is easily
290confused by ANSI color escape sequences and suchlike. Often, shell init
291files conditionalize this setup based on the TERM environment variable."
90dc758d 292 :group 'tramp
00d6fd04 293 :type 'string)
90dc758d 294
00d6fd04
MA
295(defvar tramp-methods
296 `(("rcp" (tramp-login-program "rsh")
297 (tramp-login-args (("%h") ("-l" "%u")))
298 (tramp-remote-sh "/bin/sh")
299 (tramp-copy-program "rcp")
300 (tramp-copy-args (("-p" "%k")))
301 (tramp-copy-keep-date t)
302 (tramp-password-end-of-line nil))
303 ("scp" (tramp-login-program "ssh")
2296b54d 304 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
00d6fd04
MA
305 ("-e" "none")))
306 (tramp-remote-sh "/bin/sh")
307 (tramp-copy-program "scp")
308 (tramp-copy-args (("-P" "%p") ("-p" "%k") ("-q")))
309 (tramp-copy-keep-date t)
310 (tramp-password-end-of-line nil)
311 (tramp-gw-args (("-o"
312 "GlobalKnownHostsFile=/dev/null")
313 ("-o" "UserKnownHostsFile=/dev/null")
314 ("-o" "StrictHostKeyChecking=no")))
315 (tramp-default-port 22))
316 ("scp1" (tramp-login-program "ssh")
2296b54d 317 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
00d6fd04
MA
318 ("-1" "-e" "none")))
319 (tramp-remote-sh "/bin/sh")
320 (tramp-copy-program "scp")
321 (tramp-copy-args (("-1") ("-P" "%p") ("-p" "%k")
322 ("-q")))
323 (tramp-copy-keep-date t)
324 (tramp-password-end-of-line nil)
325 (tramp-gw-args (("-o"
326 "GlobalKnownHostsFile=/dev/null")
327 ("-o" "UserKnownHostsFile=/dev/null")
328 ("-o" "StrictHostKeyChecking=no")))
329 (tramp-default-port 22))
330 ("scp2" (tramp-login-program "ssh")
2296b54d 331 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
00d6fd04
MA
332 ("-2" "-e" "none")))
333 (tramp-remote-sh "/bin/sh")
334 (tramp-copy-program "scp")
335 (tramp-copy-args (("-2") ("-P" "%p") ("-p" "%k")
336 ("-q")))
337 (tramp-copy-keep-date t)
338 (tramp-password-end-of-line nil)
339 (tramp-gw-args (("-o"
340 "GlobalKnownHostsFile=/dev/null")
341 ("-o" "UserKnownHostsFile=/dev/null")
342 ("-o" "StrictHostKeyChecking=no")))
343 (tramp-default-port 22))
344 ("scp1_old"
345 (tramp-login-program "ssh1")
346 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
347 ("-e" "none")))
348 (tramp-remote-sh "/bin/sh")
349 (tramp-copy-program "scp1")
350 (tramp-copy-args (("-p" "%k")))
351 (tramp-copy-keep-date t)
352 (tramp-password-end-of-line nil))
353 ("scp2_old"
354 (tramp-login-program "ssh2")
355 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
356 ("-e" "none")))
357 (tramp-remote-sh "/bin/sh")
358 (tramp-copy-program "scp2")
359 (tramp-copy-args (("-p" "%k")))
360 (tramp-copy-keep-date t)
361 (tramp-password-end-of-line nil))
362 ("sftp" (tramp-login-program "ssh")
363 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
364 ("-e" "none")))
365 (tramp-remote-sh "/bin/sh")
366 (tramp-copy-program "sftp")
367 (tramp-copy-args nil)
368 (tramp-copy-keep-date nil)
369 (tramp-password-end-of-line nil))
370 ("rsync" (tramp-login-program "ssh")
371 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
372 ("-e" "none")))
373 (tramp-remote-sh "/bin/sh")
374 (tramp-copy-program "rsync")
375 (tramp-copy-args (("-e" "ssh") ("-t" "%k")))
376 (tramp-copy-keep-date t)
377 (tramp-password-end-of-line nil))
946a5aeb
MA
378 ("rsyncc" (tramp-login-program "ssh")
379 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
380 ("-o" "ControlPath=%t.%%r@%%h:%%p")
381 ("-o" "ControlMaster=yes")
382 ("-e" "none")))
383 (tramp-remote-sh "/bin/sh")
384 (tramp-copy-program "rsync")
385 (tramp-copy-args (("-t" "%k")))
386 (tramp-copy-env (("RSYNC_RSH")
387 (,(concat
388 "ssh"
389 " -o ControlPath=%t.%%r@%%h:%%p"
390 " -o ControlMaster=auto"))))
391 (tramp-copy-keep-date t)
392 (tramp-password-end-of-line nil))
00d6fd04
MA
393 ("remcp" (tramp-login-program "remsh")
394 (tramp-login-args (("%h") ("-l" "%u")))
395 (tramp-remote-sh "/bin/sh")
396 (tramp-copy-program "rcp")
397 (tramp-copy-args (("-p" "%k")))
398 (tramp-copy-keep-date t)
399 (tramp-password-end-of-line nil))
400 ("rsh" (tramp-login-program "rsh")
401 (tramp-login-args (("%h") ("-l" "%u")))
402 (tramp-remote-sh "/bin/sh")
403 (tramp-copy-program nil)
404 (tramp-copy-args nil)
405 (tramp-copy-keep-date nil)
406 (tramp-password-end-of-line nil))
407 ("ssh" (tramp-login-program "ssh")
2296b54d 408 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
00d6fd04
MA
409 ("-e" "none")))
410 (tramp-remote-sh "/bin/sh")
411 (tramp-copy-program nil)
412 (tramp-copy-args nil)
413 (tramp-copy-keep-date nil)
414 (tramp-password-end-of-line nil)
415 (tramp-gw-args (("-o"
416 "GlobalKnownHostsFile=/dev/null")
417 ("-o" "UserKnownHostsFile=/dev/null")
418 ("-o" "StrictHostKeyChecking=no")))
419 (tramp-default-port 22))
420 ("ssh1" (tramp-login-program "ssh")
2296b54d 421 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
00d6fd04
MA
422 ("-1" "-e" "none")))
423 (tramp-remote-sh "/bin/sh")
424 (tramp-copy-program nil)
425 (tramp-copy-args nil)
426 (tramp-copy-keep-date nil)
427 (tramp-password-end-of-line nil)
428 (tramp-gw-args (("-o"
429 "GlobalKnownHostsFile=/dev/null")
430 ("-o" "UserKnownHostsFile=/dev/null")
431 ("-o" "StrictHostKeyChecking=no")))
432 (tramp-default-port 22))
433 ("ssh2" (tramp-login-program "ssh")
2296b54d 434 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
00d6fd04
MA
435 ("-2" "-e" "none")))
436 (tramp-remote-sh "/bin/sh")
437 (tramp-copy-program nil)
438 (tramp-copy-args nil)
439 (tramp-copy-keep-date nil)
440 (tramp-password-end-of-line nil)
441 (tramp-gw-args (("-o"
442 "GlobalKnownHostsFile=/dev/null")
443 ("-o" "UserKnownHostsFile=/dev/null")
444 ("-o" "StrictHostKeyChecking=no")))
445 (tramp-default-port 22))
446 ("ssh1_old"
447 (tramp-login-program "ssh1")
448 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
449 ("-e" "none")))
450 (tramp-remote-sh "/bin/sh")
451 (tramp-copy-program nil)
452 (tramp-copy-args nil)
453 (tramp-copy-keep-date nil)
454 (tramp-password-end-of-line nil))
455 ("ssh2_old"
456 (tramp-login-program "ssh2")
457 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
458 ("-e" "none")))
459 (tramp-remote-sh "/bin/sh")
460 (tramp-copy-program nil)
461 (tramp-copy-args nil)
462 (tramp-copy-keep-date nil)
463 (tramp-password-end-of-line nil))
464 ("remsh" (tramp-login-program "remsh")
465 (tramp-login-args (("%h") ("-l" "%u")))
466 (tramp-remote-sh "/bin/sh")
467 (tramp-copy-program nil)
468 (tramp-copy-args nil)
469 (tramp-copy-keep-date nil)
470 (tramp-password-end-of-line nil))
471 ("telnet"
472 (tramp-login-program "telnet")
473 (tramp-login-args (("%h") ("%p")))
474 (tramp-remote-sh "/bin/sh")
475 (tramp-copy-program nil)
476 (tramp-copy-args nil)
477 (tramp-copy-keep-date nil)
478 (tramp-password-end-of-line nil)
479 (tramp-default-port 23))
480 ("su" (tramp-login-program "su")
481 (tramp-login-args (("-") ("%u")))
482 (tramp-remote-sh "/bin/sh")
483 (tramp-copy-program nil)
484 (tramp-copy-args nil)
485 (tramp-copy-keep-date nil)
486 (tramp-password-end-of-line nil))
487 ("sudo" (tramp-login-program "sudo")
488 (tramp-login-args (("-u" "%u")
42bc9b6d 489 ("-s") ("-H") ("-p" "Password:")))
00d6fd04
MA
490 (tramp-remote-sh "/bin/sh")
491 (tramp-copy-program nil)
492 (tramp-copy-args nil)
493 (tramp-copy-keep-date nil)
494 (tramp-password-end-of-line nil))
495 ("scpc" (tramp-login-program "ssh")
2296b54d 496 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
00d6fd04
MA
497 ("-o" "ControlPath=%t.%%r@%%h:%%p")
498 ("-o" "ControlMaster=yes")
499 ("-e" "none")))
500 (tramp-remote-sh "/bin/sh")
501 (tramp-copy-program "scp")
502 (tramp-copy-args (("-P" "%p") ("-p" "%k") ("-q")
503 ("-o" "ControlPath=%t.%%r@%%h:%%p")
504 ("-o" "ControlMaster=auto")))
505 (tramp-copy-keep-date t)
506 (tramp-password-end-of-line nil)
507 (tramp-gw-args (("-o"
508 "GlobalKnownHostsFile=/dev/null")
509 ("-o" "UserKnownHostsFile=/dev/null")
510 ("-o" "StrictHostKeyChecking=no")))
511 (tramp-default-port 22))
512 ("scpx" (tramp-login-program "ssh")
2296b54d 513 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
00d6fd04
MA
514 ("-e" "none" "-t" "-t" "/bin/sh")))
515 (tramp-remote-sh "/bin/sh")
516 (tramp-copy-program "scp")
517 (tramp-copy-args (("-p" "%k")))
518 (tramp-copy-keep-date t)
519 (tramp-password-end-of-line nil)
520 (tramp-gw-args (("-o"
521 "GlobalKnownHostsFile=/dev/null")
522 ("-o" "UserKnownHostsFile=/dev/null")
523 ("-o" "StrictHostKeyChecking=no")))
524 (tramp-default-port 22))
525 ("sshx" (tramp-login-program "ssh")
2296b54d 526 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
00d6fd04
MA
527 ("-e" "none" "-t" "-t" "/bin/sh")))
528 (tramp-remote-sh "/bin/sh")
529 (tramp-copy-program nil)
530 (tramp-copy-args nil)
531 (tramp-copy-keep-date nil)
532 (tramp-password-end-of-line nil)
533 (tramp-gw-args (("-o"
534 "GlobalKnownHostsFile=/dev/null")
535 ("-o" "UserKnownHostsFile=/dev/null")
536 ("-o" "StrictHostKeyChecking=no")))
537 (tramp-default-port 22))
538 ("krlogin"
539 (tramp-login-program "krlogin")
540 (tramp-login-args (("%h") ("-l" "%u") ("-x")))
541 (tramp-remote-sh "/bin/sh")
542 (tramp-copy-program nil)
543 (tramp-copy-args nil)
544 (tramp-copy-keep-date nil)
545 (tramp-password-end-of-line nil))
546 ("plink" (tramp-login-program "plink")
547 (tramp-login-args (("%h") ("-l" "%u") ("-P" "%p")
548 ("-ssh")))
549 (tramp-remote-sh "/bin/sh")
550 (tramp-copy-program nil)
551 (tramp-copy-args nil)
552 (tramp-copy-keep-date nil)
553 (tramp-password-end-of-line "xy") ;see docstring for "xy"
554 (tramp-default-port 22))
555 ("plink1"
556 (tramp-login-program "plink")
557 (tramp-login-args (("%h") ("-l" "%u") ("-P" "%p")
558 ("-1" "-ssh")))
559 (tramp-remote-sh "/bin/sh")
560 (tramp-copy-program nil)
561 (tramp-copy-args nil)
562 (tramp-copy-keep-date nil)
563 (tramp-password-end-of-line "xy") ;see docstring for "xy"
564 (tramp-default-port 22))
565 ("plinkx"
566 (tramp-login-program "plink")
42bc9b6d
MA
567 ;; ("%h") must be a single element, see
568 ;; `tramp-compute-multi-hops'.
569 (tramp-login-args (("-load") ("%h") ("-t")
ce3f516f
MA
570 (,(format
571 "env 'TERM=%s' 'PROMPT_COMMAND=' 'PS1=$ '"
572 tramp-terminal-type))
00d6fd04
MA
573 ("/bin/sh")))
574 (tramp-remote-sh "/bin/sh")
575 (tramp-copy-program nil)
576 (tramp-copy-args nil)
577 (tramp-copy-keep-date nil)
578 (tramp-password-end-of-line nil))
579 ("pscp" (tramp-login-program "plink")
580 (tramp-login-args (("%h") ("-l" "%u") ("-P" "%p")
581 ("-ssh")))
582 (tramp-remote-sh "/bin/sh")
583 (tramp-copy-program "pscp")
60f2c210 584 (tramp-copy-args (("-P" "%p") ("-scp") ("-p" "%k")))
00d6fd04
MA
585 (tramp-copy-keep-date t)
586 (tramp-password-end-of-line "xy") ;see docstring for "xy"
587 (tramp-default-port 22))
588 ("psftp" (tramp-login-program "plink")
589 (tramp-login-args (("%h") ("-l" "%u") ("-P" "%p")
590 ("-ssh")))
591 (tramp-remote-sh "/bin/sh")
592 (tramp-copy-program "pscp")
60f2c210 593 (tramp-copy-args (("-P" "%p") ("-sftp") ("-p" "%k")))
00d6fd04
MA
594 (tramp-copy-keep-date t)
595 (tramp-password-end-of-line "xy")) ;see docstring for "xy"
596 ("fcp" (tramp-login-program "fsh")
597 (tramp-login-args (("%h") ("-l" "%u") ("sh" "-i")))
598 (tramp-remote-sh "/bin/sh -i")
599 (tramp-copy-program "fcp")
600 (tramp-copy-args (("-p" "%k")))
601 (tramp-copy-keep-date t)
602 (tramp-password-end-of-line nil)))
fb7933a3
KG
603 "*Alist of methods for remote files.
604This is a list of entries of the form (NAME PARAM1 PARAM2 ...).
605Each NAME stands for a remote access method. Each PARAM is a
606pair of the form (KEY VALUE). The following KEYs are defined:
fb7933a3
KG
607 * `tramp-remote-sh'
608 This specifies the Bourne shell to use on the remote host. This
609 MUST be a Bourne-like shell. It is normally not necessary to set
a4aeb9a4 610 this to any value other than \"/bin/sh\": Tramp wants to use a shell
fb7933a3
KG
611 which groks tilde expansion, but it can search for it. Also note
612 that \"/bin/sh\" exists on all Unixen, this might not be true for
613 the value that you decide to use. You Have Been Warned.
b25a52cc
KG
614 * `tramp-login-program'
615 This specifies the name of the program to use for logging in to the
00d6fd04
MA
616 remote host. This may be the name of rsh or a workalike program,
617 or the name of telnet or a workalike, or the name of su or a workalike.
b25a52cc 618 * `tramp-login-args'
fb7933a3 619 This specifies the list of arguments to pass to the above
00d6fd04 620 mentioned program. Please note that this is a list of list of arguments,
fb7933a3 621 that is, normally you don't want to put \"-a -b\" or \"-f foo\"
00d6fd04
MA
622 here. Instead, you want a list (\"-a\" \"-b\"), or (\"-f\" \"foo\").
623 There are some patterns: \"%h\" in this list is replaced by the host
624 name, \"%u\" is replaced by the user name, \"%p\" is replaced by the
625 port number, and \"%%\" can be used to obtain a literal percent character.
626 If a list containing \"%h\", \"%u\" or \"%p\" is unchanged during
627 expansion (i.e. no host or no user specified), this list is not used as
628 argument. By this, arguments like (\"-l\" \"%u\") are optional.
629 \"%t\" is replaced by the temporary file name produced with
630 `tramp-make-tramp-temp-file'. \"%k\" indicates the keep-date
631 parameter of a program, if exists.
b25a52cc
KG
632 * `tramp-copy-program'
633 This specifies the name of the program to use for remotely copying
634 the file; this might be the absolute filename of rcp or the name of
635 a workalike program.
636 * `tramp-copy-args'
fb7933a3 637 This specifies the list of parameters to pass to the above mentioned
b25a52cc 638 program, the hints for `tramp-login-args' also apply here.
00d6fd04
MA
639 * `tramp-copy-keep-date'
640 This specifies whether the copying program when the preserves the
641 timestamp of the original file.
642 * `tramp-default-port'
643 The default port of a method is needed in case of gateway connections.
644 Additionally, it is used as indication which method is prepared for
645 passing gateways.
646 * `tramp-gw-args'
647 As the attribute name says, additional arguments are specified here
648 when a method is applied via a gateway.
90f8dc03
KG
649 * `tramp-password-end-of-line'
650 This specifies the string to use for terminating the line after
651 submitting the password. If this method parameter is nil, then the
652 value of the normal variable `tramp-default-password-end-of-line'
653 is used. This parameter is necessary because the \"plink\" program
654 requires any two characters after sending the password. These do
655 not have to be newline or carriage return characters. Other login
656 programs are happy with just one character, the newline character.
657 We use \"xy\" as the value for methods using \"plink\".
b25a52cc
KG
658
659What does all this mean? Well, you should specify `tramp-login-program'
660for all methods; this program is used to log in to the remote site. Then,
661there are two ways to actually transfer the files between the local and the
662remote side. One way is using an additional rcp-like program. If you want
663to do this, set `tramp-copy-program' in the method.
fb7933a3
KG
664
665Another possibility for file transfer is inline transfer, i.e. the
b25a52cc 666file is passed through the same buffer used by `tramp-login-program'. In
fb7933a3 667this case, the file contents need to be protected since the
b25a52cc 668`tramp-login-program' might use escape codes or the connection might not
fb7933a3 669be eight-bit clean. Therefore, file contents are encoded for transit.
00d6fd04
MA
670See the variables `tramp-local-coding-commands' and
671`tramp-remote-coding-commands' for details.
fb7933a3 672
16674e4f 673So, to summarize: if the method is an out-of-band method, then you
b25a52cc 674must specify `tramp-copy-program' and `tramp-copy-args'. If it is an
00d6fd04
MA
675inline method, then these two parameters should be nil. Methods which
676are fit for gateways must have `tramp-default-port' at least.
fb7933a3
KG
677
678Notes:
679
00d6fd04
MA
680When using `su' or `sudo' the phrase `open connection to a remote
681host' sounds strange, but it is used nevertheless, for consistency.
682No connection is opened to a remote host, but `su' or `sudo' is
683started on the local host. You should specify a remote host
684`localhost' or the name of the local host. Another host name is
685useful only in combination with `tramp-default-proxies-alist'.")
fb7933a3 686
b25a52cc 687(defcustom tramp-default-method
83e20b5c
MA
688 ;; An external copy method seems to be preferred, because it is much
689 ;; more performant for large files, and it hasn't too serious delays
690 ;; for small files. But it must be ensured that there aren't
691 ;; permanent password queries. Either a password agent like
692 ;; "ssh-agent" or "Pageant" shall run, or the optional password.el
693 ;; package shall be active for password caching. "scpc" would be
694 ;; another good choice because of the "ControlMaster" option, but
695 ;; this is a more modern alternative in OpenSSH 4, which cannot be
696 ;; taken as default.
00d6fd04
MA
697 (cond
698 ;; PuTTY is installed.
699 ((executable-find "pscp")
700 (if (or (fboundp 'password-read)
701 ;; Pageant is running.
70c11b0b 702 (tramp-compat-process-running-p "Pageant"))
00d6fd04
MA
703 "pscp"
704 "plink"))
705 ;; There is an ssh installation.
706 ((executable-find "scp")
707 (if (or (fboundp 'password-read)
708 ;; ssh-agent is running.
709 (getenv "SSH_AUTH_SOCK")
710 (getenv "SSH_AGENT_PID"))
711 "scp"
712 "ssh"))
713 ;; Fallback.
714 (t "ftp"))
fb7933a3 715 "*Default method to use for transferring files.
c62c9d08 716See `tramp-methods' for possibilities.
4007ba5b 717Also see `tramp-default-method-alist'."
c62c9d08
KG
718 :group 'tramp
719 :type 'string)
720
505edaeb 721(defcustom tramp-default-method-alist
4007ba5b 722 '(("\\`localhost\\'" "\\`root\\'" "su"))
00d6fd04 723 "*Default method to use for specific host/user pairs.
c62c9d08
KG
724This is an alist of items (HOST USER METHOD). The first matching item
725specifies the method to use for a file name which does not specify a
726method. HOST and USER are regular expressions or nil, which is
727interpreted as a regular expression which always matches. If no entry
728matches, the variable `tramp-default-method' takes effect.
729
730If the file name does not specify the user, lookup is done using the
731empty string for the user name.
732
733See `tramp-methods' for a list of possibilities for METHOD."
734 :group 'tramp
735 :type '(repeat (list (regexp :tag "Host regexp")
736 (regexp :tag "User regexp")
737 (string :tag "Method"))))
738
00d6fd04
MA
739(defcustom tramp-default-user
740 nil
741 "*Default user to use for transferring files.
742It is nil by default; otherwise settings in configuration files like
743\"~/.ssh/config\" would be overwritten. Also see `tramp-default-user-alist'.
744
745This variable is regarded as obsolete, and will be removed soon."
746 :group 'tramp
747 :type '(choice (const nil) string))
748
749(defcustom tramp-default-user-alist
750 `(("\\`su\\(do\\)?\\'" nil "root")
751 ("\\`r\\(em\\)?\\(cp\\|sh\\)\\|telnet\\|plink1?\\'"
752 nil ,(user-login-name)))
753 "*Default user to use for specific method/host pairs.
754This is an alist of items (METHOD HOST USER). The first matching item
755specifies the user to use for a file name which does not specify a
756user. METHOD and USER are regular expressions or nil, which is
757interpreted as a regular expression which always matches. If no entry
758matches, the variable `tramp-default-user' takes effect.
759
760If the file name does not specify the method, lookup is done using the
761empty string for the method name."
762 :group 'tramp
763 :type '(repeat (list (regexp :tag "Method regexp")
764 (regexp :tag "Host regexp")
765 (string :tag "User"))))
766
767(defcustom tramp-default-host
768 (system-name)
769 "*Default host to use for transferring files.
770Useful for su and sudo methods mostly."
771 :group 'tramp
772 :type 'string)
773
774(defcustom tramp-default-proxies-alist nil
775 "*Route to be followed for specific host/user pairs.
776This is an alist of items (HOST USER PROXY). The first matching
777item specifies the proxy to be passed for a file name located on
778a remote target matching USER@HOST. HOST and USER are regular
70c11b0b
MA
779expressions. PROXY must be a Tramp filename without a localname
780part. Method and user name on PROXY are optional, which is
781interpreted with the default values. PROXY can contain the
782patterns %h and %u, which are replaced by the strings matching
783HOST or USER, respectively.
784
785HOST, USER or PROXY could also be Lisp forms, which will be
786evaluated. The result must be a string or nil, which is
787interpreted as a regular expression which always matches."
00d6fd04 788 :group 'tramp
70c11b0b
MA
789 :type '(repeat (list (choice :tag "Host regexp" regexp sexp)
790 (choice :tag "User regexp" regexp sexp)
791 (choice :tag "Proxy remote name" string (const nil)))))
00d6fd04 792
b96e6899
MA
793(defconst tramp-local-host-regexp
794 (concat
795 "^" (regexp-opt (list "localhost" (system-name) "127\.0\.0\.1" "::1") t) "$")
796 "*Host names which are regarded as local host.")
797
16674e4f 798(defconst tramp-completion-function-alist-rsh
00d6fd04
MA
799 '((tramp-parse-rhosts "/etc/hosts.equiv")
800 (tramp-parse-rhosts "~/.rhosts"))
b25a52cc 801 "Default list of (FUNCTION FILE) pairs to be examined for rsh methods.")
16674e4f 802
16674e4f 803(defconst tramp-completion-function-alist-ssh
00d6fd04
MA
804 '((tramp-parse-rhosts "/etc/hosts.equiv")
805 (tramp-parse-rhosts "/etc/shosts.equiv")
806 (tramp-parse-shosts "/etc/ssh_known_hosts")
807 (tramp-parse-sconfig "/etc/ssh_config")
808 (tramp-parse-shostkeys "/etc/ssh2/hostkeys")
809 (tramp-parse-sknownhosts "/etc/ssh2/knownhosts")
810 (tramp-parse-rhosts "~/.rhosts")
811 (tramp-parse-rhosts "~/.shosts")
812 (tramp-parse-shosts "~/.ssh/known_hosts")
813 (tramp-parse-sconfig "~/.ssh/config")
814 (tramp-parse-shostkeys "~/.ssh2/hostkeys")
815 (tramp-parse-sknownhosts "~/.ssh2/knownhosts"))
b25a52cc 816 "Default list of (FUNCTION FILE) pairs to be examined for ssh methods.")
16674e4f 817
16674e4f 818(defconst tramp-completion-function-alist-telnet
00d6fd04 819 '((tramp-parse-hosts "/etc/hosts"))
b25a52cc 820 "Default list of (FUNCTION FILE) pairs to be examined for telnet methods.")
16674e4f 821
16674e4f 822(defconst tramp-completion-function-alist-su
00d6fd04 823 '((tramp-parse-passwd "/etc/passwd"))
b25a52cc 824 "Default list of (FUNCTION FILE) pairs to be examined for su methods.")
292ffc15 825
00d6fd04
MA
826(defconst tramp-completion-function-alist-putty
827 '((tramp-parse-putty
828 "HKEY_CURRENT_USER\\Software\\SimonTatham\\PuTTY\\Sessions"))
829 "Default list of (FUNCTION REGISTRY) pairs to be examined for putty methods.")
830
5ec2cc41 831(defvar tramp-completion-function-alist nil
16674e4f
KG
832 "*Alist of methods for remote files.
833This is a list of entries of the form (NAME PAIR1 PAIR2 ...).
834Each NAME stands for a remote access method. Each PAIR is of the form
835\(FUNCTION FILE). FUNCTION is responsible to extract user names and host
836names from FILE for completion. The following predefined FUNCTIONs exists:
837
5ec2cc41
KG
838 * `tramp-parse-rhosts' for \"~/.rhosts\" like files,
839 * `tramp-parse-shosts' for \"~/.ssh/known_hosts\" like files,
840 * `tramp-parse-sconfig' for \"~/.ssh/config\" like files,
841 * `tramp-parse-shostkeys' for \"~/.ssh2/hostkeys/*\" like files,
842 * `tramp-parse-sknownhosts' for \"~/.ssh2/knownhosts/*\" like files,
843 * `tramp-parse-hosts' for \"/etc/hosts\" like files,
844 * `tramp-parse-passwd' for \"/etc/passwd\" like files.
845 * `tramp-parse-netrc' for \"~/.netrc\" like files.
00d6fd04 846 * `tramp-parse-putty' for PuTTY registry keys.
5ec2cc41
KG
847
848FUNCTION can also be a customer defined function. For more details see
849the info pages.")
850
851(eval-after-load "tramp"
852 '(progn
853 (tramp-set-completion-function
854 "rcp" tramp-completion-function-alist-rsh)
855 (tramp-set-completion-function
856 "scp" tramp-completion-function-alist-ssh)
857 (tramp-set-completion-function
858 "scp1" tramp-completion-function-alist-ssh)
859 (tramp-set-completion-function
860 "scp2" tramp-completion-function-alist-ssh)
861 (tramp-set-completion-function
862 "scp1_old" tramp-completion-function-alist-ssh)
863 (tramp-set-completion-function
864 "scp2_old" tramp-completion-function-alist-ssh)
865 (tramp-set-completion-function
70c11b0b 866 "rsync" tramp-completion-function-alist-ssh)
946a5aeb
MA
867 (tramp-set-completion-function
868 "rsyncc" tramp-completion-function-alist-ssh)
5ec2cc41
KG
869 (tramp-set-completion-function
870 "remcp" tramp-completion-function-alist-rsh)
871 (tramp-set-completion-function
872 "rsh" tramp-completion-function-alist-rsh)
873 (tramp-set-completion-function
874 "ssh" tramp-completion-function-alist-ssh)
875 (tramp-set-completion-function
876 "ssh1" tramp-completion-function-alist-ssh)
877 (tramp-set-completion-function
878 "ssh2" tramp-completion-function-alist-ssh)
879 (tramp-set-completion-function
880 "ssh1_old" tramp-completion-function-alist-ssh)
881 (tramp-set-completion-function
882 "ssh2_old" tramp-completion-function-alist-ssh)
883 (tramp-set-completion-function
884 "remsh" tramp-completion-function-alist-rsh)
885 (tramp-set-completion-function
886 "telnet" tramp-completion-function-alist-telnet)
887 (tramp-set-completion-function
888 "su" tramp-completion-function-alist-su)
889 (tramp-set-completion-function
890 "sudo" tramp-completion-function-alist-su)
bf247b6e 891 (tramp-set-completion-function
5ec2cc41
KG
892 "scpx" tramp-completion-function-alist-ssh)
893 (tramp-set-completion-function
894 "sshx" tramp-completion-function-alist-ssh)
895 (tramp-set-completion-function
896 "krlogin" tramp-completion-function-alist-rsh)
897 (tramp-set-completion-function
898 "plink" tramp-completion-function-alist-ssh)
899 (tramp-set-completion-function
900 "plink1" tramp-completion-function-alist-ssh)
00d6fd04
MA
901 (tramp-set-completion-function
902 "plinkx" tramp-completion-function-alist-putty)
5ec2cc41
KG
903 (tramp-set-completion-function
904 "pscp" tramp-completion-function-alist-ssh)
905 (tramp-set-completion-function
906 "fcp" tramp-completion-function-alist-ssh)))
16674e4f 907
674da028
MA
908(defconst tramp-echo-mark-marker "_echo"
909 "String marker to surround echoed commands.")
910
00d6fd04
MA
911(defconst tramp-echo-mark "_echo\b\b\b\b\b"
912 "String mark to be transmitted around shell commands.
913Used to separate their echo from the output they produce. This
914will only be used if we cannot disable remote echo via stty.
915This string must have no effect on the remote shell except for
916producing some echo which can later be detected by
674da028
MA
917`tramp-echoed-echo-mark-regexp'. Using `tramp-echo-mark-marker',
918followed by an equal number of backspaces to erase them will
919usually suffice.")
00d6fd04
MA
920
921(defconst tramp-echoed-echo-mark-regexp "_echo\\(\b\\( \b\\)?\\)\\{5\\}"
922 "Regexp which matches `tramp-echo-mark' as it gets echoed by
923the remote shell.")
924
fb7933a3
KG
925(defcustom tramp-rsh-end-of-line "\n"
926 "*String used for end of line in rsh connections.
927I don't think this ever needs to be changed, so please tell me about it
16674e4f 928if you need to change this.
90f8dc03
KG
929Also see the method parameter `tramp-password-end-of-line' and the normal
930variable `tramp-default-password-end-of-line'."
16674e4f
KG
931 :group 'tramp
932 :type 'string)
933
90f8dc03
KG
934(defcustom tramp-default-password-end-of-line
935 tramp-rsh-end-of-line
16674e4f 936 "*String used for end of line after sending a password.
90f8dc03
KG
937This variable provides the default value for the method parameter
938`tramp-password-end-of-line', see `tramp-methods' for more details.
939
16674e4f
KG
940It seems that people using plink under Windows need to send
941\"\\r\\n\" (carriage-return, then newline) after a password, but just
942\"\\n\" after all other lines. This variable can be used for the
943password, see `tramp-rsh-end-of-line' for the other cases.
944
945The default value is to use the same value as `tramp-rsh-end-of-line'."
fb7933a3
KG
946 :group 'tramp
947 :type 'string)
948
00d6fd04
MA
949;; "getconf PATH" yields:
950;; HP-UX: /usr/bin:/usr/ccs/bin:/opt/ansic/bin:/opt/langtools/bin:/opt/fortran/bin
951;; Solaris: /usr/xpg4/bin:/usr/ccs/bin:/usr/bin:/opt/SUNWspro/bin
0664ff72 952;; GNU/Linux (Debian, Suse): /bin:/usr/bin
00d6fd04 953;; FreeBSD: /usr/bin:/bin:/usr/sbin:/sbin: - beware trailing ":"!
fb7933a3 954(defcustom tramp-remote-path
00d6fd04
MA
955 '(tramp-default-remote-path "/usr/sbin" "/usr/local/bin"
956 "/local/bin" "/local/freeware/bin" "/local/gnu/bin"
fb7933a3
KG
957 "/usr/freeware/bin" "/usr/pkg/bin" "/usr/contrib/bin")
958 "*List of directories to search for executables on remote host.
00d6fd04
MA
959For every remote host, this variable will be set buffer local,
960keeping the list of existing directories on that host.
fb7933a3
KG
961
962You can use `~' in this list, but when searching for a shell which groks
00d6fd04
MA
963tilde expansion, all directory names starting with `~' will be ignored.
964
965`Default Directories' represent the list of directories given by
966the command \"getconf PATH\". It is recommended to use this
967entry on top of this list, because these are the default
70c11b0b
MA
968directories for POSIX compatible commands.
969
970`Private Directories' are the settings of the $PATH environment,
971as given in your `~/.profile'."
00d6fd04
MA
972 :group 'tramp
973 :type '(repeat (choice
974 (const :tag "Default Directories" tramp-default-remote-path)
70c11b0b 975 (const :tag "Private Directories" tramp-own-remote-path)
00d6fd04
MA
976 (string :tag "Directory"))))
977
00d6fd04 978(defcustom tramp-remote-process-environment
a0a5183a 979 `("HISTFILE=$HOME/.tramp_history" "HISTSIZE=1" "LC_ALL=C"
00d6fd04 980 ,(concat "TERM=" tramp-terminal-type)
97c696d5
MA
981 "EMACS=t" ;; Deprecated.
982 ,(format "INSIDE_EMACS=%s,tramp:%s" emacs-version tramp-version)
00d6fd04
MA
983 "CDPATH=" "HISTORY=" "MAIL=" "MAILCHECK=" "MAILPATH="
984 "autocorrect=" "correct=")
985
986 "*List of environment variables to be set on the remote host.
987
988Each element should be a string of the form ENVVARNAME=VALUE. An
989entry ENVVARNAME= diables the corresponding environment variable,
990which might have been set in the init files like ~/.profile.
991
992Special handling is applied to the PATH environment, which should
993not be set here. Instead of, it should be set via `tramp-remote-path'."
fb7933a3
KG
994 :group 'tramp
995 :type '(repeat string))
996
997(defcustom tramp-login-prompt-regexp
bc103d00 998 ".*ogin\\( .*\\)?: *"
fb7933a3 999 "*Regexp matching login-like prompts.
bc103d00
MA
1000The regexp should match at end of buffer.
1001
1002Sometimes the prompt is reported to look like \"login as:\"."
fb7933a3
KG
1003 :group 'tramp
1004 :type 'regexp)
1005
821e6e36 1006(defcustom tramp-shell-prompt-pattern
ea9d1443 1007 "^[^#$%>\n]*[#$%>] *\\(\e\\[[0-9;]*[a-zA-Z] *\\)*"
821e6e36
KG
1008 "Regexp to match prompts from remote shell.
1009Normally, Tramp expects you to configure `shell-prompt-pattern'
1010correctly, but sometimes it happens that you are connecting to a
1011remote host which sends a different kind of shell prompt. Therefore,
1012Tramp recognizes things matched by `shell-prompt-pattern' as prompt,
1013and also things matched by this variable. The default value of this
b25a52cc 1014variable is similar to the default value of `shell-prompt-pattern',
821e6e36
KG
1015which should work well in many cases."
1016 :group 'tramp
1017 :type 'regexp)
1018
fb7933a3 1019(defcustom tramp-password-prompt-regexp
00d6fd04 1020 "^.*\\([pP]assword\\|[pP]assphrase\\).*:\^@? *"
fb7933a3 1021 "*Regexp matching password-like prompts.
ac474af1 1022The regexp should match at end of buffer.
fb7933a3
KG
1023
1024The `sudo' program appears to insert a `^@' character into the prompt."
1025 :group 'tramp
1026 :type 'regexp)
1027
1028(defcustom tramp-wrong-passwd-regexp
b1d06e75
KG
1029 (concat "^.*"
1030 ;; These strings should be on the last line
a4aeb9a4 1031 (regexp-opt '("Permission denied"
b1d06e75
KG
1032 "Login incorrect"
1033 "Login Incorrect"
1034 "Connection refused"
27e813fe 1035 "Connection closed"
b1d06e75
KG
1036 "Sorry, try again."
1037 "Name or service not known"
00d6fd04 1038 "Host key verification failed."
70c11b0b 1039 "No supported authentication methods left to try!") t)
b1d06e75
KG
1040 ".*"
1041 "\\|"
1042 "^.*\\("
1043 ;; Here comes a list of regexes, separated by \\|
1044 "Received signal [0-9]+"
1045 "\\).*")
fb7933a3 1046 "*Regexp matching a `login failed' message.
ac474af1
KG
1047The regexp should match at end of buffer."
1048 :group 'tramp
1049 :type 'regexp)
1050
1051(defcustom tramp-yesno-prompt-regexp
3cdaec13
KG
1052 (concat
1053 (regexp-opt '("Are you sure you want to continue connecting (yes/no)?") t)
1054 "\\s-*")
1055 "Regular expression matching all yes/no queries which need to be confirmed.
ac474af1 1056The confirmation should be done with yes or no.
3cdaec13
KG
1057The regexp should match at end of buffer.
1058See also `tramp-yn-prompt-regexp'."
fb7933a3
KG
1059 :group 'tramp
1060 :type 'regexp)
1061
3cdaec13 1062(defcustom tramp-yn-prompt-regexp
658052a2
MA
1063 (concat
1064 (regexp-opt '("Store key in cache? (y/n)"
1065 "Update cached key? (y/n, Return cancels connection)") t)
1066 "\\s-*")
3cdaec13
KG
1067 "Regular expression matching all y/n queries which need to be confirmed.
1068The confirmation should be done with y or n.
1069The regexp should match at end of buffer.
1070See also `tramp-yesno-prompt-regexp'."
1071 :group 'tramp
1072 :type 'regexp)
487f4fb7
KG
1073
1074(defcustom tramp-terminal-prompt-regexp
1075 (concat "\\("
1076 "TERM = (.*)"
1077 "\\|"
1078 "Terminal type\\? \\[.*\\]"
1079 "\\)\\s-*")
1080 "Regular expression matching all terminal setting prompts.
1081The regexp should match at end of buffer.
1082The answer will be provided by `tramp-action-terminal', which see."
1083 :group 'tramp
1084 :type 'regexp)
3cdaec13 1085
01917a18
MA
1086(defcustom tramp-operation-not-permitted-regexp
1087 (concat "\\(" "preserving times.*" "\\|" "set mode" "\\)" ":\\s-*"
1088 (regexp-opt '("Operation not permitted") t))
1089 "Regular expression matching keep-date problems in (s)cp operations.
1090Copying has been performed successfully already, so this message can
1091be ignored safely."
1092 :group 'tramp
1093 :type 'regexp)
1094
6b2633cc
LH
1095(defcustom tramp-copy-failed-regexp
1096 (concat "\\(.+: "
1097 (regexp-opt '("Permission denied"
1098 "not a regular file"
1099 "is a directory"
1100 "No such file or directory") t)
1101 "\\)\\s-*")
1102 "Regular expression matching copy problems in (s)cp operations."
1103 :group 'tramp
1104 :type 'regexp)
1105
19a87064 1106(defcustom tramp-process-alive-regexp
38c65fca 1107 ""
19a87064 1108 "Regular expression indicating a process has finished.
38c65fca
KG
1109In fact this expression is empty by intention, it will be used only to
1110check regularly the status of the associated process.
07dfe738 1111The answer will be provided by `tramp-action-process-alive',
00d6fd04 1112`tramp-action-out-of-band', which see."
38c65fca
KG
1113 :group 'tramp
1114 :type 'regexp)
1115
fb7933a3
KG
1116(defcustom tramp-temp-name-prefix "tramp."
1117 "*Prefix to use for temporary files.
1118If this is a relative file name (such as \"tramp.\"), it is considered
1119relative to the directory name returned by the function
9e6ab520 1120`tramp-compat-temporary-file-directory' (which see). It may also be an
fb7933a3
KG
1121absolute file name; don't forget to include a prefix for the filename
1122part, though."
1123 :group 'tramp
1124 :type 'string)
1125
2296b54d
MA
1126(defconst tramp-temp-buffer-name " *tramp temp*"
1127 "Buffer name for a temporary buffer.
1128It shall be used in combination with `generate-new-buffer-name'.")
1129
4007ba5b 1130(defcustom tramp-sh-extra-args '(("/bash\\'" . "-norc -noprofile"))
c62c9d08
KG
1131 "*Alist specifying extra arguments to pass to the remote shell.
1132Entries are (REGEXP . ARGS) where REGEXP is a regular expression
1133matching the shell file name and ARGS is a string specifying the
1134arguments.
1135
1136This variable is only used when Tramp needs to start up another shell
1137for tilde expansion. The extra arguments should typically prevent the
1138shell from reading its init file."
1139 :group 'tramp
90f8dc03
KG
1140 ;; This might be the wrong way to test whether the widget type
1141 ;; `alist' is available. Who knows the right way to test it?
1142 :type (if (get 'alist 'widget-type)
1143 '(alist :key-type string :value-type string)
1144 '(repeat (cons string string))))
c62c9d08 1145
00d6fd04
MA
1146;; XEmacs is distributed with few Lisp packages. Further packages are
1147;; installed using EFS. If we use a unified filename format, then
1148;; Tramp is required in addition to EFS. (But why can't Tramp just
1149;; disable EFS when Tramp is loaded? Then XEmacs can ship with EFS
1150;; just like before.) Another reason for using a separate filename
1151;; syntax on XEmacs is that EFS hooks into XEmacs in many places, but
1152;; Tramp only knows how to deal with `file-name-handler-alist', not
1153;; the other places.
1154
1155;; Currently, we have the choice between 'ftp, 'sep, and 'url.
1156;;;###autoload
1157(defcustom tramp-syntax
1158 (if (featurep 'xemacs) 'sep 'ftp)
1159 "Tramp filename syntax to be used.
1160
1161It can have the following values:
1162
1163 'ftp -- Ange-FTP respective EFS like syntax (GNU Emacs default)
1164 'sep -- Syntax as defined for XEmacs (not available yet for GNU Emacs)
1165 'url -- URL-like syntax."
16674e4f 1166 :group 'tramp
00d6fd04
MA
1167 :type (if (featurep 'xemacs)
1168 '(choice (const :tag "EFS" ftp)
1169 (const :tag "XEmacs" sep)
1170 (const :tag "URL" url))
1171 '(choice (const :tag "Ange-FTP" ftp)
1172 (const :tag "URL" url))))
1173
1174(defconst tramp-prefix-format
1175 (cond ((equal tramp-syntax 'ftp) "/")
1176 ((equal tramp-syntax 'sep) "/[")
1177 ((equal tramp-syntax 'url) "/")
1178 (t (error "Wrong `tramp-syntax' defined")))
a4aeb9a4 1179 "*String matching the very beginning of Tramp file names.
00d6fd04 1180Used in `tramp-make-tramp-file-name'.")
16674e4f 1181
00d6fd04 1182(defconst tramp-prefix-regexp
16674e4f 1183 (concat "^" (regexp-quote tramp-prefix-format))
a4aeb9a4 1184 "*Regexp matching the very beginning of Tramp file names.
00d6fd04 1185Should always start with \"^\". Derived from `tramp-prefix-format'.")
16674e4f 1186
00d6fd04 1187(defconst tramp-method-regexp
16674e4f 1188 "[a-zA-Z_0-9-]+"
00d6fd04 1189 "*Regexp matching methods identifiers.")
16674e4f 1190
00d6fd04
MA
1191(defconst tramp-postfix-method-format
1192 (cond ((equal tramp-syntax 'ftp) ":")
1193 ((equal tramp-syntax 'sep) "/")
1194 ((equal tramp-syntax 'url) "://")
1195 (t (error "Wrong `tramp-syntax' defined")))
16674e4f 1196 "*String matching delimeter between method and user or host names.
00d6fd04 1197Used in `tramp-make-tramp-file-name'.")
16674e4f 1198
00d6fd04
MA
1199(defconst tramp-postfix-method-regexp
1200 (regexp-quote tramp-postfix-method-format)
16674e4f 1201 "*Regexp matching delimeter between method and user or host names.
00d6fd04 1202Derived from `tramp-postfix-method-format'.")
16674e4f 1203
00d6fd04
MA
1204(defconst tramp-user-regexp
1205 "[^:/ \t]+"
1206 "*Regexp matching user names.")
16674e4f 1207
b96e6899
MA
1208(defconst tramp-prefix-domain-format "%"
1209 "*String matching delimeter between user and domain names.")
1210
1211(defconst tramp-prefix-domain-regexp
1212 (regexp-quote tramp-prefix-domain-format)
1213 "*Regexp matching delimeter between user and domain names.
1214Derived from `tramp-prefix-domain-format'.")
1215
1216(defconst tramp-domain-regexp
70c11b0b 1217 "[-a-zA-Z0-9_.]+"
b96e6899
MA
1218 "*Regexp matching domain names.")
1219
1220(defconst tramp-user-with-domain-regexp
1221 (concat "\\(" tramp-user-regexp "\\)"
1222 tramp-prefix-domain-regexp
1223 "\\(" tramp-domain-regexp "\\)")
1224 "*Regexp matching user names with domain names.")
1225
00d6fd04 1226(defconst tramp-postfix-user-format
16674e4f
KG
1227 "@"
1228 "*String matching delimeter between user and host names.
00d6fd04 1229Used in `tramp-make-tramp-file-name'.")
16674e4f 1230
00d6fd04 1231(defconst tramp-postfix-user-regexp
16674e4f
KG
1232 (regexp-quote tramp-postfix-user-format)
1233 "*Regexp matching delimeter between user and host names.
00d6fd04
MA
1234Derived from `tramp-postfix-user-format'.")
1235
1236(defconst tramp-host-regexp
1237 "[a-zA-Z0-9_.-]+"
1238 "*Regexp matching host names.")
1239
b96e6899
MA
1240(defconst tramp-prefix-ipv6-format
1241 (cond ((equal tramp-syntax 'ftp) "[")
1242 ((equal tramp-syntax 'sep) "")
1243 ((equal tramp-syntax 'url) "[")
1244 (t (error "Wrong `tramp-syntax' defined")))
1245 "*String matching left hand side of IPv6 addresses.
1246Used in `tramp-make-tramp-file-name'.")
1247
1248(defconst tramp-prefix-ipv6-regexp
1249 (regexp-quote tramp-prefix-ipv6-format)
1250 "*Regexp matching left hand side of IPv6 addresses.
1251Derived from `tramp-prefix-ipv6-format'.")
1252
e0b6e3b9
MA
1253;; The following regexp is a bit sloppy. But it shall serve our
1254;; purposes. It covers also IPv4 mapped IPv6 addresses, like in
1255;; "::ffff:192.168.0.1".
b96e6899 1256(defconst tramp-ipv6-regexp
e0b6e3b9 1257 "\\(?:\\(?:[a-zA-Z0-9]+\\)?:\\)+[a-zA-Z0-9.]+"
b96e6899
MA
1258 "*Regexp matching IPv6 addresses.")
1259
1260(defconst tramp-postfix-ipv6-format
1261 (cond ((equal tramp-syntax 'ftp) "]")
1262 ((equal tramp-syntax 'sep) "")
1263 ((equal tramp-syntax 'url) "]")
1264 (t (error "Wrong `tramp-syntax' defined")))
1265 "*String matching right hand side of IPv6 addresses.
1266Used in `tramp-make-tramp-file-name'.")
1267
1268(defconst tramp-postfix-ipv6-regexp
1269 (regexp-quote tramp-postfix-ipv6-format)
1270 "*Regexp matching right hand side of IPv6 addresses.
1271Derived from `tramp-postfix-ipv6-format'.")
1272
00d6fd04
MA
1273(defconst tramp-prefix-port-format
1274 (cond ((equal tramp-syntax 'ftp) "#")
1275 ((equal tramp-syntax 'sep) "#")
1276 ((equal tramp-syntax 'url) ":")
1277 (t (error "Wrong `tramp-syntax' defined")))
1278 "*String matching delimeter between host names and port numbers.")
1279
1280(defconst tramp-prefix-port-regexp
1281 (regexp-quote tramp-prefix-port-format)
1282 "*Regexp matching delimeter between host names and port numbers.
1283Derived from `tramp-prefix-port-format'.")
1284
1285(defconst tramp-port-regexp
1286 "[0-9]+"
1287 "*Regexp matching port numbers.")
1288
1289(defconst tramp-host-with-port-regexp
1290 (concat "\\(" tramp-host-regexp "\\)"
1291 tramp-prefix-port-regexp
1292 "\\(" tramp-port-regexp "\\)")
1293 "*Regexp matching host names with port numbers.")
1294
1295(defconst tramp-postfix-host-format
1296 (cond ((equal tramp-syntax 'ftp) ":")
1297 ((equal tramp-syntax 'sep) "]")
1298 ((equal tramp-syntax 'url) "")
1299 (t (error "Wrong `tramp-syntax' defined")))
7432277c 1300 "*String matching delimeter between host names and localnames.
00d6fd04 1301Used in `tramp-make-tramp-file-name'.")
16674e4f 1302
00d6fd04 1303(defconst tramp-postfix-host-regexp
16674e4f 1304 (regexp-quote tramp-postfix-host-format)
7432277c 1305 "*Regexp matching delimeter between host names and localnames.
00d6fd04 1306Derived from `tramp-postfix-host-format'.")
16674e4f 1307
00d6fd04 1308(defconst tramp-localname-regexp
16674e4f 1309 ".*$"
00d6fd04 1310 "*Regexp matching localnames.")
16674e4f
KG
1311
1312;; File name format.
505edaeb 1313
00d6fd04 1314(defconst tramp-file-name-structure
16674e4f
KG
1315 (list
1316 (concat
1317 tramp-prefix-regexp
00d6fd04
MA
1318 "\\(" "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp "\\)?"
1319 "\\(" "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp "\\)?"
b96e6899
MA
1320 "\\(" "\\(" tramp-host-regexp
1321 "\\|"
1322 tramp-prefix-ipv6-regexp tramp-ipv6-regexp
1323 tramp-postfix-ipv6-regexp "\\)"
1324 "\\(" tramp-prefix-port-regexp tramp-port-regexp "\\)?" "\\)?"
00d6fd04
MA
1325 tramp-postfix-host-regexp
1326 "\\(" tramp-localname-regexp "\\)")
b96e6899 1327 2 4 5 8)
16674e4f 1328
fb7933a3 1329 "*List of five elements (REGEXP METHOD USER HOST FILE), detailing \
a4aeb9a4 1330the Tramp file name structure.
fb7933a3 1331
a4aeb9a4 1332The first element REGEXP is a regular expression matching a Tramp file
fb7933a3
KG
1333name. The regex should contain parentheses around the method name,
1334the user name, the host name, and the file name parts.
1335
1336The second element METHOD is a number, saying which pair of
1337parentheses matches the method name. The third element USER is
1338similar, but for the user name. The fourth element HOST is similar,
1339but for the host name. The fifth element FILE is for the file name.
1340These numbers are passed directly to `match-string', which see. That
1341means the opening parentheses are counted to identify the pair.
1342
00d6fd04 1343See also `tramp-file-name-regexp'.")
fb7933a3
KG
1344
1345;;;###autoload
505edaeb 1346(defconst tramp-file-name-regexp-unified
b96e6899 1347 "\\`/\\([^[/:]+\\|[^/]+]\\):"
505edaeb
KG
1348 "Value for `tramp-file-name-regexp' for unified remoting.
1349Emacs (not XEmacs) uses a unified filename syntax for Ange-FTP and
00d6fd04 1350Tramp. See `tramp-file-name-structure' for more explanations.")
505edaeb
KG
1351
1352;;;###autoload
1353(defconst tramp-file-name-regexp-separate
1354 "\\`/\\[.*\\]"
1355 "Value for `tramp-file-name-regexp' for separate remoting.
1356XEmacs uses a separate filename syntax for Tramp and EFS.
00d6fd04 1357See `tramp-file-name-structure' for more explanations.")
505edaeb
KG
1358
1359;;;###autoload
00d6fd04
MA
1360(defconst tramp-file-name-regexp-url
1361 "\\`/[^/:]+://"
1362 "Value for `tramp-file-name-regexp' for URL-like remoting.
1363See `tramp-file-name-structure' for more explanations.")
1364
1365;;;###autoload
1366(defconst tramp-file-name-regexp
1367 (cond ((equal tramp-syntax 'ftp) tramp-file-name-regexp-unified)
1368 ((equal tramp-syntax 'sep) tramp-file-name-regexp-separate)
1369 ((equal tramp-syntax 'url) tramp-file-name-regexp-url)
1370 (t (error "Wrong `tramp-syntax' defined")))
94be87e8 1371 "*Regular expression matching file names handled by Tramp.
a4aeb9a4 1372This regexp should match Tramp file names but no other file names.
fb7933a3
KG
1373\(When tramp.el is loaded, this regular expression is prepended to
1374`file-name-handler-alist', and that is searched sequentially. Thus,
a4aeb9a4
MA
1375if the Tramp entry appears rather early in the `file-name-handler-alist'
1376and is a bit too general, then some files might be considered Tramp
00d6fd04 1377files which are not really Tramp files.
fb7933a3
KG
1378
1379Please note that the entry in `file-name-handler-alist' is made when
1380this file (tramp.el) is loaded. This means that this variable must be set
1381before loading tramp.el. Alternatively, `file-name-handler-alist' can be
1382updated after changing this variable.
1383
00d6fd04 1384Also see `tramp-file-name-structure'.")
fb7933a3 1385
16674e4f 1386;;;###autoload
8a798e41 1387(defconst tramp-root-regexp
00d6fd04 1388 (if (memq system-type '(cygwin windows-nt))
57671b72
MA
1389 "^\\([a-zA-Z]:\\)?/"
1390 "^/")
8a798e41
MA
1391 "Beginning of an incomplete Tramp file name.
1392Usually, it is just \"^/\". On W32 systems, there might be a
57671b72 1393volume letter, which will be removed by `tramp-drop-volume-letter'.")
8a798e41
MA
1394
1395;;;###autoload
1396(defconst tramp-completion-file-name-regexp-unified
1397 (concat tramp-root-regexp "[^/]*$")
16674e4f 1398 "Value for `tramp-completion-file-name-regexp' for unified remoting.
8a798e41
MA
1399GNU Emacs uses a unified filename syntax for Tramp and Ange-FTP.
1400See `tramp-file-name-structure' for more explanations.")
fb7933a3 1401
16674e4f
KG
1402;;;###autoload
1403(defconst tramp-completion-file-name-regexp-separate
57671b72 1404 (concat tramp-root-regexp "\\([[][^]]*\\)?$")
16674e4f
KG
1405 "Value for `tramp-completion-file-name-regexp' for separate remoting.
1406XEmacs uses a separate filename syntax for Tramp and EFS.
00d6fd04 1407See `tramp-file-name-structure' for more explanations.")
fb7933a3 1408
16674e4f 1409;;;###autoload
00d6fd04 1410(defconst tramp-completion-file-name-regexp-url
8a798e41 1411 (concat tramp-root-regexp "[^/:]+\\(:\\(/\\(/[^/]*\\)?\\)?\\)?$")
00d6fd04
MA
1412 "Value for `tramp-completion-file-name-regexp' for URL-like remoting.
1413See `tramp-file-name-structure' for more explanations.")
1414
1415;;;###autoload
1416(defconst tramp-completion-file-name-regexp
1417 (cond ((equal tramp-syntax 'ftp) tramp-completion-file-name-regexp-unified)
1418 ((equal tramp-syntax 'sep) tramp-completion-file-name-regexp-separate)
1419 ((equal tramp-syntax 'url) tramp-completion-file-name-regexp-url)
1420 (t (error "Wrong `tramp-syntax' defined")))
a4aeb9a4
MA
1421 "*Regular expression matching file names handled by Tramp completion.
1422This regexp should match partial Tramp file names only.
16674e4f
KG
1423
1424Please note that the entry in `file-name-handler-alist' is made when
1425this file (tramp.el) is loaded. This means that this variable must be set
1426before loading tramp.el. Alternatively, `file-name-handler-alist' can be
1427updated after changing this variable.
1428
00d6fd04 1429Also see `tramp-file-name-structure'.")
fb7933a3 1430
00d6fd04
MA
1431(defconst tramp-actions-before-shell
1432 '((tramp-login-prompt-regexp tramp-action-login)
1433 (tramp-password-prompt-regexp tramp-action-password)
1434 (tramp-wrong-passwd-regexp tramp-action-permission-denied)
ac474af1 1435 (shell-prompt-pattern tramp-action-succeed)
821e6e36 1436 (tramp-shell-prompt-pattern tramp-action-succeed)
3cdaec13 1437 (tramp-yesno-prompt-regexp tramp-action-yesno)
487f4fb7 1438 (tramp-yn-prompt-regexp tramp-action-yn)
19a87064
MA
1439 (tramp-terminal-prompt-regexp tramp-action-terminal)
1440 (tramp-process-alive-regexp tramp-action-process-alive))
ac474af1
KG
1441 "List of pattern/action pairs.
1442Whenever a pattern matches, the corresponding action is performed.
1443Each item looks like (PATTERN ACTION).
1444
1445The PATTERN should be a symbol, a variable. The value of this
1446variable gives the regular expression to search for. Note that the
1447regexp must match at the end of the buffer, \"\\'\" is implicitly
1448appended to it.
1449
1450The ACTION should also be a symbol, but a function. When the
00d6fd04 1451corresponding PATTERN matches, the ACTION function is called.")
ac474af1 1452
00d6fd04 1453(defconst tramp-actions-copy-out-of-band
38c65fca
KG
1454 '((tramp-password-prompt-regexp tramp-action-password)
1455 (tramp-wrong-passwd-regexp tramp-action-permission-denied)
00d6fd04 1456 (tramp-copy-failed-regexp tramp-action-permission-denied)
19a87064 1457 (tramp-process-alive-regexp tramp-action-out-of-band))
38c65fca
KG
1458 "List of pattern/action pairs.
1459This list is used for copying/renaming with out-of-band methods.
90f8dc03 1460
00d6fd04
MA
1461See `tramp-actions-before-shell' for more info.")
1462
1463;; Chunked sending kludge. We set this to 500 for black-listed constellations
7432277c 1464;; known to have a bug in `process-send-string'; some ssh connections appear
7177e2a3
MA
1465;; to drop bytes when data is sent too quickly. There is also a connection
1466;; buffer local variable, which is computed depending on remote host properties
1467;; when `tramp-chunksize' is zero or nil.
7432277c
KG
1468(defcustom tramp-chunksize
1469 (when (and (not (featurep 'xemacs))
1470 (memq system-type '(hpux)))
1471 500)
55880756
MA
1472;; Parentheses in docstring starting at beginning of line are escaped.
1473;; Fontification is messed up when
1474;; `open-paren-in-column-0-is-defun-start' set to t.
7432277c
KG
1475 "*If non-nil, chunksize for sending input to local process.
1476It is necessary only on systems which have a buggy `process-send-string'
1477implementation. The necessity, whether this variable must be set, can be
1478checked via the following code:
1479
1480 (with-temp-buffer
11948172
MA
1481 (let* ((user \"xxx\") (host \"yyy\")
1482 (init 0) (step 50)
1483 (sent init) (received init))
1484 (while (= sent received)
1485 (setq sent (+ sent step))
1486 (erase-buffer)
1487 (let ((proc (start-process (buffer-name) (current-buffer)
1488 \"ssh\" \"-l\" user host \"wc\" \"-c\")))
1489 (when (memq (process-status proc) '(run open))
1490 (process-send-string proc (make-string sent ?\\ ))
1491 (process-send-eof proc)
1492 (process-send-eof proc))
1493 (while (not (progn (goto-char (point-min))
1494 (re-search-forward \"\\\\w+\" (point-max) t)))
1495 (accept-process-output proc 1))
1496 (when (memq (process-status proc) '(run open))
1497 (setq received (string-to-number (match-string 0)))
1498 (delete-process proc)
1499 (message \"Bytes sent: %s\\tBytes received: %s\" sent received)
1500 (sit-for 0))))
1501 (if (> sent (+ init step))
1502 (message \"You should set `tramp-chunksize' to a maximum of %s\"
1503 (- sent step))
1504 (message \"Test does not work\")
1505 (display-buffer (current-buffer))
1506 (sit-for 30))))
1507
1508In the Emacs normally running Tramp, evaluate the above code
55880756 1509\(replace \"xxx\" and \"yyy\" by the remote user and host name,
11948172
MA
1510respectively). You can do this, for example, by pasting it into
1511the `*scratch*' buffer and then hitting C-j with the cursor after the
1512last closing parenthesis. Note that it works only if you have configured
1513\"ssh\" to run without password query, see ssh-agent(1).
1514
1515You will see the number of bytes sent successfully to the remote host.
1516If that number exceeds 1000, you can stop the execution by hitting
1517C-g, because your Emacs is likely clean.
1518
11948172
MA
1519When it is necessary to set `tramp-chunksize', you might consider to
1520use an out-of-the-band method (like \"scp\") instead of an internal one
55880756 1521\(like \"ssh\"), because setting `tramp-chunksize' to non-nil decreases
11948172 1522performance.
c951aecb 1523
00d6fd04
MA
1524If your Emacs is buggy, the code stops and gives you an indication
1525about the value `tramp-chunksize' should be set. Maybe you could just
1526experiment a bit, e.g. changing the values of `init' and `step'
1527in the third line of the code.
1528
7432277c
KG
1529Please raise a bug report via \"M-x tramp-bug\" if your system needs
1530this variable to be set as well."
1531 :group 'tramp
b1a2b924 1532 :type '(choice (const nil) integer))
7432277c 1533
5ec2cc41
KG
1534;; Logging in to a remote host normally requires obtaining a pty. But
1535;; Emacs on MacOS X has process-connection-type set to nil by default,
1536;; so on those systems Tramp doesn't obtain a pty. Here, we allow
1537;; for an override of the system default.
1538(defcustom tramp-process-connection-type t
1539 "Overrides `process-connection-type' for connections from Tramp.
1540Tramp binds process-connection-type to the value given here before
1541opening a connection to a remote host."
1542 :group 'tramp
1543 :type '(choice (const nil) (const t) (const pty)))
1544
b50dd0d2
MA
1545(defcustom tramp-completion-reread-directory-timeout 10
1546 "Defines seconds since last remote command before rereading a directory.
1547A remote directory might have changed its contents. In order to
1548make it visible during file name completion in the minibuffer,
1549Tramp flushes its cache and rereads the directory contents when
1550more than `tramp-completion-reread-directory-timeout' seconds
1551have been gone since last remote command execution. A value of 0
1552would require an immediate reread during filename completion, nil
1553means to use always cached values for the directory contents."
1554 :group 'tramp
1555 :type '(choice (const nil) integer))
1556
fb7933a3
KG
1557;;; Internal Variables:
1558
4007ba5b 1559(defvar tramp-end-of-output
a0a5183a 1560 (format
70c11b0b
MA
1561 "///%s$"
1562 (md5 (concat (prin1-to-string process-environment) (current-time-string))))
1563 "String used to recognize end of output.
1564The '$' character at the end is quoted; the string cannot be
1565detected as prompt when being sent on echoing hosts, therefore.")
fb7933a3 1566
fb7933a3 1567(defvar tramp-current-method nil
00d6fd04 1568 "Connection method for this *tramp* buffer.")
fb7933a3
KG
1569
1570(defvar tramp-current-user nil
00d6fd04 1571 "Remote login name for this *tramp* buffer.")
fb7933a3
KG
1572
1573(defvar tramp-current-host nil
00d6fd04
MA
1574 "Remote host for this *tramp* buffer.")
1575
1576(defconst tramp-uudecode
1577 "(echo begin 600 /tmp/tramp.$$; tail +2) | uudecode
fabf2143 1578cat /tmp/tramp.$$
00d6fd04 1579rm -f /tmp/tramp.$$"
fabf2143 1580 "Shell function to implement `uudecode' to standard output.
c08e6004
MA
1581Many systems support `uudecode -o /dev/stdout' or `uudecode -o -'
1582for this or `uudecode -p', but some systems don't, and for them
1583we have this shell function.")
fabf2143
KG
1584
1585;; Perl script to implement `file-attributes' in a Lisp `read'able
1586;; output. If you are hacking on this, note that you get *no* output
1587;; unless this spits out a complete line, including the '\n' at the
1588;; end.
8daea7fc 1589;; The device number is returned as "-1", because there will be a virtual
b946a456 1590;; device number set in `tramp-handle-file-attributes'.
00d6fd04
MA
1591(defconst tramp-perl-file-attributes
1592 "%s -e '
c82c5727
LH
1593@stat = lstat($ARGV[0]);
1594if (($stat[2] & 0170000) == 0120000)
1595{
1596 $type = readlink($ARGV[0]);
1597 $type = \"\\\"$type\\\"\";
1598}
1599elsif (($stat[2] & 0170000) == 040000)
1600{
1601 $type = \"t\";
1602}
1603else
1604{
1605 $type = \"nil\"
1606};
1607$uid = ($ARGV[1] eq \"integer\") ? $stat[4] : \"\\\"\" . getpwuid($stat[4]) . \"\\\"\";
1608$gid = ($ARGV[1] eq \"integer\") ? $stat[5] : \"\\\"\" . getgrgid($stat[5]) . \"\\\"\";
1609printf(
d4443a0d 1610 \"(%%s %%u %%s %%s (%%u %%u) (%%u %%u) (%%u %%u) %%u.0 %%u t (%%u . %%u) -1)\\n\",
c82c5727
LH
1611 $type,
1612 $stat[3],
1613 $uid,
1614 $gid,
1615 $stat[8] >> 16 & 0xffff,
1616 $stat[8] & 0xffff,
1617 $stat[9] >> 16 & 0xffff,
1618 $stat[9] & 0xffff,
1619 $stat[10] >> 16 & 0xffff,
1620 $stat[10] & 0xffff,
1621 $stat[7],
1622 $stat[2],
1623 $stat[1] >> 16 & 0xffff,
1624 $stat[1] & 0xffff
00d6fd04 1625);' \"$1\" \"$2\" \"$3\" 2>/dev/null"
fb7933a3 1626 "Perl script to produce output suitable for use with `file-attributes'
00d6fd04
MA
1627on the remote file system.
1628Escape sequence %s is replaced with name of Perl binary.
1629This string is passed to `format', so percent characters need to be doubled.")
fb7933a3 1630
00d6fd04
MA
1631(defconst tramp-perl-directory-files-and-attributes
1632 "%s -e '
8cb0a559
LH
1633chdir($ARGV[0]) or printf(\"\\\"Cannot change to $ARGV[0]: $''!''\\\"\\n\"), exit();
1634opendir(DIR,\".\") or printf(\"\\\"Cannot open directory $ARGV[0]: $''!''\\\"\\n\"), exit();
c82c5727
LH
1635@list = readdir(DIR);
1636closedir(DIR);
1637$n = scalar(@list);
1638printf(\"(\\n\");
1639for($i = 0; $i < $n; $i++)
1640{
1641 $filename = $list[$i];
1642 @stat = lstat($filename);
1643 if (($stat[2] & 0170000) == 0120000)
1644 {
1645 $type = readlink($filename);
1646 $type = \"\\\"$type\\\"\";
1647 }
1648 elsif (($stat[2] & 0170000) == 040000)
1649 {
1650 $type = \"t\";
1651 }
1652 else
1653 {
1654 $type = \"nil\"
1655 };
1656 $uid = ($ARGV[1] eq \"integer\") ? $stat[4] : \"\\\"\" . getpwuid($stat[4]) . \"\\\"\";
1657 $gid = ($ARGV[1] eq \"integer\") ? $stat[5] : \"\\\"\" . getgrgid($stat[5]) . \"\\\"\";
1658 printf(
b946a456 1659 \"(\\\"%%s\\\" %%s %%u %%s %%s (%%u %%u) (%%u %%u) (%%u %%u) %%u.0 %%u t (%%u . %%u) (%%u . %%u))\\n\",
c82c5727
LH
1660 $filename,
1661 $type,
1662 $stat[3],
1663 $uid,
1664 $gid,
1665 $stat[8] >> 16 & 0xffff,
1666 $stat[8] & 0xffff,
1667 $stat[9] >> 16 & 0xffff,
1668 $stat[9] & 0xffff,
1669 $stat[10] >> 16 & 0xffff,
1670 $stat[10] & 0xffff,
1671 $stat[7],
1672 $stat[2],
1673 $stat[1] >> 16 & 0xffff,
1674 $stat[1] & 0xffff,
1675 $stat[0] >> 16 & 0xffff,
1676 $stat[0] & 0xffff);
1677}
00d6fd04 1678printf(\")\\n\");' \"$1\" \"$2\" \"$3\" 2>/dev/null"
c82c5727 1679 "Perl script implementing `directory-files-attributes' as Lisp `read'able
00d6fd04
MA
1680output.
1681Escape sequence %s is replaced with name of Perl binary.
1682This string is passed to `format', so percent characters need to be doubled.")
c82c5727 1683
ac474af1
KG
1684;; ;; These two use uu encoding.
1685;; (defvar tramp-perl-encode "%s -e'\
1686;; print qq(begin 644 xxx\n);
1687;; my $s = q();
1688;; my $res = q();
1689;; while (read(STDIN, $s, 45)) {
1690;; print pack(q(u), $s);
1691;; }
1692;; print qq(`\n);
1693;; print qq(end\n);
1694;; '"
1695;; "Perl program to use for encoding a file.
1696;; Escape sequence %s is replaced with name of Perl binary.")
1697
1698;; (defvar tramp-perl-decode "%s -ne '
1699;; print unpack q(u), $_;
1700;; '"
1701;; "Perl program to use for decoding a file.
1702;; Escape sequence %s is replaced with name of Perl binary.")
1703
1704;; These two use base64 encoding.
00d6fd04
MA
1705(defconst tramp-perl-encode-with-module
1706 "%s -MMIME::Base64 -0777 -ne 'print encode_base64($_)' 2>/dev/null"
ac474af1 1707 "Perl program to use for encoding a file.
b1d06e75 1708Escape sequence %s is replaced with name of Perl binary.
89509ea0 1709This string is passed to `format', so percent characters need to be doubled.
b1d06e75
KG
1710This implementation requires the MIME::Base64 Perl module to be installed
1711on the remote host.")
1712
00d6fd04
MA
1713(defconst tramp-perl-decode-with-module
1714 "%s -MMIME::Base64 -0777 -ne 'print decode_base64($_)' 2>/dev/null"
b1d06e75
KG
1715 "Perl program to use for decoding a file.
1716Escape sequence %s is replaced with name of Perl binary.
89509ea0 1717This string is passed to `format', so percent characters need to be doubled.
b1d06e75
KG
1718This implementation requires the MIME::Base64 Perl module to be installed
1719on the remote host.")
1720
00d6fd04 1721(defconst tramp-perl-encode
b1d06e75
KG
1722 "%s -e '
1723# This script contributed by Juanma Barranquero <lektu@terra.es>.
46932a8d 1724# Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009
cbd12ed7 1725# Free Software Foundation, Inc.
b1d06e75
KG
1726use strict;
1727
fa32e96a 1728my %%trans = do {
b1d06e75
KG
1729 my $i = 0;
1730 map {(substr(unpack(q(B8), chr $i++), 2, 6), $_)}
1731 split //, q(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/);
1732};
1733
36541701 1734binmode(\\*STDIN);
b1d06e75
KG
1735
1736# We read in chunks of 54 bytes, to generate output lines
1737# of 72 chars (plus end of line)
36541701 1738$/ = \\54;
b1d06e75
KG
1739
1740while (my $data = <STDIN>) {
1741 my $pad = q();
1742
1743 # Only for the last chunk, and only if did not fill the last three-byte packet
1744 if (eof) {
fa32e96a 1745 my $mod = length($data) %% 3;
b1d06e75
KG
1746 $pad = q(=) x (3 - $mod) if $mod;
1747 }
1748
1749 # Not the fastest method, but it is simple: unpack to binary string, split
1750 # by groups of 6 bits and convert back from binary to byte; then map into
1751 # the translation table
1752 print
1753 join q(),
1754 map($trans{$_},
1755 (substr(unpack(q(B*), $data) . q(00000), 0, 432) =~ /....../g)),
1756 $pad,
36541701 1757 qq(\\n);
00d6fd04 1758}' 2>/dev/null"
b1d06e75 1759 "Perl program to use for encoding a file.
fa32e96a 1760Escape sequence %s is replaced with name of Perl binary.
ccf29586 1761This string is passed to `format', so percent characters need to be doubled.")
ac474af1 1762
00d6fd04 1763(defconst tramp-perl-decode
b1d06e75
KG
1764 "%s -e '
1765# This script contributed by Juanma Barranquero <lektu@terra.es>.
46932a8d 1766# Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009
cbd12ed7 1767# Free Software Foundation, Inc.
b1d06e75
KG
1768use strict;
1769
fa32e96a 1770my %%trans = do {
b1d06e75 1771 my $i = 0;
16674e4f 1772 map {($_, substr(unpack(q(B8), chr $i++), 2, 6))}
b1d06e75
KG
1773 split //, q(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/)
1774};
1775
fa32e96a 1776my %%bytes = map {(unpack(q(B8), chr $_), chr $_)} 0 .. 255;
b1d06e75 1777
36541701 1778binmode(\\*STDOUT);
b1d06e75
KG
1779
1780# We are going to accumulate into $pending to accept any line length
1781# (we do not check they are <= 76 chars as the RFC says)
1782my $pending = q();
1783
1784while (my $data = <STDIN>) {
1785 chomp $data;
1786
1787 # If we find one or two =, we have reached the end and
1788 # any following data is to be discarded
1789 my $finished = $data =~ s/(==?).*/$1/;
1790 $pending .= $data;
1791
1792 my $len = length($pending);
16674e4f 1793 my $chunk = substr($pending, 0, $len & ~3);
414da5ab 1794 $pending = substr($pending, $len & ~3 + 1);
b1d06e75
KG
1795
1796 # Easy method: translate from chars to (pregenerated) six-bit packets, join,
1797 # split in 8-bit chunks and convert back to char.
1798 print join q(),
1799 map $bytes{$_},
1800 ((join q(), map {$trans{$_} || q()} split //, $chunk) =~ /......../g);
1801
1802 last if $finished;
00d6fd04 1803}' 2>/dev/null"
ac474af1 1804 "Perl program to use for decoding a file.
fa32e96a 1805Escape sequence %s is replaced with name of Perl binary.
ccf29586 1806This string is passed to `format', so percent characters need to be doubled.")
fb7933a3 1807
946a5aeb
MA
1808(defconst tramp-vc-registered-read-file-names
1809 "echo \"(\"
1810for file in \"$@\"; do
1811 if %s $file; then
1812 echo \"(\\\"$file\\\" \\\"file-exists-p\\\" t)\"
1813 else
1814 echo \"(\\\"$file\\\" \\\"file-exists-p\\\" nil)\"
1815 fi
1816 if %s $file; then
1817 echo \"(\\\"$file\\\" \\\"file-readable-p\\\" t)\"
1818 else
1819 echo \"(\\\"$file\\\" \\\"file-readable-p\\\" nil)\"
1820 fi
1821done
1822echo \")\""
1823 "Script to check existence of VC related files.
1824It must be send formatted with two strings; the tests for file
1825existence, and file readability.")
1826
9ce8462a
MA
1827(defconst tramp-file-mode-type-map
1828 '((0 . "-") ; Normal file (SVID-v2 and XPG2)
1829 (1 . "p") ; fifo
1830 (2 . "c") ; character device
1831 (3 . "m") ; multiplexed character device (v7)
1832 (4 . "d") ; directory
1833 (5 . "?") ; Named special file (XENIX)
1834 (6 . "b") ; block device
1835 (7 . "?") ; multiplexed block device (v7)
1836 (8 . "-") ; regular file
1837 (9 . "n") ; network special file (HP-UX)
1838 (10 . "l") ; symlink
1839 (11 . "?") ; ACL shadow inode (Solaris, not userspace)
1840 (12 . "s") ; socket
1841 (13 . "D") ; door special (Solaris)
1842 (14 . "w")) ; whiteout (BSD)
fb7933a3
KG
1843 "A list of file types returned from the `stat' system call.
1844This is used to map a mode number to a permission string.")
1845
fb7933a3 1846;; New handlers should be added here. The following operations can be
c0fc6170
MA
1847;; handled using the normal primitives: file-name-sans-versions,
1848;; get-file-buffer.
fb7933a3 1849(defconst tramp-file-name-handler-alist
00d6fd04 1850 '((load . tramp-handle-load)
fb7933a3 1851 (make-symbolic-link . tramp-handle-make-symbolic-link)
c0fc6170 1852 (file-name-as-directory . tramp-handle-file-name-as-directory)
fb7933a3
KG
1853 (file-name-directory . tramp-handle-file-name-directory)
1854 (file-name-nondirectory . tramp-handle-file-name-nondirectory)
1855 (file-truename . tramp-handle-file-truename)
1856 (file-exists-p . tramp-handle-file-exists-p)
1857 (file-directory-p . tramp-handle-file-directory-p)
1858 (file-executable-p . tramp-handle-file-executable-p)
fb7933a3
KG
1859 (file-readable-p . tramp-handle-file-readable-p)
1860 (file-regular-p . tramp-handle-file-regular-p)
1861 (file-symlink-p . tramp-handle-file-symlink-p)
1862 (file-writable-p . tramp-handle-file-writable-p)
1863 (file-ownership-preserved-p . tramp-handle-file-ownership-preserved-p)
1864 (file-newer-than-file-p . tramp-handle-file-newer-than-file-p)
1865 (file-attributes . tramp-handle-file-attributes)
1866 (file-modes . tramp-handle-file-modes)
fb7933a3 1867 (directory-files . tramp-handle-directory-files)
c82c5727 1868 (directory-files-and-attributes . tramp-handle-directory-files-and-attributes)
fb7933a3
KG
1869 (file-name-all-completions . tramp-handle-file-name-all-completions)
1870 (file-name-completion . tramp-handle-file-name-completion)
1871 (add-name-to-file . tramp-handle-add-name-to-file)
1872 (copy-file . tramp-handle-copy-file)
1873 (rename-file . tramp-handle-rename-file)
1874 (set-file-modes . tramp-handle-set-file-modes)
ce3f516f 1875 (set-file-times . tramp-handle-set-file-times)
fb7933a3
KG
1876 (make-directory . tramp-handle-make-directory)
1877 (delete-directory . tramp-handle-delete-directory)
1878 (delete-file . tramp-handle-delete-file)
1879 (directory-file-name . tramp-handle-directory-file-name)
00d6fd04
MA
1880 ;; `executable-find' is not official yet.
1881 (executable-find . tramp-handle-executable-find)
1882 (start-file-process . tramp-handle-start-file-process)
0457dd55 1883 (process-file . tramp-handle-process-file)
00d6fd04 1884 (shell-command . tramp-handle-shell-command)
fb7933a3
KG
1885 (insert-directory . tramp-handle-insert-directory)
1886 (expand-file-name . tramp-handle-expand-file-name)
00d6fd04 1887 (substitute-in-file-name . tramp-handle-substitute-in-file-name)
fb7933a3 1888 (file-local-copy . tramp-handle-file-local-copy)
19a87064 1889 (file-remote-p . tramp-handle-file-remote-p)
fb7933a3 1890 (insert-file-contents . tramp-handle-insert-file-contents)
94be87e8
MA
1891 (insert-file-contents-literally
1892 . tramp-handle-insert-file-contents-literally)
fb7933a3 1893 (write-region . tramp-handle-write-region)
38c65fca 1894 (find-backup-file-name . tramp-handle-find-backup-file-name)
c1105d05 1895 (make-auto-save-file-name . tramp-handle-make-auto-save-file-name)
fb7933a3 1896 (unhandled-file-name-directory . tramp-handle-unhandled-file-name-directory)
5ec2cc41 1897 (dired-compress-file . tramp-handle-dired-compress-file)
fb7933a3
KG
1898 (dired-recursive-delete-directory
1899 . tramp-handle-dired-recursive-delete-directory)
70c11b0b 1900 (dired-uncache . tramp-handle-dired-uncache)
fb7933a3 1901 (set-visited-file-modtime . tramp-handle-set-visited-file-modtime)
49096407
MA
1902 (verify-visited-file-modtime . tramp-handle-verify-visited-file-modtime)
1903 (vc-registered . tramp-handle-vc-registered))
c1105d05 1904 "Alist of handler functions.
fb7933a3
KG
1905Operations not mentioned here will be handled by the normal Emacs functions.")
1906
a4aeb9a4 1907;; Handlers for partial Tramp file names. For Emacs just
41c8e348 1908;; `file-name-all-completions' is needed.
a01b1e22 1909;;;###autoload
16674e4f 1910(defconst tramp-completion-file-name-handler-alist
a01b1e22 1911 '((file-name-all-completions . tramp-completion-handle-file-name-all-completions)
41c8e348 1912 (file-name-completion . tramp-completion-handle-file-name-completion))
16674e4f
KG
1913 "Alist of completion handler functions.
1914Used for file names matching `tramp-file-name-regexp'. Operations not
1915mentioned here will be handled by `tramp-file-name-handler-alist' or the
1916normal Emacs functions.")
1917
4007ba5b 1918;; Handlers for foreign methods, like FTP or SMB, shall be plugged here.
ea9d1443
KG
1919(defvar tramp-foreign-file-name-handler-alist
1920 ;; (identity . tramp-sh-file-name-handler) should always be the last
1921 ;; entry, since `identity' always matches.
1922 '((identity . tramp-sh-file-name-handler))
4007ba5b
KG
1923 "Alist of elements (FUNCTION . HANDLER) for foreign methods handled specially.
1924If (FUNCTION FILENAME) returns non-nil, then all I/O on that file is done by
1925calling HANDLER.")
1926
0664ff72 1927;;; Internal functions which must come first:
fb7933a3 1928
00d6fd04
MA
1929(defsubst tramp-debug-message (vec fmt-string &rest args)
1930 "Append message to debug buffer.
1931Message is formatted with FMT-STRING as control string and the remaining
1932ARGS to actually emit the message (if applicable)."
1933 (when (get-buffer (tramp-buffer-name vec))
1934 (with-current-buffer (tramp-get-debug-buffer vec)
1935 (goto-char (point-max))
70c11b0b
MA
1936 ;; Headline.
1937 (when (bobp)
1938 (insert
1939 (format
1940 ";; %sEmacs: %s Tramp: %s -*- mode: outline; -*-"
1941 (if (featurep 'sxemacs) "SX" (if (featurep 'xemacs) "X" "GNU "))
1942 emacs-version tramp-version)))
00d6fd04
MA
1943 (unless (bolp)
1944 (insert "\n"))
70c11b0b 1945 ;; Timestamp.
736ac90f
MA
1946 (let ((now (current-time)))
1947 (insert (format-time-string "%T." now))
1948 (insert (format "%06d " (nth 2 now))))
70c11b0b 1949 ;; Calling function.
00d6fd04
MA
1950 (let ((btn 1) btf fn)
1951 (while (not fn)
1952 (setq btf (nth 1 (backtrace-frame btn)))
1953 (if (not btf)
1954 (setq fn "")
1955 (when (symbolp btf)
1956 (setq fn (symbol-name btf))
1957 (unless (and (string-match "^tramp" fn)
1958 (not (string-match
1959 "^tramp\\(-debug\\)?\\(-message\\|-error\\)$"
1960 fn)))
1961 (setq fn nil)))
1962 (setq btn (1+ btn))))
1963 ;; The following code inserts filename and line number.
1964 ;; Should be deactivated by default, because it is time
1965 ;; consuming.
1966; (let ((ffn (find-function-noselect (intern fn))))
1967; (insert
1968; (format
1969; "%s:%d: "
1970; (file-name-nondirectory (buffer-file-name (car ffn)))
1971; (with-current-buffer (car ffn)
1972; (1+ (count-lines (point-min) (cdr ffn)))))))
1973 (insert (format "%s " fn)))
70c11b0b 1974 ;; The message.
00d6fd04
MA
1975 (insert (apply 'format fmt-string args)))))
1976
946a5aeb
MA
1977(defvar tramp-message-show-message t
1978 "Show Tramp message in the minibuffer.
1979This variable is used to disable messages from `tramp-error'.
1980The messages are visible anyway, because an error is raised.")
1981
00d6fd04 1982(defsubst tramp-message (vec-or-proc level fmt-string &rest args)
fb7933a3 1983 "Emit a message depending on verbosity level.
a4aeb9a4 1984VEC-OR-PROC identifies the Tramp buffer to use. It can be either a
00d6fd04
MA
1985vector or a process. LEVEL says to be quiet if `tramp-verbose' is
1986less than LEVEL. The message is emitted only if `tramp-verbose' is
1987greater than or equal to LEVEL.
1988
1989The message is also logged into the debug buffer when `tramp-verbose'
1990is greater than or equal 4.
1991
1992Calls functions `message' and `tramp-debug-message' with FMT-STRING as
1993control string and the remaining ARGS to actually emit the message (if
1994applicable)."
1995 (condition-case nil
1996 (when (<= level tramp-verbose)
1997 ;; Match data must be preserved!
1998 (save-match-data
1999 ;; Display only when there is a minimum level.
946a5aeb 2000 (when (and tramp-message-show-message (<= level 3))
00d6fd04
MA
2001 (apply 'message
2002 (concat
2003 (cond
2004 ((= level 0) "")
2005 ((= level 1) "")
2006 ((= level 2) "Warning: ")
2007 (t "Tramp: "))
2008 fmt-string)
2009 args))
2010 ;; Log only when there is a minimum level.
2011 (when (>= tramp-verbose 4)
2012 (when (and vec-or-proc
2013 (processp vec-or-proc)
2014 (buffer-name (process-buffer vec-or-proc)))
2015 (with-current-buffer (process-buffer vec-or-proc)
2016 ;; Translate proc to vec.
2017 (setq vec-or-proc (tramp-dissect-file-name default-directory))))
2018 (when (and vec-or-proc (vectorp vec-or-proc))
2019 (apply 'tramp-debug-message
2020 vec-or-proc
2021 (concat (format "(%d) # " level) fmt-string)
2022 args)))))
2023 ;; Suppress all errors.
2024 (error nil)))
2025
2026(defsubst tramp-error (vec-or-proc signal fmt-string &rest args)
2027 "Emit an error.
2028VEC-OR-PROC identifies the connection to use, SIGNAL is the
2029signal identifier to be raised, remaining args passed to
2030`tramp-message'. Finally, signal SIGNAL is raised."
946a5aeb
MA
2031 (let (tramp-message-show-message)
2032 (tramp-message
2033 vec-or-proc 1 "%s"
2034 (error-message-string
2035 (list signal
2036 (get signal 'error-message)
2037 (apply 'format fmt-string args))))
2038 (signal signal (list (apply 'format fmt-string args)))))
00d6fd04
MA
2039
2040(defsubst tramp-error-with-buffer
2041 (buffer vec-or-proc signal fmt-string &rest args)
2042 "Emit an error, and show BUFFER.
2043If BUFFER is nil, show the connection buffer. Wait for 30\", or until
2044an input event arrives. The other arguments are passed to `tramp-error'."
2045 (save-window-excursion
2046 (unwind-protect
2047 (apply 'tramp-error vec-or-proc signal fmt-string args)
2048 (when (and vec-or-proc (not (zerop tramp-verbose)))
2049 (let ((enable-recursive-minibuffers t))
2050 (pop-to-buffer
2051 (or (and (bufferp buffer) buffer)
2052 (and (processp vec-or-proc) (process-buffer vec-or-proc))
2053 (tramp-get-buffer vec-or-proc)))
2054 (sit-for 30))))))
fb7933a3 2055
c62c9d08
KG
2056(defmacro with-parsed-tramp-file-name (filename var &rest body)
2057 "Parse a Tramp filename and make components available in the body.
2058
2059First arg FILENAME is evaluated and dissected into its components.
2060Second arg VAR is a symbol. It is used as a variable name to hold
2061the filename structure. It is also used as a prefix for the variables
2062holding the components. For example, if VAR is the symbol `foo', then
00d6fd04
MA
2063`foo' will be bound to the whole structure, `foo-method' will be bound to
2064the method component, and so on for `foo-user', `foo-host', `foo-localname'.
c62c9d08
KG
2065
2066Remaining args are Lisp expressions to be evaluated (inside an implicit
2067`progn').
2068
00d6fd04
MA
2069If VAR is nil, then we bind `v' to the structure and `method', `user',
2070`host', `localname' to the components."
c62c9d08 2071 `(let* ((,(or var 'v) (tramp-dissect-file-name ,filename))
c62c9d08
KG
2072 (,(if var (intern (concat (symbol-name var) "-method")) 'method)
2073 (tramp-file-name-method ,(or var 'v)))
2074 (,(if var (intern (concat (symbol-name var) "-user")) 'user)
2075 (tramp-file-name-user ,(or var 'v)))
2076 (,(if var (intern (concat (symbol-name var) "-host")) 'host)
2077 (tramp-file-name-host ,(or var 'v)))
7432277c
KG
2078 (,(if var (intern (concat (symbol-name var) "-localname")) 'localname)
2079 (tramp-file-name-localname ,(or var 'v))))
c62c9d08
KG
2080 ,@body))
2081
2082(put 'with-parsed-tramp-file-name 'lisp-indent-function 2)
00d6fd04 2083(put 'with-parsed-tramp-file-name 'edebug-form-spec '(form symbolp body))
9e6ab520 2084(font-lock-add-keywords 'emacs-lisp-mode '("\\<with-parsed-tramp-file-name\\>"))
c62c9d08 2085
00d6fd04
MA
2086(defmacro with-file-property (vec file property &rest body)
2087 "Check in Tramp cache for PROPERTY, otherwise execute BODY and set cache.
2088FILE must be a local file name on a connection identified via VEC."
2089 `(if (file-name-absolute-p ,file)
2090 (let ((value (tramp-get-file-property ,vec ,file ,property 'undef)))
2091 (when (eq value 'undef)
2092 ;; We cannot pass @body as parameter to
2093 ;; `tramp-set-file-property' because it mangles our
2094 ;; debug messages.
2095 (setq value (progn ,@body))
2096 (tramp-set-file-property ,vec ,file ,property value))
2097 value)
2098 ,@body))
9ce8462a 2099
00d6fd04
MA
2100(put 'with-file-property 'lisp-indent-function 3)
2101(put 'with-file-property 'edebug-form-spec t)
9e6ab520 2102(font-lock-add-keywords 'emacs-lisp-mode '("\\<with-file-property\\>"))
00d6fd04
MA
2103
2104(defmacro with-connection-property (key property &rest body)
2105 "Checks in Tramp for property PROPERTY, otherwise executes BODY and set."
2106 `(let ((value (tramp-get-connection-property ,key ,property 'undef)))
2107 (when (eq value 'undef)
2108 ;; We cannot pass ,@body as parameter to
2109 ;; `tramp-set-connection-property' because it mangles our debug
2110 ;; messages.
2111 (setq value (progn ,@body))
2112 (tramp-set-connection-property ,key ,property value))
2113 value))
9ce8462a 2114
00d6fd04
MA
2115(put 'with-connection-property 'lisp-indent-function 2)
2116(put 'with-connection-property 'edebug-form-spec t)
9e6ab520 2117(font-lock-add-keywords 'emacs-lisp-mode '("\\<with-connection-property\\>"))
00d6fd04 2118
628c97b2
GM
2119(eval-and-compile ; silence compiler
2120 (if (memq system-type '(cygwin windows-nt))
2121 (defun tramp-drop-volume-letter (name)
2122 "Cut off unnecessary drive letter from file NAME.
2123The function `tramp-handle-expand-file-name' calls `expand-file-name'
2124locally on a remote file name. When the local system is a W32 system
2125but the remote system is Unix, this introduces a superfluous drive
2126letter into the file name. This function removes it."
2127 (save-match-data
2128 (if (string-match tramp-root-regexp name)
2129 (replace-match "/" nil t name)
2130 name)))
2131
2132 (defalias 'tramp-drop-volume-letter 'identity)))
2133
9c13938d 2134(defsubst tramp-make-tramp-temp-file (vec)
a6e96327 2135 "Create a temporary file on the remote host identified by VEC.
9c13938d
MA
2136Return the local name of the temporary file."
2137 (let ((prefix
2138 (tramp-make-tramp-file-name
2139 (tramp-file-name-method vec)
2140 (tramp-file-name-user vec)
2141 (tramp-file-name-host vec)
113e2a84
MA
2142 (tramp-drop-volume-letter
2143 (expand-file-name
2144 tramp-temp-name-prefix (tramp-get-remote-tmpdir vec)))))
9c13938d
MA
2145 result)
2146 (while (not result)
2147 ;; `make-temp-file' would be the natural choice for
2148 ;; implementation. But it calls `write-region' internally,
2149 ;; which also needs a temporary file - we would end in an
2150 ;; infinite loop.
2151 (setq result (make-temp-name prefix))
2152 (if (file-exists-p result)
2153 (setq result nil)
2154 ;; This creates the file by side effect.
2155 (set-file-times result)
2156 (set-file-modes result (tramp-octal-to-decimal "0700"))))
2157
2158 ;; Return the local part.
2159 (with-parsed-tramp-file-name result nil localname)))
8a4438b6
MA
2160
2161
16674e4f
KG
2162;;; Config Manipulation Functions:
2163
2164(defun tramp-set-completion-function (method function-list)
2165 "Sets the list of completion functions for METHOD.
2166FUNCTION-LIST is a list of entries of the form (FUNCTION FILE).
2167The FUNCTION is intended to parse FILE according its syntax.
2168It might be a predefined FUNCTION, or a user defined FUNCTION.
2169Predefined FUNCTIONs are `tramp-parse-rhosts', `tramp-parse-shosts',
8fc29035 2170`tramp-parse-sconfig', `tramp-parse-hosts', `tramp-parse-passwd',
8daea7fc
KG
2171and `tramp-parse-netrc'.
2172
16674e4f
KG
2173Example:
2174
2175 (tramp-set-completion-function
2176 \"ssh\"
8daea7fc
KG
2177 '((tramp-parse-sconfig \"/etc/ssh_config\")
2178 (tramp-parse-sconfig \"~/.ssh/config\")))"
16674e4f 2179
5ec2cc41
KG
2180 (let ((r function-list)
2181 (v function-list))
2182 (setq tramp-completion-function-alist
2183 (delete (assoc method tramp-completion-function-alist)
2184 tramp-completion-function-alist))
2185
2186 (while v
00d6fd04 2187 ;; Remove double entries.
5ec2cc41
KG
2188 (when (member (car v) (cdr v))
2189 (setcdr v (delete (car v) (cdr v))))
00d6fd04 2190 ;; Check for function and file or registry key.
5ec2cc41 2191 (unless (and (functionp (nth 0 (car v)))
00d6fd04
MA
2192 (if (string-match "^HKEY_CURRENT_USER" (nth 1 (car v)))
2193 ;; Windows registry.
2194 (and (memq system-type '(cygwin windows-nt))
a4aeb9a4
MA
2195 (zerop
2196 (tramp-local-call-process
2197 "reg" nil nil nil "query" (nth 1 (car v)))))
00d6fd04
MA
2198 ;; Configuration file.
2199 (file-exists-p (nth 1 (car v)))))
5ec2cc41
KG
2200 (setq r (delete (car v) r)))
2201 (setq v (cdr v)))
2202
2203 (when r
4007ba5b 2204 (add-to-list 'tramp-completion-function-alist
5ec2cc41 2205 (cons method r)))))
16674e4f
KG
2206
2207(defun tramp-get-completion-function (method)
00d6fd04 2208 "Returns a list of completion functions for METHOD.
16674e4f 2209For definition of that list see `tramp-set-completion-function'."
00d6fd04
MA
2210 (cons
2211 ;; Hosts visited once shall be remembered.
2212 `(tramp-parse-connection-properties ,method)
2213 ;; The method related defaults.
2214 (cdr (assoc method tramp-completion-function-alist))))
16674e4f 2215
d037d501 2216
0664ff72 2217;;; Fontification of `read-file-name':
d037d501 2218
0664ff72 2219;; rfn-eshadow.el is part of Emacs 22. It is autoloaded.
d037d501
MA
2220(defvar tramp-rfn-eshadow-overlay)
2221(make-variable-buffer-local 'tramp-rfn-eshadow-overlay)
2222
2223(defun tramp-rfn-eshadow-setup-minibuffer ()
2224 "Set up a minibuffer for `file-name-shadow-mode'.
2225Adds another overlay hiding filename parts according to Tramp's
2226special handling of `substitute-in-file-name'."
9ce8462a 2227 (when (symbol-value 'minibuffer-completing-file-name)
d037d501 2228 (setq tramp-rfn-eshadow-overlay
9e6ab520
MA
2229 (funcall (symbol-function 'make-overlay)
2230 (funcall (symbol-function 'minibuffer-prompt-end))
2231 (funcall (symbol-function 'minibuffer-prompt-end))))
d037d501 2232 ;; Copy rfn-eshadow-overlay properties.
9e6ab520
MA
2233 (let ((props (funcall (symbol-function 'overlay-properties)
2234 (symbol-value 'rfn-eshadow-overlay))))
d037d501 2235 (while props
9e6ab520
MA
2236 (funcall (symbol-function 'overlay-put)
2237 tramp-rfn-eshadow-overlay (pop props) (pop props))))))
d037d501
MA
2238
2239(when (boundp 'rfn-eshadow-setup-minibuffer-hook)
2240 (add-hook 'rfn-eshadow-setup-minibuffer-hook
48846dc5
MA
2241 'tramp-rfn-eshadow-setup-minibuffer)
2242 (add-hook 'tramp-unload-hook
2243 '(lambda ()
2244 (remove-hook 'rfn-eshadow-setup-minibuffer-hook
2245 'tramp-rfn-eshadow-setup-minibuffer))))
d037d501 2246
adcbca53
MA
2247(defconst tramp-rfn-eshadow-update-overlay-regexp
2248 (format "[^%s/~]*\\(/\\|~\\)" tramp-postfix-host-format))
2249
d037d501
MA
2250(defun tramp-rfn-eshadow-update-overlay ()
2251 "Update `rfn-eshadow-overlay' to cover shadowed part of minibuffer input.
2252This is intended to be used as a minibuffer `post-command-hook' for
2253`file-name-shadow-mode'; the minibuffer should have already
2254been set up by `rfn-eshadow-setup-minibuffer'."
2255 ;; In remote files name, there is a shadowing just for the local part.
9e6ab520
MA
2256 (let ((end (or (funcall (symbol-function 'overlay-end)
2257 (symbol-value 'rfn-eshadow-overlay))
2258 (funcall (symbol-function 'minibuffer-prompt-end)))))
2259 (when (file-remote-p (buffer-substring-no-properties end (point-max)))
bd316474
KY
2260 (save-excursion
2261 (save-restriction
2262 (narrow-to-region
adcbca53
MA
2263 (1+ (or (string-match
2264 tramp-rfn-eshadow-update-overlay-regexp (buffer-string) end)
2265 end))
2266 (point-max))
bd316474
KY
2267 (let ((rfn-eshadow-overlay tramp-rfn-eshadow-overlay)
2268 (rfn-eshadow-update-overlay-hook nil))
dea31ca6 2269 (move-overlay rfn-eshadow-overlay (point-max) (point-max))
bd316474 2270 (funcall (symbol-function 'rfn-eshadow-update-overlay))))))))
d037d501
MA
2271
2272(when (boundp 'rfn-eshadow-update-overlay-hook)
2273 (add-hook 'rfn-eshadow-update-overlay-hook
2274 'tramp-rfn-eshadow-update-overlay))
2275
2276
fb7933a3
KG
2277;;; File Name Handler Functions:
2278
fb7933a3
KG
2279(defun tramp-handle-make-symbolic-link
2280 (filename linkname &optional ok-if-already-exists)
00d6fd04 2281 "Like `make-symbolic-link' for Tramp files.
cebb4ec6 2282If LINKNAME is a non-Tramp file, it is used verbatim as the target of
7432277c 2283the symlink. If LINKNAME is a Tramp file, only the localname component is
cebb4ec6
KG
2284used as the target of the symlink.
2285
7432277c
KG
2286If LINKNAME is a Tramp file and the localname component is relative, then
2287it is expanded first, before the localname component is taken. Note that
cebb4ec6
KG
2288this can give surprising results if the user/host for the source and
2289target of the symlink differ."
c62c9d08 2290 (with-parsed-tramp-file-name linkname l
00d6fd04 2291 (let ((ln (tramp-get-remote-ln l))
87bdd2c7
MA
2292 (cwd (tramp-run-real-handler
2293 'file-name-directory (list l-localname))))
c62c9d08 2294 (unless ln
00d6fd04
MA
2295 (tramp-error
2296 l 'file-error
2297 "Making a symbolic link. ln(1) does not exist on the remote host."))
c62c9d08
KG
2298
2299 ;; Do the 'confirm if exists' thing.
cebb4ec6 2300 (when (file-exists-p linkname)
c62c9d08
KG
2301 ;; What to do?
2302 (if (or (null ok-if-already-exists) ; not allowed to exist
2303 (and (numberp ok-if-already-exists)
2304 (not (yes-or-no-p
2305 (format
2306 "File %s already exists; make it a link anyway? "
7432277c 2307 l-localname)))))
00d6fd04
MA
2308 (tramp-error
2309 l 'file-already-exists "File %s already exists" l-localname)
cebb4ec6
KG
2310 (delete-file linkname)))
2311
7432277c 2312 ;; If FILENAME is a Tramp name, use just the localname component.
cebb4ec6 2313 (when (tramp-tramp-file-p filename)
1834b39f
MA
2314 (setq filename
2315 (tramp-file-name-localname
2316 (tramp-dissect-file-name (expand-file-name filename)))))
bf247b6e 2317
c62c9d08
KG
2318 ;; Right, they are on the same host, regardless of user, method, etc.
2319 ;; We now make the link on the remote machine. This will occur as the user
2320 ;; that FILENAME belongs to.
2321 (zerop
2322 (tramp-send-command-and-check
00d6fd04 2323 l (format "cd %s && %s -sf %s %s" cwd ln filename l-localname) t)))))
fb7933a3 2324
fb7933a3 2325(defun tramp-handle-load (file &optional noerror nomessage nosuffix must-suffix)
00d6fd04
MA
2326 "Like `load' for Tramp files."
2327 (with-parsed-tramp-file-name (expand-file-name file) nil
c62c9d08
KG
2328 (unless nosuffix
2329 (cond ((file-exists-p (concat file ".elc"))
2330 (setq file (concat file ".elc")))
2331 ((file-exists-p (concat file ".el"))
2332 (setq file (concat file ".el")))))
2333 (when must-suffix
2334 ;; The first condition is always true for absolute file names.
2335 ;; Included for safety's sake.
2336 (unless (or (file-name-directory file)
2337 (string-match "\\.elc?\\'" file))
00d6fd04
MA
2338 (tramp-error
2339 v 'file-error
2340 "File `%s' does not include a `.el' or `.elc' suffix" file)))
c62c9d08
KG
2341 (unless noerror
2342 (when (not (file-exists-p file))
00d6fd04 2343 (tramp-error v 'file-error "Cannot load nonexistent file `%s'" file)))
c62c9d08
KG
2344 (if (not (file-exists-p file))
2345 nil
00d6fd04 2346 (unless nomessage (tramp-message v 0 "Loading %s..." file))
c62c9d08
KG
2347 (let ((local-copy (file-local-copy file)))
2348 ;; MUST-SUFFIX doesn't exist on XEmacs, so let it default to nil.
ce2cc728
MA
2349 (unwind-protect
2350 (load local-copy noerror t t)
2351 (delete-file local-copy)))
00d6fd04 2352 (unless nomessage (tramp-message v 0 "Loading %s...done" file))
c62c9d08 2353 t)))
fb7933a3 2354
a4aeb9a4 2355;; Localname manipulation functions that grok Tramp localnames...
c0fc6170
MA
2356(defun tramp-handle-file-name-as-directory (file)
2357 "Like `file-name-as-directory' but aware of Tramp files."
2358 ;; `file-name-as-directory' would be sufficient except localname is
2359 ;; the empty string.
2360 (let ((v (tramp-dissect-file-name file t)))
2361 ;; Run the command on the localname portion only.
2362 (tramp-make-tramp-file-name
2363 (tramp-file-name-method v)
2364 (tramp-file-name-user v)
2365 (tramp-file-name-host v)
2366 (tramp-run-real-handler
2367 'file-name-as-directory (list (or (tramp-file-name-localname v) ""))))))
2368
fb7933a3 2369(defun tramp-handle-file-name-directory (file)
00d6fd04 2370 "Like `file-name-directory' but aware of Tramp files."
9ce8462a
MA
2371 ;; Everything except the last filename thing is the directory. We
2372 ;; cannot apply `with-parsed-tramp-file-name', because this expands
2373 ;; the remote file name parts. This is a problem when we are in
2374 ;; file name completion.
2375 (let ((v (tramp-dissect-file-name file t)))
a01b1e22
MA
2376 ;; Run the command on the localname portion only.
2377 (tramp-make-tramp-file-name
9ce8462a
MA
2378 (tramp-file-name-method v)
2379 (tramp-file-name-user v)
2380 (tramp-file-name-host v)
87bdd2c7
MA
2381 (tramp-run-real-handler
2382 'file-name-directory (list (or (tramp-file-name-localname v) ""))))))
fb7933a3
KG
2383
2384(defun tramp-handle-file-name-nondirectory (file)
00d6fd04 2385 "Like `file-name-nondirectory' but aware of Tramp files."
c62c9d08 2386 (with-parsed-tramp-file-name file nil
87bdd2c7 2387 (tramp-run-real-handler 'file-name-nondirectory (list localname))))
fb7933a3
KG
2388
2389(defun tramp-handle-file-truename (filename &optional counter prev-dirs)
00d6fd04 2390 "Like `file-truename' for Tramp files."
48ddd622 2391 (with-parsed-tramp-file-name (expand-file-name filename) nil
00d6fd04 2392 (with-file-property v localname "file-truename"
aff67808 2393 (let* ((directory-sep-char ?/) ; for XEmacs
70c11b0b 2394 (steps (tramp-compat-split-string localname "/"))
87bdd2c7
MA
2395 (localnamedir (tramp-run-real-handler
2396 'file-name-as-directory (list localname)))
00d6fd04
MA
2397 (is-dir (string= localname localnamedir))
2398 (thisstep nil)
2399 (numchase 0)
2400 ;; Don't make the following value larger than necessary.
2401 ;; People expect an error message in a timely fashion when
2402 ;; something is wrong; otherwise they might think that Emacs
2403 ;; is hung. Of course, correctness has to come first.
2404 (numchase-limit 20)
2405 (result nil) ;result steps in reverse order
2406 symlink-target)
2407 (tramp-message v 4 "Finding true name for `%s'" filename)
2408 (while (and steps (< numchase numchase-limit))
2409 (setq thisstep (pop steps))
2410 (tramp-message
2411 v 5 "Check %s"
2412 (mapconcat 'identity
2413 (append '("") (reverse result) (list thisstep))
2414 "/"))
2415 (setq symlink-target
2416 (nth 0 (file-attributes
2417 (tramp-make-tramp-file-name
2418 method user host
2419 (mapconcat 'identity
2420 (append '("")
2421 (reverse result)
2422 (list thisstep))
2423 "/")))))
2424 (cond ((string= "." thisstep)
2425 (tramp-message v 5 "Ignoring step `.'"))
2426 ((string= ".." thisstep)
2427 (tramp-message v 5 "Processing step `..'")
2428 (pop result))
2429 ((stringp symlink-target)
2430 ;; It's a symlink, follow it.
2431 (tramp-message v 5 "Follow symlink to %s" symlink-target)
2432 (setq numchase (1+ numchase))
2433 (when (file-name-absolute-p symlink-target)
2434 (setq result nil))
2435 ;; If the symlink was absolute, we'll get a string like
2436 ;; "/user@host:/some/target"; extract the
2437 ;; "/some/target" part from it.
2438 (when (tramp-tramp-file-p symlink-target)
2439 (unless (tramp-equal-remote filename symlink-target)
2440 (tramp-error
2441 v 'file-error
2442 "Symlink target `%s' on wrong host" symlink-target))
2443 (setq symlink-target localname))
2444 (setq steps
70c11b0b 2445 (append (tramp-compat-split-string symlink-target "/")
00d6fd04
MA
2446 steps)))
2447 (t
2448 ;; It's a file.
2449 (setq result (cons thisstep result)))))
2450 (when (>= numchase numchase-limit)
2451 (tramp-error
2452 v 'file-error
2453 "Maximum number (%d) of symlinks exceeded" numchase-limit))
2454 (setq result (reverse result))
2455 ;; Combine list to form string.
2456 (setq result
2457 (if result
2458 (mapconcat 'identity (cons "" result) "/")
2459 "/"))
2460 (when (and is-dir (or (string= "" result)
2461 (not (string= (substring result -1) "/"))))
2462 (setq result (concat result "/")))
2463 (tramp-message v 4 "True name of `%s' is `%s'" filename result)
2464 (tramp-make-tramp-file-name method user host result)))))
fb7933a3
KG
2465
2466;; Basic functions.
2467
2468(defun tramp-handle-file-exists-p (filename)
00d6fd04 2469 "Like `file-exists-p' for Tramp files."
c62c9d08 2470 (with-parsed-tramp-file-name filename nil
00d6fd04 2471 (with-file-property v localname "file-exists-p"
fb7933a3 2472 (zerop (tramp-send-command-and-check
00d6fd04 2473 v
fb7933a3 2474 (format
00d6fd04
MA
2475 "%s %s"
2476 (tramp-get-file-exists-command v)
7432277c 2477 (tramp-shell-quote-argument localname)))))))
fb7933a3 2478
00d6fd04
MA
2479;; Inodes don't exist for some file systems. Therefore we must
2480;; generate virtual ones. Used in `find-buffer-visiting'. The method
2481;; applied might be not so efficient (Ange-FTP uses hashes). But
2482;; performance isn't the major issue given that file transfer will
2483;; take time.
2484(defvar tramp-inodes nil
2485 "Keeps virtual inodes numbers.")
2486
8daea7fc
KG
2487;; Devices must distinguish physical file systems. The device numbers
2488;; provided by "lstat" aren't unique, because we operate on different hosts.
2489;; So we use virtual device numbers, generated by Tramp. Both Ange-FTP and
2490;; EFS use device number "-1". In order to be different, we use device number
b946a456 2491;; (-1 . x), whereby "x" is unique for a given (method user host).
8daea7fc
KG
2492(defvar tramp-devices nil
2493 "Keeps virtual device numbers.")
2494
fb7933a3
KG
2495;; CCC: This should check for an error condition and signal failure
2496;; when something goes wrong.
2497;; Daniel Pittman <daniel@danann.net>
c951aecb 2498(defun tramp-handle-file-attributes (filename &optional id-format)
00d6fd04
MA
2499 "Like `file-attributes' for Tramp files."
2500 (unless id-format (setq id-format 'integer))
2501 (with-parsed-tramp-file-name (expand-file-name filename) nil
2502 (with-file-property v localname (format "file-attributes-%s" id-format)
2503 (when (file-exists-p filename)
2504 ;; file exists, find out stuff
2505 (save-excursion
2506 (tramp-convert-file-attributes
2507 v
2508 (if (tramp-get-remote-stat v)
2509 (tramp-handle-file-attributes-with-stat v localname id-format)
2510 (if (tramp-get-remote-perl v)
2511 (tramp-handle-file-attributes-with-perl v localname id-format)
2512 (tramp-handle-file-attributes-with-ls
2513 v localname id-format)))))))))
2514
2515(defun tramp-handle-file-attributes-with-ls (vec localname &optional id-format)
2516 "Implement `file-attributes' for Tramp files using the ls(1) command."
fb7933a3
KG
2517 (let (symlinkp dirp
2518 res-inode res-filemodes res-numlinks
2519 res-uid res-gid res-size res-symlink-target)
00d6fd04 2520 (tramp-message vec 5 "file attributes with ls: %s" localname)
fb7933a3 2521 (tramp-send-command
00d6fd04 2522 vec
fb7933a3 2523 (format "%s %s %s"
00d6fd04 2524 (tramp-get-ls-command vec)
c82c5727 2525 (if (eq id-format 'integer) "-ildn" "-ild")
7432277c 2526 (tramp-shell-quote-argument localname)))
fb7933a3 2527 ;; parse `ls -l' output ...
00d6fd04
MA
2528 (with-current-buffer (tramp-get-buffer vec)
2529 (goto-char (point-min))
2530 ;; ... inode
2531 (setq res-inode
2532 (condition-case err
2533 (read (current-buffer))
2534 (invalid-read-syntax
2535 (when (and (equal (cadr err)
2536 "Integer constant overflow in reader")
2537 (string-match
2538 "^[0-9]+\\([0-9][0-9][0-9][0-9][0-9]\\)\\'"
2539 (car (cddr err))))
2540 (let* ((big (read (substring (car (cddr err)) 0
2541 (match-beginning 1))))
2542 (small (read (match-string 1 (car (cddr err)))))
2543 (twiddle (/ small 65536)))
2544 (cons (+ big twiddle)
2545 (- small (* twiddle 65536))))))))
2546 ;; ... file mode flags
2547 (setq res-filemodes (symbol-name (read (current-buffer))))
2548 ;; ... number links
2549 (setq res-numlinks (read (current-buffer)))
2550 ;; ... uid and gid
2551 (setq res-uid (read (current-buffer)))
2552 (setq res-gid (read (current-buffer)))
2553 (if (eq id-format 'integer)
2554 (progn
2555 (unless (numberp res-uid) (setq res-uid -1))
2556 (unless (numberp res-gid) (setq res-gid -1)))
2557 (progn
2558 (unless (stringp res-uid) (setq res-uid (symbol-name res-uid)))
2559 (unless (stringp res-gid) (setq res-gid (symbol-name res-gid)))))
2560 ;; ... size
2561 (setq res-size (read (current-buffer)))
2562 ;; From the file modes, figure out other stuff.
2563 (setq symlinkp (eq ?l (aref res-filemodes 0)))
2564 (setq dirp (eq ?d (aref res-filemodes 0)))
2565 ;; if symlink, find out file name pointed to
2566 (when symlinkp
2567 (search-forward "-> ")
2568 (setq res-symlink-target
9e6ab520 2569 (buffer-substring (point) (tramp-compat-line-end-position))))
00d6fd04
MA
2570 ;; return data gathered
2571 (list
2572 ;; 0. t for directory, string (name linked to) for symbolic
2573 ;; link, or nil.
2574 (or dirp res-symlink-target)
2575 ;; 1. Number of links to file.
2576 res-numlinks
2577 ;; 2. File uid.
2578 res-uid
2579 ;; 3. File gid.
2580 res-gid
2581 ;; 4. Last access time, as a list of two integers. First
2582 ;; integer has high-order 16 bits of time, second has low 16
2583 ;; bits.
2584 ;; 5. Last modification time, likewise.
2585 ;; 6. Last status change time, likewise.
2586 '(0 0) '(0 0) '(0 0) ;CCC how to find out?
2587 ;; 7. Size in bytes (-1, if number is out of range).
2588 res-size
2589 ;; 8. File modes, as a string of ten letters or dashes as in ls -l.
2590 res-filemodes
1437876c 2591 ;; 9. t if file's gid would change if file were deleted and
00d6fd04
MA
2592 ;; recreated. Will be set in `tramp-convert-file-attributes'
2593 t
2594 ;; 10. inode number.
2595 res-inode
2596 ;; 11. Device number. Will be replaced by a virtual device number.
2597 -1
2598 ))))
fb7933a3
KG
2599
2600(defun tramp-handle-file-attributes-with-perl
00d6fd04
MA
2601 (vec localname &optional id-format)
2602 "Implement `file-attributes' for Tramp files using a Perl script."
2603 (tramp-message vec 5 "file attributes with perl: %s" localname)
2604 (tramp-maybe-send-script
2605 vec tramp-perl-file-attributes "tramp_perl_file_attributes")
2606 (tramp-send-command-and-read
2607 vec
2608 (format "tramp_perl_file_attributes %s %s"
2609 (tramp-shell-quote-argument localname) id-format)))
2610
2611(defun tramp-handle-file-attributes-with-stat
2612 (vec localname &optional id-format)
2613 "Implement `file-attributes' for Tramp files using stat(1) command."
2614 (tramp-message vec 5 "file attributes with stat: %s" localname)
2615 (tramp-send-command-and-read
2616 vec
2617 (format
d4443a0d 2618 "%s -c '((\"%%N\") %%h %s %s %%X.0 %%Y.0 %%Z.0 %%s.0 \"%%A\" t %%i.0 -1)' %s"
00d6fd04
MA
2619 (tramp-get-remote-stat vec)
2620 (if (eq id-format 'integer) "%u" "\"%U\"")
2621 (if (eq id-format 'integer) "%g" "\"%G\"")
2622 (tramp-shell-quote-argument localname))))
8daea7fc 2623
fb7933a3 2624(defun tramp-handle-set-visited-file-modtime (&optional time-list)
00d6fd04 2625 "Like `set-visited-file-modtime' for Tramp files."
fb7933a3
KG
2626 (unless (buffer-file-name)
2627 (error "Can't set-visited-file-modtime: buffer `%s' not visiting a file"
2628 (buffer-name)))
48ddd622
MA
2629 (if time-list
2630 (tramp-run-real-handler 'set-visited-file-modtime (list time-list))
11948172
MA
2631 (let ((f (buffer-file-name))
2632 coding-system-used)
48ddd622
MA
2633 (with-parsed-tramp-file-name f nil
2634 (let* ((attr (file-attributes f))
2635 ;; '(-1 65535) means file doesn't exists yet.
2636 (modtime (or (nth 5 attr) '(-1 65535))))
11948172
MA
2637 (when (boundp 'last-coding-system-used)
2638 (setq coding-system-used (symbol-value 'last-coding-system-used)))
48ddd622
MA
2639 ;; We use '(0 0) as a don't-know value. See also
2640 ;; `tramp-handle-file-attributes-with-ls'.
48ddd622
MA
2641 (if (not (equal modtime '(0 0)))
2642 (tramp-run-real-handler 'set-visited-file-modtime (list modtime))
00d6fd04 2643 (progn
48ddd622 2644 (tramp-send-command
00d6fd04 2645 v
48ddd622 2646 (format "%s -ild %s"
00d6fd04 2647 (tramp-get-ls-command v)
48ddd622 2648 (tramp-shell-quote-argument localname)))
48ddd622
MA
2649 (setq attr (buffer-substring (point)
2650 (progn (end-of-line) (point)))))
00d6fd04
MA
2651 (tramp-set-file-property
2652 v localname "visited-file-modtime-ild" attr))
11948172
MA
2653 (when (boundp 'last-coding-system-used)
2654 (set 'last-coding-system-used coding-system-used))
d2a2c17f 2655 nil)))))
fb7933a3 2656
c62c9d08
KG
2657;; This function makes the same assumption as
2658;; `tramp-handle-set-visited-file-modtime'.
2659(defun tramp-handle-verify-visited-file-modtime (buf)
00d6fd04 2660 "Like `verify-visited-file-modtime' for Tramp files.
c08e6004
MA
2661At the time `verify-visited-file-modtime' calls this function, we
2662already know that the buffer is visiting a file and that
2663`visited-file-modtime' does not return 0. Do not call this
2664function directly, unless those two cases are already taken care
2665of."
c62c9d08 2666 (with-current-buffer buf
b15d0c4c
MA
2667 ;; There is no file visiting the buffer, or the buffer has no
2668 ;; recorded last modification time.
2669 (if (or (not (buffer-file-name))
2670 (eq (visited-file-modtime) 0))
d2a2c17f 2671 t
b15d0c4c
MA
2672 (let ((f (buffer-file-name)))
2673 (with-parsed-tramp-file-name f nil
bce04fee 2674 (tramp-flush-file-property v localname)
b15d0c4c
MA
2675 (let* ((attr (file-attributes f))
2676 (modtime (nth 5 attr))
2677 (mt (visited-file-modtime)))
bf247b6e 2678
70c11b0b
MA
2679 (cond
2680 ;; File exists, and has a known modtime.
b15d0c4c
MA
2681 ((and attr (not (equal modtime '(0 0))))
2682 (< (abs (tramp-time-diff
2683 modtime
2684 ;; For compatibility, deal with both the old
70c11b0b
MA
2685 ;; (HIGH . LOW) and the new (HIGH LOW) return
2686 ;; values of `visited-file-modtime'.
b15d0c4c
MA
2687 (if (atom (cdr mt))
2688 (list (car mt) (cdr mt))
2689 mt)))
2690 2))
70c11b0b 2691 ;; Modtime has the don't know value.
b15d0c4c 2692 (attr
00d6fd04
MA
2693 (tramp-send-command
2694 v
2695 (format "%s -ild %s"
2696 (tramp-get-ls-command v)
2697 (tramp-shell-quote-argument localname)))
2698 (with-current-buffer (tramp-get-buffer v)
b15d0c4c
MA
2699 (setq attr (buffer-substring
2700 (point) (progn (end-of-line) (point)))))
00d6fd04
MA
2701 (equal
2702 attr
2703 (tramp-get-file-property
2704 v localname "visited-file-modtime-ild" "")))
70c11b0b
MA
2705 ;; If file does not exist, say it is not modified if and
2706 ;; only if that agrees with the buffer's record.
b15d0c4c 2707 (t (equal mt '(-1 65535))))))))))
c62c9d08 2708
fb7933a3 2709(defun tramp-handle-set-file-modes (filename mode)
00d6fd04 2710 "Like `set-file-modes' for Tramp files."
c62c9d08 2711 (with-parsed-tramp-file-name filename nil
00d6fd04
MA
2712 (tramp-flush-file-property v localname)
2713 (unless (zerop (tramp-send-command-and-check
2714 v
2715 (format "chmod %s %s"
2716 (tramp-decimal-to-octal mode)
2717 (tramp-shell-quote-argument localname))))
2718 ;; FIXME: extract the proper text from chmod's stderr.
2719 (tramp-error
2720 v 'file-error "Error while changing file's mode %s" filename))))
fb7933a3 2721
ce3f516f
MA
2722(defun tramp-handle-set-file-times (filename &optional time)
2723 "Like `set-file-times' for Tramp files."
2724 (zerop
9e6ab520 2725 (if (file-remote-p filename)
ce3f516f 2726 (with-parsed-tramp-file-name filename nil
8d60099b 2727 (tramp-flush-file-property v localname)
ce3f516f
MA
2728 (let ((time (if (or (null time) (equal time '(0 0)))
2729 (current-time)
2730 time))
2731 (utc
2732 ;; With GNU Emacs, `format-time-string' has an
2733 ;; optional parameter UNIVERSAL. This is preferred,
2734 ;; because we could handle the case when the remote
2735 ;; host is located in a different time zone as the
2736 ;; local host.
2737 (and (functionp 'subr-arity)
2738 (subrp (symbol-function 'format-time-string))
2739 (= 3 (cdr (funcall (symbol-function 'subr-arity)
2740 (symbol-function
2741 'format-time-string)))))))
2742 (tramp-send-command-and-check
2743 v (format "%s touch -t %s %s"
2744 (if utc "TZ=UTC; export TZ;" "")
2745 (if utc
2746 (format-time-string "%Y%m%d%H%M.%S" time t)
2747 (format-time-string "%Y%m%d%H%M.%S" time))
2748 (tramp-shell-quote-argument localname)))))
8d60099b 2749
ce3f516f
MA
2750 ;; We handle also the local part, because in older Emacsen,
2751 ;; without `set-file-times', this function is an alias for this.
2752 ;; We are local, so we don't need the UTC settings.
a4aeb9a4 2753 (tramp-local-call-process
ce3f516f
MA
2754 "touch" nil nil nil "-t"
2755 (format-time-string "%Y%m%d%H%M.%S" time)
2756 (tramp-shell-quote-argument filename)))))
2757
8d60099b
MA
2758(defun tramp-set-file-uid-gid (filename &optional uid gid)
2759 "Set the ownership for FILENAME.
2760If UID and GID are provided, these values are used; otherwise uid
2761and gid of the corresponding user is taken. Both parameters must be integers."
70c11b0b
MA
2762 ;; Modern Unices allow chown only for root. So we might need
2763 ;; another implementation, see `dired-do-chown'. OTOH, it is mostly
2764 ;; working with su(do)? when it is needed, so it shall succeed in
2765 ;; the majority of cases.
9e6ab520 2766 (if (file-remote-p filename)
8d60099b 2767 (with-parsed-tramp-file-name filename nil
93c3eb7c
MA
2768 (if (and (zerop (user-uid)) (tramp-local-host-p v))
2769 ;; If we are root on the local host, we can do it directly.
2770 (tramp-set-file-uid-gid localname uid gid)
2771 (let ((uid (or (and (integerp uid) uid)
2772 (tramp-get-remote-uid v 'integer)))
2773 (gid (or (and (integerp gid) gid)
2774 (tramp-get-remote-gid v 'integer))))
2775 (tramp-send-command
2776 v (format
2777 "chown %d:%d %s" uid gid
2778 (tramp-shell-quote-argument localname))))))
8d60099b
MA
2779
2780 ;; We handle also the local part, because there doesn't exist
70c11b0b 2781 ;; `set-file-uid-gid'. On W32 "chown" might not work.
8d60099b 2782 (let ((uid (or (and (integerp uid) uid) (tramp-get-local-uid 'integer)))
a4aeb9a4
MA
2783 (gid (or (and (integerp gid) gid) (tramp-get-local-gid 'integer))))
2784 (tramp-local-call-process
2785 "chown" nil nil nil
2786 (format "%d:%d" uid gid) (tramp-shell-quote-argument filename)))))
8d60099b 2787
fb7933a3
KG
2788;; Simple functions using the `test' command.
2789
2790(defun tramp-handle-file-executable-p (filename)
00d6fd04 2791 "Like `file-executable-p' for Tramp files."
c62c9d08 2792 (with-parsed-tramp-file-name filename nil
00d6fd04
MA
2793 (with-file-property v localname "file-executable-p"
2794 (zerop (tramp-run-test "-x" filename)))))
fb7933a3
KG
2795
2796(defun tramp-handle-file-readable-p (filename)
00d6fd04 2797 "Like `file-readable-p' for Tramp files."
c62c9d08 2798 (with-parsed-tramp-file-name filename nil
00d6fd04
MA
2799 (with-file-property v localname "file-readable-p"
2800 (zerop (tramp-run-test "-r" filename)))))
fb7933a3
KG
2801
2802;; When the remote shell is started, it looks for a shell which groks
2803;; tilde expansion. Here, we assume that all shells which grok tilde
2804;; expansion will also provide a `test' command which groks `-nt' (for
2805;; newer than). If this breaks, tell me about it and I'll try to do
2806;; something smarter about it.
2807(defun tramp-handle-file-newer-than-file-p (file1 file2)
00d6fd04 2808 "Like `file-newer-than-file-p' for Tramp files."
fb7933a3
KG
2809 (cond ((not (file-exists-p file1))
2810 nil)
2811 ((not (file-exists-p file2))
2812 t)
91879624 2813 ;; We are sure both files exist at this point.
fb7933a3
KG
2814 (t
2815 (save-excursion
91879624
KG
2816 ;; We try to get the mtime of both files. If they are not
2817 ;; equal to the "dont-know" value, then we subtract the times
2818 ;; and obtain the result.
2819 (let ((fa1 (file-attributes file1))
2820 (fa2 (file-attributes file2)))
2821 (if (and (not (equal (nth 5 fa1) '(0 0)))
2822 (not (equal (nth 5 fa2) '(0 0))))
01917a18 2823 (> 0 (tramp-time-diff (nth 5 fa2) (nth 5 fa1)))
91879624
KG
2824 ;; If one of them is the dont-know value, then we can
2825 ;; still try to run a shell command on the remote host.
2826 ;; However, this only works if both files are Tramp
2827 ;; files and both have the same method, same user, same
2828 ;; host.
00d6fd04
MA
2829 (unless (tramp-equal-remote file1 file2)
2830 (with-parsed-tramp-file-name
2831 (if (tramp-tramp-file-p file1) file1 file2) nil
2832 (tramp-error
2833 v 'file-error
2834 "Files %s and %s must have same method, user, host"
2835 file1 file2)))
2836 (with-parsed-tramp-file-name file1 nil
2837 (zerop (tramp-run-test2
2838 (tramp-get-test-nt-command v) file1 file2)))))))))
fb7933a3
KG
2839
2840;; Functions implemented using the basic functions above.
2841
2842(defun tramp-handle-file-modes (filename)
00d6fd04 2843 "Like `file-modes' for Tramp files."
5da24108
MA
2844 (let ((truename (or (file-truename filename) filename)))
2845 (when (file-exists-p truename)
2846 (tramp-mode-string-to-int (nth 8 (file-attributes truename))))))
fb7933a3 2847
b86c1cd8
MA
2848(defun tramp-default-file-modes (filename)
2849 "Return file modes of FILENAME as integer.
2850If the file modes of FILENAME cannot be determined, return the
974647ac
MA
2851value of `default-file-modes', without execute permissions."
2852 (or (file-modes filename)
2853 (logand (default-file-modes) (tramp-octal-to-decimal "0666"))))
b86c1cd8 2854
fb7933a3 2855(defun tramp-handle-file-directory-p (filename)
00d6fd04 2856 "Like `file-directory-p' for Tramp files."
fb7933a3
KG
2857 ;; Care must be taken that this function returns `t' for symlinks
2858 ;; pointing to directories. Surely the most obvious implementation
2859 ;; would be `test -d', but that returns false for such symlinks.
2860 ;; CCC: Stefan Monnier says that `test -d' follows symlinks. And
2861 ;; I now think he's right. So we could be using `test -d', couldn't
2862 ;; we?
2863 ;;
2864 ;; Alternatives: `cd %s', `test -d %s'
c62c9d08 2865 (with-parsed-tramp-file-name filename nil
00d6fd04
MA
2866 (with-file-property v localname "file-directory-p"
2867 (zerop (tramp-run-test "-d" filename)))))
fb7933a3
KG
2868
2869(defun tramp-handle-file-regular-p (filename)
00d6fd04
MA
2870 "Like `file-regular-p' for Tramp files."
2871 (and (file-exists-p filename)
2872 (eq ?- (aref (nth 8 (file-attributes filename)) 0))))
fb7933a3
KG
2873
2874(defun tramp-handle-file-symlink-p (filename)
00d6fd04 2875 "Like `file-symlink-p' for Tramp files."
c62c9d08 2876 (with-parsed-tramp-file-name filename nil
c951aecb 2877 (let ((x (car (file-attributes filename))))
b25a52cc
KG
2878 (when (stringp x)
2879 ;; When Tramp is running on VMS, then `file-name-absolute-p'
2880 ;; might do weird things.
2881 (if (file-name-absolute-p x)
00d6fd04 2882 (tramp-make-tramp-file-name method user host x)
b25a52cc 2883 x)))))
fb7933a3
KG
2884
2885(defun tramp-handle-file-writable-p (filename)
00d6fd04 2886 "Like `file-writable-p' for Tramp files."
c62c9d08 2887 (with-parsed-tramp-file-name filename nil
00d6fd04
MA
2888 (with-file-property v localname "file-writable-p"
2889 (if (file-exists-p filename)
2890 ;; Existing files must be writable.
2891 (zerop (tramp-run-test "-w" filename))
2892 ;; If file doesn't exist, check if directory is writable.
2893 (and (zerop (tramp-run-test
2894 "-d" (file-name-directory filename)))
2895 (zerop (tramp-run-test
2896 "-w" (file-name-directory filename))))))))
fb7933a3
KG
2897
2898(defun tramp-handle-file-ownership-preserved-p (filename)
00d6fd04 2899 "Like `file-ownership-preserved-p' for Tramp files."
c62c9d08 2900 (with-parsed-tramp-file-name filename nil
00d6fd04
MA
2901 (with-file-property v localname "file-ownership-preserved-p"
2902 (let ((attributes (file-attributes filename)))
2903 ;; Return t if the file doesn't exist, since it's true that no
2904 ;; information would be lost by an (attempted) delete and create.
2905 (or (null attributes)
2906 (= (nth 2 attributes) (tramp-get-remote-uid v 'integer)))))))
fb7933a3
KG
2907
2908;; Other file name ops.
2909
fb7933a3 2910(defun tramp-handle-directory-file-name (directory)
00d6fd04 2911 "Like `directory-file-name' for Tramp files."
7432277c
KG
2912 ;; If localname component of filename is "/", leave it unchanged.
2913 ;; Otherwise, remove any trailing slash from localname component.
8daea7fc
KG
2914 ;; Method, host, etc, are unchanged. Does it make sense to try
2915 ;; to avoid parsing the filename?
c62c9d08 2916 (with-parsed-tramp-file-name directory nil
7432277c
KG
2917 (if (and (not (zerop (length localname)))
2918 (eq (aref localname (1- (length localname))) ?/)
2919 (not (string= localname "/")))
8daea7fc
KG
2920 (substring directory 0 -1)
2921 directory)))
fb7933a3
KG
2922
2923;; Directory listings.
2924
00d6fd04
MA
2925(defun tramp-handle-directory-files
2926 (directory &optional full match nosort files-only)
2927 "Like `directory-files' for Tramp files."
2928 ;; FILES-ONLY is valid for XEmacs only.
2929 (when (file-directory-p directory)
2930 (setq directory (expand-file-name directory))
2931 (let ((temp (nreverse (file-name-all-completions "" directory)))
2932 result item)
2933
2934 (while temp
2935 (setq item (directory-file-name (pop temp)))
2936 (when (and (or (null match) (string-match match item))
2937 (or (null files-only)
2938 ;; files only
2939 (and (equal files-only t) (file-regular-p item))
2940 ;; directories only
2941 (file-directory-p item)))
2942 (push (if full (expand-file-name item directory) item)
2943 result)))
c62c9d08
KG
2944 result)))
2945
c82c5727
LH
2946(defun tramp-handle-directory-files-and-attributes
2947 (directory &optional full match nosort id-format)
00d6fd04
MA
2948 "Like `directory-files-and-attributes' for Tramp files."
2949 (unless id-format (setq id-format 'integer))
2950 (when (file-directory-p directory)
2951 (setq directory (expand-file-name directory))
2952 (let* ((temp
9e6ab520 2953 (tramp-compat-copy-tree
00d6fd04
MA
2954 (with-parsed-tramp-file-name directory nil
2955 (with-file-property
2956 v localname
2957 (format "directory-files-and-attributes-%s" id-format)
2958 (save-excursion
2959 (mapcar
2960 '(lambda (x)
2961 (cons (car x)
2962 (tramp-convert-file-attributes v (cdr x))))
2963 (if (tramp-get-remote-stat v)
2964 (tramp-handle-directory-files-and-attributes-with-stat
2965 v localname id-format)
2966 (if (tramp-get-remote-perl v)
2967 (tramp-handle-directory-files-and-attributes-with-perl
2968 v localname id-format)))))))))
2969 result item)
2970
2971 (while temp
2972 (setq item (pop temp))
2973 (when (or (null match) (string-match match (car item)))
2974 (when full
2975 (setcar item (expand-file-name (car item) directory)))
2976 (push item result)))
2977
2978 (if nosort
2979 result
2980 (sort result (lambda (x y) (string< (car x) (car y))))))))
2981
2982(defun tramp-handle-directory-files-and-attributes-with-perl
2983 (vec localname &optional id-format)
2984 "Implement `directory-files-and-attributes' for Tramp files using a Perl script."
2985 (tramp-message vec 5 "directory-files-and-attributes with perl: %s" localname)
2986 (tramp-maybe-send-script
2987 vec tramp-perl-directory-files-and-attributes
2988 "tramp_perl_directory_files_and_attributes")
2989 (let ((object
2990 (tramp-send-command-and-read
2991 vec
2992 (format "tramp_perl_directory_files_and_attributes %s %s"
2993 (tramp-shell-quote-argument localname) id-format))))
2994 (when (stringp object) (tramp-error vec 'file-error object))
2995 object))
2996
2997(defun tramp-handle-directory-files-and-attributes-with-stat
2998 (vec localname &optional id-format)
2999 "Implement `directory-files-and-attributes' for Tramp files using stat(1) command."
3000 (tramp-message vec 5 "directory-files-and-attributes with stat: %s" localname)
3001 (tramp-send-command-and-read
3002 vec
3003 (format
3004 (concat
70c11b0b
MA
3005 ;; We must care about filenames with spaces, or starting with
3006 ;; "-"; this would confuse xargs. "ls -aQ" might be a solution,
3007 ;; but it does not work on all remote systems. Therefore, we
3008 ;; quote the filenames via sed.
3009 "cd %s; echo \"(\"; (%s -a | sed -e s/\\$/\\\"/g -e s/^/\\\"/g | xargs "
d4443a0d 3010 "%s -c '(\"%%n\" (\"%%N\") %%h %s %s %%X.0 %%Y.0 %%Z.0 %%s.0 \"%%A\" t %%i.0 -1)'); "
00d6fd04
MA
3011 "echo \")\"")
3012 (tramp-shell-quote-argument localname)
3013 (tramp-get-ls-command vec)
3014 (tramp-get-remote-stat vec)
3015 (if (eq id-format 'integer) "%u" "\"%U\"")
3016 (if (eq id-format 'integer) "%g" "\"%G\""))))
c82c5727 3017
c62c9d08 3018;; This function should return "foo/" for directories and "bar" for
00d6fd04 3019;; files.
c62c9d08 3020(defun tramp-handle-file-name-all-completions (filename directory)
00d6fd04
MA
3021 "Like `file-name-all-completions' for Tramp files."
3022 (unless (save-match-data (string-match "/" filename))
9c13938d 3023 (with-parsed-tramp-file-name (expand-file-name directory) nil
b50dd0d2
MA
3024 ;; Flush the directory cache. There could be changed directory
3025 ;; contents.
3026 (when (and (integerp tramp-completion-reread-directory-timeout)
3027 (> (tramp-time-diff
3028 (current-time)
3029 (tramp-get-file-property
3030 v localname "last-completion" '(0 0 0)))
3031 tramp-completion-reread-directory-timeout))
3032 (tramp-flush-file-property v localname))
3033
00d6fd04
MA
3034 (all-completions
3035 filename
3036 (mapcar
3037 'list
3038 (with-file-property v localname "file-name-all-completions"
3039 (let (result)
3040 (tramp-barf-unless-okay
3041 v
3042 (format "cd %s" (tramp-shell-quote-argument localname))
3043 "tramp-handle-file-name-all-completions: Couldn't `cd %s'"
3044 (tramp-shell-quote-argument localname))
3045
3046 ;; Get a list of directories and files, including reliably
3047 ;; tagging the directories with a trailing '/'. Because I
3048 ;; rock. --daniel@danann.net
3049 (tramp-send-command
3050 v
65a099b6 3051 (format (concat "%s -a 2>/dev/null | while read f; do "
00d6fd04
MA
3052 "if %s -d \"$f\" 2>/dev/null; "
3053 "then echo \"$f/\"; else echo \"$f\"; fi; done")
3054 (tramp-get-ls-command v)
3055 (tramp-get-test-command v)))
3056
3057 ;; Now grab the output.
3058 (with-current-buffer (tramp-get-buffer v)
3059 (goto-char (point-max))
3060 (while (zerop (forward-line -1))
9e6ab520
MA
3061 (push (buffer-substring
3062 (point) (tramp-compat-line-end-position))
00d6fd04
MA
3063 result)))
3064
b50dd0d2
MA
3065 (tramp-set-file-property
3066 v localname "last-completion" (current-time))
00d6fd04 3067 result)))))))
fb7933a3
KG
3068
3069;; The following isn't needed for Emacs 20 but for 19.34?
e1e17cae
MA
3070(defun tramp-handle-file-name-completion
3071 (filename directory &optional predicate)
00d6fd04 3072 "Like `file-name-completion' for Tramp files."
fb7933a3
KG
3073 (unless (tramp-tramp-file-p directory)
3074 (error
3075 "tramp-handle-file-name-completion invoked on non-tramp directory `%s'"
3076 directory))
83e20b5c
MA
3077 (try-completion
3078 filename
3079 (mapcar 'list (file-name-all-completions filename directory))
3080 (when predicate
3081 (lambda (x) (funcall predicate (expand-file-name (car x) directory))))))
fb7933a3
KG
3082
3083;; cp, mv and ln
3084
3085(defun tramp-handle-add-name-to-file
3086 (filename newname &optional ok-if-already-exists)
00d6fd04
MA
3087 "Like `add-name-to-file' for Tramp files."
3088 (unless (tramp-equal-remote filename newname)
3089 (with-parsed-tramp-file-name
3090 (if (tramp-tramp-file-p filename) filename newname) nil
3091 (tramp-error
3092 v 'file-error
3093 "add-name-to-file: %s"
3094 "only implemented for same method, same user, same host")))
c62c9d08
KG
3095 (with-parsed-tramp-file-name filename v1
3096 (with-parsed-tramp-file-name newname v2
00d6fd04 3097 (let ((ln (when v1 (tramp-get-remote-ln v1))))
c62c9d08
KG
3098 (when (and (not ok-if-already-exists)
3099 (file-exists-p newname)
3100 (not (numberp ok-if-already-exists))
3101 (y-or-n-p
3102 (format
3103 "File %s already exists; make it a new name anyway? "
3104 newname)))
00d6fd04
MA
3105 (tramp-error
3106 v2 'file-error
3107 "add-name-to-file: file %s already exists" newname))
3108 (tramp-flush-file-property v2 v2-localname)
c62c9d08 3109 (tramp-barf-unless-okay
00d6fd04 3110 v1
7432277c
KG
3111 (format "%s %s %s" ln (tramp-shell-quote-argument v1-localname)
3112 (tramp-shell-quote-argument v2-localname))
c62c9d08
KG
3113 "error with add-name-to-file, see buffer `%s' for details"
3114 (buffer-name))))))
fb7933a3
KG
3115
3116(defun tramp-handle-copy-file
8d60099b 3117 (filename newname &optional ok-if-already-exists keep-date preserve-uid-gid)
00d6fd04 3118 "Like `copy-file' for Tramp files."
fb7933a3 3119 ;; Check if both files are local -- invoke normal copy-file.
9e6ab520 3120 ;; Otherwise, use Tramp from local system.
fb7933a3
KG
3121 (setq filename (expand-file-name filename))
3122 (setq newname (expand-file-name newname))
9e6ab520 3123 (cond
a4aeb9a4 3124 ;; At least one file a Tramp file?
9e6ab520
MA
3125 ((or (tramp-tramp-file-p filename)
3126 (tramp-tramp-file-p newname))
3127 (tramp-do-copy-or-rename-file
3128 'copy filename newname ok-if-already-exists keep-date preserve-uid-gid))
3129 ;; Compat section.
3130 (preserve-uid-gid
fb7933a3 3131 (tramp-run-real-handler
8d60099b 3132 'copy-file
9e6ab520
MA
3133 (list filename newname ok-if-already-exists keep-date preserve-uid-gid)))
3134 (t
3135 (tramp-run-real-handler
3136 'copy-file (list filename newname ok-if-already-exists keep-date)))))
fb7933a3
KG
3137
3138(defun tramp-handle-rename-file
3139 (filename newname &optional ok-if-already-exists)
00d6fd04 3140 "Like `rename-file' for Tramp files."
fb7933a3 3141 ;; Check if both files are local -- invoke normal rename-file.
a4aeb9a4 3142 ;; Otherwise, use Tramp from local system.
fb7933a3
KG
3143 (setq filename (expand-file-name filename))
3144 (setq newname (expand-file-name newname))
a4aeb9a4 3145 ;; At least one file a Tramp file?
fb7933a3
KG
3146 (if (or (tramp-tramp-file-p filename)
3147 (tramp-tramp-file-p newname))
3148 (tramp-do-copy-or-rename-file
8d60099b 3149 'rename filename newname ok-if-already-exists t t)
00d6fd04
MA
3150 (tramp-run-real-handler
3151 'rename-file (list filename newname ok-if-already-exists))))
fb7933a3
KG
3152
3153(defun tramp-do-copy-or-rename-file
8d60099b 3154 (op filename newname &optional ok-if-already-exists keep-date preserve-uid-gid)
fb7933a3
KG
3155 "Copy or rename a remote file.
3156OP must be `copy' or `rename' and indicates the operation to perform.
3157FILENAME specifies the file to copy or rename, NEWNAME is the name of
3158the new file (for copy) or the new name of the file (for rename).
3159OK-IF-ALREADY-EXISTS means don't barf if NEWNAME exists already.
3160KEEP-DATE means to make sure that NEWNAME has the same timestamp
8d60099b
MA
3161as FILENAME. PRESERVE-UID-GID, when non-nil, instructs to keep
3162the uid and gid if both files are on the same host.
fb7933a3
KG
3163
3164This function is invoked by `tramp-handle-copy-file' and
3165`tramp-handle-rename-file'. It is an error if OP is neither of `copy'
3166and `rename'. FILENAME and NEWNAME must be absolute file names."
3167 (unless (memq op '(copy rename))
3168 (error "Unknown operation `%s', must be `copy' or `rename'" op))
90dc758d 3169 (let ((t1 (tramp-tramp-file-p filename))
00d6fd04 3170 (t2 (tramp-tramp-file-p newname)))
5ec2cc41 3171
da1975d7
MA
3172 (when (and (not ok-if-already-exists) (file-exists-p newname))
3173 (with-parsed-tramp-file-name (if t1 filename newname) nil
3174 (tramp-error
3175 v 'file-already-exists "File %s already exists" newname)))
5ec2cc41 3176
905fb90e
MA
3177 (with-parsed-tramp-file-name (if t1 filename newname) nil
3178 (tramp-message v 0 "Transferring %s to %s..." filename newname))
3179
00d6fd04
MA
3180 (prog1
3181 (cond
3182 ;; Both are Tramp files.
3183 ((and t1 t2)
3184 (with-parsed-tramp-file-name filename v1
3185 (with-parsed-tramp-file-name newname v2
3186 (cond
3187 ;; Shortcut: if method, host, user are the same for both
3188 ;; files, we invoke `cp' or `mv' on the remote host
3189 ;; directly.
3190 ((tramp-equal-remote filename newname)
3191 (tramp-do-copy-or-rename-file-directly
8d60099b
MA
3192 op filename newname
3193 ok-if-already-exists keep-date preserve-uid-gid))
3194
905fb90e
MA
3195 ;; Try out-of-band operation.
3196 ((and (tramp-method-out-of-band-p v1)
00d6fd04
MA
3197 (> (nth 7 (file-attributes filename))
3198 tramp-copy-size-limit))
3199 (tramp-do-copy-or-rename-file-out-of-band
3200 op filename newname keep-date))
8d60099b 3201
00d6fd04
MA
3202 ;; No shortcut was possible. So we copy the
3203 ;; file first. If the operation was `rename', we go
3204 ;; back and delete the original file (if the copy was
3205 ;; successful). The approach is simple-minded: we
3206 ;; create a new buffer, insert the contents of the
3207 ;; source file into it, then write out the buffer to
3208 ;; the target file. The advantage is that it doesn't
3209 ;; matter which filename handlers are used for the
3210 ;; source and target file.
3211 (t
3212 (tramp-do-copy-or-rename-file-via-buffer
3213 op filename newname keep-date))))))
3214
3215 ;; One file is a Tramp file, the other one is local.
3216 ((or t1 t2)
3217 (with-parsed-tramp-file-name (if t1 filename newname) nil
8d60099b
MA
3218 (cond
3219 ;; Fast track on local machine.
3220 ((tramp-local-host-p v)
3221 (tramp-do-copy-or-rename-file-directly
3222 op filename newname
3223 ok-if-already-exists keep-date preserve-uid-gid))
3224
3225 ;; If the Tramp file has an out-of-band method, the corresponding
3226 ;; copy-program can be invoked.
3227 ((and (tramp-method-out-of-band-p v)
3228 (> (nth 7 (file-attributes filename))
3229 tramp-copy-size-limit))
3230 (tramp-do-copy-or-rename-file-out-of-band
3231 op filename newname keep-date))
3232
3233 ;; Use the inline method via a Tramp buffer.
3234 (t (tramp-do-copy-or-rename-file-via-buffer
3235 op filename newname keep-date)))))
00d6fd04
MA
3236
3237 (t
3238 ;; One of them must be a Tramp file.
3239 (error "Tramp implementation says this cannot happen")))
8d60099b 3240
484ea0b6
MA
3241 ;; In case of `rename', we must flush the cache of the source file.
3242 (when (and t1 (eq op 'rename))
3243 (with-parsed-tramp-file-name filename nil
3244 (tramp-flush-file-property v localname)))
3245
00d6fd04
MA
3246 ;; When newname did exist, we have wrong cached values.
3247 (when t2
3248 (with-parsed-tramp-file-name newname nil
905fb90e
MA
3249 (tramp-flush-file-property v localname)))
3250
3251 (with-parsed-tramp-file-name (if t1 filename newname) nil
3252 (tramp-message v 0 "Transferring %s to %s...done" filename newname)))))
7432277c 3253
38c65fca 3254(defun tramp-do-copy-or-rename-file-via-buffer (op filename newname keep-date)
90dc758d
KG
3255 "Use an Emacs buffer to copy or rename a file.
3256First arg OP is either `copy' or `rename' and indicates the operation.
3257FILENAME is the source file, NEWNAME the target file.
3258KEEP-DATE is non-nil if NEWNAME should have the same timestamp as FILENAME."
8a798e41
MA
3259 (with-temp-buffer
3260 ;; We must disable multibyte, because binary data shall not be
3261 ;; converted.
3262 (set-buffer-multibyte nil)
3263 (let ((coding-system-for-read 'binary)
3264 (jka-compr-inhibit t))
3265 (insert-file-contents-literally filename))
3266 ;; We don't want the target file to be compressed, so we let-bind
3267 ;; `jka-compr-inhibit' to t.
3268 (let ((coding-system-for-write 'binary)
3269 (jka-compr-inhibit t))
3270 (write-region (point-min) (point-max) newname)))
3271 ;; KEEP-DATE handling.
3272 (when keep-date (set-file-times newname (nth 5 (file-attributes filename))))
3273 ;; Set the mode.
b86c1cd8 3274 (set-file-modes newname (tramp-default-file-modes filename))
8a798e41
MA
3275 ;; If the operation was `rename', delete the original file.
3276 (unless (eq op 'copy) (delete-file filename)))
fb7933a3
KG
3277
3278(defun tramp-do-copy-or-rename-file-directly
8d60099b 3279 (op filename newname ok-if-already-exists keep-date preserve-uid-gid)
fb7933a3
KG
3280 "Invokes `cp' or `mv' on the remote system.
3281OP must be one of `copy' or `rename', indicating `cp' or `mv',
8d60099b
MA
3282respectively. FILENAME specifies the file to copy or rename,
3283NEWNAME is the name of the new file (for copy) or the new name of
3284the file (for rename). Both files must reside on the same host.
3285KEEP-DATE means to make sure that NEWNAME has the same timestamp
3286as FILENAME. PRESERVE-UID-GID, when non-nil, instructs to keep
3287the uid and gid from FILENAME."
8a4438b6 3288 (let ((t1 (tramp-tramp-file-p filename))
4f4126e6
MA
3289 (t2 (tramp-tramp-file-p newname))
3290 (file-times (nth 5 (file-attributes filename)))
3291 (file-modes (tramp-default-file-modes filename)))
8a4438b6
MA
3292 (with-parsed-tramp-file-name (if t1 filename newname) nil
3293 (let* ((cmd (cond ((and (eq op 'copy) preserve-uid-gid) "cp -f -p")
3294 ((eq op 'copy) "cp -f")
3295 ((eq op 'rename) "mv -f")
3296 (t (tramp-error
3297 v 'file-error
3298 "Unknown operation `%s', must be `copy' or `rename'"
3299 op))))
3300 (localname1
3301 (if t1 (tramp-handle-file-remote-p filename 'localname) filename))
3302 (localname2
3303 (if t2 (tramp-handle-file-remote-p newname 'localname) newname))
258800f8 3304 (prefix (file-remote-p (if t1 filename newname))))
8d60099b 3305
8d60099b 3306 (cond
8a4438b6
MA
3307 ;; Both files are on a remote host, with same user.
3308 ((and t1 t2)
3309 (tramp-send-command
3310 v
3311 (format "%s %s %s" cmd
3312 (tramp-shell-quote-argument localname1)
3313 (tramp-shell-quote-argument localname2)))
3314 (with-current-buffer (tramp-get-buffer v)
3315 (goto-char (point-min))
3316 (unless
3317 (or
3318 (and keep-date
3319 ;; Mask cp -f error.
3320 (re-search-forward
3321 tramp-operation-not-permitted-regexp nil t))
3322 (zerop (tramp-send-command-and-check v nil)))
3323 (tramp-error-with-buffer
3324 nil v 'file-error
3325 "Copying directly failed, see buffer `%s' for details."
3326 (buffer-name)))))
3327
3328 ;; We are on the local host.
3329 ((or t1 t2)
8d60099b 3330 (cond
8a4438b6 3331 ;; We can do it directly.
87bdd2c7
MA
3332 ((let (file-name-handler-alist)
3333 (and (file-readable-p localname1)
3334 (file-writable-p (file-name-directory localname2))
3335 (or (file-directory-p localname2)
3336 (file-writable-p localname2))))
8d60099b 3337 (if (eq op 'copy)
9e6ab520
MA
3338 (tramp-compat-copy-file
3339 localname1 localname2 ok-if-already-exists
3340 keep-date preserve-uid-gid)
87bdd2c7
MA
3341 (tramp-run-real-handler
3342 'rename-file (list localname1 localname2 ok-if-already-exists))))
8a4438b6
MA
3343
3344 ;; We can do it directly with `tramp-send-command'
946a5aeb
MA
3345 ((and (file-readable-p (concat prefix localname1))
3346 (file-writable-p
3347 (file-name-directory (concat prefix localname2)))
3348 (or (file-directory-p (concat prefix localname2))
3349 (file-writable-p (concat prefix localname2))))
8a4438b6
MA
3350 (tramp-do-copy-or-rename-file-directly
3351 op (concat prefix localname1) (concat prefix localname2)
3352 ok-if-already-exists keep-date t)
3353 ;; We must change the ownership to the local user.
8d60099b 3354 (tramp-set-file-uid-gid
8a4438b6
MA
3355 (concat prefix localname2)
3356 (tramp-get-local-uid 'integer)
3357 (tramp-get-local-gid 'integer)))
8d60099b 3358
8a4438b6
MA
3359 ;; We need a temporary file in between.
3360 (t
2c418c5b
MA
3361 ;; Create the temporary file.
3362 (let ((tmpfile (tramp-compat-make-temp-file localname1)))
917b89a6 3363 (unwind-protect
2c418c5b
MA
3364 (progn
3365 (cond
3366 (t1
917b89a6
MA
3367 (or
3368 (zerop
3369 (tramp-send-command-and-check
3370 v (format
3371 "%s %s %s" cmd
3372 (tramp-shell-quote-argument localname1)
3373 (tramp-shell-quote-argument tmpfile))))
3374 (tramp-error-with-buffer
3375 nil v 'file-error
3376 "Copying directly failed, see buffer `%s' for details."
3377 (tramp-get-buffer v)))
2c418c5b 3378 ;; We must change the ownership as remote user.
917b89a6
MA
3379 ;; Since this does not work reliable, we also
3380 ;; give read permissions.
3381 (set-file-modes
3382 (concat prefix tmpfile) (tramp-octal-to-decimal "0777"))
2c418c5b
MA
3383 (tramp-set-file-uid-gid
3384 (concat prefix tmpfile)
3385 (tramp-get-local-uid 'integer)
3386 (tramp-get-local-gid 'integer)))
3387 (t2
3388 (if (eq op 'copy)
3389 (tramp-compat-copy-file
5ab38c3c 3390 localname1 tmpfile t
2c418c5b
MA
3391 keep-date preserve-uid-gid)
3392 (tramp-run-real-handler
3393 'rename-file
5ab38c3c 3394 (list localname1 tmpfile t)))
2c418c5b 3395 ;; We must change the ownership as local user.
917b89a6
MA
3396 ;; Since this does not work reliable, we also
3397 ;; give read permissions.
3398 (set-file-modes tmpfile (tramp-octal-to-decimal "0777"))
2c418c5b
MA
3399 (tramp-set-file-uid-gid
3400 tmpfile
3401 (tramp-get-remote-uid v 'integer)
3402 (tramp-get-remote-gid v 'integer))))
3403
3404 ;; Move the temporary file to its destination.
3405 (cond
3406 (t2
917b89a6
MA
3407 (or
3408 (zerop
3409 (tramp-send-command-and-check
3410 v (format
3411 "cp -f -p %s %s"
3412 (tramp-shell-quote-argument tmpfile)
3413 (tramp-shell-quote-argument localname2))))
3414 (tramp-error-with-buffer
3415 nil v 'file-error
3416 "Copying directly failed, see buffer `%s' for details."
3417 (tramp-get-buffer v))))
2c418c5b 3418 (t1
ce2cc728
MA
3419 (tramp-run-real-handler
3420 'rename-file
2c418c5b
MA
3421 (list tmpfile localname2 ok-if-already-exists)))))
3422
917b89a6
MA
3423 ;; Save exit.
3424 (condition-case nil
3425 (delete-file tmpfile)
3426 (error)))))))))
8d60099b
MA
3427
3428 ;; Set the time and mode. Mask possible errors.
8d60099b 3429 (condition-case nil
1f107aed 3430 (when keep-date
4f4126e6
MA
3431 (set-file-times newname file-times)
3432 (set-file-modes newname file-modes))
8d60099b
MA
3433 (error)))))
3434
5ec2cc41 3435(defun tramp-do-copy-or-rename-file-out-of-band (op filename newname keep-date)
7432277c 3436 "Invoke rcp program to copy.
905fb90e 3437The method used must be an out-of-band method."
38c65fca 3438 (let ((t1 (tramp-tramp-file-p filename))
5ec2cc41 3439 (t2 (tramp-tramp-file-p newname))
946a5aeb 3440 copy-program copy-args copy-env copy-keep-date port spec
00d6fd04
MA
3441 source target)
3442
3443 (with-parsed-tramp-file-name (if t1 filename newname) nil
905fb90e 3444 (if (and t1 t2)
00d6fd04 3445
905fb90e
MA
3446 ;; Both are Tramp files. We shall optimize it, when the
3447 ;; methods for filename and newname are the same.
3448 (let ((tmpfile (tramp-compat-make-temp-file localname)))
3449 (unwind-protect
3450 (progn
3451 (tramp-do-copy-or-rename-file-out-of-band
3452 op filename tmpfile keep-date)
3453 (tramp-do-copy-or-rename-file-out-of-band
3454 'rename tmpfile newname keep-date))
3455 ;; Save exit.
3456 (condition-case nil
3457 (delete-file tmpfile)
3458 (error))))
3459
3460 ;; Expand hops. Might be necessary for gateway methods.
3461 (setq v (car (tramp-compute-multi-hops v)))
3462 (aset v 3 localname)
3463
3464 ;; Check which ones of source and target are Tramp files.
3465 (setq source (if t1 (tramp-make-copy-program-file-name v) filename)
3466 target (if t2 (tramp-make-copy-program-file-name v) newname))
3467
3468 ;; Check for port number. Until now, there's no need for handling
3469 ;; like method, user, host.
3470 (setq host (tramp-file-name-real-host v)
3471 port (tramp-file-name-port v)
3472 port (or (and port (number-to-string port)) ""))
3473
3474 ;; Compose copy command.
3475 (setq spec `((?h . ,host) (?u . ,user) (?p . ,port)
3476 (?t . ,(tramp-get-connection-property
3477 (tramp-get-connection-process v) "temp-file" ""))
3478 (?k . ,(if keep-date " " "")))
3479 copy-program (tramp-get-method-parameter
3480 method 'tramp-copy-program)
3481 copy-keep-date (tramp-get-method-parameter
3482 method 'tramp-copy-keep-date)
3483 copy-args
3484 (delq
3485 nil
3486 (mapcar
3487 '(lambda (x)
3488 (setq
3489 x
3490 ;; " " is indication for keep-date argument.
3491 (delete " " (mapcar '(lambda (y) (format-spec y spec)) x)))
3492 (unless (member "" x) (mapconcat 'identity x " ")))
946a5aeb
MA
3493 (tramp-get-method-parameter method 'tramp-copy-args)))
3494 copy-env
3495 (delq
3496 nil
3497 (mapcar
3498 '(lambda (x)
3499 (setq x (mapcar '(lambda (y) (format-spec y spec)) x))
3500 (unless (member "" x) (mapconcat 'identity x " ")))
3501 (tramp-get-method-parameter method 'tramp-copy-env))))
905fb90e
MA
3502
3503 ;; Check for program.
3504 (when (and (fboundp 'executable-find)
3505 (not (let ((default-directory
3506 (tramp-compat-temporary-file-directory)))
3507 (executable-find copy-program))))
3508 (tramp-error
3509 v 'file-error "Cannot find copy program: %s" copy-program))
00d6fd04 3510
905fb90e
MA
3511 (unwind-protect
3512 (with-temp-buffer
3513 ;; The default directory must be remote.
3514 (let ((default-directory
946a5aeb
MA
3515 (file-name-directory (if t1 filename newname)))
3516 (process-environment (copy-sequence process-environment)))
905fb90e
MA
3517 ;; Set the transfer process properties.
3518 (tramp-set-connection-property
3519 v "process-name" (buffer-name (current-buffer)))
3520 (tramp-set-connection-property
3521 v "process-buffer" (current-buffer))
946a5aeb
MA
3522 (while copy-env
3523 (tramp-message v 5 "%s=\"%s\"" (car copy-env) (cadr copy-env))
3524 (setenv (pop copy-env) (pop copy-env)))
905fb90e
MA
3525
3526 ;; Use an asynchronous process. By this, password can
3527 ;; be handled. The default directory must be local, in
3528 ;; order to apply the correct `copy-program'. We don't
3529 ;; set a timeout, because the copying of large files can
3530 ;; last longer than 60 secs.
3531 (let ((p (let ((default-directory
3532 (tramp-compat-temporary-file-directory)))
3533 (apply 'start-process
3534 (tramp-get-connection-property
3535 v "process-name" nil)
3536 (tramp-get-connection-property
3537 v "process-buffer" nil)
3538 copy-program
3539 (append copy-args (list source target))))))
3540 (tramp-message
3541 v 6 "%s" (mapconcat 'identity (process-command p) " "))
3542 (tramp-set-process-query-on-exit-flag p nil)
3543 (tramp-process-actions p v tramp-actions-copy-out-of-band))))
00d6fd04 3544
905fb90e
MA
3545 ;; Reset the transfer process properties.
3546 (tramp-set-connection-property v "process-name" nil)
3547 (tramp-set-connection-property v "process-buffer" nil))
00d6fd04 3548
905fb90e
MA
3549 ;; Handle KEEP-DATE argument.
3550 (when (and keep-date (not copy-keep-date))
3551 (set-file-times newname (nth 5 (file-attributes filename))))
01917a18 3552
905fb90e
MA
3553 ;; Set the mode.
3554 (unless (and keep-date copy-keep-date)
3555 (set-file-modes newname (tramp-default-file-modes filename))))
5ec2cc41 3556
905fb90e
MA
3557 ;; If the operation was `rename', delete the original file.
3558 (unless (eq op 'copy)
3559 (delete-file filename)))))
7432277c 3560
fb7933a3 3561(defun tramp-handle-make-directory (dir &optional parents)
00d6fd04 3562 "Like `make-directory' for Tramp files."
ac474af1 3563 (setq dir (expand-file-name dir))
c62c9d08 3564 (with-parsed-tramp-file-name dir nil
b1d06e75
KG
3565 (save-excursion
3566 (tramp-barf-unless-okay
00d6fd04 3567 v
9c13938d 3568 (format "%s %s"
b1d06e75 3569 (if parents "mkdir -p" "mkdir")
7432277c 3570 (tramp-shell-quote-argument localname))
b1d06e75 3571 "Couldn't make directory %s" dir))))
fb7933a3 3572
fb7933a3 3573(defun tramp-handle-delete-directory (directory)
00d6fd04 3574 "Like `delete-directory' for Tramp files."
ac474af1 3575 (setq directory (expand-file-name directory))
c62c9d08 3576 (with-parsed-tramp-file-name directory nil
00d6fd04
MA
3577 (tramp-flush-directory-property v localname)
3578 (unless (zerop (tramp-send-command-and-check
3579 v
cfb5c0db 3580 (format "rmdir %s" (tramp-shell-quote-argument localname))))
00d6fd04 3581 (tramp-error v 'file-error "Couldn't delete %s" directory))))
fb7933a3
KG
3582
3583(defun tramp-handle-delete-file (filename)
00d6fd04 3584 "Like `delete-file' for Tramp files."
ac474af1 3585 (setq filename (expand-file-name filename))
c62c9d08 3586 (with-parsed-tramp-file-name filename nil
00d6fd04
MA
3587 (tramp-flush-file-property v localname)
3588 (unless (zerop (tramp-send-command-and-check
3589 v
3590 (format "rm -f %s"
3591 (tramp-shell-quote-argument localname))))
3592 (tramp-error v 'file-error "Couldn't delete %s" filename))))
fb7933a3
KG
3593
3594;; Dired.
3595
3596;; CCC: This does not seem to be enough. Something dies when
a4aeb9a4 3597;; we try and delete two directories under Tramp :/
fb7933a3
KG
3598(defun tramp-handle-dired-recursive-delete-directory (filename)
3599 "Recursively delete the directory given.
00d6fd04 3600This is like `dired-recursive-delete-directory' for Tramp files."
c62c9d08 3601 (with-parsed-tramp-file-name filename nil
260821d3 3602 (tramp-flush-directory-property v localname)
00d6fd04 3603 ;; Run a shell command 'rm -r <localname>'
260821d3 3604 ;; Code shamelessly stolen from the dired implementation and, um, hacked :)
00d6fd04
MA
3605 (unless (file-exists-p filename)
3606 (tramp-error v 'file-error "No such directory: %s" filename))
fb7933a3 3607 ;; Which is better, -r or -R? (-r works for me <daniel@danann.net>)
00d6fd04
MA
3608 (tramp-send-command
3609 v
9c13938d 3610 (format "rm -rf %s" (tramp-shell-quote-argument localname))
00d6fd04
MA
3611 ;; Don't read the output, do it explicitely.
3612 nil t)
fb7933a3
KG
3613 ;; Wait for the remote system to return to us...
3614 ;; This might take a while, allow it plenty of time.
00d6fd04 3615 (tramp-wait-for-output (tramp-get-connection-process v) 120)
fb7933a3 3616 ;; Make sure that it worked...
07dfe738 3617 (and (file-exists-p filename)
00d6fd04
MA
3618 (tramp-error
3619 v 'file-error "Failed to recursively delete %s" filename))))
bf247b6e 3620
5ec2cc41 3621(defun tramp-handle-dired-compress-file (file &rest ok-flag)
00d6fd04 3622 "Like `dired-compress-file' for Tramp files."
5ec2cc41
KG
3623 ;; OK-FLAG is valid for XEmacs only, but not implemented.
3624 ;; Code stolen mainly from dired-aux.el.
3625 (with-parsed-tramp-file-name file nil
00d6fd04 3626 (tramp-flush-file-property v localname)
5ec2cc41
KG
3627 (save-excursion
3628 (let ((suffixes
3629 (if (not (featurep 'xemacs))
3630 ;; Emacs case
3631 (symbol-value 'dired-compress-file-suffixes)
3632 ;; XEmacs has `dired-compression-method-alist', which is
3633 ;; transformed into `dired-compress-file-suffixes' structure.
3634 (mapcar
3635 '(lambda (x)
3636 (list (concat (regexp-quote (nth 1 x)) "\\'")
3637 nil
3638 (mapconcat 'identity (nth 3 x) " ")))
3639 (symbol-value 'dired-compression-method-alist))))
3640 suffix)
3641 ;; See if any suffix rule matches this file name.
3642 (while suffixes
3643 (let (case-fold-search)
3644 (if (string-match (car (car suffixes)) localname)
3645 (setq suffix (car suffixes) suffixes nil))
3646 (setq suffixes (cdr suffixes))))
3647
3648 (cond ((file-symlink-p file)
3649 nil)
3650 ((and suffix (nth 2 suffix))
3651 ;; We found an uncompression rule.
00d6fd04 3652 (tramp-message v 0 "Uncompressing %s..." file)
5ec2cc41 3653 (when (zerop (tramp-send-command-and-check
00d6fd04
MA
3654 v (concat (nth 2 suffix) " " localname)))
3655 (tramp-message v 0 "Uncompressing %s...done" file)
38c65fca
KG
3656 ;; `dired-remove-file' is not defined in XEmacs
3657 (funcall (symbol-function 'dired-remove-file) file)
5ec2cc41
KG
3658 (string-match (car suffix) file)
3659 (concat (substring file 0 (match-beginning 0)))))
3660 (t
3661 ;; We don't recognize the file as compressed, so compress it.
3662 ;; Try gzip.
00d6fd04 3663 (tramp-message v 0 "Compressing %s..." file)
5ec2cc41 3664 (when (zerop (tramp-send-command-and-check
00d6fd04
MA
3665 v (concat "gzip -f " localname)))
3666 (tramp-message v 0 "Compressing %s...done" file)
38c65fca
KG
3667 ;; `dired-remove-file' is not defined in XEmacs
3668 (funcall (symbol-function 'dired-remove-file) file)
5ec2cc41
KG
3669 (cond ((file-exists-p (concat file ".gz"))
3670 (concat file ".gz"))
3671 ((file-exists-p (concat file ".z"))
3672 (concat file ".z"))
3673 (t nil)))))))))
fb7933a3 3674
70c11b0b
MA
3675(defun tramp-handle-dired-uncache (dir)
3676 "Like `dired-uncache' for Tramp files."
3677 (with-parsed-tramp-file-name dir nil
3678 (tramp-flush-file-property v localname)))
3679
fb7933a3
KG
3680;; Pacify byte-compiler. The function is needed on XEmacs only. I'm
3681;; not sure at all that this is the right way to do it, but let's hope
3682;; it works for now, and wait for a guru to point out the Right Way to
3683;; achieve this.
3684;;(eval-when-compile
3685;; (unless (fboundp 'dired-insert-set-properties)
3686;; (fset 'dired-insert-set-properties 'ignore)))
3687;; Gerd suggests this:
3688(eval-when-compile (require 'dired))
3689;; Note that dired is required at run-time, too, when it is needed.
3690;; It is only needed on XEmacs for the function
3691;; `dired-insert-set-properties'.
3692
3693(defun tramp-handle-insert-directory
3694 (filename switches &optional wildcard full-directory-p)
00d6fd04
MA
3695 "Like `insert-directory' for Tramp files."
3696 (setq filename (expand-file-name filename))
3697 (with-parsed-tramp-file-name filename nil
00d6fd04
MA
3698 (if (and (featurep 'ls-lisp)
3699 (not (symbol-value 'ls-lisp-use-insert-directory-program)))
3700 (tramp-run-real-handler
3701 'insert-directory (list filename switches wildcard full-directory-p))
8e754ea2
MA
3702 (when (and (string-match "^--dired\\s-+" switches)
3703 (not (tramp-get-ls-command-with-dired v)))
00d6fd04
MA
3704 (setq switches (replace-match "" nil t switches)))
3705 (tramp-message
3706 v 4 "Inserting directory `ls %s %s', wildcard %s, fulldir %s"
c82c5727
LH
3707 switches filename (if wildcard "yes" "no")
3708 (if full-directory-p "yes" "no"))
3709 (when wildcard
87bdd2c7
MA
3710 (setq wildcard (tramp-run-real-handler
3711 'file-name-nondirectory (list localname)))
3712 (setq localname (tramp-run-real-handler
3713 'file-name-directory (list localname))))
c82c5727
LH
3714 (when (listp switches)
3715 (setq switches (mapconcat 'identity switches " ")))
3716 (unless full-directory-p
3717 (setq switches (concat "-d " switches)))
3718 (when wildcard
3719 (setq switches (concat switches " " wildcard)))
00d6fd04
MA
3720 ;; If `full-directory-p', we just say `ls -l FILENAME'.
3721 ;; Else we chdir to the parent directory, then say `ls -ld BASENAME'.
3722 (if full-directory-p
3723 (tramp-send-command
3724 v
3725 (format "%s %s %s"
3726 (tramp-get-ls-command v)
3727 switches
3728 (if wildcard
3729 localname
3730 (tramp-shell-quote-argument (concat localname ".")))))
3731 (tramp-barf-unless-okay
3732 v
3733 (format "cd %s" (tramp-shell-quote-argument
87bdd2c7
MA
3734 (tramp-run-real-handler
3735 'file-name-directory (list localname))))
00d6fd04 3736 "Couldn't `cd %s'"
87bdd2c7
MA
3737 (tramp-shell-quote-argument
3738 (tramp-run-real-handler 'file-name-directory (list localname))))
00d6fd04
MA
3739 (tramp-send-command
3740 v
3741 (format "%s %s %s"
3742 (tramp-get-ls-command v)
3743 switches
3744 (if (or wildcard
87bdd2c7
MA
3745 (zerop (length
3746 (tramp-run-real-handler
3747 'file-name-nondirectory (list localname)))))
00d6fd04
MA
3748 ""
3749 (tramp-shell-quote-argument
87bdd2c7
MA
3750 (tramp-run-real-handler
3751 'file-name-nondirectory (list localname)))))))
8e754ea2
MA
3752 (let ((beg (point)))
3753 ;; We cannot use `insert-buffer-substring' because the Tramp
3754 ;; buffer changes its contents before insertion due to calling
3755 ;; `expand-file' and alike.
3756 (insert
3757 (with-current-buffer (tramp-get-buffer v)
3758 (buffer-string)))
3759
3760 ;; Check for "--dired" output.
3761 (goto-char (point-max))
3762 (forward-line -2)
3763 (when (looking-at "//DIRED//")
3764 (let ((end (line-end-position))
3765 (linebeg (point)))
3766 ;; Now read the numeric positions of file names.
3767 (goto-char linebeg)
3768 (forward-word 1)
3769 (forward-char 3)
3770 (while (< (point) end)
3771 (let ((start (+ beg (read (current-buffer))))
3772 (end (+ beg (read (current-buffer)))))
3773 (if (memq (char-after end) '(?\n ?\s))
3774 ;; End is followed by \n or by " -> ".
3775 (put-text-property start end 'dired-filename t)))))
3776 ;; Reove training lines.
3777 (goto-char (point-max))
3778 (forward-line -1)
3779 (while (looking-at "//")
3780 (forward-line 1)
3781 (delete-region (match-beginning 0) (point))
3782 (forward-line -1))))
3783 (goto-char (point-max)))))
fb7933a3 3784
fb7933a3 3785(defun tramp-handle-unhandled-file-name-directory (filename)
00d6fd04 3786 "Like `unhandled-file-name-directory' for Tramp files."
8a798e41
MA
3787 ;; With Emacs 23, we could simply return `nil'. But we must keep it
3788 ;; for backward compatibility.
ce3f516f 3789 (expand-file-name "~/"))
fb7933a3
KG
3790
3791;; Canonicalization of file names.
3792
fb7933a3 3793(defun tramp-handle-expand-file-name (name &optional dir)
00d6fd04 3794 "Like `expand-file-name' for Tramp files.
7432277c
KG
3795If the localname part of the given filename starts with \"/../\" then
3796the result will be a local, non-Tramp, filename."
fb7933a3
KG
3797 ;; If DIR is not given, use DEFAULT-DIRECTORY or "/".
3798 (setq dir (or dir default-directory "/"))
3799 ;; Unless NAME is absolute, concat DIR and NAME.
3800 (unless (file-name-absolute-p name)
3801 (setq name (concat (file-name-as-directory dir) name)))
00d6fd04 3802 ;; If NAME is not a Tramp file, run the real handler.
fb7933a3 3803 (if (not (tramp-tramp-file-p name))
00d6fd04 3804 (tramp-run-real-handler 'expand-file-name (list name nil))
fb7933a3 3805 ;; Dissect NAME.
c62c9d08 3806 (with-parsed-tramp-file-name name nil
87bdd2c7 3807 (unless (tramp-run-real-handler 'file-name-absolute-p (list localname))
7432277c 3808 (setq localname (concat "~/" localname)))
00d6fd04
MA
3809 ;; Tilde expansion if necessary. This needs a shell which
3810 ;; groks tilde expansion! The function `tramp-find-shell' is
3811 ;; supposed to find such a shell on the remote host. Please
3812 ;; tell me about it when this doesn't work on your system.
3813 (when (string-match "\\`\\(~[^/]*\\)\\(.*\\)\\'" localname)
3814 (let ((uname (match-string 1 localname))
3815 (fname (match-string 2 localname)))
3816 ;; We cannot simply apply "~/", because under sudo "~/" is
3817 ;; expanded to the local user home directory but to the
3818 ;; root home directory. On the other hand, using always
3819 ;; the default user name for tilde expansion is not
3820 ;; appropriate either, because ssh and companions might
3821 ;; use a user name from the config file.
3822 (when (and (string-equal uname "~")
3823 (string-match "\\`su\\(do\\)?\\'" method))
3824 (setq uname (concat uname user)))
3825 (setq uname
3826 (with-connection-property v uname
3827 (tramp-send-command v (format "cd %s; pwd" uname))
3828 (with-current-buffer (tramp-get-buffer v)
3829 (goto-char (point-min))
9e6ab520 3830 (buffer-substring (point) (tramp-compat-line-end-position)))))
00d6fd04
MA
3831 (setq localname (concat uname fname))))
3832 ;; There might be a double slash, for example when "~/"
cb85dcd0 3833 ;; expands to "/". Remove this.
00d6fd04
MA
3834 (while (string-match "//" localname)
3835 (setq localname (replace-match "/" t t localname)))
3836 ;; No tilde characters in file name, do normal
3837 ;; expand-file-name (this does "/./" and "/../"). We bind
3838 ;; `directory-sep-char' here for XEmacs on Windows, which
3839 ;; would otherwise use backslash. `default-directory' is
3840 ;; bound, because on Windows there would be problems with UNC
3841 ;; shares or Cygwin mounts.
aff67808
MA
3842 (let ((directory-sep-char ?/)
3843 (default-directory (tramp-compat-temporary-file-directory)))
3844 (tramp-make-tramp-file-name
3845 method user host
3846 (tramp-drop-volume-letter
87bdd2c7
MA
3847 (tramp-run-real-handler
3848 'expand-file-name (list localname))))))))
00d6fd04 3849
c23c3394
MA
3850(defun tramp-replace-environment-variables (filename)
3851 "Replace environment variables in FILENAME.
3852Return the string with the replaced variables."
2e271195
MA
3853 (save-match-data
3854 (let ((idx (string-match "$\\w+" filename)))
3855 ;; `$' is coded as `$$'.
3856 (when (and idx (or (zerop idx) (not (eq ?$ (aref filename (1- idx))))))
3857 (setq filename
3858 (replace-match
3859 (substitute-in-file-name (match-string 0 filename))
3860 t nil filename)))
3861 filename)))
c23c3394 3862
00d6fd04
MA
3863(defun tramp-handle-substitute-in-file-name (filename)
3864 "Like `substitute-in-file-name' for Tramp files.
3865\"//\" and \"/~\" substitute only in the local filename part.
3866If the URL Tramp syntax is chosen, \"//\" as method delimeter and \"/~\" at
3867beginning of local filename are not substituted."
c23c3394
MA
3868 ;; First, we must replace environment variables.
3869 (setq filename (tramp-replace-environment-variables filename))
00d6fd04
MA
3870 (with-parsed-tramp-file-name filename nil
3871 (if (equal tramp-syntax 'url)
3872 ;; We need to check localname only. The other parts cannot contain
3873 ;; "//" or "/~".
3874 (if (and (> (length localname) 1)
3875 (or (string-match "//" localname)
3876 (string-match "/~" localname 1)))
3877 (tramp-run-real-handler 'substitute-in-file-name (list filename))
3878 (tramp-make-tramp-file-name
3879 (when method (substitute-in-file-name method))
3880 (when user (substitute-in-file-name user))
3881 (when host (substitute-in-file-name host))
87bdd2c7
MA
3882 (when localname
3883 (tramp-run-real-handler
3884 'substitute-in-file-name (list localname)))))
00d6fd04
MA
3885 ;; Ignore in LOCALNAME everything before "//" or "/~".
3886 (when (and (stringp localname) (string-match ".+?/\\(/\\|~\\)" localname))
3887 (setq filename
b08104a0
MA
3888 (concat (file-remote-p filename)
3889 (replace-match "\\1" nil nil localname)))
00d6fd04
MA
3890 ;; "/m:h:~" does not work for completion. We use "/m:h:~/".
3891 (when (string-match "~$" filename)
3892 (setq filename (concat filename "/"))))
3893 (tramp-run-real-handler 'substitute-in-file-name (list filename)))))
3894
3895;; In XEmacs, electricity is implemented via a key map for ?/ and ?~,
3896;; which calls corresponding functions (see minibuf.el).
3897(when (fboundp 'minibuffer-electric-separator)
9e6ab520 3898 (mapc
00d6fd04
MA
3899 '(lambda (x)
3900 (eval
3901 `(defadvice ,x
3902 (around ,(intern (format "tramp-advice-%s" x)) activate)
3903 "Invoke `substitute-in-file-name' for Tramp files."
3904 (if (and (symbol-value 'minibuffer-electric-file-name-behavior)
3905 (tramp-tramp-file-p (buffer-substring)))
3906 ;; We don't need to handle `last-input-event', because
3907 ;; due to the key map we know it must be ?/ or ?~.
3908 (let ((s (concat (buffer-substring (point-min) (point))
c28f19e5 3909 (string last-command-char))))
00d6fd04
MA
3910 (delete-region (point-min) (point))
3911 (insert (substitute-in-file-name s))
c28f19e5 3912 (setq ad-return-value last-command-char))
00d6fd04
MA
3913 ad-do-it))))
3914
3915 '(minibuffer-electric-separator
3916 minibuffer-electric-tilde)))
3917
3918
0664ff72 3919;;; Remote commands:
fb7933a3 3920
00d6fd04
MA
3921(defun tramp-handle-executable-find (command)
3922 "Like `executable-find' for Tramp files."
3923 (with-parsed-tramp-file-name default-directory nil
f84638eb 3924 (tramp-find-executable v command (tramp-get-remote-path v) t)))
00d6fd04
MA
3925
3926;; We use BUFFER also as connection buffer during setup. Because of
3927;; this, its original contents must be saved, and restored once
3928;; connection has been setup.
3929(defun tramp-handle-start-file-process (name buffer program &rest args)
3930 "Like `start-file-process' for Tramp files."
3931 (with-parsed-tramp-file-name default-directory nil
3932 (unwind-protect
38d63e6a
MA
3933 (let ((name1 name)
3934 (i 0))
2296b54d 3935 (unless buffer
6ce63faf 3936 ;; BUFFER can be nil. We use a temporary buffer.
2296b54d 3937 (setq buffer (generate-new-buffer tramp-temp-buffer-name)))
38d63e6a
MA
3938 (while (get-process name1)
3939 ;; NAME must be unique as process name.
3940 (setq i (1+ i)
3941 name1 (format "%s<%d>" name i)))
3942 (setq name name1)
00d6fd04
MA
3943 ;; Set the new process properties.
3944 (tramp-set-connection-property v "process-name" name)
2296b54d 3945 (tramp-set-connection-property v "process-buffer" buffer)
00d6fd04 3946 ;; Activate narrowing in order to save BUFFER contents.
11c71217
MA
3947 ;; Clear also the modification time; otherwise we might be
3948 ;; interrupted by `verify-visited-file-modtime'.
00d6fd04 3949 (with-current-buffer (tramp-get-connection-buffer v)
11c71217 3950 (clear-visited-file-modtime)
00d6fd04
MA
3951 (narrow-to-region (point-max) (point-max)))
3952 ;; Goto working directory. `tramp-send-command' opens a new
3953 ;; connection.
3954 (tramp-send-command
3955 v (format "cd %s" (tramp-shell-quote-argument localname)))
3956 ;; Send the command.
3957 (tramp-send-command
3958 v
2296b54d 3959 (format "exec %s"
00d6fd04 3960 (mapconcat 'tramp-shell-quote-argument
2296b54d 3961 (cons program args) " "))
00d6fd04 3962 nil t) ; nooutput
6ce63faf
MA
3963 ;; Set query flag for this process.
3964 (tramp-set-process-query-on-exit-flag
3965 (tramp-get-connection-process v) t)
00d6fd04
MA
3966 ;; Return process.
3967 (tramp-get-connection-process v))
3968 ;; Save exit.
ce3f516f 3969 (with-current-buffer (tramp-get-connection-buffer v)
6ce63faf
MA
3970 (if (string-match tramp-temp-buffer-name (buffer-name))
3971 (progn
3972 (set-process-buffer (tramp-get-connection-process v) nil)
3973 (kill-buffer (current-buffer)))
3974 (widen)
3975 (goto-char (point-max))))
00d6fd04
MA
3976 (tramp-set-connection-property v "process-name" nil)
3977 (tramp-set-connection-property v "process-buffer" nil))))
3978
3979(defun tramp-handle-process-file
3980 (program &optional infile destination display &rest args)
3981 "Like `process-file' for Tramp files."
3982 ;; The implementation is not complete yet.
3983 (when (and (numberp destination) (zerop destination))
3984 (error "Implementation does not handle immediate return"))
3985
3986 (with-parsed-tramp-file-name default-directory nil
a6e96327 3987 (let (command input tmpinput stderr tmpstderr outbuf ret)
00d6fd04
MA
3988 ;; Compute command.
3989 (setq command (mapconcat 'tramp-shell-quote-argument
3990 (cons program args) " "))
3991 ;; Determine input.
3992 (if (null infile)
3993 (setq input "/dev/null")
3994 (setq infile (expand-file-name infile))
3995 (if (tramp-equal-remote default-directory infile)
3996 ;; INFILE is on the same remote host.
3997 (setq input (with-parsed-tramp-file-name infile nil localname))
3998 ;; INFILE must be copied to remote host.
a6e96327
MA
3999 (setq input (tramp-make-tramp-temp-file v)
4000 tmpinput (tramp-make-tramp-file-name method user host input))
4001 (copy-file infile tmpinput t)))
00d6fd04
MA
4002 (when input (setq command (format "%s <%s" command input)))
4003
4004 ;; Determine output.
4005 (cond
bede3e9f 4006 ;; Just a buffer.
00d6fd04
MA
4007 ((bufferp destination)
4008 (setq outbuf destination))
bede3e9f 4009 ;; A buffer name.
00d6fd04
MA
4010 ((stringp destination)
4011 (setq outbuf (get-buffer-create destination)))
4012 ;; (REAL-DESTINATION ERROR-DESTINATION)
4013 ((consp destination)
bede3e9f 4014 ;; output.
00d6fd04
MA
4015 (cond
4016 ((bufferp (car destination))
4017 (setq outbuf (car destination)))
4018 ((stringp (car destination))
0664ff72
MA
4019 (setq outbuf (get-buffer-create (car destination))))
4020 ((car destination)
4021 (setq outbuf (current-buffer))))
bede3e9f 4022 ;; stderr.
00d6fd04
MA
4023 (cond
4024 ((stringp (cadr destination))
4025 (setcar (cdr destination) (expand-file-name (cadr destination)))
4026 (if (tramp-equal-remote default-directory (cadr destination))
4027 ;; stderr is on the same remote host.
4028 (setq stderr (with-parsed-tramp-file-name
4029 (cadr destination) nil localname))
4030 ;; stderr must be copied to remote host. The temporary
4031 ;; file must be deleted after execution.
a6e96327
MA
4032 (setq stderr (tramp-make-tramp-temp-file v)
4033 tmpstderr (tramp-make-tramp-file-name
4034 method user host stderr))))
bede3e9f 4035 ;; stderr to be discarded.
00d6fd04
MA
4036 ((null (cadr destination))
4037 (setq stderr "/dev/null"))))
4038 ;; 't
4039 (destination
4040 (setq outbuf (current-buffer))))
4041 (when stderr (setq command (format "%s 2>%s" command stderr)))
4042
00d6fd04
MA
4043 ;; Goto working directory.
4044 (tramp-send-command
4045 v (format "cd %s" (tramp-shell-quote-argument localname)))
4046 ;; Send the command. It might not return in time, so we protect it.
4047 (condition-case nil
4048 (unwind-protect
4049 (tramp-send-command v command)
4050 ;; We should show the output anyway.
4051 (when outbuf
27e813fe
MA
4052 (let ((output-string
4053 (with-current-buffer (tramp-get-connection-buffer v)
4054 (buffer-substring (point-min) (point-max)))))
4055 (with-current-buffer outbuf
4056 (insert output-string)))
00d6fd04 4057 (when display (display-buffer outbuf))))
260821d3
MA
4058 ;; When the user did interrupt, we should do it also. We use
4059 ;; return code -1 as marker.
4060 (quit
4061 (kill-buffer (tramp-get-connection-buffer v))
4062 (setq ret -1))
4063 ;; Handle errors.
00d6fd04
MA
4064 (error
4065 (kill-buffer (tramp-get-connection-buffer v))
4066 (setq ret 1)))
a6e96327
MA
4067
4068 ;; Check return code.
4069 (unless ret (setq ret (tramp-send-command-and-check v nil)))
4070 ;; Provide error file.
4071 (when tmpstderr (rename-file tmpstderr (cadr destination) t))
260821d3
MA
4072 ;; Cleanup. We remove all file cache values for the connection,
4073 ;; because the remote process could have changed them.
a6e96327 4074 (when tmpinput (delete-file tmpinput))
946a5aeb
MA
4075
4076 ;; `process-file-side-effects' has been introduced with GNU
4077 ;; Emacs 23.2. If set to `nil', no remote file will be changed
4078 ;; by `program'. If it doesn't exist, we assume its default
4079 ;; value 't'.
4080 (unless (and (boundp 'process-file-side-effects)
4081 (not (symbol-value 'process-file-side-effects)))
4082 (tramp-flush-directory-property v ""))
4083
00d6fd04 4084 ;; Return exit status.
260821d3
MA
4085 (if (equal ret -1)
4086 (keyboard-quit)
4087 ret))))
00d6fd04 4088
a4aeb9a4
MA
4089(defun tramp-local-call-process
4090 (program &optional infile destination display &rest args)
4091 "Calls `call-process' on the local host.
4092This is needed because for some Emacs flavors Tramp has
4093defadviced `call-process' to behave like `process-file'. The
4094Lisp error raised when PROGRAM is nil is trapped also, returning 1."
4095 (let ((default-directory
4096 (if (file-remote-p default-directory)
4097 (tramp-compat-temporary-file-directory)
4098 default-directory)))
4099 (if (executable-find program)
4100 (apply 'call-process program infile destination display args)
4101 1)))
4102
00d6fd04
MA
4103(defun tramp-handle-call-process-region
4104 (start end program &optional delete buffer display &rest args)
4105 "Like `call-process-region' for Tramp files."
258800f8 4106 (let ((tmpfile (tramp-compat-make-temp-file "")))
00d6fd04
MA
4107 (write-region start end tmpfile)
4108 (when delete (delete-region start end))
4109 (unwind-protect
4110 (apply 'call-process program tmpfile buffer display args)
4111 (delete-file tmpfile))))
4112
4113(defun tramp-handle-shell-command
4114 (command &optional output-buffer error-buffer)
4115 "Like `shell-command' for Tramp files."
ce3f516f 4116 (let* ((asynchronous (string-match "[ \t]*&[ \t]*\\'" command))
b8bfcf96
MA
4117 ;; We cannot use `shell-file-name' and `shell-command-switch',
4118 ;; they are variables of the local host.
4119 (args (list "/bin/sh" "-c" (substring command 0 asynchronous)))
5d2ebd96 4120 current-buffer-p
ce3f516f 4121 (output-buffer
27e813fe
MA
4122 (cond
4123 ((bufferp output-buffer) output-buffer)
4124 ((stringp output-buffer) (get-buffer-create output-buffer))
5d2ebd96
AS
4125 (output-buffer
4126 (setq current-buffer-p t)
4127 (current-buffer))
42bc9b6d 4128 (t (get-buffer-create
27e813fe
MA
4129 (if asynchronous
4130 "*Async Shell Command*"
4131 "*Shell Command Output*")))))
4132 (error-buffer
4133 (cond
4134 ((bufferp error-buffer) error-buffer)
4135 ((stringp error-buffer) (get-buffer-create error-buffer))))
ce3f516f 4136 (buffer
27e813fe 4137 (if (and (not asynchronous) error-buffer)
ce3f516f
MA
4138 (with-parsed-tramp-file-name default-directory nil
4139 (list output-buffer (tramp-make-tramp-temp-file v)))
42bc9b6d 4140 output-buffer))
cfb5c0db 4141 (p (get-buffer-process output-buffer)))
42bc9b6d
MA
4142
4143 ;; Check whether there is another process running. Tramp does not
4144 ;; support 2 (asynchronous) processes in parallel.
cfb5c0db 4145 (when p
42bc9b6d 4146 (if (yes-or-no-p "A command is running. Kill it? ")
699a11fb
GM
4147 (condition-case nil
4148 (kill-process p)
4149 (error nil))
42bc9b6d
MA
4150 (error "Shell command in progress")))
4151
f34db316
AS
4152 (if current-buffer-p
4153 (progn
4154 (barf-if-buffer-read-only)
4155 (push-mark nil t))
5d2ebd96
AS
4156 (with-current-buffer output-buffer
4157 (setq buffer-read-only nil)
4158 (erase-buffer)))
42bc9b6d 4159
5d2ebd96 4160 (if (and (not current-buffer-p) (integerp asynchronous))
42bc9b6d
MA
4161 (prog1
4162 ;; Run the process.
3412f35d 4163 (apply 'start-file-process "*Async Shell*" buffer args)
42bc9b6d 4164 ;; Display output.
cfb5c0db
MA
4165 (pop-to-buffer output-buffer)
4166 (setq mode-line-process '(":%s"))
4167 (require 'shell) (shell-mode))
42bc9b6d
MA
4168
4169 (prog1
4170 ;; Run the process.
4171 (apply 'process-file (car args) nil buffer nil (cdr args))
4172 ;; Insert error messages if they were separated.
4173 (when (listp buffer)
4174 (with-current-buffer error-buffer
4175 (insert-file-contents (cadr buffer)))
4176 (delete-file (cadr buffer)))
f34db316
AS
4177 (if current-buffer-p
4178 ;; This is like exchange-point-and-mark, but doesn't
4179 ;; activate the mark. It is cleaner to avoid activation,
4180 ;; even though the command loop would deactivate the mark
4181 ;; because we inserted text.
4182 (goto-char (prog1 (mark t)
4183 (set-marker (mark-marker) (point)
4184 (current-buffer))))
4185 ;; There's some output, display it.
4186 (when (with-current-buffer output-buffer (> (point-max) (point-min)))
4187 (if (functionp 'display-message-or-buffer)
4188 (funcall (symbol-function 'display-message-or-buffer)
4189 output-buffer)
4190 (pop-to-buffer output-buffer))))))))
00d6fd04
MA
4191
4192;; File Editing.
4193
4194(defvar tramp-handle-file-local-copy-hook nil
4195 "Normal hook to be run at the end of `tramp-handle-file-local-copy'.")
4196
fb7933a3 4197(defun tramp-handle-file-local-copy (filename)
00d6fd04 4198 "Like `file-local-copy' for Tramp files."
0f205eee 4199
c62c9d08 4200 (with-parsed-tramp-file-name filename nil
2988341a
MA
4201 (unless (file-exists-p filename)
4202 (tramp-error
4203 v 'file-error
4204 "Cannot make local copy of non-existing file `%s'" filename))
4205
0f205eee 4206 (let ((rem-enc (tramp-get-remote-coding v "remote-encoding"))
00d6fd04 4207 (loc-dec (tramp-get-local-coding v "local-decoding"))
258800f8 4208 (tmpfile (tramp-compat-make-temp-file filename)))
5ec2cc41 4209
2988341a
MA
4210 (condition-case err
4211 (cond
4212 ;; `copy-file' handles direct copy and out-of-band methods.
4213 ((or (tramp-local-host-p v)
4214 (and (tramp-method-out-of-band-p v)
4215 (> (nth 7 (file-attributes filename))
4216 tramp-copy-size-limit)))
4217 (copy-file filename tmpfile t t))
4218
4219 ;; Use inline encoding for file transfer.
4220 (rem-enc
4221 (save-excursion
4222 (tramp-message v 5 "Encoding remote file %s..." filename)
4223 (tramp-barf-unless-okay
4224 v
4225 (format "%s < %s" rem-enc (tramp-shell-quote-argument localname))
4226 "Encoding remote file failed")
4227 (tramp-message v 5 "Encoding remote file %s...done" filename)
4228
4229 (if (and (symbolp loc-dec) (fboundp loc-dec))
4230 ;; If local decoding is a function, we call it. We
4231 ;; must disable multibyte, because
4232 ;; `uudecode-decode-region' doesn't handle it
4233 ;; correctly.
0f205eee
MA
4234 (with-temp-buffer
4235 (set-buffer-multibyte nil)
4236 (insert-buffer-substring (tramp-get-buffer v))
4237 (tramp-message
4238 v 5 "Decoding remote file %s with function %s..."
4239 filename loc-dec)
4240 (funcall loc-dec (point-min) (point-max))
4241 (let ((coding-system-for-write 'binary))
2988341a
MA
4242 (write-region (point-min) (point-max) tmpfile)))
4243
4244 ;; If tramp-decoding-function is not defined for this
4245 ;; method, we invoke tramp-decoding-command instead.
4246 (let ((tmpfile2 (tramp-compat-make-temp-file filename)))
4247 (let ((coding-system-for-write 'binary))
4248 (write-region (point-min) (point-max) tmpfile2))
4249 (tramp-message
4250 v 5 "Decoding remote file %s with command %s..."
4251 filename loc-dec)
4252 (unwind-protect
4253 (tramp-call-local-coding-command loc-dec tmpfile2 tmpfile)
4254 (delete-file tmpfile2))))
4255
4256 (tramp-message v 5 "Decoding remote file %s...done" filename)
4257 ;; Set proper permissions.
b86c1cd8 4258 (set-file-modes tmpfile (tramp-default-file-modes filename))
2988341a
MA
4259 ;; Set local user ownership.
4260 (tramp-set-file-uid-gid tmpfile)))
4261
4262 ;; Oops, I don't know what to do.
4263 (t (tramp-error
4264 v 'file-error "Wrong method specification for `%s'" method)))
4265
4266 ;; Error handling.
4267 ((error quit)
4268 (delete-file tmpfile)
4269 (signal (car err) (cdr err))))
0f205eee 4270
00d6fd04 4271 (run-hooks 'tramp-handle-file-local-copy-hook)
94be87e8 4272 tmpfile)))
fb7933a3 4273
bce04fee 4274(defun tramp-handle-file-remote-p (filename &optional identification connected)
00d6fd04 4275 "Like `file-remote-p' for Tramp files."
15cc764c
KG
4276 (when (tramp-tramp-file-p filename)
4277 (with-parsed-tramp-file-name filename nil
00d6fd04
MA
4278 (and (or (not connected)
4279 (let ((p (tramp-get-connection-process v)))
4280 (and p (processp p) (memq (process-status p) '(run open)))))
ce3f516f
MA
4281 (cond
4282 ((eq identification 'method) method)
4283 ((eq identification 'user) user)
4284 ((eq identification 'host) host)
8d60099b 4285 ((eq identification 'localname) localname)
ce3f516f 4286 (t (tramp-make-tramp-file-name method user host "")))))))
fb7933a3 4287
eb562962
MA
4288(defun tramp-find-file-name-coding-system-alist (filename tmpname)
4289 "Like `find-operation-coding-system' for Tramp filenames.
4290Tramp's `insert-file-contents' and `write-region' work over
4291temporary file names. If `file-coding-system-alist' contains an
4292expression, which matches more than the file name suffix, the
4293coding system might not be determined. This function repairs it."
4294 (let (result)
4295 (dolist (elt file-coding-system-alist result)
4296 (when (and (consp elt) (string-match (car elt) filename))
4297 ;; We found a matching entry in `file-coding-system-alist'.
4298 ;; So we add a similar entry, but with the temporary file name
4299 ;; as regexp.
4300 (add-to-list
4301 'result (cons (regexp-quote tmpname) (cdr elt)) 'append)))))
4302
fb7933a3
KG
4303(defun tramp-handle-insert-file-contents
4304 (filename &optional visit beg end replace)
00d6fd04 4305 "Like `insert-file-contents' for Tramp files."
fb7933a3
KG
4306 (barf-if-buffer-read-only)
4307 (setq filename (expand-file-name filename))
736ac90f 4308 (let (coding-system-used result local-copy remote-copy)
2ac33804
MA
4309 (with-parsed-tramp-file-name filename nil
4310 (unwind-protect
70c11b0b
MA
4311 (if (not (file-exists-p filename))
4312 ;; We don't raise a Tramp error, because it might be
4313 ;; suppressed, like in `find-file-noselect-1'.
4314 (signal 'file-error
4315 (list "File not found on remote host" filename))
4316
4317 (if (and (tramp-local-host-p v)
4318 (let (file-name-handler-alist)
4319 (file-readable-p localname)))
4320 ;; Short track: if we are on the local host, we can
4321 ;; run directly.
4322 (setq result
4323 (tramp-run-real-handler
4324 'insert-file-contents
4325 (list localname visit beg end replace)))
4326
736ac90f
MA
4327 ;; When we shall insert only a part of the file, we copy
4328 ;; this part.
4329 (when (or beg end)
4330 (setq remote-copy (tramp-make-tramp-temp-file v))
4331 (tramp-send-command
4332 v
4333 (cond
4334 ((and beg end)
4335 (format "tail -c +%d %s | head -c +%d >%s"
4336 (1+ beg) (tramp-shell-quote-argument localname)
4337 (- end beg) remote-copy))
4338 (beg
4339 (format "tail -c +%d %s >%s"
4340 (1+ beg) (tramp-shell-quote-argument localname)
4341 remote-copy))
4342 (end
4343 (format "head -c +%d %s >%s"
4344 (1+ end) (tramp-shell-quote-argument localname)
4345 remote-copy)))))
4346
70c11b0b
MA
4347 ;; `insert-file-contents-literally' takes care to avoid
4348 ;; calling jka-compr. By let-binding
4349 ;; `inhibit-file-name-operation', we propagate that care
4350 ;; to the `file-local-copy' operation.
4351 (setq local-copy
4352 (let ((inhibit-file-name-operation
4353 (when (eq inhibit-file-name-operation
4354 'insert-file-contents)
4355 'file-local-copy)))
736ac90f
MA
4356 (file-local-copy
4357 (if (stringp remote-copy)
4358 (tramp-make-tramp-file-name
4359 method user host remote-copy)
4360 filename))))
70c11b0b
MA
4361 (tramp-message
4362 v 4 "Inserting local temp file `%s'..." local-copy)
4363
4364 ;; We must ensure that `file-coding-system-alist'
4365 ;; matches `local-copy'.
4366 (let ((file-coding-system-alist
4367 (tramp-find-file-name-coding-system-alist
4368 filename local-copy)))
4369 (setq result
4370 (insert-file-contents
736ac90f 4371 local-copy nil nil nil replace))
70c11b0b
MA
4372 ;; Now `last-coding-system-used' has right value.
4373 ;; Remember it.
4374 (when (boundp 'last-coding-system-used)
4375 (setq coding-system-used
4376 (symbol-value 'last-coding-system-used))))
8d60099b 4377
70c11b0b
MA
4378 (tramp-message
4379 v 4 "Inserting local temp file `%s'...done" local-copy)
4380 (when (boundp 'last-coding-system-used)
2ac33804 4381 (set 'last-coding-system-used coding-system-used))))
70c11b0b 4382
2ac33804
MA
4383 ;; Save exit.
4384 (progn
4385 (when visit
4386 (setq buffer-file-name filename)
4387 (setq buffer-read-only (not (file-writable-p filename)))
4388 (set-visited-file-modtime)
4389 (set-buffer-modified-p nil))
4390 (when (stringp local-copy)
4391 (delete-file local-copy))
4392 (when (stringp remote-copy)
4393 (delete-file
4394 (tramp-make-tramp-file-name method user host remote-copy))))))
70c11b0b
MA
4395
4396 ;; Result.
4397 (list (expand-file-name filename)
4398 (cadr result))))
fb7933a3 4399
94be87e8
MA
4400;; This is needed for XEmacs only. Code stolen from files.el.
4401(defun tramp-handle-insert-file-contents-literally
4402 (filename &optional visit beg end replace)
4403 "Like `insert-file-contents-literally' for Tramp files."
4404 (let ((format-alist nil)
4405 (after-insert-file-functions nil)
4406 (coding-system-for-read 'no-conversion)
4407 (coding-system-for-write 'no-conversion)
4408 (find-buffer-file-type-function
4409 (if (fboundp 'find-buffer-file-type)
4410 (symbol-function 'find-buffer-file-type)
4411 nil))
4412 (inhibit-file-name-handlers '(jka-compr-handler image-file-handler))
4413 (inhibit-file-name-operation 'insert-file-contents))
4414 (unwind-protect
4415 (progn
4416 (fset 'find-buffer-file-type (lambda (filename) t))
4417 (insert-file-contents filename visit beg end replace))
70c11b0b 4418 ;; Save exit.
94be87e8
MA
4419 (if find-buffer-file-type-function
4420 (fset 'find-buffer-file-type find-buffer-file-type-function)
4421 (fmakunbound 'find-buffer-file-type)))))
4422
38c65fca 4423(defun tramp-handle-find-backup-file-name (filename)
00d6fd04 4424 "Like `find-backup-file-name' for Tramp files."
07dfe738
KG
4425 (with-parsed-tramp-file-name filename nil
4426 ;; We set both variables. It doesn't matter whether it is
4427 ;; Emacs or XEmacs
4428 (let ((backup-directory-alist
4429 ;; Emacs case
4430 (when (boundp 'backup-directory-alist)
b86c1cd8 4431 (if (symbol-value 'tramp-backup-directory-alist)
07dfe738
KG
4432 (mapcar
4433 '(lambda (x)
4434 (cons
4435 (car x)
4436 (if (and (stringp (cdr x))
4437 (file-name-absolute-p (cdr x))
4438 (not (tramp-file-name-p (cdr x))))
00d6fd04 4439 (tramp-make-tramp-file-name method user host (cdr x))
07dfe738
KG
4440 (cdr x))))
4441 (symbol-value 'tramp-backup-directory-alist))
4442 (symbol-value 'backup-directory-alist))))
4443
4444 (bkup-backup-directory-info
4445 ;; XEmacs case
4446 (when (boundp 'bkup-backup-directory-info)
b86c1cd8 4447 (if (symbol-value 'tramp-bkup-backup-directory-info)
07dfe738
KG
4448 (mapcar
4449 '(lambda (x)
4450 (nconc
4451 (list (car x))
4452 (list
4453 (if (and (stringp (car (cdr x)))
4454 (file-name-absolute-p (car (cdr x)))
4455 (not (tramp-file-name-p (car (cdr x)))))
4456 (tramp-make-tramp-file-name
00d6fd04 4457 method user host (car (cdr x)))
07dfe738
KG
4458 (car (cdr x))))
4459 (cdr (cdr x))))
4460 (symbol-value 'tramp-bkup-backup-directory-info))
4461 (symbol-value 'bkup-backup-directory-info)))))
4462
4463 (tramp-run-real-handler 'find-backup-file-name (list filename)))))
38c65fca 4464
c1105d05 4465(defun tramp-handle-make-auto-save-file-name ()
00d6fd04 4466 "Like `make-auto-save-file-name' for Tramp files.
c1105d05 4467Returns a file name in `tramp-auto-save-directory' for autosaving this file."
00d6fd04
MA
4468 (let ((tramp-auto-save-directory tramp-auto-save-directory)
4469 (buffer-file-name
4470 (tramp-subst-strs-in-string
4471 '(("_" . "|")
4472 ("/" . "_a")
4473 (":" . "_b")
4474 ("|" . "__")
4475 ("[" . "_l")
4476 ("]" . "_r"))
4477 (buffer-file-name))))
1a762140
MA
4478 ;; File name must be unique. This is ensured with Emacs 22 (see
4479 ;; UNIQUIFY element of `auto-save-file-name-transforms'); but for
4480 ;; all other cases we must do it ourselves.
4481 (when (boundp 'auto-save-file-name-transforms)
9e6ab520 4482 (mapc
1a762140
MA
4483 '(lambda (x)
4484 (when (and (string-match (car x) buffer-file-name)
4485 (not (car (cddr x))))
4486 (setq tramp-auto-save-directory
f3c071dd 4487 (or tramp-auto-save-directory
9e6ab520 4488 (tramp-compat-temporary-file-directory)))))
1a762140
MA
4489 (symbol-value 'auto-save-file-name-transforms)))
4490 ;; Create directory.
4491 (when tramp-auto-save-directory
00d6fd04
MA
4492 (setq buffer-file-name
4493 (expand-file-name buffer-file-name tramp-auto-save-directory))
1a762140
MA
4494 (unless (file-exists-p tramp-auto-save-directory)
4495 (make-directory tramp-auto-save-directory t)))
00d6fd04
MA
4496 ;; Run plain `make-auto-save-file-name'. There might be an advice when
4497 ;; it is not a magic file name operation (since Emacs 22).
4498 ;; We must deactivate it temporarily.
4499 (if (not (ad-is-active 'make-auto-save-file-name))
4500 (tramp-run-real-handler 'make-auto-save-file-name nil)
4501 ;; else
4502 (ad-deactivate 'make-auto-save-file-name)
4503 (prog1
4504 (tramp-run-real-handler 'make-auto-save-file-name nil)
4505 (ad-activate 'make-auto-save-file-name)))))
4506
4507(defvar tramp-handle-write-region-hook nil
4508 "Normal hook to be run at the end of `tramp-handle-write-region'.")
4509
4510;; CCC grok APPEND, LOCKNAME
fb7933a3
KG
4511(defun tramp-handle-write-region
4512 (start end filename &optional append visit lockname confirm)
00d6fd04 4513 "Like `write-region' for Tramp files."
fb7933a3 4514 (setq filename (expand-file-name filename))
c62c9d08 4515 (with-parsed-tramp-file-name filename nil
00d6fd04
MA
4516 (unless (null append)
4517 (tramp-error
4518 v 'file-error "Cannot append to file using Tramp (`%s')" filename))
4519 ;; Following part commented out because we don't know what to do about
4520 ;; file locking, and it does not appear to be a problem to ignore it.
4521 ;; Ange-ftp ignores it, too.
4522 ;; (when (and lockname (stringp lockname))
4523 ;; (setq lockname (expand-file-name lockname)))
4524 ;; (unless (or (eq lockname nil)
4525 ;; (string= lockname filename))
4526 ;; (error
4527 ;; "tramp-handle-write-region: LOCKNAME must be nil or equal FILENAME"))
8d60099b 4528
94be87e8 4529 ;; XEmacs takes a coding system as the seventh argument, not `confirm'.
00d6fd04
MA
4530 (when (and (not (featurep 'xemacs)) confirm (file-exists-p filename))
4531 (unless (y-or-n-p (format "File %s exists; overwrite anyway? " filename))
4532 (tramp-error v 'file-error "File not overwritten")))
8d60099b 4533
a4aeb9a4 4534 (let ((uid (or (nth 2 (tramp-compat-file-attributes filename 'integer))
9c13938d 4535 (tramp-get-remote-uid v 'integer)))
a4aeb9a4 4536 (gid (or (nth 3 (tramp-compat-file-attributes filename 'integer))
9c13938d
MA
4537 (tramp-get-remote-gid v 'integer))))
4538
4539 (if (and (tramp-local-host-p v)
93c3eb7c 4540 ;; `file-writable-p' calls `file-expand-file-name'. We
87bdd2c7
MA
4541 ;; cannot use `tramp-run-real-handler' therefore.
4542 (let (file-name-handler-alist)
82f3844e
MA
4543 (and
4544 (file-writable-p (file-name-directory localname))
4545 (or (file-directory-p localname)
4546 (file-writable-p localname)))))
9c13938d 4547 ;; Short track: if we are on the local host, we can run directly.
93c3eb7c
MA
4548 (progn
4549 (tramp-run-real-handler
4550 'write-region
4551 (list start end localname append 'no-message lockname confirm))
3e2fa353 4552 (tramp-flush-file-property v localname))
9c13938d
MA
4553
4554 (let ((rem-dec (tramp-get-remote-coding v "remote-decoding"))
4555 (loc-enc (tramp-get-local-coding v "local-encoding"))
b86c1cd8 4556 (modes (save-excursion (tramp-default-file-modes filename)))
9c13938d
MA
4557 ;; We use this to save the value of
4558 ;; `last-coding-system-used' after writing the tmp file.
4559 ;; At the end of the function, we set
4560 ;; `last-coding-system-used' to this saved value. This
4561 ;; way, any intermediary coding systems used while
4562 ;; talking to the remote shell or suchlike won't hose
4563 ;; this variable. This approach was snarfed from
4564 ;; ange-ftp.el.
4565 coding-system-used
4566 ;; Write region into a tmp file. This isn't really
4567 ;; needed if we use an encoding function, but currently
4568 ;; we use it always because this makes the logic
4569 ;; simpler.
4570 (tmpfile (tramp-compat-make-temp-file filename)))
4571
4572 ;; We say `no-message' here because we don't want the
4573 ;; visited file modtime data to be clobbered from the temp
4574 ;; file. We call `set-visited-file-modtime' ourselves later
eb562962
MA
4575 ;; on. We must ensure that `file-coding-system-alist'
4576 ;; matches `tmpfile'.
4577 (let ((file-coding-system-alist
4578 (tramp-find-file-name-coding-system-alist filename tmpfile)))
ce2cc728
MA
4579 (condition-case err
4580 (tramp-run-real-handler
4581 'write-region
4582 (list start end tmpfile append 'no-message lockname confirm))
2988341a
MA
4583 ((error quit)
4584 (delete-file tmpfile)
4585 (signal (car err) (cdr err))))
ce2cc728 4586
eb562962
MA
4587 ;; Now, `last-coding-system-used' has the right value. Remember it.
4588 (when (boundp 'last-coding-system-used)
4589 (setq coding-system-used
4590 (symbol-value 'last-coding-system-used))))
4591
9c13938d
MA
4592 ;; The permissions of the temporary file should be set. If
4593 ;; filename does not exist (eq modes nil) it has been
4594 ;; renamed to the backup file. This case `save-buffer'
4595 ;; handles permissions.
4596 (when modes (set-file-modes tmpfile modes))
4597
4598 ;; This is a bit lengthy due to the different methods
4599 ;; possible for file transfer. First, we check whether the
4600 ;; method uses an rcp program. If so, we call it.
4601 ;; Otherwise, both encoding and decoding command must be
4602 ;; specified. However, if the method _also_ specifies an
4603 ;; encoding function, then that is used for encoding the
4604 ;; contents of the tmp file.
4605 (cond
4606 ;; `rename-file' handles direct copy and out-of-band methods.
4607 ((or (tramp-local-host-p v)
4608 (and (tramp-method-out-of-band-p v)
1d7e9a01
MA
4609 (> (- (or end (point-max)) (or start (point-min)))
4610 tramp-copy-size-limit)))
ce2cc728
MA
4611 (condition-case err
4612 (rename-file tmpfile filename t)
2988341a
MA
4613 ((error quit)
4614 (delete-file tmpfile)
4615 (signal (car err) (cdr err)))))
9c13938d 4616
1d7e9a01 4617 ;; Use inline file transfer.
9c13938d 4618 (rem-dec
1d7e9a01 4619 ;; Encode tmpfile.
9c13938d
MA
4620 (tramp-message v 5 "Encoding region...")
4621 (unwind-protect
4622 (with-temp-buffer
4623 ;; Use encoding function or command.
4624 (if (and (symbolp loc-enc) (fboundp loc-enc))
4625 (progn
4626 (tramp-message
4627 v 5 "Encoding region using function `%s'..."
4628 (symbol-name loc-enc))
4629 (let ((coding-system-for-read 'binary))
4630 (insert-file-contents-literally tmpfile))
70c11b0b
MA
4631 ;; The following `let' is a workaround for the
4632 ;; base64.el that comes with pgnus-0.84. If
4633 ;; both of the following conditions are
4634 ;; satisfied, it tries to write to a local
4635 ;; file in default-directory, but at this
4636 ;; point, default-directory is remote.
4637 ;; (`call-process-region' can't write to
4638 ;; remote files, it seems.) The file in
4639 ;; question is a tmp file anyway.
9c13938d
MA
4640 (let ((default-directory
4641 (tramp-compat-temporary-file-directory)))
4642 (funcall loc-enc (point-min) (point-max))))
8d60099b 4643
9c13938d
MA
4644 (tramp-message
4645 v 5 "Encoding region using command `%s'..." loc-enc)
4646 (unless (equal 0 (tramp-call-local-coding-command
4647 loc-enc tmpfile t))
4648 (tramp-error
4649 v 'file-error
4650 "Cannot write to `%s', local encoding command `%s' failed"
4651 filename loc-enc)))
4652
4653 ;; Send buffer into remote decoding command which
4654 ;; writes to remote file. Because this happens on
4655 ;; the remote host, we cannot use the function.
4656 (goto-char (point-max))
4657 (unless (bolp) (newline))
8d60099b 4658 (tramp-message
9c13938d
MA
4659 v 5 "Decoding region into remote file %s..." filename)
4660 (tramp-send-command
4661 v
4662 (format
4663 "%s >%s <<'EOF'\n%sEOF"
4664 rem-dec
4665 (tramp-shell-quote-argument localname)
4666 (buffer-string)))
4667 (tramp-barf-unless-okay
4668 v nil
4669 "Couldn't write region to `%s', decode using `%s' failed"
4670 filename rem-dec)
4671 ;; When `file-precious-flag' is set, the region is
4672 ;; written to a temporary file. Check that the
4673 ;; checksum is equal to that from the local tmpfile.
4674 (when file-precious-flag
4675 (erase-buffer)
4676 (and
a4aeb9a4
MA
4677 ;; cksum runs locally, if possible.
4678 (zerop (tramp-local-call-process "cksum" tmpfile t))
4679 ;; cksum runs remotely.
9c13938d
MA
4680 (zerop
4681 (tramp-send-command-and-check
4682 v
4683 (format
4684 "cksum <%s" (tramp-shell-quote-argument localname))))
a4aeb9a4 4685 ;; ... they are different.
9c13938d
MA
4686 (not
4687 (string-equal
4688 (buffer-string)
4689 (with-current-buffer (tramp-get-buffer v)
4690 (buffer-string))))
4691 (tramp-error
4692 v 'file-error
4693 (concat "Couldn't write region to `%s',"
4694 " decode using `%s' failed")
4695 filename rem-dec)))
4696 (tramp-message
4697 v 5 "Decoding region into remote file %s...done" filename)
4698 (tramp-flush-file-property v localname))
8d60099b 4699
9c13938d
MA
4700 ;; Save exit.
4701 (delete-file tmpfile)))
8d60099b 4702
9c13938d
MA
4703 ;; That's not expected.
4704 (t
4705 (tramp-error
4706 v 'file-error
4707 (concat "Method `%s' should specify both encoding and "
4708 "decoding command or an rcp program")
4709 method)))
258800f8 4710
9c13938d
MA
4711 ;; Make `last-coding-system-used' have the right value.
4712 (when coding-system-used
4713 (set 'last-coding-system-used coding-system-used))))
0f205eee 4714
57671b72
MA
4715 ;; We must protect `last-coding-system-used', now we have set it
4716 ;; to its correct value.
4717 (let (last-coding-system-used)
4718 ;; Set file modification time.
4719 (when (or (eq visit t) (stringp visit))
4720 (set-visited-file-modtime
4721 ;; We must pass modtime explicitely, because filename can
4722 ;; be different from (buffer-file-name), f.e. if
4723 ;; `file-precious-flag' is set.
4724 (nth 5 (file-attributes filename))))
4725
4726 ;; Set the ownership.
4727 (tramp-set-file-uid-gid filename uid gid)
4728 (when (or (eq visit t) (null visit) (stringp visit))
4729 (tramp-message v 0 "Wrote %s" filename))
4730 (run-hooks 'tramp-handle-write-region-hook)))))
fb7933a3 4731
946a5aeb
MA
4732(defvar tramp-vc-registered-file-names nil
4733 "List used to collect file names, which are checked during `vc-registered'.")
4734
4735;; VC backends check for the existence of various different special
4736;; files. This is very time consuming, because every single check
4737;; requires a remote command (the file cache must be invalidated).
4738;; Therefore, we apply a kind of optimization. We install the file
4739;; name handler `tramp-vc-file-name-handler', which does nothing but
4740;; remembers all file names for which `file-exists-p' or
4741;; `file-readable-p' has been applied. A first run of `vc-registered'
4742;; is performed. Afterwards, a script is applied for all collected
4743;; file names, using just one remote command. The result of this
4744;; script is used to fill the file cache with actual values. Now we
4745;; can reset the file name handlers, and we make a second run of
4746;; `vc-registered', which returns the expected result without sending
4747;; any other remote command.
49096407
MA
4748(defun tramp-handle-vc-registered (file)
4749 "Like `vc-registered' for Tramp files."
946a5aeb
MA
4750 ;; There could be new files, created by the vc backend. We cannot
4751 ;; reuse the old cache entries, therefore.
4752 (with-parsed-tramp-file-name file nil
4753 (let (tramp-vc-registered-file-names
4754 (tramp-cache-inhibit-cache (current-time))
4755 (file-name-handler-alist
4756 `((,tramp-file-name-regexp . tramp-vc-file-name-handler))))
4757
4758 ;; Here we collect only file names, which need an operation.
4759 (tramp-run-real-handler 'vc-registered (list file))
4760 (tramp-message v 10 "\n%s" tramp-vc-registered-file-names)
4761
4762 ;; Send just one command, in order to fill the cache.
4763 (tramp-maybe-send-script
4764 v
4765 (format tramp-vc-registered-read-file-names
4766 (tramp-get-file-exists-command v)
4767 (format "%s -r" (tramp-get-test-command v)))
4768 "tramp_vc_registered_read_file_names")
4769
4770 (dolist
4771 (elt
4772 (tramp-send-command-and-read
4773 v
4774 (format
4775 "tramp_vc_registered_read_file_names %s"
4776 (mapconcat 'tramp-shell-quote-argument
4777 tramp-vc-registered-file-names
4778 " "))))
4779
4780 (tramp-set-file-property v (car elt) (cadr elt) (cadr (cdr elt)))))
4781
4782 ;; Second run. Now all requests shall be answered from the file
4783 ;; cache. We unset `process-file-side-effects' in order to keep
4784 ;; the cache when `process-file' calls appear.
4785 (let (process-file-side-effects)
4786 (tramp-run-real-handler 'vc-registered (list file)))))
49096407 4787
a01b1e22
MA
4788;;;###autoload
4789(progn (defun tramp-run-real-handler (operation args)
fb7933a3 4790 "Invoke normal file name handler for OPERATION.
c62c9d08
KG
4791First arg specifies the OPERATION, second arg is a list of arguments to
4792pass to the OPERATION."
4007ba5b
KG
4793 (let* ((inhibit-file-name-handlers
4794 `(tramp-file-name-handler
946a5aeb 4795 tramp-vc-file-name-handler
4007ba5b
KG
4796 tramp-completion-file-name-handler
4797 cygwin-mount-name-hook-function
4798 cygwin-mount-map-drive-hook-function
4799 .
4800 ,(and (eq inhibit-file-name-operation operation)
4801 inhibit-file-name-handlers)))
4802 (inhibit-file-name-operation operation))
a01b1e22 4803 (apply operation args))))
16674e4f 4804
a01b1e22
MA
4805;;;###autoload
4806(progn (defun tramp-completion-run-real-handler (operation args)
16674e4f
KG
4807 "Invoke `tramp-file-name-handler' for OPERATION.
4808First arg specifies the OPERATION, second arg is a list of arguments to
4809pass to the OPERATION."
4007ba5b
KG
4810 (let* ((inhibit-file-name-handlers
4811 `(tramp-completion-file-name-handler
4812 cygwin-mount-name-hook-function
4813 cygwin-mount-map-drive-hook-function
4814 .
4815 ,(and (eq inhibit-file-name-operation operation)
4816 inhibit-file-name-handlers)))
4817 (inhibit-file-name-operation operation))
a01b1e22 4818 (apply operation args))))
fb7933a3 4819
4007ba5b
KG
4820;; We handle here all file primitives. Most of them have the file
4821;; name as first parameter; nevertheless we check for them explicitly
04bf5b65 4822;; in order to be signaled if a new primitive appears. This
4007ba5b
KG
4823;; scenario is needed because there isn't a way to decide by
4824;; syntactical means whether a foreign method must be called. It would
19a87064 4825;; ease the life if `file-name-handler-alist' would support a decision
4007ba5b
KG
4826;; function as well but regexp only.
4827(defun tramp-file-name-for-operation (operation &rest args)
4828 "Return file name related to OPERATION file primitive.
4829ARGS are the arguments OPERATION has been called with."
4830 (cond
4831 ; FILE resp DIRECTORY
4832 ((member operation
4833 (list 'access-file 'byte-compiler-base-file-name 'delete-directory
4834 'delete-file 'diff-latest-backup-file 'directory-file-name
4835 'directory-files 'directory-files-and-attributes
4836 'dired-compress-file 'dired-uncache
4837 'file-accessible-directory-p 'file-attributes
4838 'file-directory-p 'file-executable-p 'file-exists-p
19a87064
MA
4839 'file-local-copy 'file-remote-p 'file-modes
4840 'file-name-as-directory 'file-name-directory
4841 'file-name-nondirectory 'file-name-sans-versions
4842 'file-ownership-preserved-p 'file-readable-p
4843 'file-regular-p 'file-symlink-p 'file-truename
4844 'file-writable-p 'find-backup-file-name 'find-file-noselect
4845 'get-file-buffer 'insert-directory 'insert-file-contents
4846 'load 'make-directory 'make-directory-internal
4847 'set-file-modes 'substitute-in-file-name
4848 'unhandled-file-name-directory 'vc-registered
ce3f516f
MA
4849 ; Emacs 22 only
4850 'set-file-times
4007ba5b
KG
4851 ; XEmacs only
4852 'abbreviate-file-name 'create-file-buffer
4853 'dired-file-modtime 'dired-make-compressed-filename
4854 'dired-recursive-delete-directory 'dired-set-file-modtime
4855 'dired-shell-unhandle-file-name 'dired-uucode-file
5615d63f 4856 'insert-file-contents-literally 'make-temp-name 'recover-file
4007ba5b 4857 'vm-imap-check-mail 'vm-pop-check-mail 'vm-spool-check-mail))
8daea7fc
KG
4858 (if (file-name-absolute-p (nth 0 args))
4859 (nth 0 args)
4860 (expand-file-name (nth 0 args))))
4007ba5b
KG
4861 ; FILE DIRECTORY resp FILE1 FILE2
4862 ((member operation
4863 (list 'add-name-to-file 'copy-file 'expand-file-name
4864 'file-name-all-completions 'file-name-completion
4865 'file-newer-than-file-p 'make-symbolic-link 'rename-file
4866 ; XEmacs only
4867 'dired-make-relative-symlink
4868 'vm-imap-move-mail 'vm-pop-move-mail 'vm-spool-move-mail))
4869 (save-match-data
4870 (cond
4871 ((string-match tramp-file-name-regexp (nth 0 args)) (nth 0 args))
4872 ((string-match tramp-file-name-regexp (nth 1 args)) (nth 1 args))
4873 (t (buffer-file-name (current-buffer))))))
4874 ; START END FILE
4875 ((eq operation 'write-region)
4876 (nth 2 args))
4877 ; BUF
4878 ((member operation
00d6fd04 4879 (list 'set-visited-file-modtime 'verify-visited-file-modtime
b50dd0d2 4880 ; since Emacs 22 only
00d6fd04
MA
4881 'make-auto-save-file-name
4882 ; XEmacs only
4007ba5b
KG
4883 'backup-buffer))
4884 (buffer-file-name
4885 (if (bufferp (nth 0 args)) (nth 0 args) (current-buffer))))
4886 ; COMMAND
4887 ((member operation
00d6fd04
MA
4888 (list ; not in Emacs 23
4889 'dired-call-process
01917a18 4890 ; Emacs only
b71c9e75 4891 'shell-command
00d6fd04 4892 ; since Emacs 22 only
0457dd55 4893 'process-file
00d6fd04
MA
4894 ; since Emacs 23 only
4895 'start-file-process
4007ba5b 4896 ; XEmacs only
00d6fd04
MA
4897 'dired-print-file 'dired-shell-call-process
4898 ; nowhere yet
4899 'executable-find 'start-process 'call-process))
4007ba5b
KG
4900 default-directory)
4901 ; unknown file primitive
4902 (t (error "unknown file I/O primitive: %s" operation))))
4903
4904(defun tramp-find-foreign-file-name-handler (filename)
4905 "Return foreign file name handler if exists."
9ce8462a
MA
4906 (when (and (stringp filename) (tramp-tramp-file-p filename))
4907 (let ((v (tramp-dissect-file-name filename t))
4908 (handler tramp-foreign-file-name-handler-alist)
4909 elt res)
4910 ;; When we are not fully sure that filename completion is safe,
4911 ;; we should not return a handler.
4912 (when (or (tramp-file-name-method v) (tramp-file-name-user v)
1834b39f
MA
4913 (and (tramp-file-name-host v)
4914 (not (member (tramp-file-name-host v)
4915 (mapcar 'car tramp-methods))))
9ce8462a
MA
4916 (not (tramp-completion-mode-p)))
4917 (while handler
4918 (setq elt (car handler)
4919 handler (cdr handler))
4920 (when (funcall (car elt) filename)
4921 (setq handler nil
4922 res (cdr elt))))
4923 res))))
4007ba5b 4924
fb7933a3
KG
4925;; Main function.
4926;;;###autoload
4927(defun tramp-file-name-handler (operation &rest args)
ea9d1443 4928 "Invoke Tramp file name handler.
a4aeb9a4 4929Falls back to normal file name handler if no Tramp file name handler exists."
2e271195
MA
4930 (if tramp-mode
4931 (save-match-data
4932 (let* ((filename
4933 (tramp-replace-environment-variables
4934 (apply 'tramp-file-name-for-operation operation args)))
4935 (completion (tramp-completion-mode-p))
4936 (foreign (tramp-find-foreign-file-name-handler filename)))
4937 (with-parsed-tramp-file-name filename nil
4938 (cond
4939 ;; When we are in completion mode, some operations
4940 ;; shouldn't be handled by backend.
4941 ((and completion (zerop (length localname))
4942 (memq operation '(file-exists-p file-directory-p)))
4943 t)
4944 ((and completion (zerop (length localname))
4945 (memq operation '(file-name-as-directory)))
4946 filename)
4947 ;; Call the backend function.
4948 (foreign (apply foreign operation args))
4949 ;; Nothing to do for us.
4950 (t (tramp-run-real-handler operation args))))))
4951 ;; When `tramp-mode' is not enabled, we don't do anything.
4952 (tramp-run-real-handler operation args)))
fb7933a3 4953
07dfe738
KG
4954;; In Emacs, there is some concurrency due to timers. If a timer
4955;; interrupts Tramp and wishes to use the same connection buffer as
4956;; the "main" Emacs, then garbage might occur in the connection
4957;; buffer. Therefore, we need to make sure that a timer does not use
4958;; the same connection buffer as the "main" Emacs. We implement a
4959;; cheap global lock, instead of locking each connection buffer
4960;; separately. The global lock is based on two variables,
4961;; `tramp-locked' and `tramp-locker'. `tramp-locked' is set to true
4962;; (with setq) to indicate a lock. But Tramp also calls itself during
4963;; processing of a single file operation, so we need to allow
4964;; recursive calls. That's where the `tramp-locker' variable comes in
4965;; -- it is let-bound to t during the execution of the current
4966;; handler. So if `tramp-locked' is t and `tramp-locker' is also t,
4967;; then we should just proceed because we have been called
4968;; recursively. But if `tramp-locker' is nil, then we are a timer
4969;; interrupting the "main" Emacs, and then we signal an error.
4970
4971(defvar tramp-locked nil
4972 "If non-nil, then Tramp is currently busy.
4973Together with `tramp-locker', this implements a locking mechanism
4974preventing reentrant calls of Tramp.")
4975
4976(defvar tramp-locker nil
4977 "If non-nil, then a caller has locked Tramp.
4978Together with `tramp-locked', this implements a locking mechanism
4979preventing reentrant calls of Tramp.")
4980
ea9d1443
KG
4981(defun tramp-sh-file-name-handler (operation &rest args)
4982 "Invoke remote-shell Tramp file name handler.
4983Fall back to normal file name handler if no Tramp handler exists."
07dfe738 4984 (when (and tramp-locked (not tramp-locker))
11c71217 4985 (setq tramp-locked nil)
00d6fd04 4986 (signal 'file-error (list "Forbidden reentrant call of Tramp")))
07dfe738
KG
4987 (let ((tl tramp-locked))
4988 (unwind-protect
4989 (progn
4990 (setq tramp-locked t)
4991 (let ((tramp-locker t))
4992 (save-match-data
4993 (let ((fn (assoc operation tramp-file-name-handler-alist)))
4994 (if fn
4995 (apply (cdr fn) args)
4996 (tramp-run-real-handler operation args))))))
4997 (setq tramp-locked tl))))
ea9d1443 4998
946a5aeb
MA
4999(defun tramp-vc-file-name-handler (operation &rest args)
5000 "Invoke special file name handler, which collects files to be handled."
5001 (save-match-data
5002 (let ((filename
5003 (tramp-replace-environment-variables
5004 (apply 'tramp-file-name-for-operation operation args)))
5005 (fn (assoc operation tramp-file-name-handler-alist)))
5006 (with-parsed-tramp-file-name filename nil
5007 (cond
5008 ;; That's what we want: file names, for which checks are
5009 ;; applied. We assume, that VC uses only `file-exists-p' and
5010 ;; `file-readable-p' checks; otherwise we must extend the
5011 ;; list. We do not perform any action, but return nil, in
5012 ;; order to keep `vc-registered' running.
5013 ((and fn (memq operation '(file-exists-p file-readable-p)))
5014 (add-to-list 'tramp-vc-registered-file-names localname 'append)
5015 nil)
5016 ;; Tramp file name handlers like `expand-file-name'. They
5017 ;; must still work.
5018 (fn
5019 (save-match-data (apply (cdr fn) args)))
5020 ;; Default file name handlers, we don't care.
5021 (t (tramp-run-real-handler operation args)))))))
5022
16674e4f 5023;;;###autoload
1ecc6145 5024(progn (defun tramp-completion-file-name-handler (operation &rest args)
a4aeb9a4
MA
5025 "Invoke Tramp file name completion handler.
5026Falls back to normal file name handler if no Tramp file name handler exists."
57671b72
MA
5027 ;; We bind `directory-sep-char' here for XEmacs on Windows, which
5028 ;; would otherwise use backslash.
aff67808
MA
5029 (let ((directory-sep-char ?/)
5030 (fn (assoc operation tramp-completion-file-name-handler-alist)))
2e271195
MA
5031 ;; When `tramp-mode' is not enabled, we don't do anything.
5032 (if (and fn tramp-mode)
aff67808
MA
5033 (save-match-data (apply (cdr fn) args))
5034 (tramp-completion-run-real-handler operation args)))))
a01b1e22 5035
b25a52cc 5036;;;###autoload
69cee873 5037(defsubst tramp-register-file-name-handler ()
a4aeb9a4 5038 "Add Tramp file name handler to `file-name-handler-alist'."
00d6fd04
MA
5039 ;; Remove autoloaded handler from file name handler alist. Useful,
5040 ;; if `tramp-syntax' has been changed.
5041 (let ((a1 (rassq 'tramp-file-name-handler file-name-handler-alist)))
5042 (setq file-name-handler-alist (delete a1 file-name-handler-alist)))
5043 ;; Add the handler.
a01b1e22
MA
5044 (add-to-list 'file-name-handler-alist
5045 (cons tramp-file-name-regexp 'tramp-file-name-handler))
69cee873
MA
5046 ;; If jka-compr is already loaded, move it to the front of
5047 ;; `file-name-handler-alist'.
5048 (let ((jka (rassoc 'jka-compr-handler file-name-handler-alist)))
5049 (when jka
5050 (setq file-name-handler-alist
5051 (cons jka (delete jka file-name-handler-alist))))))
5052
00d6fd04
MA
5053;; `tramp-file-name-handler' must be registered before evaluation of
5054;; site-start and init files, because there might exist remote files
5055;; already, f.e. files kept via recentf-mode.
5056;;;###autoload(tramp-register-file-name-handler)
5057(tramp-register-file-name-handler)
5058
69cee873
MA
5059;;;###autoload
5060(defsubst tramp-register-completion-file-name-handler ()
a4aeb9a4 5061 "Add Tramp completion file name handler to `file-name-handler-alist'."
00d6fd04
MA
5062 ;; Remove autoloaded handler from file name handler alist. Useful,
5063 ;; if `tramp-syntax' has been changed.
5064 (let ((a1 (rassq
5065 'tramp-completion-file-name-handler file-name-handler-alist)))
5066 (setq file-name-handler-alist (delete a1 file-name-handler-alist)))
56c195af
MA
5067 ;; In XEmacs, there is another Tramp syntax, so we can enable this
5068 ;; unconditionally. In GNU Emacs <= 22, method/user/host name
5069 ;; completion shall be bound to `partial-completion-mode'. Starting
5070 ;; with GNU Emacs 23, this is replaced by `completion-styles',
5071 ;; containing symbol `partial-completion'. `ido-mode' and
5072 ;; `icy-mode' are other packages which extend file name completion.
5073 (when (or (and (boundp 'partial-completion-mode)
5074 (symbol-value 'partial-completion-mode))
5075 (and (boundp 'completion-styles)
5076 (member 'partial-completion (symbol-value 'completion-styles)))
5077 (featurep 'xemacs)
9e6ab520
MA
5078 (featurep 'ido)
5079 (featurep 'icicles))
8c04e197
MA
5080 (add-to-list 'file-name-handler-alist
5081 (cons tramp-completion-file-name-regexp
5082 'tramp-completion-file-name-handler))
a01b1e22
MA
5083 (put 'tramp-completion-file-name-handler 'safe-magic t))
5084 ;; If jka-compr is already loaded, move it to the front of
5085 ;; `file-name-handler-alist'.
5086 (let ((jka (rassoc 'jka-compr-handler file-name-handler-alist)))
5087 (when jka
5088 (setq file-name-handler-alist
5089 (cons jka (delete jka file-name-handler-alist))))))
5090
5091;; During autoload, it shall be checked whether
2ac33804 5092;; `partial-completion-mode' is active. Therefore, registering of
69cee873 5093;; `tramp-completion-file-name-handler' will be delayed.
8c04e197 5094;;;###autoload(add-hook
1ecc6145 5095;;;###autoload 'after-init-hook
343bb7bd 5096;;;###autoload 'tramp-register-completion-file-name-handler)
69cee873 5097(tramp-register-completion-file-name-handler)
b25a52cc 5098
fb7933a3 5099;;;###autoload
8c04e197 5100(defun tramp-unload-file-name-handlers ()
a69c01a0
MA
5101 (setq file-name-handler-alist
5102 (delete (rassoc 'tramp-file-name-handler
5103 file-name-handler-alist)
5104 (delete (rassoc 'tramp-completion-file-name-handler
5105 file-name-handler-alist)
5106 file-name-handler-alist))))
5107
8c04e197 5108(add-hook 'tramp-unload-hook 'tramp-unload-file-name-handlers)
a69c01a0 5109
0664ff72 5110;;; File name handler functions for completion mode:
a6e96327
MA
5111
5112(defvar tramp-completion-mode nil
5113 "If non-nil, external packages signal that they are in file name completion.
5114
5115This is necessary, because Tramp uses a heuristic depending on last
5116input event. This fails when external packages use other characters
5117but <TAB>, <SPACE> or ?\\? for file name completion. This variable
5118should never be set globally, the intention is to let-bind it.")
16674e4f
KG
5119
5120;; Necessary because `tramp-file-name-regexp-unified' and
00d6fd04
MA
5121;; `tramp-completion-file-name-regexp-unified' aren't different. If
5122;; nil, `tramp-completion-run-real-handler' is called (i.e. forwarding
5123;; to `tramp-file-name-handler'). Otherwise, it takes
5124;; `tramp-run-real-handler'. Using `last-input-event' is a little bit
5125;; risky, because completing a file might require loading other files,
5126;; like "~/.netrc", and for them it shouldn't be decided based on that
5127;; variable. On the other hand, those files shouldn't have partial
a4aeb9a4
MA
5128;; Tramp file name syntax. Maybe another variable should be introduced
5129;; overwriting this check in such cases. Or we change Tramp file name
00d6fd04 5130;; syntax in order to avoid ambiguities, like in XEmacs ...
6c4e47fa 5131(defun tramp-completion-mode-p ()
16674e4f 5132 "Checks whether method / user name / host name completion is active."
6c4e47fa 5133 (or
a6e96327
MA
5134 ;; Signal from outside.
5135 tramp-completion-mode
5136 ;; Emacs.
94be87e8 5137 (equal last-input-event 'tab)
6c4e47fa 5138 (and (natnump last-input-event)
94be87e8 5139 (or
a6e96327 5140 ;; ?\t has event-modifier 'control.
800a97b8 5141 (equal last-input-event ?\t)
94be87e8 5142 (and (not (event-modifiers last-input-event))
800a97b8
SM
5143 (or (equal last-input-event ?\?)
5144 (equal last-input-event ?\ )))))
a6e96327 5145 ;; XEmacs.
6c4e47fa
MA
5146 (and (featurep 'xemacs)
5147 ;; `last-input-event' might be nil.
5148 (not (null last-input-event))
5149 ;; `last-input-event' may have no character approximation.
5150 (funcall (symbol-function 'event-to-character) last-input-event)
94be87e8 5151 (or
a6e96327 5152 ;; ?\t has event-modifier 'control.
800a97b8 5153 (equal
94be87e8
MA
5154 (funcall (symbol-function 'event-to-character)
5155 last-input-event) ?\t)
5156 (and (not (event-modifiers last-input-event))
800a97b8 5157 (or (equal
94be87e8
MA
5158 (funcall (symbol-function 'event-to-character)
5159 last-input-event) ?\?)
800a97b8 5160 (equal
94be87e8
MA
5161 (funcall (symbol-function 'event-to-character)
5162 last-input-event) ?\ )))))))
16674e4f 5163
16674e4f
KG
5164;; Method, host name and user name completion.
5165;; `tramp-completion-dissect-file-name' returns a list of
5166;; tramp-file-name structures. For all of them we return possible completions.
a01b1e22 5167;;;###autoload
16674e4f 5168(defun tramp-completion-handle-file-name-all-completions (filename directory)
00d6fd04 5169 "Like `file-name-all-completions' for partial Tramp files."
16674e4f 5170
00d6fd04
MA
5171 (let* ((fullname (tramp-drop-volume-letter
5172 (expand-file-name filename directory)))
5173 ;; Possible completion structures.
5174 (v (tramp-completion-dissect-file-name fullname))
5175 result result1)
5176
5177 (while v
5178 (let* ((car (car v))
5179 (method (tramp-file-name-method car))
5180 (user (tramp-file-name-user car))
5181 (host (tramp-file-name-host car))
5182 (localname (tramp-file-name-localname car))
5183 (m (tramp-find-method method user host))
5184 (tramp-current-user user) ; see `tramp-parse-passwd'
5185 all-user-hosts)
5186
5187 (unless localname ;; Nothing to complete.
5188
5189 (if (or user host)
5190
5191 ;; Method dependent user / host combinations.
5192 (progn
9e6ab520 5193 (mapc
00d6fd04
MA
5194 (lambda (x)
5195 (setq all-user-hosts
5196 (append all-user-hosts
5197 (funcall (nth 0 x) (nth 1 x)))))
5198 (tramp-get-completion-function m))
5199
9e6ab520
MA
5200 (setq result
5201 (append result
5202 (mapcar
5203 (lambda (x)
5204 (tramp-get-completion-user-host
5205 method user host (nth 0 x) (nth 1 x)))
5206 (delq nil all-user-hosts)))))
00d6fd04
MA
5207
5208 ;; Possible methods.
5209 (setq result
5210 (append result (tramp-get-completion-methods m)))))
5211
5212 (setq v (cdr v))))
5213
5214 ;; Unify list, remove nil elements.
5215 (while result
5216 (let ((car (car result)))
5217 (when car
5218 (add-to-list
5219 'result1
5220 (substring car (length (tramp-drop-volume-letter directory)))))
5221 (setq result (cdr result))))
5222
5223 ;; Complete local parts.
5224 (append
5225 result1
5226 (condition-case nil
5227 (tramp-completion-run-real-handler
5228 'file-name-all-completions (list filename directory))
5229 (error nil)))))
16674e4f
KG
5230
5231;; Method, host name and user name completion for a file.
a01b1e22 5232;;;###autoload
e1e17cae
MA
5233(defun tramp-completion-handle-file-name-completion
5234 (filename directory &optional predicate)
00d6fd04 5235 "Like `file-name-completion' for Tramp files."
e1e17cae
MA
5236 (try-completion
5237 filename
5238 (mapcar 'list (file-name-all-completions filename directory))
83e20b5c
MA
5239 (when predicate
5240 (lambda (x) (funcall predicate (expand-file-name (car x) directory))))))
16674e4f
KG
5241
5242;; I misuse a little bit the tramp-file-name structure in order to handle
5243;; completion possibilities for partial methods / user names / host names.
5244;; Return value is a list of tramp-file-name structures according to possible
00d6fd04 5245;; completions. If "localname" is non-nil it means there
16674e4f
KG
5246;; shouldn't be a completion anymore.
5247
5248;; Expected results:
5249
00d6fd04
MA
5250;; "/x" "/[x" "/x@" "/[x@" "/x@y" "/[x@y"
5251;; [nil nil "x" nil] [nil "x" nil nil] [nil "x" "y" nil]
5252;; [nil "x" nil nil]
5253;; ["x" nil nil nil]
5254
5255;; "/x:" "/x:y" "/x:y:"
5256;; [nil nil "x" ""] [nil nil "x" "y"] ["x" nil "y" ""]
5257;; "/[x/" "/[x/y"
5258;; ["x" nil "" nil] ["x" nil "y" nil]
5259;; ["x" "" nil nil] ["x" "y" nil nil]
5260
5261;; "/x:y@" "/x:y@z" "/x:y@z:"
5262;; [nil nil "x" "y@"] [nil nil "x" "y@z"] ["x" "y" "z" ""]
5263;; "/[x/y@" "/[x/y@z"
5264;; ["x" nil "y" nil] ["x" "y" "z" nil]
16674e4f
KG
5265(defun tramp-completion-dissect-file-name (name)
5266 "Returns a list of `tramp-file-name' structures.
5267They are collected by `tramp-completion-dissect-file-name1'."
5268
5269 (let* ((result)
4007ba5b 5270 (x-nil "\\|\\(\\)")
b96e6899
MA
5271 (tramp-completion-ipv6-regexp
5272 (format
5273 "[^%s]*"
5274 (if (zerop (length tramp-postfix-ipv6-format))
5275 tramp-postfix-host-format
5276 tramp-postfix-ipv6-format)))
4007ba5b
KG
5277 ;; "/method" "/[method"
5278 (tramp-completion-file-name-structure1
5279 (list (concat tramp-prefix-regexp "\\(" tramp-method-regexp x-nil "\\)$")
5280 1 nil nil nil))
5281 ;; "/user" "/[user"
5282 (tramp-completion-file-name-structure2
5283 (list (concat tramp-prefix-regexp "\\(" tramp-user-regexp x-nil "\\)$")
5284 nil 1 nil nil))
5285 ;; "/host" "/[host"
5286 (tramp-completion-file-name-structure3
5287 (list (concat tramp-prefix-regexp "\\(" tramp-host-regexp x-nil "\\)$")
5288 nil nil 1 nil))
b96e6899 5289 ;; "/[ipv6" "/[ipv6"
4007ba5b 5290 (tramp-completion-file-name-structure4
b96e6899
MA
5291 (list (concat tramp-prefix-regexp
5292 tramp-prefix-ipv6-regexp
5293 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
5294 nil nil 1 nil))
5295 ;; "/user@host" "/[user@host"
5296 (tramp-completion-file-name-structure5
4007ba5b
KG
5297 (list (concat tramp-prefix-regexp
5298 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
5299 "\\(" tramp-host-regexp x-nil "\\)$")
5300 nil 1 2 nil))
b96e6899
MA
5301 ;; "/user@[ipv6" "/[user@ipv6"
5302 (tramp-completion-file-name-structure6
5303 (list (concat tramp-prefix-regexp
5304 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
5305 tramp-prefix-ipv6-regexp
5306 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
5307 nil 1 2 nil))
00d6fd04 5308 ;; "/method:user" "/[method/user" "/method://user"
b96e6899 5309 (tramp-completion-file-name-structure7
4007ba5b 5310 (list (concat tramp-prefix-regexp
00d6fd04 5311 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
4007ba5b
KG
5312 "\\(" tramp-user-regexp x-nil "\\)$")
5313 1 2 nil nil))
00d6fd04 5314 ;; "/method:host" "/[method/host" "/method://host"
b96e6899 5315 (tramp-completion-file-name-structure8
4007ba5b 5316 (list (concat tramp-prefix-regexp
00d6fd04 5317 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
4007ba5b
KG
5318 "\\(" tramp-host-regexp x-nil "\\)$")
5319 1 nil 2 nil))
b96e6899
MA
5320 ;; "/method:[ipv6" "/[method/ipv6" "/method://[ipv6"
5321 (tramp-completion-file-name-structure9
5322 (list (concat tramp-prefix-regexp
5323 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
5324 tramp-prefix-ipv6-regexp
5325 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
5326 1 nil 2 nil))
00d6fd04 5327 ;; "/method:user@host" "/[method/user@host" "/method://user@host"
b96e6899 5328 (tramp-completion-file-name-structure10
4007ba5b 5329 (list (concat tramp-prefix-regexp
00d6fd04 5330 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
4007ba5b
KG
5331 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
5332 "\\(" tramp-host-regexp x-nil "\\)$")
00d6fd04 5333 1 2 3 nil))
b96e6899
MA
5334 ;; "/method:user@[ipv6" "/[method/user@ipv6" "/method://user@[ipv6"
5335 (tramp-completion-file-name-structure11
5336 (list (concat tramp-prefix-regexp
5337 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
5338 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
5339 tramp-prefix-ipv6-regexp
5340 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
5341 1 2 3 nil))
00d6fd04 5342 ;; "/method: "/method:/"
b96e6899 5343 (tramp-completion-file-name-structure12
00d6fd04
MA
5344 (list
5345 (if (equal tramp-syntax 'url)
5346 (concat tramp-prefix-regexp
5347 "\\(" tramp-method-regexp "\\)"
5348 "\\(" (substring tramp-postfix-method-regexp 0 1)
5349 "\\|" (substring tramp-postfix-method-regexp 1 2) "\\)"
5350 "\\(" "\\)$")
5351 ;; Should not match if not URL syntax.
5352 (concat tramp-prefix-regexp "/$"))
5353 1 3 nil nil))
5354 ;; "/method: "/method:/"
b96e6899 5355 (tramp-completion-file-name-structure13
00d6fd04
MA
5356 (list
5357 (if (equal tramp-syntax 'url)
5358 (concat tramp-prefix-regexp
5359 "\\(" tramp-method-regexp "\\)"
5360 "\\(" (substring tramp-postfix-method-regexp 0 1)
5361 "\\|" (substring tramp-postfix-method-regexp 1 2) "\\)"
5362 "\\(" "\\)$")
5363 ;; Should not match if not URL syntax.
5364 (concat tramp-prefix-regexp "/$"))
5365 1 nil 3 nil)))
4007ba5b 5366
9e6ab520 5367 (mapc (lambda (regexp)
16674e4f
KG
5368 (add-to-list 'result
5369 (tramp-completion-dissect-file-name1 regexp name)))
5370 (list
5371 tramp-completion-file-name-structure1
5372 tramp-completion-file-name-structure2
5373 tramp-completion-file-name-structure3
5374 tramp-completion-file-name-structure4
5375 tramp-completion-file-name-structure5
5376 tramp-completion-file-name-structure6
5377 tramp-completion-file-name-structure7
00d6fd04
MA
5378 tramp-completion-file-name-structure8
5379 tramp-completion-file-name-structure9
b96e6899
MA
5380 tramp-completion-file-name-structure10
5381 tramp-completion-file-name-structure11
5382 tramp-completion-file-name-structure12
5383 tramp-completion-file-name-structure13
16674e4f
KG
5384 tramp-file-name-structure))
5385
5386 (delq nil result)))
5387
5388(defun tramp-completion-dissect-file-name1 (structure name)
5389 "Returns a `tramp-file-name' structure matching STRUCTURE.
00d6fd04 5390The structure consists of remote method, remote user,
7432277c 5391remote host and localname (filename on remote host)."
fb7933a3 5392
00d6fd04
MA
5393 (save-match-data
5394 (when (string-match (nth 0 structure) name)
5395 (let ((method (and (nth 1 structure)
5396 (match-string (nth 1 structure) name)))
5397 (user (and (nth 2 structure)
5398 (match-string (nth 2 structure) name)))
5399 (host (and (nth 3 structure)
5400 (match-string (nth 3 structure) name)))
5401 (localname (and (nth 4 structure)
5402 (match-string (nth 4 structure) name))))
5403 (vector method user host localname)))))
16674e4f
KG
5404
5405;; This function returns all possible method completions, adding the
5406;; trailing method delimeter.
16674e4f
KG
5407(defun tramp-get-completion-methods (partial-method)
5408 "Returns all method completions for PARTIAL-METHOD."
4007ba5b
KG
5409 (mapcar
5410 (lambda (method)
5411 (and method
5412 (string-match (concat "^" (regexp-quote partial-method)) method)
00d6fd04
MA
5413 (tramp-completion-make-tramp-file-name method nil nil nil)))
5414 (mapcar 'car tramp-methods)))
16674e4f
KG
5415
5416;; Compares partial user and host names with possible completions.
5417(defun tramp-get-completion-user-host (method partial-user partial-host user host)
5418 "Returns the most expanded string for user and host name completion.
5419PARTIAL-USER must match USER, PARTIAL-HOST must match HOST."
5420 (cond
5421
5422 ((and partial-user partial-host)
5423 (if (and host
5424 (string-match (concat "^" (regexp-quote partial-host)) host)
5425 (string-equal partial-user (or user partial-user)))
5426 (setq user partial-user)
5427 (setq user nil
5428 host nil)))
5429
5430 (partial-user
5431 (setq host nil)
5432 (unless
5433 (and user (string-match (concat "^" (regexp-quote partial-user)) user))
5434 (setq user nil)))
5435
5436 (partial-host
5437 (setq user nil)
5438 (unless
5439 (and host (string-match (concat "^" (regexp-quote partial-host)) host))
5440 (setq host nil)))
5441
5442 (t (setq user nil
5443 host nil)))
5444
292ffc15 5445 (unless (zerop (+ (length user) (length host)))
00d6fd04 5446 (tramp-completion-make-tramp-file-name method user host nil)))
16674e4f
KG
5447
5448(defun tramp-parse-rhosts (filename)
5449 "Return a list of (user host) tuples allowed to access.
292ffc15 5450Either user or host may be nil."
00d6fd04
MA
5451 ;; On Windows, there are problems in completion when
5452 ;; `default-directory' is remote.
9e6ab520 5453 (let ((default-directory (tramp-compat-temporary-file-directory))
00d6fd04 5454 res)
8daea7fc 5455 (when (file-readable-p filename)
16674e4f
KG
5456 (with-temp-buffer
5457 (insert-file-contents filename)
5458 (goto-char (point-min))
5459 (while (not (eobp))
292ffc15 5460 (push (tramp-parse-rhosts-group) res))))
16674e4f
KG
5461 res))
5462
16674e4f
KG
5463(defun tramp-parse-rhosts-group ()
5464 "Return a (user host) tuple allowed to access.
292ffc15 5465Either user or host may be nil."
16674e4f
KG
5466 (let ((result)
5467 (regexp
5468 (concat
5469 "^\\(" tramp-host-regexp "\\)"
5470 "\\([ \t]+" "\\(" tramp-user-regexp "\\)" "\\)?")))
9e6ab520 5471 (narrow-to-region (point) (tramp-compat-line-end-position))
16674e4f
KG
5472 (when (re-search-forward regexp nil t)
5473 (setq result (append (list (match-string 3) (match-string 1)))))
5474 (widen)
5475 (forward-line 1)
5476 result))
5477
5478(defun tramp-parse-shosts (filename)
5479 "Return a list of (user host) tuples allowed to access.
5480User is always nil."
00d6fd04
MA
5481 ;; On Windows, there are problems in completion when
5482 ;; `default-directory' is remote.
9e6ab520 5483 (let ((default-directory (tramp-compat-temporary-file-directory))
00d6fd04 5484 res)
8daea7fc 5485 (when (file-readable-p filename)
16674e4f
KG
5486 (with-temp-buffer
5487 (insert-file-contents filename)
5488 (goto-char (point-min))
5489 (while (not (eobp))
292ffc15 5490 (push (tramp-parse-shosts-group) res))))
16674e4f
KG
5491 res))
5492
5493(defun tramp-parse-shosts-group ()
5494 "Return a (user host) tuple allowed to access.
5495User is always nil."
16674e4f
KG
5496 (let ((result)
5497 (regexp (concat "^\\(" tramp-host-regexp "\\)")))
9e6ab520 5498 (narrow-to-region (point) (tramp-compat-line-end-position))
16674e4f
KG
5499 (when (re-search-forward regexp nil t)
5500 (setq result (list nil (match-string 1))))
5501 (widen)
5502 (or
5503 (> (skip-chars-forward ",") 0)
5504 (forward-line 1))
5505 result))
5506
8daea7fc
KG
5507(defun tramp-parse-sconfig (filename)
5508 "Return a list of (user host) tuples allowed to access.
5509User is always nil."
00d6fd04
MA
5510 ;; On Windows, there are problems in completion when
5511 ;; `default-directory' is remote.
9e6ab520 5512 (let ((default-directory (tramp-compat-temporary-file-directory))
00d6fd04 5513 res)
8daea7fc
KG
5514 (when (file-readable-p filename)
5515 (with-temp-buffer
5516 (insert-file-contents filename)
5517 (goto-char (point-min))
5518 (while (not (eobp))
5519 (push (tramp-parse-sconfig-group) res))))
5520 res))
5521
5522(defun tramp-parse-sconfig-group ()
5523 "Return a (user host) tuple allowed to access.
5524User is always nil."
8daea7fc
KG
5525 (let ((result)
5526 (regexp (concat "^[ \t]*Host[ \t]+" "\\(" tramp-host-regexp "\\)")))
9e6ab520 5527 (narrow-to-region (point) (tramp-compat-line-end-position))
8daea7fc
KG
5528 (when (re-search-forward regexp nil t)
5529 (setq result (list nil (match-string 1))))
5530 (widen)
5531 (or
5532 (> (skip-chars-forward ",") 0)
5533 (forward-line 1))
5534 result))
5535
5ec2cc41
KG
5536(defun tramp-parse-shostkeys (dirname)
5537 "Return a list of (user host) tuples allowed to access.
5538User is always nil."
00d6fd04
MA
5539 ;; On Windows, there are problems in completion when
5540 ;; `default-directory' is remote.
9e6ab520 5541 (let* ((default-directory (tramp-compat-temporary-file-directory))
00d6fd04
MA
5542 (regexp (concat "^key_[0-9]+_\\(" tramp-host-regexp "\\)\\.pub$"))
5543 (files (when (file-directory-p dirname) (directory-files dirname)))
5544 result)
5ec2cc41
KG
5545 (while files
5546 (when (string-match regexp (car files))
5547 (push (list nil (match-string 1 (car files))) result))
5548 (setq files (cdr files)))
5549 result))
5550
5551(defun tramp-parse-sknownhosts (dirname)
5552 "Return a list of (user host) tuples allowed to access.
5553User is always nil."
00d6fd04
MA
5554 ;; On Windows, there are problems in completion when
5555 ;; `default-directory' is remote.
9e6ab520 5556 (let* ((default-directory (tramp-compat-temporary-file-directory))
00d6fd04
MA
5557 (regexp (concat "^\\(" tramp-host-regexp
5558 "\\)\\.ssh-\\(dss\\|rsa\\)\\.pub$"))
5559 (files (when (file-directory-p dirname) (directory-files dirname)))
5560 result)
5ec2cc41
KG
5561 (while files
5562 (when (string-match regexp (car files))
5563 (push (list nil (match-string 1 (car files))) result))
5564 (setq files (cdr files)))
5565 result))
5566
16674e4f
KG
5567(defun tramp-parse-hosts (filename)
5568 "Return a list of (user host) tuples allowed to access.
5569User is always nil."
00d6fd04
MA
5570 ;; On Windows, there are problems in completion when
5571 ;; `default-directory' is remote.
9e6ab520 5572 (let ((default-directory (tramp-compat-temporary-file-directory))
00d6fd04 5573 res)
8daea7fc 5574 (when (file-readable-p filename)
16674e4f
KG
5575 (with-temp-buffer
5576 (insert-file-contents filename)
5577 (goto-char (point-min))
5578 (while (not (eobp))
292ffc15 5579 (push (tramp-parse-hosts-group) res))))
16674e4f
KG
5580 res))
5581
5582(defun tramp-parse-hosts-group ()
5583 "Return a (user host) tuple allowed to access.
5584User is always nil."
16674e4f 5585 (let ((result)
b96e6899
MA
5586 (regexp
5587 (concat "^\\(" tramp-ipv6-regexp "\\|" tramp-host-regexp "\\)")))
9e6ab520 5588 (narrow-to-region (point) (tramp-compat-line-end-position))
16674e4f 5589 (when (re-search-forward regexp nil t)
b96e6899 5590 (setq result (list nil (match-string 1))))
16674e4f
KG
5591 (widen)
5592 (or
5593 (> (skip-chars-forward " \t") 0)
5594 (forward-line 1))
5595 result))
5596
8daea7fc
KG
5597;; For su-alike methods it would be desirable to return "root@localhost"
5598;; as default. Unfortunately, we have no information whether any user name
00d6fd04 5599;; has been typed already. So we use `tramp-current-user' as indication,
8daea7fc 5600;; assuming it is set in `tramp-completion-handle-file-name-all-completions'.
16674e4f
KG
5601(defun tramp-parse-passwd (filename)
5602 "Return a list of (user host) tuples allowed to access.
5603Host is always \"localhost\"."
00d6fd04
MA
5604 ;; On Windows, there are problems in completion when
5605 ;; `default-directory' is remote.
9e6ab520 5606 (let ((default-directory (tramp-compat-temporary-file-directory))
00d6fd04 5607 res)
8daea7fc 5608 (if (zerop (length tramp-current-user))
16674e4f 5609 '(("root" nil))
8daea7fc 5610 (when (file-readable-p filename)
16674e4f
KG
5611 (with-temp-buffer
5612 (insert-file-contents filename)
5613 (goto-char (point-min))
5614 (while (not (eobp))
292ffc15 5615 (push (tramp-parse-passwd-group) res))))
16674e4f
KG
5616 res)))
5617
5618(defun tramp-parse-passwd-group ()
5619 "Return a (user host) tuple allowed to access.
292ffc15 5620Host is always \"localhost\"."
16674e4f
KG
5621 (let ((result)
5622 (regexp (concat "^\\(" tramp-user-regexp "\\):")))
9e6ab520 5623 (narrow-to-region (point) (tramp-compat-line-end-position))
16674e4f
KG
5624 (when (re-search-forward regexp nil t)
5625 (setq result (list (match-string 1) "localhost")))
5626 (widen)
5627 (forward-line 1)
5628 result))
5629
292ffc15
KG
5630(defun tramp-parse-netrc (filename)
5631 "Return a list of (user host) tuples allowed to access.
5632User may be nil."
00d6fd04
MA
5633 ;; On Windows, there are problems in completion when
5634 ;; `default-directory' is remote.
9e6ab520 5635 (let ((default-directory (tramp-compat-temporary-file-directory))
00d6fd04 5636 res)
8daea7fc 5637 (when (file-readable-p filename)
292ffc15
KG
5638 (with-temp-buffer
5639 (insert-file-contents filename)
5640 (goto-char (point-min))
5641 (while (not (eobp))
5642 (push (tramp-parse-netrc-group) res))))
5643 res))
5644
5645(defun tramp-parse-netrc-group ()
5646 "Return a (user host) tuple allowed to access.
5647User may be nil."
292ffc15
KG
5648 (let ((result)
5649 (regexp
5650 (concat
5651 "^[ \t]*machine[ \t]+" "\\(" tramp-host-regexp "\\)"
5652 "\\([ \t]+login[ \t]+" "\\(" tramp-user-regexp "\\)" "\\)?")))
9e6ab520 5653 (narrow-to-region (point) (tramp-compat-line-end-position))
292ffc15
KG
5654 (when (re-search-forward regexp nil t)
5655 (setq result (list (match-string 3) (match-string 1))))
5656 (widen)
5657 (forward-line 1)
5658 result))
5659
00d6fd04
MA
5660(defun tramp-parse-putty (registry)
5661 "Return a list of (user host) tuples allowed to access.
5662User is always nil."
5663 ;; On Windows, there are problems in completion when
5664 ;; `default-directory' is remote.
9e6ab520 5665 (let ((default-directory (tramp-compat-temporary-file-directory))
00d6fd04
MA
5666 res)
5667 (with-temp-buffer
a4aeb9a4 5668 (when (zerop (tramp-local-call-process "reg" nil t nil "query" registry))
00d6fd04
MA
5669 (goto-char (point-min))
5670 (while (not (eobp))
5671 (push (tramp-parse-putty-group registry) res))))
5672 res))
5673
5674(defun tramp-parse-putty-group (registry)
5675 "Return a (user host) tuple allowed to access.
5676User is always nil."
5677 (let ((result)
5678 (regexp (concat (regexp-quote registry) "\\\\\\(.+\\)")))
9e6ab520 5679 (narrow-to-region (point) (tramp-compat-line-end-position))
00d6fd04
MA
5680 (when (re-search-forward regexp nil t)
5681 (setq result (list nil (match-string 1))))
5682 (widen)
5683 (forward-line 1)
5684 result))
5685
fb7933a3
KG
5686;;; Internal Functions:
5687
00d6fd04
MA
5688(defun tramp-maybe-send-script (vec script name)
5689 "Define in remote shell function NAME implemented as SCRIPT.
5690Only send the definition if it has not already been done."
5691 (let* ((p (tramp-get-connection-process vec))
5692 (scripts (tramp-get-connection-property p "scripts" nil)))
1834b39f 5693 (unless (member name scripts)
00d6fd04
MA
5694 (tramp-message vec 5 "Sending script `%s'..." name)
5695 ;; The script could contain a call of Perl. This is masked with `%s'.
5696 (tramp-send-command-and-check
5697 vec
5698 (format "%s () {\n%s\n}" name
5699 (format script (tramp-get-remote-perl vec))))
5700 (tramp-set-connection-property p "scripts" (cons name scripts))
5701 (tramp-message vec 5 "Sending script `%s'...done." name))))
c82c5727 5702
fb7933a3 5703(defun tramp-set-auto-save ()
00d6fd04 5704 (when (and ;; ange-ftp has its own auto-save mechanism
7177e2a3
MA
5705 (eq (tramp-find-foreign-file-name-handler (buffer-file-name))
5706 'tramp-sh-file-name-handler)
fb7933a3
KG
5707 auto-save-default)
5708 (auto-save-mode 1)))
5709(add-hook 'find-file-hooks 'tramp-set-auto-save t)
a69c01a0
MA
5710(add-hook 'tramp-unload-hook
5711 '(lambda ()
5712 (remove-hook 'find-file-hooks 'tramp-set-auto-save)))
fb7933a3
KG
5713
5714(defun tramp-run-test (switch filename)
5715 "Run `test' on the remote system, given a SWITCH and a FILENAME.
5716Returns the exit code of the `test' program."
00d6fd04
MA
5717 (with-parsed-tramp-file-name filename nil
5718 (tramp-send-command-and-check
5719 v
5720 (format
5721 "%s %s %s"
5722 (tramp-get-test-command v)
5723 switch
5724 (tramp-shell-quote-argument localname)))))
5725
5726(defun tramp-run-test2 (format-string file1 file2)
5727 "Run `test'-like program on the remote system, given FILE1, FILE2.
5728FORMAT-STRING contains the program name, switches, and place holders.
5729Returns the exit code of the `test' program. Barfs if the methods,
fb7933a3 5730hosts, or files, disagree."
00d6fd04
MA
5731 (unless (tramp-equal-remote file1 file2)
5732 (with-parsed-tramp-file-name (if (tramp-tramp-file-p file1) file1 file2) nil
5733 (tramp-error
5734 v 'file-error
5735 "tramp-run-test2 only implemented for same method, user, host")))
5736 (with-parsed-tramp-file-name file1 v1
5737 (with-parsed-tramp-file-name file1 v2
fb7933a3 5738 (tramp-send-command-and-check
00d6fd04
MA
5739 v1
5740 (format format-string
5741 (tramp-shell-quote-argument v1-localname)
5742 (tramp-shell-quote-argument v2-localname))))))
fb7933a3 5743
00d6fd04
MA
5744(defun tramp-buffer-name (vec)
5745 "A name for the connection buffer VEC."
5746 ;; We must use `tramp-file-name-real-host', because for gateway
5747 ;; methods the default port will be expanded later on, which would
5748 ;; tamper the name.
5749 (let ((method (tramp-file-name-method vec))
5750 (user (tramp-file-name-user vec))
5751 (host (tramp-file-name-real-host vec)))
5752 (if (not (zerop (length user)))
5753 (format "*tramp/%s %s@%s*" method user host)
5754 (format "*tramp/%s %s*" method host))))
5755
5756(defun tramp-get-buffer (vec)
5757 "Get the connection buffer to be used for VEC."
5758 (or (get-buffer (tramp-buffer-name vec))
5759 (with-current-buffer (get-buffer-create (tramp-buffer-name vec))
5760 (setq buffer-undo-list t)
5761 (setq default-directory
5762 (tramp-make-tramp-file-name
5763 (tramp-file-name-method vec)
5764 (tramp-file-name-user vec)
5765 (tramp-file-name-host vec)
5766 "/"))
5767 (current-buffer))))
5768
5769(defun tramp-get-connection-buffer (vec)
5770 "Get the connection buffer to be used for VEC.
5771In case a second asynchronous communication has been started, it is different
5772from `tramp-get-buffer'."
5773 (or (tramp-get-connection-property vec "process-buffer" nil)
5774 (tramp-get-buffer vec)))
5775
5776(defun tramp-get-connection-process (vec)
5777 "Get the connection process to be used for VEC.
5778In case a second asynchronous communication has been started, it is different
5779from the default one."
5780 (get-process
5781 (or (tramp-get-connection-property vec "process-name" nil)
5782 (tramp-buffer-name vec))))
5783
5784(defun tramp-debug-buffer-name (vec)
5785 "A name for the debug buffer for VEC."
5786 ;; We must use `tramp-file-name-real-host', because for gateway
5787 ;; methods the default port will be expanded later on, which would
5788 ;; tamper the name.
5789 (let ((method (tramp-file-name-method vec))
5790 (user (tramp-file-name-user vec))
5791 (host (tramp-file-name-real-host vec)))
5792 (if (not (zerop (length user)))
5793 (format "*debug tramp/%s %s@%s*" method user host)
5794 (format "*debug tramp/%s %s*" method host))))
5795
5796(defun tramp-get-debug-buffer (vec)
5797 "Get the debug buffer for VEC."
01917a18 5798 (with-current-buffer
00d6fd04
MA
5799 (get-buffer-create (tramp-debug-buffer-name vec))
5800 (when (bobp)
5801 (setq buffer-undo-list t)
9ce8462a
MA
5802 ;; Activate outline-mode. This runs `text-mode-hook' and
5803 ;; `outline-mode-hook'. We must prevent that local processes
5804 ;; die. Yes: I've seen `flyspell-mode', which starts "ispell"
5805 ;; ...
9e6ab520 5806 (let ((default-directory (tramp-compat-temporary-file-directory)))
00d6fd04 5807 (outline-mode))
9ce8462a 5808 (set (make-local-variable 'outline-regexp)
736ac90f 5809 "[0-9]+:[0-9]+:[0-9]+\\.[0-9]+ [a-z0-9-]+ (\\([0-9]+\\)) #")
9ce8462a
MA
5810; (set (make-local-variable 'outline-regexp)
5811; "[a-z.-]+:[0-9]+: [a-z0-9-]+ (\\([0-9]+\\)) #")
5812 (set (make-local-variable 'outline-level) 'tramp-outline-level))
01917a18 5813 (current-buffer)))
fb7933a3 5814
00d6fd04
MA
5815(defun tramp-outline-level ()
5816 "Return the depth to which a statement is nested in the outline.
5817Point must be at the beginning of a header line.
5818
5819The outline level is equal to the verbosity of the Tramp message."
5820 (1+ (string-to-number (match-string 1))))
fb7933a3 5821
00d6fd04
MA
5822(defun tramp-find-executable
5823 (vec progname dirlist &optional ignore-tilde ignore-path)
5824 "Searches for PROGNAME in $PATH and all directories mentioned in DIRLIST.
5825First arg VEC specifies the connection, PROGNAME is the program
5826to search for, and DIRLIST gives the list of directories to
5827search. If IGNORE-TILDE is non-nil, directory names starting
5828with `~' will be ignored. If IGNORE-PATH is non-nil, searches
5829only in DIRLIST.
fb7933a3 5830
7432277c 5831Returns the absolute file name of PROGNAME, if found, and nil otherwise.
fb7933a3
KG
5832
5833This function expects to be in the right *tramp* buffer."
00d6fd04
MA
5834 (with-current-buffer (tramp-get-buffer vec)
5835 (let (result)
5836 ;; Check whether the executable is in $PATH. "which(1)" does not
5837 ;; report always a correct error code; therefore we check the
5838 ;; number of words it returns.
5839 (unless ignore-path
5840 (tramp-send-command vec (format "which \\%s | wc -w" progname))
5841 (goto-char (point-min))
5842 (if (looking-at "^1$")
5843 (setq result (concat "\\" progname))))
5844 (unless result
5845 (when ignore-tilde
5846 ;; Remove all ~/foo directories from dirlist. In Emacs 20,
5847 ;; `remove' is in CL, and we want to avoid CL dependencies.
5848 (let (newdl d)
5849 (while dirlist
5850 (setq d (car dirlist))
5851 (setq dirlist (cdr dirlist))
5852 (unless (char-equal ?~ (aref d 0))
5853 (setq newdl (cons d newdl))))
5854 (setq dirlist (nreverse newdl))))
5855 (tramp-send-command
5856 vec
5857 (format (concat "while read d; "
5858 "do if test -x $d/%s -a -f $d/%s; "
5859 "then echo tramp_executable $d/%s; "
5860 "break; fi; done <<'EOF'\n"
5861 "%s\nEOF")
5862 progname progname progname (mapconcat 'identity dirlist "\n")))
5863 (goto-char (point-max))
5864 (when (search-backward "tramp_executable " nil t)
5865 (skip-chars-forward "^ ")
5866 (skip-chars-forward " ")
9e6ab520
MA
5867 (setq result (buffer-substring
5868 (point) (tramp-compat-line-end-position)))))
00d6fd04
MA
5869 result)))
5870
5871(defun tramp-set-remote-path (vec)
5872 "Sets the remote environment PATH to existing directories.
5873I.e., for each directory in `tramp-remote-path', it is tested
5874whether it exists and if so, it is added to the environment
5875variable PATH."
5876 (tramp-message vec 5 (format "Setting $PATH environment variable"))
f84638eb
MA
5877 (tramp-send-command
5878 vec (format "PATH=%s; export PATH"
5879 (mapconcat 'identity (tramp-get-remote-path vec) ":"))))
fb7933a3 5880
cfb5c0db
MA
5881;; ------------------------------------------------------------
5882;; -- Communication with external shell --
5883;; ------------------------------------------------------------
fb7933a3 5884
00d6fd04 5885(defun tramp-find-file-exists-command (vec)
fb7933a3
KG
5886 "Find a command on the remote host for checking if a file exists.
5887Here, we are looking for a command which has zero exit status if the
5888file exists and nonzero exit status otherwise."
00d6fd04 5889 (let ((existing "/")
fb7933a3 5890 (nonexisting
00d6fd04
MA
5891 (tramp-shell-quote-argument "/ this file does not exist "))
5892 result)
fb7933a3
KG
5893 ;; The algorithm is as follows: we try a list of several commands.
5894 ;; For each command, we first run `$cmd /' -- this should return
5895 ;; true, as the root directory always exists. And then we run
00d6fd04 5896 ;; `$cmd /this\ file\ does\ not\ exist ', hoping that the file indeed
fb7933a3
KG
5897 ;; does not exist. This should return false. We use the first
5898 ;; command we find that seems to work.
5899 ;; The list of commands to try is as follows:
00d6fd04
MA
5900 ;; `ls -d' This works on most systems, but NetBSD 1.4
5901 ;; has a bug: `ls' always returns zero exit
5902 ;; status, even for files which don't exist.
5903 ;; `test -e' Some Bourne shells have a `test' builtin
5904 ;; which does not know the `-e' option.
5905 ;; `/bin/test -e' For those, the `test' binary on disk normally
5906 ;; provides the option. Alas, the binary
5907 ;; is sometimes `/bin/test' and sometimes it's
5908 ;; `/usr/bin/test'.
5909 ;; `/usr/bin/test -e' In case `/bin/test' does not exist.
fb7933a3 5910 (unless (or
00d6fd04
MA
5911 (and (setq result (format "%s -e" (tramp-get-test-command vec)))
5912 (zerop (tramp-send-command-and-check
5913 vec (format "%s %s" result existing)))
5914 (not (zerop (tramp-send-command-and-check
5915 vec (format "%s %s" result nonexisting)))))
5916 (and (setq result "/bin/test -e")
5917 (zerop (tramp-send-command-and-check
5918 vec (format "%s %s" result existing)))
5919 (not (zerop (tramp-send-command-and-check
5920 vec (format "%s %s" result nonexisting)))))
5921 (and (setq result "/usr/bin/test -e")
5922 (zerop (tramp-send-command-and-check
5923 vec (format "%s %s" result existing)))
5924 (not (zerop (tramp-send-command-and-check
5925 vec (format "%s %s" result nonexisting)))))
5926 (and (setq result (format "%s -d" (tramp-get-ls-command vec)))
5927 (zerop (tramp-send-command-and-check
5928 vec (format "%s %s" result existing)))
5929 (not (zerop (tramp-send-command-and-check
5930 vec (format "%s %s" result nonexisting))))))
5931 (tramp-error
5932 vec 'file-error "Couldn't find command to check if file exists"))
5933 result))
bf247b6e 5934
fb7933a3 5935;; CCC test ksh or bash found for tilde expansion?
00d6fd04
MA
5936(defun tramp-find-shell (vec)
5937 "Opens a shell on the remote host which groks tilde expansion."
5938 (unless (tramp-get-connection-property vec "remote-shell" nil)
5939 (let (shell)
5940 (with-current-buffer (tramp-get-buffer vec)
7e780ff1 5941 (tramp-send-command vec "echo ~root" t)
00d6fd04
MA
5942 (cond
5943 ((string-match "^~root$" (buffer-string))
5944 (setq shell
f84638eb
MA
5945 (or (tramp-find-executable
5946 vec "bash" (tramp-get-remote-path vec) t)
5947 (tramp-find-executable
5948 vec "ksh" (tramp-get-remote-path vec) t)))
00d6fd04
MA
5949 (unless shell
5950 (tramp-error
5951 vec 'file-error
5952 "Couldn't find a shell which groks tilde expansion"))
5953 ;; Find arguments for this shell.
5954 (let ((alist tramp-sh-extra-args)
5955 item extra-args)
5956 (while (and alist (null extra-args))
5957 (setq item (pop alist))
5958 (when (string-match (car item) shell)
5959 (setq extra-args (cdr item))))
5960 (when extra-args (setq shell (concat shell " " extra-args))))
5961 (tramp-message
5962 vec 5 "Starting remote shell `%s' for tilde expansion..." shell)
a4aeb9a4
MA
5963 (let ((tramp-end-of-output "$ "))
5964 (tramp-send-command
b08104a0 5965 vec
70c11b0b
MA
5966 (format "PROMPT_COMMAND='' PS1=%s PS2='' PS3='' exec %s"
5967 (shell-quote-argument tramp-end-of-output) shell)
b08104a0 5968 t))
a0a5183a 5969 ;; Setting prompts.
00d6fd04 5970 (tramp-message vec 5 "Setting remote shell prompt...")
70c11b0b
MA
5971 (tramp-send-command
5972 vec (format "PS1=%s" (shell-quote-argument tramp-end-of-output)) t)
9fa0d3aa
MA
5973 (tramp-send-command vec "PS2=''" t)
5974 (tramp-send-command vec "PS3=''" t)
5975 (tramp-send-command vec "PROMPT_COMMAND=''" t)
00d6fd04 5976 (tramp-message vec 5 "Setting remote shell prompt...done"))
a0a5183a 5977
00d6fd04
MA
5978 (t (tramp-message
5979 vec 5 "Remote `%s' groks tilde expansion, good"
5980 (tramp-get-method-parameter
5981 (tramp-file-name-method vec) 'tramp-remote-sh))
5982 (tramp-set-connection-property
5983 vec "remote-shell"
5984 (tramp-get-method-parameter
5985 (tramp-file-name-method vec) 'tramp-remote-sh))))))))
fb7933a3 5986
bf247b6e
KS
5987;; ------------------------------------------------------------
5988;; -- Functions for establishing connection --
5989;; ------------------------------------------------------------
fb7933a3 5990
ac474af1
KG
5991;; The following functions are actions to be taken when seeing certain
5992;; prompts from the remote host. See the variable
5993;; `tramp-actions-before-shell' for usage of these functions.
5994
00d6fd04 5995(defun tramp-action-login (proc vec)
ac474af1 5996 "Send the login name."
00d6fd04
MA
5997 (when (not (stringp tramp-current-user))
5998 (save-window-excursion
5999 (let ((enable-recursive-minibuffers t))
6000 (pop-to-buffer (tramp-get-connection-buffer vec))
6001 (setq tramp-current-user (read-string (match-string 0))))))
6002 (tramp-message vec 3 "Sending login name `%s'" tramp-current-user)
6003 (with-current-buffer (tramp-get-connection-buffer vec)
6004 (tramp-message vec 6 "\n%s" (buffer-string)))
6005 (tramp-send-string vec tramp-current-user))
6006
6007(defun tramp-action-password (proc vec)
ac474af1 6008 "Query the user for a password."
70c11b0b
MA
6009 (with-current-buffer (process-buffer proc)
6010 (tramp-check-for-regexp proc tramp-password-prompt-regexp)
6011 (tramp-message vec 3 "Sending %s" (match-string 1)))
00d6fd04
MA
6012 (tramp-enter-password proc))
6013
6014(defun tramp-action-succeed (proc vec)
ac474af1 6015 "Signal success in finding shell prompt."
ac474af1
KG
6016 (throw 'tramp-action 'ok))
6017
00d6fd04 6018(defun tramp-action-permission-denied (proc vec)
ac474af1 6019 "Signal permission denied."
00d6fd04 6020 (kill-process proc)
ac474af1
KG
6021 (throw 'tramp-action 'permission-denied))
6022
00d6fd04 6023(defun tramp-action-yesno (proc vec)
3cdaec13
KG
6024 "Ask the user for confirmation using `yes-or-no-p'.
6025Send \"yes\" to remote process on confirmation, abort otherwise.
6026See also `tramp-action-yn'."
ac474af1 6027 (save-window-excursion
00d6fd04
MA
6028 (let ((enable-recursive-minibuffers t))
6029 (save-match-data (pop-to-buffer (tramp-get-connection-buffer vec)))
6030 (unless (yes-or-no-p (match-string 0))
6031 (kill-process proc)
6032 (throw 'tramp-action 'permission-denied))
6033 (with-current-buffer (tramp-get-connection-buffer vec)
6034 (tramp-message vec 6 "\n%s" (buffer-string)))
6035 (tramp-send-string vec "yes"))))
6036
6037(defun tramp-action-yn (proc vec)
3cdaec13
KG
6038 "Ask the user for confirmation using `y-or-n-p'.
6039Send \"y\" to remote process on confirmation, abort otherwise.
6040See also `tramp-action-yesno'."
6041 (save-window-excursion
00d6fd04
MA
6042 (let ((enable-recursive-minibuffers t))
6043 (save-match-data (pop-to-buffer (tramp-get-connection-buffer vec)))
6044 (unless (y-or-n-p (match-string 0))
6045 (kill-process proc)
6046 (throw 'tramp-action 'permission-denied))
6047 (with-current-buffer (tramp-get-connection-buffer vec)
6048 (tramp-message vec 6 "\n%s" (buffer-string)))
6049 (tramp-send-string vec "y"))))
6050
6051(defun tramp-action-terminal (proc vec)
487f4fb7
KG
6052 "Tell the remote host which terminal type to use.
6053The terminal type can be configured with `tramp-terminal-type'."
00d6fd04 6054 (tramp-message vec 5 "Setting `%s' as terminal type." tramp-terminal-type)
7e780ff1
MA
6055 (with-current-buffer (tramp-get-connection-buffer vec)
6056 (tramp-message vec 6 "\n%s" (buffer-string)))
00d6fd04 6057 (tramp-send-string vec tramp-terminal-type))
487f4fb7 6058
00d6fd04 6059(defun tramp-action-process-alive (proc vec)
19a87064 6060 "Check whether a process has finished."
00d6fd04 6061 (unless (memq (process-status proc) '(run open))
19a87064
MA
6062 (throw 'tramp-action 'process-died)))
6063
00d6fd04 6064(defun tramp-action-out-of-band (proc vec)
38c65fca 6065 "Check whether an out-of-band copy has finished."
00d6fd04
MA
6066 (cond ((and (memq (process-status proc) '(stop exit))
6067 (zerop (process-exit-status proc)))
6068 (tramp-message vec 3 "Process has finished.")
38c65fca 6069 (throw 'tramp-action 'ok))
00d6fd04
MA
6070 ((or (and (memq (process-status proc) '(stop exit))
6071 (not (zerop (process-exit-status proc))))
6072 (memq (process-status proc) '(signal)))
01917a18
MA
6073 ;; `scp' could have copied correctly, but set modes could have failed.
6074 ;; This can be ignored.
00d6fd04
MA
6075 (with-current-buffer (process-buffer proc)
6076 (goto-char (point-min))
6077 (if (re-search-forward tramp-operation-not-permitted-regexp nil t)
6078 (progn
6079 (tramp-message vec 5 "'set mode' error ignored.")
6080 (tramp-message vec 3 "Process has finished.")
6081 (throw 'tramp-action 'ok))
6082 (tramp-message vec 3 "Process has died.")
6083 (throw 'tramp-action 'process-died))))
38c65fca
KG
6084 (t nil)))
6085
ac474af1
KG
6086;; Functions for processing the actions.
6087
00d6fd04 6088(defun tramp-process-one-action (proc vec actions)
ac474af1 6089 "Wait for output from the shell and perform one action."
00d6fd04 6090 (let (found todo item pattern action)
e6466697 6091 (while (not found)
00d6fd04
MA
6092 ;; Reread output once all actions have been performed.
6093 ;; Obviously, the output was not complete.
6094 (tramp-accept-process-output proc 1)
e6466697
MA
6095 (setq todo actions)
6096 (while todo
e6466697 6097 (setq item (pop todo))
95d610cb 6098 (setq pattern (format "\\(%s\\)\\'" (symbol-value (nth 0 item))))
e6466697 6099 (setq action (nth 1 item))
00d6fd04
MA
6100 (tramp-message
6101 vec 5 "Looking for regexp \"%s\" from remote shell" pattern)
6102 (when (tramp-check-for-regexp proc pattern)
6103 (tramp-message vec 5 "Call `%s'" (symbol-name action))
6104 (setq found (funcall action proc vec)))))
e6466697
MA
6105 found))
6106
00d6fd04 6107(defun tramp-process-actions (proc vec actions &optional timeout)
e6466697 6108 "Perform actions until success or TIMEOUT."
5c7043a2
MA
6109 ;; Enable auth-sorce and password-cache.
6110 (tramp-set-connection-property proc "first-password-request" t)
ac474af1
KG
6111 (let (exit)
6112 (while (not exit)
00d6fd04 6113 (tramp-message proc 3 "Waiting for prompts from remote shell")
ac474af1
KG
6114 (setq exit
6115 (catch 'tramp-action
e6466697
MA
6116 (if timeout
6117 (with-timeout (timeout)
00d6fd04
MA
6118 (tramp-process-one-action proc vec actions))
6119 (tramp-process-one-action proc vec actions)))))
6120 (with-current-buffer (tramp-get-connection-buffer vec)
6121 (tramp-message vec 6 "\n%s" (buffer-string)))
ac474af1 6122 (unless (eq exit 'ok)
9c13938d 6123 (tramp-clear-passwd vec)
00d6fd04
MA
6124 (tramp-error-with-buffer
6125 nil vec 'file-error
6126 (cond
6127 ((eq exit 'permission-denied) "Permission denied")
6128 ((eq exit 'process-died) "Process died")
6129 (t "Login failed"))))))
fb7933a3
KG
6130
6131;; Utility functions.
6132
00d6fd04 6133(defun tramp-accept-process-output (&optional proc timeout timeout-msecs)
d2a2c17f
MA
6134 "Like `accept-process-output' for Tramp processes.
6135This is needed in order to hide `last-coding-system-used', which is set
6136for process communication also."
00d6fd04
MA
6137 (with-current-buffer (process-buffer proc)
6138 (tramp-message proc 10 "%s %s" proc (process-status proc))
6139 (let (buffer-read-only last-coding-system-used)
6140 ;; Under Windows XP, accept-process-output doesn't return
6141 ;; sometimes. So we add an additional timeout.
6142 (with-timeout ((or timeout 1))
6143 (accept-process-output proc timeout timeout-msecs)))
6144 (tramp-message proc 10 "\n%s" (buffer-string))))
6145
6146(defun tramp-check-for-regexp (proc regexp)
6147 "Check whether REGEXP is contained in process buffer of PROC.
6148Erase echoed commands if exists."
6149 (with-current-buffer (process-buffer proc)
6150 (goto-char (point-min))
674da028 6151
00d6fd04
MA
6152 ;; Check whether we need to remove echo output.
6153 (when (and (tramp-get-connection-property proc "check-remote-echo" nil)
6154 (re-search-forward tramp-echoed-echo-mark-regexp nil t))
6155 (let ((begin (match-beginning 0)))
6156 (when (re-search-forward tramp-echoed-echo-mark-regexp nil t)
6157 ;; Discard echo from remote output.
6158 (tramp-set-connection-property proc "check-remote-echo" nil)
6159 (tramp-message proc 5 "echo-mark found")
6160 (forward-line)
6161 (delete-region begin (point))
6162 (goto-char (point-min)))))
674da028 6163
70c11b0b
MA
6164 (when (not (tramp-get-connection-property proc "check-remote-echo" nil))
6165 ;; No echo to be handled, now we can look for the regexp.
674da028 6166 (goto-char (point-min))
00d6fd04 6167 (re-search-forward regexp nil t))))
d2a2c17f 6168
fb7933a3
KG
6169(defun tramp-wait-for-regexp (proc timeout regexp)
6170 "Wait for a REGEXP to appear from process PROC within TIMEOUT seconds.
6171Expects the output of PROC to be sent to the current buffer. Returns
6172the string that matched, or nil. Waits indefinitely if TIMEOUT is
6173nil."
00d6fd04
MA
6174 (with-current-buffer (process-buffer proc)
6175 (let ((found (tramp-check-for-regexp proc regexp))
6176 (start-time (current-time)))
6177 (cond (timeout
6178 ;; Work around a bug in XEmacs 21, where the timeout
6179 ;; expires faster than it should. This degenerates
6180 ;; to polling for buggy XEmacsen, but oh, well.
6181 (while (and (not found)
6182 (< (tramp-time-diff (current-time) start-time)
6183 timeout))
6184 (with-timeout (timeout)
6185 (while (not found)
6186 (tramp-accept-process-output proc 1)
6187 (unless (memq (process-status proc) '(run open))
6188 (tramp-error-with-buffer
6189 nil proc 'file-error "Process has died"))
6190 (setq found (tramp-check-for-regexp proc regexp))))))
6191 (t
6192 (while (not found)
6193 (tramp-accept-process-output proc 1)
6194 (unless (memq (process-status proc) '(run open))
6195 (tramp-error-with-buffer
6196 nil proc 'file-error "Process has died"))
6197 (setq found (tramp-check-for-regexp proc regexp)))))
6198 (tramp-message proc 6 "\n%s" (buffer-string))
fb7933a3 6199 (when (not found)
00d6fd04
MA
6200 (if timeout
6201 (tramp-error
6202 proc 'file-error "[[Regexp `%s' not found in %d secs]]"
6203 regexp timeout)
6204 (tramp-error proc 'file-error "[[Regexp `%s' not found]]" regexp)))
6205 found)))
fb7933a3 6206
b25a52cc
KG
6207(defun tramp-barf-if-no-shell-prompt (proc timeout &rest error-args)
6208 "Wait for shell prompt and barf if none appears.
6209Looks at process PROC to see if a shell prompt appears in TIMEOUT
6210seconds. If not, it produces an error message with the given ERROR-ARGS."
7e780ff1
MA
6211 (unless
6212 (tramp-wait-for-regexp
6213 proc timeout
6214 (format
6215 "\\(%s\\|%s\\)\\'" shell-prompt-pattern tramp-shell-prompt-pattern))
00d6fd04
MA
6216 (apply 'tramp-error-with-buffer nil proc 'file-error error-args)))
6217
7e780ff1
MA
6218;; We don't call `tramp-send-string' in order to hide the password
6219;; from the debug buffer, and because end-of-line handling of the
6220;; string.
6221(defun tramp-enter-password (proc)
00d6fd04
MA
6222 "Prompt for a password and send it to the remote end."
6223 (process-send-string
7e780ff1
MA
6224 proc (concat (tramp-read-passwd proc)
6225 (or (tramp-get-method-parameter
6226 tramp-current-method
6227 'tramp-password-end-of-line)
6228 tramp-default-password-end-of-line))))
00d6fd04
MA
6229
6230(defun tramp-open-connection-setup-interactive-shell (proc vec)
fb7933a3 6231 "Set up an interactive shell.
00d6fd04
MA
6232Mainly sets the prompt and the echo correctly. PROC is the shell
6233process to set up. VEC specifies the connection."
a4aeb9a4 6234 (let ((tramp-end-of-output "$ "))
8950769a
MA
6235 ;; It is useful to set the prompt in the following command because
6236 ;; some people have a setting for $PS1 which /bin/sh doesn't know
6237 ;; about and thus /bin/sh will display a strange prompt. For
6238 ;; example, if $PS1 has "${CWD}" in the value, then ksh will
6239 ;; display the current working directory but /bin/sh will display
6240 ;; a dollar sign. The following command line sets $PS1 to a sane
6241 ;; value, and works under Bourne-ish shells as well as csh-like
6242 ;; shells. Daniel Pittman reports that the unusual positioning of
6243 ;; the single quotes makes it work under `rc', too. We also unset
6244 ;; the variable $ENV because that is read by some sh
6245 ;; implementations (eg, bash when called as sh) on startup; this
6246 ;; way, we avoid the startup file clobbering $PS1. $PROMP_COMMAND
6247 ;; is another way to set the prompt in /bin/bash, it must be
6248 ;; discarded as well.
a4aeb9a4
MA
6249 (tramp-send-command
6250 vec
6251 (format
70c11b0b
MA
6252 "exec env ENV='' PROMPT_COMMAND='' PS1=%s PS2='' PS3='' %s"
6253 (shell-quote-argument tramp-end-of-output)
a4aeb9a4
MA
6254 (tramp-get-method-parameter
6255 (tramp-file-name-method vec) 'tramp-remote-sh))
8950769a
MA
6256 t)
6257
6258 ;; Disable echo.
6259 (tramp-message vec 5 "Setting up remote shell environment")
6260 (tramp-send-command vec "stty -inlcr -echo kill '^U' erase '^H'" t)
6261 ;; Check whether the echo has really been disabled. Some
6262 ;; implementations, like busybox of embedded GNU/Linux, don't
6263 ;; support disabling.
6264 (tramp-send-command vec "echo foo" t)
6265 (with-current-buffer (process-buffer proc)
6266 (goto-char (point-min))
6267 (when (looking-at "echo foo")
6268 (tramp-set-connection-property proc "remote-echo" t)
6269 (tramp-message vec 5 "Remote echo still on. Ok.")
6270 ;; Make sure backspaces and their echo are enabled and no line
6271 ;; width magic interferes with them.
6272 (tramp-send-command vec "stty icanon erase ^H cols 32767" t))))
e42c6bbc 6273
7e780ff1 6274 (tramp-message vec 5 "Setting shell prompt")
70c11b0b
MA
6275 (tramp-send-command
6276 vec (format "PS1=%s" (shell-quote-argument tramp-end-of-output)) t)
9fa0d3aa
MA
6277 (tramp-send-command vec "PS2=''" t)
6278 (tramp-send-command vec "PS3=''" t)
6279 (tramp-send-command vec "PROMPT_COMMAND=''" t)
e42c6bbc 6280
fb7933a3
KG
6281 ;; Try to set up the coding system correctly.
6282 ;; CCC this can't be the right way to do it. Hm.
00d6fd04 6283 (tramp-message vec 5 "Determining coding system")
7e780ff1 6284 (tramp-send-command vec "echo foo ; echo bar" t)
00d6fd04 6285 (with-current-buffer (process-buffer proc)
fb7933a3
KG
6286 (goto-char (point-min))
6287 (if (featurep 'mule)
00d6fd04
MA
6288 ;; Use MULE to select the right EOL convention for communicating
6289 ;; with the process.
311dd93f 6290 (let* ((cs (or (funcall (symbol-function 'process-coding-system) proc)
00d6fd04
MA
6291 (cons 'undecided 'undecided)))
6292 cs-decode cs-encode)
6293 (when (symbolp cs) (setq cs (cons cs cs)))
6294 (setq cs-decode (car cs))
6295 (setq cs-encode (cdr cs))
6296 (unless cs-decode (setq cs-decode 'undecided))
6297 (unless cs-encode (setq cs-encode 'undecided))
6298 (setq cs-encode (tramp-coding-system-change-eol-conversion
6299 cs-encode 'unix))
6300 (when (search-forward "\r" nil t)
6301 (setq cs-decode (tramp-coding-system-change-eol-conversion
6302 cs-decode 'dos)))
311dd93f 6303 (funcall (symbol-function 'set-buffer-process-coding-system)
70c11b0b
MA
6304 cs-decode cs-encode)
6305 (tramp-message
6306 vec 5 "Setting coding system to `%s' and `%s'" cs-decode cs-encode))
fb7933a3
KG
6307 ;; Look for ^M and do something useful if found.
6308 (when (search-forward "\r" nil t)
00d6fd04
MA
6309 ;; We have found a ^M but cannot frob the process coding system
6310 ;; because we're running on a non-MULE Emacs. Let's try
6311 ;; stty, instead.
7e780ff1
MA
6312 (tramp-send-command vec "stty -onlcr" t))))
6313 (tramp-send-command vec "set +o vi +o emacs" t)
e42c6bbc
MA
6314
6315 ;; Check whether the output of "uname -sr" has been changed. If
6316 ;; yes, this is a strong indication that we must expire all
d8ac123e
MA
6317 ;; connection properties. We start again with
6318 ;; `tramp-maybe-open-connection', it will be catched there.
e42c6bbc
MA
6319 (tramp-message vec 5 "Checking system information")
6320 (let ((old-uname (tramp-get-connection-property vec "uname" nil))
6321 (new-uname
6322 (tramp-set-connection-property
6323 vec "uname"
6324 (tramp-send-command-and-read vec "echo \\\"`uname -sr`\\\""))))
6325 (when (and (stringp old-uname) (not (string-equal old-uname new-uname)))
d8ac123e
MA
6326 (with-current-buffer (tramp-get-debug-buffer vec)
6327 ;; Keep the debug buffer
2296b54d
MA
6328 (rename-buffer
6329 (generate-new-buffer-name tramp-temp-buffer-name) 'unique)
d8ac123e
MA
6330 (funcall (symbol-function 'tramp-cleanup-connection) vec)
6331 (if (= (point-min) (point-max))
6332 (kill-buffer nil)
6333 (rename-buffer (tramp-debug-buffer-name vec) 'unique))
6334 ;; We call `tramp-get-buffer' in order to keep the debug buffer.
6335 (tramp-get-buffer vec)
6336 (tramp-message
6337 vec 3
6338 "Connection reset, because remote host changed from `%s' to `%s'"
6339 old-uname new-uname)
6340 (throw 'uname-changed (tramp-maybe-open-connection vec)))))
e42c6bbc
MA
6341
6342 ;; Check whether the remote host suffers from buggy
6343 ;; `send-process-string'. This is known for FreeBSD (see comment in
6344 ;; `send_process', file process.c). I've tested sending 624 bytes
6345 ;; successfully, sending 625 bytes failed. Emacs makes a hack when
6346 ;; this host type is detected locally. It cannot handle remote
6347 ;; hosts, though.
00d6fd04
MA
6348 (with-connection-property proc "chunksize"
6349 (cond
6350 ((and (integerp tramp-chunksize) (> tramp-chunksize 0))
6351 tramp-chunksize)
6352 (t
6353 (tramp-message
6354 vec 5 "Checking remote host type for `send-process-string' bug")
6355 (if (string-match
e42c6bbc 6356 "^FreeBSD" (tramp-get-connection-property vec "uname" ""))
00d6fd04 6357 500 0))))
e42c6bbc 6358
00d6fd04
MA
6359 ;; Set remote PATH variable.
6360 (tramp-set-remote-path vec)
e42c6bbc 6361
fb7933a3
KG
6362 ;; Search for a good shell before searching for a command which
6363 ;; checks if a file exists. This is done because Tramp wants to use
6364 ;; "test foo; echo $?" to check if various conditions hold, and
6365 ;; there are buggy /bin/sh implementations which don't execute the
6366 ;; "echo $?" part if the "test" part has an error. In particular,
6367 ;; the Solaris /bin/sh is a problem. I'm betting that all systems
6368 ;; with buggy /bin/sh implementations will have a working bash or
6369 ;; ksh. Whee...
00d6fd04 6370 (tramp-find-shell vec)
e42c6bbc 6371
00d6fd04 6372 ;; Disable unexpected output.
7e780ff1 6373 (tramp-send-command vec "mesg n; biff n" t)
e42c6bbc 6374
00d6fd04
MA
6375 ;; Set the environment.
6376 (tramp-message vec 5 "Setting default environment")
661aaece
MA
6377
6378 ;; On OpenSolaris, there is a bug when HISTFILE is changed in place
6379 ;; <http://bugs.opensolaris.org/view_bug.do?bug_id=6834184>. We
6380 ;; apply the workaround.
6381 (if (string-equal (tramp-get-connection-property vec "uname" "") "SunOS 5.11")
6382 (tramp-send-command vec "unset HISTFILE"))
6383
00d6fd04
MA
6384 (let ((env (copy-sequence tramp-remote-process-environment))
6385 unset item)
6386 (while env
70c11b0b 6387 (setq item (tramp-compat-split-string (car env) "="))
00d6fd04
MA
6388 (if (and (stringp (cadr item)) (not (string-equal (cadr item) "")))
6389 (tramp-send-command
7e780ff1 6390 vec (format "%s=%s; export %s" (car item) (cadr item) (car item)) t)
00d6fd04
MA
6391 (push (car item) unset))
6392 (setq env (cdr env)))
6393 (when unset
fb7933a3 6394 (tramp-send-command
7e780ff1 6395 vec (format "unset %s" (mapconcat 'identity unset " "))))) t)
fb7933a3 6396
ac474af1
KG
6397;; CCC: We should either implement a Perl version of base64 encoding
6398;; and decoding. Then we just use that in the last item. The other
6399;; alternative is to use the Perl version of UU encoding. But then
6400;; we need a Lisp version of uuencode.
16674e4f
KG
6401;;
6402;; Old text from documentation of tramp-methods:
6403;; Using a uuencode/uudecode inline method is discouraged, please use one
6404;; of the base64 methods instead since base64 encoding is much more
6405;; reliable and the commands are more standardized between the different
6406;; Unix versions. But if you can't use base64 for some reason, please
6407;; note that the default uudecode command does not work well for some
6408;; Unices, in particular AIX and Irix. For AIX, you might want to use
6409;; the following command for uudecode:
6410;;
6411;; sed '/^begin/d;/^[` ]$/d;/^end/d' | iconv -f uucode -t ISO8859-1
6412;;
6413;; For Irix, no solution is known yet.
6414
00d6fd04
MA
6415(defconst tramp-local-coding-commands
6416 '((b64 base64-encode-region base64-decode-region)
6417 (uu tramp-uuencode-region uudecode-decode-region)
6418 (pack
6419 "perl -e 'binmode STDIN; binmode STDOUT; print pack(q{u*}, join q{}, <>)'"
6420 "perl -e 'binmode STDIN; binmode STDOUT; print unpack(q{u*}, join q{}, <>)'"))
6421 "List of local coding commands for inline transfer.
16674e4f
KG
6422Each item is a list that looks like this:
6423
00d6fd04 6424\(FORMAT ENCODING DECODING)
ac474af1 6425
00d6fd04
MA
6426FORMAT is symbol describing the encoding/decoding format. It can be
6427`b64' for base64 encoding, `uu' for uu encoding, or `pack' for simple packing.
ac474af1 6428
00d6fd04
MA
6429ENCODING and DECODING can be strings, giving commands, or symbols,
6430giving functions. If they are strings, then they can contain
16674e4f
KG
6431the \"%s\" format specifier. If that specifier is present, the input
6432filename will be put into the command line at that spot. If the
6433specifier is not present, the input should be read from standard
6434input.
ac474af1 6435
16674e4f
KG
6436If they are functions, they will be called with two arguments, start
6437and end of region, and are expected to replace the region contents
6438with the encoded or decoded results, respectively.")
ac474af1 6439
00d6fd04 6440(defconst tramp-remote-coding-commands
3dc847a3
MA
6441 '((b64 "base64" "base64 -d")
6442 (b64 "mimencode -b" "mimencode -u -b")
00d6fd04
MA
6443 (b64 "mmencode -b" "mmencode -u -b")
6444 (b64 "recode data..base64" "recode base64..data")
6445 (b64 tramp-perl-encode-with-module tramp-perl-decode-with-module)
6446 (b64 tramp-perl-encode tramp-perl-decode)
6447 (uu "uuencode xxx" "uudecode -o /dev/stdout")
6448 (uu "uuencode xxx" "uudecode -o -")
6449 (uu "uuencode xxx" "uudecode -p")
6450 (uu "uuencode xxx" tramp-uudecode)
6451 (pack
6452 "perl -e 'binmode STDIN; binmode STDOUT; print pack(q{u*}, join q{}, <>)'"
6453 "perl -e 'binmode STDIN; binmode STDOUT; print unpack(q{u*}, join q{}, <>)'"))
6454 "List of remote coding commands for inline transfer.
6455Each item is a list that looks like this:
6456
6457\(FORMAT ENCODING DECODING)
6458
6459FORMAT is symbol describing the encoding/decoding format. It can be
6460`b64' for base64 encoding, `uu' for uu encoding, or `pack' for simple packing.
6461
6462ENCODING and DECODING can be strings, giving commands, or symbols,
6463giving variables. If they are strings, then they can contain
6464the \"%s\" format specifier. If that specifier is present, the input
6465filename will be put into the command line at that spot. If the
6466specifier is not present, the input should be read from standard
6467input.
6468
6469If they are variables, this variable is a string containing a Perl
6470implementation for this functionality. This Perl program will be transferred
6471to the remote host, and it is avalible as shell function with the same name.")
6472
6473(defun tramp-find-inline-encoding (vec)
ac474af1 6474 "Find an inline transfer encoding that works.
00d6fd04
MA
6475Goes through the list `tramp-local-coding-commands' and
6476`tramp-remote-coding-commands'."
6477 (save-excursion
6478 (let ((local-commands tramp-local-coding-commands)
6479 (magic "xyzzy")
6480 loc-enc loc-dec rem-enc rem-dec litem ritem found)
6481 (while (and local-commands (not found))
6482 (setq litem (pop local-commands))
6483 (catch 'wont-work-local
6484 (let ((format (nth 0 litem))
6485 (remote-commands tramp-remote-coding-commands))
6486 (setq loc-enc (nth 1 litem))
6487 (setq loc-dec (nth 2 litem))
6488 ;; If the local encoder or decoder is a string, the
6489 ;; corresponding command has to work locally.
6490 (if (not (stringp loc-enc))
6491 (tramp-message
6492 vec 5 "Checking local encoding function `%s'" loc-enc)
6493 (tramp-message
6494 vec 5 "Checking local encoding command `%s' for sanity" loc-enc)
6495 (unless (zerop (tramp-call-local-coding-command
6496 loc-enc nil nil))
6497 (throw 'wont-work-local nil)))
6498 (if (not (stringp loc-dec))
6499 (tramp-message
6500 vec 5 "Checking local decoding function `%s'" loc-dec)
6501 (tramp-message
6502 vec 5 "Checking local decoding command `%s' for sanity" loc-dec)
6503 (unless (zerop (tramp-call-local-coding-command
6504 loc-dec nil nil))
6505 (throw 'wont-work-local nil)))
6506 ;; Search for remote coding commands with the same format
6507 (while (and remote-commands (not found))
6508 (setq ritem (pop remote-commands))
6509 (catch 'wont-work-remote
6510 (when (equal format (nth 0 ritem))
6511 (setq rem-enc (nth 1 ritem))
6512 (setq rem-dec (nth 2 ritem))
6513 ;; Check if remote encoding and decoding commands can be
6514 ;; called remotely with null input and output. This makes
6515 ;; sure there are no syntax errors and the command is really
6516 ;; found. Note that we do not redirect stdout to /dev/null,
6517 ;; for two reasons: when checking the decoding command, we
6518 ;; actually check the output it gives. And also, when
6519 ;; redirecting "mimencode" output to /dev/null, then as root
6520 ;; it might change the permissions of /dev/null!
6521 (when (not (stringp rem-enc))
6522 (let ((name (symbol-name rem-enc)))
6523 (while (string-match (regexp-quote "-") name)
6524 (setq name (replace-match "_" nil t name)))
6525 (tramp-maybe-send-script vec (symbol-value rem-enc) name)
6526 (setq rem-enc name)))
6527 (tramp-message
6528 vec 5
6529 "Checking remote encoding command `%s' for sanity" rem-enc)
6530 (unless (zerop (tramp-send-command-and-check
6531 vec (format "%s </dev/null" rem-enc) t))
6532 (throw 'wont-work-remote nil))
6533
6534 (when (not (stringp rem-dec))
6535 (let ((name (symbol-name rem-dec)))
6536 (while (string-match (regexp-quote "-") name)
6537 (setq name (replace-match "_" nil t name)))
6538 (tramp-maybe-send-script vec (symbol-value rem-dec) name)
6539 (setq rem-dec name)))
6540 (tramp-message
6541 vec 5
6542 "Checking remote decoding command `%s' for sanity" rem-dec)
6543 (unless (zerop (tramp-send-command-and-check
6544 vec
6545 (format "echo %s | %s | %s"
6546 magic rem-enc rem-dec) t))
6547 (throw 'wont-work-remote nil))
6548
6549 (with-current-buffer (tramp-get-buffer vec)
6550 (goto-char (point-min))
6551 (unless (looking-at (regexp-quote magic))
6552 (throw 'wont-work-remote nil)))
6553
6554 ;; `rem-enc' and `rem-dec' could be a string meanwhile.
6555 (setq rem-enc (nth 1 ritem))
6556 (setq rem-dec (nth 2 ritem))
6557 (setq found t)))))))
6558
1d7e9a01 6559 ;; Did we find something?
00d6fd04 6560 (unless found
1d7e9a01 6561 (tramp-message vec 2 "Couldn't find an inline transfer encoding"))
00d6fd04
MA
6562
6563 ;; Set connection properties.
6564 (tramp-message vec 5 "Using local encoding `%s'" loc-enc)
6565 (tramp-set-connection-property vec "local-encoding" loc-enc)
6566 (tramp-message vec 5 "Using local decoding `%s'" loc-dec)
6567 (tramp-set-connection-property vec "local-decoding" loc-dec)
6568 (tramp-message vec 5 "Using remote encoding `%s'" rem-enc)
6569 (tramp-set-connection-property vec "remote-encoding" rem-enc)
6570 (tramp-message vec 5 "Using remote decoding `%s'" rem-dec)
6571 (tramp-set-connection-property vec "remote-decoding" rem-dec))))
16674e4f
KG
6572
6573(defun tramp-call-local-coding-command (cmd input output)
6574 "Call the local encoding or decoding command.
6575If CMD contains \"%s\", provide input file INPUT there in command.
6576Otherwise, INPUT is passed via standard input.
6577INPUT can also be nil which means `/dev/null'.
6578OUTPUT can be a string (which specifies a filename), or t (which
6579means standard output and thus the current buffer), or nil (which
6580means discard it)."
a4aeb9a4
MA
6581 (tramp-local-call-process
6582 tramp-encoding-shell
6583 (when (and input (not (string-match "%s" cmd))) input)
6584 (if (eq output t) t nil)
6585 nil
6586 tramp-encoding-command-switch
6587 (concat
6588 (if (string-match "%s" cmd) (format cmd input) cmd)
6589 (if (stringp output) (concat "> " output) ""))))
00d6fd04
MA
6590
6591(defun tramp-compute-multi-hops (vec)
6592 "Expands VEC according to `tramp-default-proxies-alist'.
6593Gateway hops are already opened."
6594 (let ((target-alist `(,vec))
6595 (choices tramp-default-proxies-alist)
6596 item proxy)
6597
6598 ;; Look for proxy hosts to be passed.
6599 (while choices
6600 (setq item (pop choices)
70c11b0b 6601 proxy (eval (nth 2 item)))
00d6fd04
MA
6602 (when (and
6603 ;; host
70c11b0b 6604 (string-match (or (eval (nth 0 item)) "")
00d6fd04
MA
6605 (or (tramp-file-name-host (car target-alist)) ""))
6606 ;; user
70c11b0b 6607 (string-match (or (eval (nth 1 item)) "")
00d6fd04
MA
6608 (or (tramp-file-name-user (car target-alist)) "")))
6609 (if (null proxy)
6610 ;; No more hops needed.
6611 (setq choices nil)
6612 ;; Replace placeholders.
6613 (setq proxy
6614 (format-spec
6615 proxy
6616 `((?u . ,(or (tramp-file-name-user (car target-alist)) ""))
6617 (?h . ,(or (tramp-file-name-host (car target-alist)) "")))))
6618 (with-parsed-tramp-file-name proxy l
6619 ;; Add the hop.
6620 (add-to-list 'target-alist l)
6621 ;; Start next search.
6622 (setq choices tramp-default-proxies-alist)))))
6623
6624 ;; Handle gateways.
8a4438b6
MA
6625 (when (and (boundp 'tramp-gw-tunnel-method)
6626 (string-match (format
6627 "^\\(%s\\|%s\\)$"
6628 (symbol-value 'tramp-gw-tunnel-method)
6629 (symbol-value 'tramp-gw-socks-method))
6630 (tramp-file-name-method (car target-alist))))
00d6fd04
MA
6631 (let ((gw (pop target-alist))
6632 (hop (pop target-alist)))
6633 ;; Is the method prepared for gateways?
6634 (unless (tramp-get-method-parameter
6635 (tramp-file-name-method hop) 'tramp-default-port)
6636 (tramp-error
6637 vec 'file-error
6638 "Method `%s' is not supported for gateway access."
6639 (tramp-file-name-method hop)))
6640 ;; Add default port if needed.
6641 (unless
6642 (string-match
6643 tramp-host-with-port-regexp (tramp-file-name-host hop))
6644 (aset hop 2
6645 (concat
6646 (tramp-file-name-host hop) tramp-prefix-port-format
6647 (number-to-string
6648 (tramp-get-method-parameter
6649 (tramp-file-name-method hop) 'tramp-default-port)))))
6650 ;; Open the gateway connection.
6651 (add-to-list
6652 'target-alist
6653 (vector
6654 (tramp-file-name-method hop) (tramp-file-name-user hop)
9e6ab520 6655 (funcall (symbol-function 'tramp-gw-open-connection) vec gw hop) nil))
00d6fd04
MA
6656 ;; For the password prompt, we need the correct values.
6657 ;; Therefore, we must remember the gateway vector. But we
6658 ;; cannot do it as connection property, because it shouldn't
6659 ;; be persistent. And we have no started process yet either.
6660 (tramp-set-file-property (car target-alist) "" "gateway" hop)))
6661
6662 ;; Foreign and out-of-band methods are not supported for multi-hops.
6663 (when (cdr target-alist)
6664 (setq choices target-alist)
6665 (while choices
6666 (setq item (pop choices))
6667 (when
6668 (or
6669 (not
6670 (tramp-get-method-parameter
6671 (tramp-file-name-method item) 'tramp-login-program))
6672 (tramp-get-method-parameter
6673 (tramp-file-name-method item) 'tramp-copy-program))
6674 (tramp-error
6675 vec 'file-error
6676 "Method `%s' is not supported for multi-hops."
6677 (tramp-file-name-method item)))))
6678
2991e49f
MA
6679 ;; In case the host name is not used for the remote shell
6680 ;; command, the user could be misguided by applying a random
6681 ;; hostname.
6682 (let* ((v (car target-alist))
6683 (method (tramp-file-name-method v))
6684 (host (tramp-file-name-host v)))
6685 (unless
6686 (or
6687 ;; There are multi-hops.
6688 (cdr target-alist)
6689 ;; The host name is used for the remote shell command.
6690 (member
6691 '("%h") (tramp-get-method-parameter method 'tramp-login-args))
6692 ;; The host is local. We cannot use `tramp-local-host-p'
6693 ;; here, because it opens a connection as well.
b96e6899 6694 (string-match tramp-local-host-regexp host))
2991e49f 6695 (tramp-error
42bc9b6d
MA
6696 v 'file-error
6697 "Host `%s' looks like a remote host, `%s' can only use the local host"
6698 host method)))
2991e49f 6699
00d6fd04
MA
6700 ;; Result.
6701 target-alist))
6702
6703(defun tramp-maybe-open-connection (vec)
6704 "Maybe open a connection VEC.
fb7933a3
KG
6705Does not do anything if a connection is already open, but re-opens the
6706connection if a previous connection has died for some reason."
d8ac123e
MA
6707 (catch 'uname-changed
6708 (let ((p (tramp-get-connection-process vec))
6709 (process-environment (copy-sequence process-environment)))
6710
6711 ;; If too much time has passed since last command was sent, look
6712 ;; whether process is still alive. If it isn't, kill it. When
6713 ;; using ssh, it can sometimes happen that the remote end has
6714 ;; hung up but the local ssh client doesn't recognize this until
6715 ;; it tries to send some data to the remote end. So that's why
6716 ;; we try to send a command from time to time, then look again
6717 ;; whether the process is really alive.
6718 (condition-case nil
6719 (when (and (> (tramp-time-diff
6720 (current-time)
6721 (tramp-get-connection-property
6722 p "last-cmd-time" '(0 0 0)))
6723 60)
6724 p (processp p) (memq (process-status p) '(run open)))
6725 (tramp-send-command vec "echo are you awake" t t)
6726 (unless (and (memq (process-status p) '(run open))
6727 (tramp-wait-for-output p 10))
6728 ;; The error will be catched locally.
6729 (tramp-error vec 'file-error "Awake did fail")))
6730 (file-error
6731 (tramp-flush-connection-property vec)
6732 (tramp-flush-connection-property p)
6733 (delete-process p)
6734 (setq p nil)))
6735
6736 ;; New connection must be opened.
6737 (unless (and p (processp p) (memq (process-status p) '(run open)))
6738
6739 ;; We call `tramp-get-buffer' in order to get a debug buffer for
6740 ;; messages from the beginning.
6741 (tramp-get-buffer vec)
6742 (if (zerop (length (tramp-file-name-user vec)))
6743 (tramp-message
6744 vec 3 "Opening connection for %s using %s..."
6745 (tramp-file-name-host vec)
6746 (tramp-file-name-method vec))
00d6fd04 6747 (tramp-message
d8ac123e
MA
6748 vec 3 "Opening connection for %s@%s using %s..."
6749 (tramp-file-name-user vec)
00d6fd04 6750 (tramp-file-name-host vec)
d8ac123e
MA
6751 (tramp-file-name-method vec)))
6752
6753 ;; Start new process.
6754 (when (and p (processp p))
6755 (delete-process p))
6756 (setenv "TERM" tramp-terminal-type)
6757 (setenv "LC_ALL" "C")
6758 (setenv "PROMPT_COMMAND")
6759 (setenv "PS1" "$ ")
6760 (let* ((target-alist (tramp-compute-multi-hops vec))
6761 (process-connection-type tramp-process-connection-type)
6762 (process-adaptive-read-buffering nil)
6763 (coding-system-for-read nil)
6764 ;; This must be done in order to avoid our file name handler.
6765 (p (let ((default-directory
6766 (tramp-compat-temporary-file-directory)))
6767 (start-process
6768 (or (tramp-get-connection-property vec "process-name" nil)
6769 (tramp-buffer-name vec))
6770 (tramp-get-connection-buffer vec)
70c11b0b 6771 tramp-encoding-shell))))
00d6fd04 6772
d8ac123e
MA
6773 (tramp-message
6774 vec 6 "%s" (mapconcat 'identity (process-command p) " "))
6775
6776 ;; Check whether process is alive.
d8ac123e
MA
6777 (tramp-set-process-query-on-exit-flag p nil)
6778 (tramp-message vec 3 "Waiting 60s for local shell to come up...")
6779 (tramp-barf-if-no-shell-prompt
6780 p 60 "Couldn't find local shell prompt %s" tramp-encoding-shell)
6781
6782 ;; Now do all the connections as specified.
6783 (while target-alist
6784 (let* ((hop (car target-alist))
6785 (l-method (tramp-file-name-method hop))
6786 (l-user (tramp-file-name-user hop))
6787 (l-host (tramp-file-name-host hop))
6788 (l-port nil)
6789 (login-program
6790 (tramp-get-method-parameter l-method 'tramp-login-program))
6791 (login-args
6792 (tramp-get-method-parameter l-method 'tramp-login-args))
6793 (gw-args
6794 (tramp-get-method-parameter l-method 'tramp-gw-args))
6795 (gw (tramp-get-file-property hop "" "gateway" nil))
6796 (g-method (and gw (tramp-file-name-method gw)))
6797 (g-user (and gw (tramp-file-name-user gw)))
6798 (g-host (and gw (tramp-file-name-host gw)))
6799 (command login-program)
6800 ;; We don't create the temporary file. In fact, it
6801 ;; is just a prefix for the ControlPath option of
6802 ;; ssh; the real temporary file has another name, and
6803 ;; it is created and protected by ssh. It is also
6804 ;; removed by ssh, when the connection is closed.
6805 (tmpfile
6806 (tramp-set-connection-property
6807 p "temp-file"
6808 (make-temp-name
6809 (expand-file-name
6810 tramp-temp-name-prefix
6811 (tramp-compat-temporary-file-directory)))))
6812 spec)
6813
6814 ;; Add gateway arguments if necessary.
6815 (when (and gw gw-args)
6816 (setq login-args (append login-args gw-args)))
6817
6818 ;; Check for port number. Until now, there's no need
6819 ;; for handling like method, user, host.
6820 (when (string-match tramp-host-with-port-regexp l-host)
6821 (setq l-port (match-string 2 l-host)
6822 l-host (match-string 1 l-host)))
6823
6824 ;; Set variables for computing the prompt for reading
2296b54d 6825 ;; password. They can also be derived from a gateway.
d8ac123e
MA
6826 (setq tramp-current-method (or g-method l-method)
6827 tramp-current-user (or g-user l-user)
6828 tramp-current-host (or g-host l-host))
6829
6830 ;; Replace login-args place holders.
6831 (setq
6832 l-host (or l-host "")
6833 l-user (or l-user "")
6834 l-port (or l-port "")
6835 spec `((?h . ,l-host) (?u . ,l-user) (?p . ,l-port)
6836 (?t . ,tmpfile))
6837 command
6838 (concat
6839 command " "
6840 (mapconcat
6841 '(lambda (x)
6842 (setq x (mapcar '(lambda (y) (format-spec y spec)) x))
6843 (unless (member "" x) (mapconcat 'identity x " ")))
6844 login-args " ")
d8ac123e
MA
6845 ;; Local shell could be a Windows COMSPEC. It doesn't
6846 ;; know the ";" syntax, but we must exit always for
70c11b0b
MA
6847 ;; `start-file-process'. "exec" does not work either.
6848 " && exit || exit"))
d8ac123e
MA
6849
6850 ;; Send the command.
6851 (tramp-message vec 3 "Sending command `%s'" command)
6852 (tramp-send-command vec command t t)
6853 (tramp-process-actions p vec tramp-actions-before-shell 60)
6854 (tramp-message vec 3 "Found remote shell prompt on `%s'" l-host))
6855 ;; Next hop.
6856 (setq target-alist (cdr target-alist)))
6857
6858 ;; Make initial shell settings.
6859 (tramp-open-connection-setup-interactive-shell p vec))))))
00d6fd04
MA
6860
6861(defun tramp-send-command (vec command &optional neveropen nooutput)
6862 "Send the COMMAND to connection VEC.
6863Erases temporary buffer before sending the command. If optional
6864arg NEVEROPEN is non-nil, never try to open the connection. This
6865is meant to be used from `tramp-maybe-open-connection' only. The
6866function waits for output unless NOOUTPUT is set."
6867 (unless neveropen (tramp-maybe-open-connection vec))
6868 (let ((p (tramp-get-connection-process vec)))
8950769a 6869 (when (tramp-get-connection-property p "remote-echo" nil)
00d6fd04
MA
6870 ;; We mark the command string that it can be erased in the output buffer.
6871 (tramp-set-connection-property p "check-remote-echo" t)
6872 (setq command (format "%s%s%s" tramp-echo-mark command tramp-echo-mark)))
6873 (tramp-message vec 6 "%s" command)
6874 (tramp-send-string vec command)
6875 (unless nooutput (tramp-wait-for-output p))))
6876
00d6fd04 6877(defun tramp-wait-for-output (proc &optional timeout)
fb7933a3 6878 "Wait for output from remote rsh command."
00d6fd04 6879 (with-current-buffer (process-buffer proc)
bede3e9f
MA
6880 (let* (;; Initially, `tramp-end-of-output' is "$ ". There might
6881 ;; be leading escape sequences, which must be ignored.
6882 (regexp (format "[^$\n]*%s\r?$" (regexp-quote tramp-end-of-output)))
6883 ;; Sometimes, the commands do not return a newline but a
6884 ;; null byte before the shell prompt, for example "git
6885 ;; ls-files -c -z ...".
6886 (regexp1 (format "\\(^\\|\000\\)%s" regexp))
6887 (found (tramp-wait-for-regexp proc timeout regexp1)))
00d6fd04
MA
6888 (if found
6889 (let (buffer-read-only)
6890 (goto-char (point-max))
0664ff72 6891 (re-search-backward regexp nil t)
00d6fd04
MA
6892 (delete-region (point) (point-max)))
6893 (if timeout
6894 (tramp-error
6895 proc 'file-error
6896 "[[Remote prompt `%s' not found in %d secs]]"
6897 tramp-end-of-output timeout)
6898 (tramp-error
6899 proc 'file-error
6900 "[[Remote prompt `%s' not found]]" tramp-end-of-output)))
6901 ;; Return value is whether end-of-output sentinel was found.
6902 found)))
fb7933a3 6903
00d6fd04 6904(defun tramp-send-command-and-check (vec command &optional subshell)
fb7933a3 6905 "Run COMMAND and check its exit status.
fb7933a3
KG
6906Sends `echo $?' along with the COMMAND for checking the exit status. If
6907COMMAND is nil, just sends `echo $?'. Returns the exit status found.
6908
6909If the optional argument SUBSHELL is non-nil, the command is executed in
6910a subshell, ie surrounded by parentheses."
00d6fd04
MA
6911 (tramp-send-command
6912 vec
6913 (concat (if subshell "( " "")
6914 command
6915 (if command " 2>/dev/null; " "")
6916 "echo tramp_exit_status $?"
6917 (if subshell " )" " ")))
6918 (with-current-buffer (tramp-get-connection-buffer vec)
6919 (goto-char (point-max))
6920 (unless (re-search-backward "tramp_exit_status [0-9]+" nil t)
6921 (tramp-error
6922 vec 'file-error "Couldn't find exit status of `%s'" command))
6923 (skip-chars-forward "^ ")
6924 (prog1
6925 (read (current-buffer))
6926 (let (buffer-read-only) (delete-region (match-beginning 0) (point-max))))))
6927
6928(defun tramp-barf-unless-okay (vec command fmt &rest args)
fb7933a3
KG
6929 "Run COMMAND, check exit status, throw error if exit status not okay.
6930Similar to `tramp-send-command-and-check' but accepts two more arguments
6931FMT and ARGS which are passed to `error'."
00d6fd04
MA
6932 (unless (zerop (tramp-send-command-and-check vec command))
6933 (apply 'tramp-error vec 'file-error fmt args)))
6934
6935(defun tramp-send-command-and-read (vec command)
6936 "Run COMMAND and return the output, which must be a Lisp expression.
6937In case there is no valid Lisp expression, it raises an error"
6938 (tramp-barf-unless-okay vec command "`%s' returns with error" command)
6939 (with-current-buffer (tramp-get-connection-buffer vec)
6940 ;; Read the expression.
6941 (goto-char (point-min))
6942 (condition-case nil
6943 (prog1 (read (current-buffer))
6944 ;; Error handling.
9e6ab520 6945 (when (re-search-forward "\\S-" (tramp-compat-line-end-position) t)
9ce8462a 6946 (error nil)))
00d6fd04
MA
6947 (error (tramp-error
6948 vec 'file-error
6949 "`%s' does not return a valid Lisp expression: `%s'"
6950 command (buffer-string))))))
fb7933a3 6951
7432277c
KG
6952;; It seems that Tru64 Unix does not like it if long strings are sent
6953;; to it in one go. (This happens when sending the Perl
6954;; `file-attributes' implementation, for instance.) Therefore, we
27e813fe 6955;; have this function which sends the string in chunks.
00d6fd04
MA
6956(defun tramp-send-string (vec string)
6957 "Send the STRING via connection VEC.
7432277c
KG
6958
6959The STRING is expected to use Unix line-endings, but the lines sent to
6960the remote host use line-endings as defined in the variable
00d6fd04
MA
6961`tramp-rsh-end-of-line'. The communication buffer is erased before sending."
6962 (let* ((p (tramp-get-connection-process vec))
6963 (chunksize (tramp-get-connection-property p "chunksize" nil)))
6964 (unless p
6965 (tramp-error
6966 vec 'file-error "Can't send string to remote host -- not logged in"))
6967 (tramp-set-connection-property p "last-cmd-time" (current-time))
6968 (tramp-message vec 10 "%s" string)
6969 (with-current-buffer (tramp-get-connection-buffer vec)
6970 ;; Clean up the buffer. We cannot call `erase-buffer' because
6971 ;; narrowing might be in effect.
6972 (let (buffer-read-only) (delete-region (point-min) (point-max)))
27e813fe 6973 ;; Replace "\n" by `tramp-rsh-end-of-line'.
00d6fd04
MA
6974 (setq string
6975 (mapconcat 'identity
70c11b0b 6976 (tramp-compat-split-string string "\n")
00d6fd04
MA
6977 tramp-rsh-end-of-line))
6978 (unless (or (string= string "")
6979 (string-equal (substring string -1) tramp-rsh-end-of-line))
6980 (setq string (concat string tramp-rsh-end-of-line)))
27e813fe 6981 ;; Send the string.
00d6fd04
MA
6982 (if (and chunksize (not (zerop chunksize)))
6983 (let ((pos 0)
6984 (end (length string)))
6985 (while (< pos end)
6986 (tramp-message
6987 vec 10 "Sending chunk from %s to %s"
6988 pos (min (+ pos chunksize) end))
6989 (process-send-string
6990 p (substring string pos (min (+ pos chunksize) end)))
6991 (setq pos (+ pos chunksize))))
6992 (process-send-string p string)))))
fb7933a3
KG
6993
6994(defun tramp-mode-string-to-int (mode-string)
6995 "Converts a ten-letter `drwxrwxrwx'-style mode string into mode bits."
f3c071dd
MA
6996 (let* (case-fold-search
6997 (mode-chars (string-to-vector mode-string))
fb7933a3
KG
6998 (owner-read (aref mode-chars 1))
6999 (owner-write (aref mode-chars 2))
7000 (owner-execute-or-setid (aref mode-chars 3))
7001 (group-read (aref mode-chars 4))
7002 (group-write (aref mode-chars 5))
7003 (group-execute-or-setid (aref mode-chars 6))
7004 (other-read (aref mode-chars 7))
7005 (other-write (aref mode-chars 8))
7006 (other-execute-or-sticky (aref mode-chars 9)))
7007 (save-match-data
7008 (logior
f3c071dd
MA
7009 (cond
7010 ((char-equal owner-read ?r) (tramp-octal-to-decimal "00400"))
7011 ((char-equal owner-read ?-) 0)
7012 (t (error "Second char `%c' must be one of `r-'" owner-read)))
7013 (cond
7014 ((char-equal owner-write ?w) (tramp-octal-to-decimal "00200"))
7015 ((char-equal owner-write ?-) 0)
7016 (t (error "Third char `%c' must be one of `w-'" owner-write)))
7017 (cond
7018 ((char-equal owner-execute-or-setid ?x)
7019 (tramp-octal-to-decimal "00100"))
7020 ((char-equal owner-execute-or-setid ?S)
7021 (tramp-octal-to-decimal "04000"))
7022 ((char-equal owner-execute-or-setid ?s)
7023 (tramp-octal-to-decimal "04100"))
7024 ((char-equal owner-execute-or-setid ?-) 0)
7025 (t (error "Fourth char `%c' must be one of `xsS-'"
7026 owner-execute-or-setid)))
7027 (cond
7028 ((char-equal group-read ?r) (tramp-octal-to-decimal "00040"))
7029 ((char-equal group-read ?-) 0)
7030 (t (error "Fifth char `%c' must be one of `r-'" group-read)))
7031 (cond
7032 ((char-equal group-write ?w) (tramp-octal-to-decimal "00020"))
7033 ((char-equal group-write ?-) 0)
7034 (t (error "Sixth char `%c' must be one of `w-'" group-write)))
7035 (cond
7036 ((char-equal group-execute-or-setid ?x)
7037 (tramp-octal-to-decimal "00010"))
7038 ((char-equal group-execute-or-setid ?S)
7039 (tramp-octal-to-decimal "02000"))
7040 ((char-equal group-execute-or-setid ?s)
7041 (tramp-octal-to-decimal "02010"))
7042 ((char-equal group-execute-or-setid ?-) 0)
7043 (t (error "Seventh char `%c' must be one of `xsS-'"
7044 group-execute-or-setid)))
7045 (cond
7046 ((char-equal other-read ?r)
7047 (tramp-octal-to-decimal "00004"))
7048 ((char-equal other-read ?-) 0)
7049 (t (error "Eighth char `%c' must be one of `r-'" other-read)))
7050 (cond
7051 ((char-equal other-write ?w) (tramp-octal-to-decimal "00002"))
7052 ((char-equal other-write ?-) 0)
fb7933a3 7053 (t (error "Nineth char `%c' must be one of `w-'" other-write)))
f3c071dd
MA
7054 (cond
7055 ((char-equal other-execute-or-sticky ?x)
7056 (tramp-octal-to-decimal "00001"))
7057 ((char-equal other-execute-or-sticky ?T)
7058 (tramp-octal-to-decimal "01000"))
7059 ((char-equal other-execute-or-sticky ?t)
7060 (tramp-octal-to-decimal "01001"))
7061 ((char-equal other-execute-or-sticky ?-) 0)
7062 (t (error "Tenth char `%c' must be one of `xtT-'"
7063 other-execute-or-sticky)))))))
fb7933a3 7064
00d6fd04
MA
7065(defun tramp-convert-file-attributes (vec attr)
7066 "Convert file-attributes ATTR generated by perl script, stat or ls.
c82c5727
LH
7067Convert file mode bits to string and set virtual device number.
7068Return ATTR."
00d6fd04
MA
7069 ;; Convert last access time.
7070 (unless (listp (nth 4 attr))
7071 (setcar (nthcdr 4 attr)
7072 (list (floor (nth 4 attr) 65536)
7073 (floor (mod (nth 4 attr) 65536)))))
7074 ;; Convert last modification time.
7075 (unless (listp (nth 5 attr))
7076 (setcar (nthcdr 5 attr)
7077 (list (floor (nth 5 attr) 65536)
7078 (floor (mod (nth 5 attr) 65536)))))
7079 ;; Convert last status change time.
7080 (unless (listp (nth 6 attr))
7081 (setcar (nthcdr 6 attr)
7082 (list (floor (nth 6 attr) 65536)
7083 (floor (mod (nth 6 attr) 65536)))))
d4443a0d
MA
7084 ;; Convert file size.
7085 (when (< (nth 7 attr) 0)
7086 (setcar (nthcdr 7 attr) -1))
9e6ab520
MA
7087 (when (and (floatp (nth 7 attr))
7088 (<= (nth 7 attr) (tramp-compat-most-positive-fixnum)))
d4443a0d 7089 (setcar (nthcdr 7 attr) (round (nth 7 attr))))
ca637b2a 7090 ;; Convert file mode bits to string.
c82c5727 7091 (unless (stringp (nth 8 attr))
dea31ca6
MA
7092 (setcar (nthcdr 8 attr) (tramp-file-mode-from-int (nth 8 attr)))
7093 (when (stringp (car attr))
7094 (aset (nth 8 attr) 0 ?l)))
00d6fd04 7095 ;; Convert directory indication bit.
5da24108
MA
7096 (when (string-match "^d" (nth 8 attr))
7097 (setcar attr t))
7098 ;; Convert symlink from `tramp-handle-file-attributes-with-stat'.
7099 (when (consp (car attr))
7100 (if (and (stringp (caar attr))
00d6fd04
MA
7101 (string-match ".+ -> .\\(.+\\)." (caar attr)))
7102 (setcar attr (match-string 1 (caar attr)))
7103 (setcar attr nil)))
7104 ;; Set file's gid change bit.
7105 (setcar (nthcdr 9 attr)
7106 (if (numberp (nth 3 attr))
7107 (not (= (nth 3 attr)
7108 (tramp-get-remote-gid vec 'integer)))
7109 (not (string-equal
7110 (nth 3 attr)
7111 (tramp-get-remote-gid vec 'string)))))
7112 ;; Convert inode.
7113 (unless (listp (nth 10 attr))
7114 (setcar (nthcdr 10 attr)
ce3f516f 7115 (condition-case nil
b946a456 7116 (cons (floor (nth 10 attr) 65536)
ce3f516f
MA
7117 (floor (mod (nth 10 attr) 65536)))
7118 ;; Inodes can be incredible huge. We must hide this.
7119 (error (tramp-get-inode vec)))))
c82c5727
LH
7120 ;; Set virtual device number.
7121 (setcar (nthcdr 11 attr)
00d6fd04 7122 (tramp-get-device vec))
c82c5727
LH
7123 attr)
7124
ce3f516f 7125(defun tramp-get-inode (vec)
00d6fd04
MA
7126 "Returns the virtual inode number.
7127If it doesn't exist, generate a new one."
ce3f516f
MA
7128 (let ((string (tramp-make-tramp-file-name
7129 (tramp-file-name-method vec)
7130 (tramp-file-name-user vec)
7131 (tramp-file-name-host vec)
7132 "")))
00d6fd04
MA
7133 (unless (assoc string tramp-inodes)
7134 (add-to-list 'tramp-inodes
7135 (list string (length tramp-inodes))))
7136 (nth 1 (assoc string tramp-inodes))))
7137
7138(defun tramp-get-device (vec)
c82c5727
LH
7139 "Returns the virtual device number.
7140If it doesn't exist, generate a new one."
00d6fd04
MA
7141 (let ((string (tramp-make-tramp-file-name
7142 (tramp-file-name-method vec)
7143 (tramp-file-name-user vec)
7144 (tramp-file-name-host vec)
7145 "")))
c82c5727
LH
7146 (unless (assoc string tramp-devices)
7147 (add-to-list 'tramp-devices
7148 (list string (length tramp-devices))))
b946a456 7149 (cons -1 (nth 1 (assoc string tramp-devices)))))
fb7933a3
KG
7150
7151(defun tramp-file-mode-from-int (mode)
7152 "Turn an integer representing a file mode into an ls(1)-like string."
7153 (let ((type (cdr (assoc (logand (lsh mode -12) 15) tramp-file-mode-type-map)))
7154 (user (logand (lsh mode -6) 7))
7155 (group (logand (lsh mode -3) 7))
7156 (other (logand (lsh mode -0) 7))
7157 (suid (> (logand (lsh mode -9) 4) 0))
7158 (sgid (> (logand (lsh mode -9) 2) 0))
7159 (sticky (> (logand (lsh mode -9) 1) 0)))
7160 (setq user (tramp-file-mode-permissions user suid "s"))
7161 (setq group (tramp-file-mode-permissions group sgid "s"))
7162 (setq other (tramp-file-mode-permissions other sticky "t"))
7163 (concat type user group other)))
7164
fb7933a3
KG
7165(defun tramp-file-mode-permissions (perm suid suid-text)
7166 "Convert a permission bitset into a string.
7167This is used internally by `tramp-file-mode-from-int'."
7168 (let ((r (> (logand perm 4) 0))
7169 (w (> (logand perm 2) 0))
7170 (x (> (logand perm 1) 0)))
7171 (concat (or (and r "r") "-")
7172 (or (and w "w") "-")
7173 (or (and suid x suid-text) ; suid, execute
7174 (and suid (upcase suid-text)) ; suid, !execute
7175 (and x "x") "-")))) ; !suid
7176
fb7933a3
KG
7177(defun tramp-decimal-to-octal (i)
7178 "Return a string consisting of the octal digits of I.
7179Not actually used. Use `(format \"%o\" i)' instead?"
7180 (cond ((< i 0) (error "Cannot convert negative number to octal"))
7181 ((not (integerp i)) (error "Cannot convert non-integer to octal"))
7182 ((zerop i) "0")
7183 (t (concat (tramp-decimal-to-octal (/ i 8))
7184 (number-to-string (% i 8))))))
7185
fb7933a3
KG
7186;; Kudos to Gerd Moellmann for this suggestion.
7187(defun tramp-octal-to-decimal (ostr)
7188 "Given a string of octal digits, return a decimal number."
7189 (let ((x (or ostr "")))
7190 ;; `save-match' is in `tramp-mode-string-to-int' which calls this.
7191 (unless (string-match "\\`[0-7]*\\'" x)
7192 (error "Non-octal junk in string `%s'" x))
7193 (string-to-number ostr 8)))
7194
7195(defun tramp-shell-case-fold (string)
7196 "Converts STRING to shell glob pattern which ignores case."
7197 (mapconcat
7198 (lambda (c)
7199 (if (equal (downcase c) (upcase c))
7200 (vector c)
7201 (format "[%c%c]" (downcase c) (upcase c))))
7202 string
7203 ""))
7204
7205
bf247b6e 7206;; ------------------------------------------------------------
a4aeb9a4 7207;; -- Tramp file names --
bf247b6e 7208;; ------------------------------------------------------------
fb7933a3
KG
7209;; Conversion functions between external representation and
7210;; internal data structure. Convenience functions for internal
7211;; data structure.
7212
00d6fd04
MA
7213(defun tramp-file-name-p (vec)
7214 "Check whether VEC is a Tramp object."
7215 (and (vectorp vec) (= 4 (length vec))))
7216
7217(defun tramp-file-name-method (vec)
7218 "Return method component of VEC."
7219 (and (tramp-file-name-p vec) (aref vec 0)))
7220
7221(defun tramp-file-name-user (vec)
7222 "Return user component of VEC."
7223 (and (tramp-file-name-p vec) (aref vec 1)))
7224
7225(defun tramp-file-name-host (vec)
7226 "Return host component of VEC."
7227 (and (tramp-file-name-p vec) (aref vec 2)))
7228
7229(defun tramp-file-name-localname (vec)
7230 "Return localname component of VEC."
7231 (and (tramp-file-name-p vec) (aref vec 3)))
7232
dea31ca6 7233;; The user part of a Tramp file name vector can be of kind
b96e6899 7234;; "user%domain". Sometimes, we must extract these parts.
dea31ca6
MA
7235(defun tramp-file-name-real-user (vec)
7236 "Return the user name of VEC without domain."
7237 (let ((user (tramp-file-name-user vec)))
7238 (if (and (stringp user)
b96e6899 7239 (string-match tramp-user-with-domain-regexp user))
dea31ca6
MA
7240 (match-string 1 user)
7241 user)))
7242
7243(defun tramp-file-name-domain (vec)
7244 "Return the domain name of VEC."
7245 (let ((user (tramp-file-name-user vec)))
7246 (and (stringp user)
b96e6899 7247 (string-match tramp-user-with-domain-regexp user)
dea31ca6
MA
7248 (match-string 2 user))))
7249
00d6fd04
MA
7250;; The host part of a Tramp file name vector can be of kind
7251;; "host#port". Sometimes, we must extract these parts.
8a4438b6 7252(defun tramp-file-name-real-host (vec)
00d6fd04
MA
7253 "Return the host name of VEC without port."
7254 (let ((host (tramp-file-name-host vec)))
7255 (if (and (stringp host)
7256 (string-match tramp-host-with-port-regexp host))
7257 (match-string 1 host)
7258 host)))
7259
8a4438b6 7260(defun tramp-file-name-port (vec)
00d6fd04
MA
7261 "Return the port number of VEC."
7262 (let ((host (tramp-file-name-host vec)))
7263 (and (stringp host)
7264 (string-match tramp-host-with-port-regexp host)
7265 (string-to-number (match-string 2 host)))))
fb7933a3
KG
7266
7267(defun tramp-tramp-file-p (name)
a4aeb9a4 7268 "Return t if NAME is a Tramp file."
fb7933a3
KG
7269 (save-match-data
7270 (string-match tramp-file-name-regexp name)))
bf247b6e 7271
8a4438b6 7272(defun tramp-find-method (method user host)
00d6fd04
MA
7273 "Return the right method string to use.
7274This is METHOD, if non-nil. Otherwise, do a lookup in
7275`tramp-default-method-alist'."
7276 (or method
7277 (let ((choices tramp-default-method-alist)
7278 lmethod item)
7279 (while choices
7280 (setq item (pop choices))
7281 (when (and (string-match (or (nth 0 item) "") (or host ""))
7282 (string-match (or (nth 1 item) "") (or user "")))
7283 (setq lmethod (nth 2 item))
7284 (setq choices nil)))
7285 lmethod)
7286 tramp-default-method))
7287
8a4438b6 7288(defun tramp-find-user (method user host)
00d6fd04
MA
7289 "Return the right user string to use.
7290This is USER, if non-nil. Otherwise, do a lookup in
7291`tramp-default-user-alist'."
7292 (or user
7293 (let ((choices tramp-default-user-alist)
7294 luser item)
7295 (while choices
7296 (setq item (pop choices))
7297 (when (and (string-match (or (nth 0 item) "") (or method ""))
7298 (string-match (or (nth 1 item) "") (or host "")))
7299 (setq luser (nth 2 item))
7300 (setq choices nil)))
7301 luser)
7302 tramp-default-user))
7303
8a4438b6 7304(defun tramp-find-host (method user host)
00d6fd04
MA
7305 "Return the right host string to use.
7306This is HOST, if non-nil. Otherwise, it is `tramp-default-host'."
7307 (or (and (> (length host) 0) host)
7308 tramp-default-host))
7309
9ce8462a 7310(defun tramp-dissect-file-name (name &optional nodefault)
00d6fd04 7311 "Return a `tramp-file-name' structure.
9ce8462a
MA
7312The structure consists of remote method, remote user, remote host
7313and localname (file name on remote host). If NODEFAULT is
7314non-nil, the file name parts are not expanded to their default
7315values."
4007ba5b 7316 (save-match-data
00d6fd04 7317 (let ((match (string-match (nth 0 tramp-file-name-structure) name)))
a4aeb9a4 7318 (unless match (error "Not a Tramp file name: %s" name))
00d6fd04
MA
7319 (let ((method (match-string (nth 1 tramp-file-name-structure) name))
7320 (user (match-string (nth 2 tramp-file-name-structure) name))
7321 (host (match-string (nth 3 tramp-file-name-structure) name))
7322 (localname (match-string (nth 4 tramp-file-name-structure) name)))
5d449a36
MA
7323 (when (member method '("multi" "multiu"))
7324 (error
7325 "`%s' method is no longer supported, see (info \"(tramp)Multi-hops\")"
7326 method))
b96e6899
MA
7327 (when host
7328 (when (string-match tramp-prefix-ipv6-regexp host)
7329 (setq host (replace-match "" nil t host)))
7330 (when (string-match tramp-postfix-ipv6-regexp host)
7331 (setq host (replace-match "" nil t host))))
9ce8462a
MA
7332 (if nodefault
7333 (vector method user host localname)
7334 (vector
7335 (tramp-find-method method user host)
7336 (tramp-find-user method user host)
7337 (tramp-find-host method user host)
7338 localname))))))
00d6fd04
MA
7339
7340(defun tramp-equal-remote (file1 file2)
7341 "Checks, whether the remote parts of FILE1 and FILE2 are identical.
7342The check depends on method, user and host name of the files. If
7343one of the components is missing, the default values are used.
7344The local file name parts of FILE1 and FILE2 are not taken into
7345account.
fb7933a3 7346
00d6fd04
MA
7347Example:
7348
7349 (tramp-equal-remote \"/ssh::/etc\" \"/<your host name>:/home\")
7350
7351would yield `t'. On the other hand, the following check results in nil:
7352
7353 (tramp-equal-remote \"/sudo::/etc\" \"/su::/etc\")"
9e6ab520
MA
7354 (and (stringp (file-remote-p file1))
7355 (stringp (file-remote-p file2))
94be87e8 7356 (string-equal (file-remote-p file1) (file-remote-p file2))))
00d6fd04
MA
7357
7358(defun tramp-make-tramp-file-name (method user host localname)
7359 "Constructs a Tramp file name from METHOD, USER, HOST and LOCALNAME."
7360 (concat tramp-prefix-format
7361 (when (not (zerop (length method)))
7362 (concat method tramp-postfix-method-format))
7363 (when (not (zerop (length user)))
7364 (concat user tramp-postfix-user-format))
b96e6899
MA
7365 (when host
7366 (if (string-match tramp-ipv6-regexp host)
7367 (concat tramp-prefix-ipv6-format host tramp-postfix-ipv6-format)
7368 host))
7369 tramp-postfix-host-format
00d6fd04
MA
7370 (when localname localname)))
7371
7372(defun tramp-completion-make-tramp-file-name (method user host localname)
7373 "Constructs a Tramp file name from METHOD, USER, HOST and LOCALNAME.
7374It must not be a complete Tramp file name, but as long as there are
7375necessary only. This function will be used in file name completion."
7376 (concat tramp-prefix-format
7377 (when (not (zerop (length method)))
7378 (concat method tramp-postfix-method-format))
7379 (when (not (zerop (length user)))
7380 (concat user tramp-postfix-user-format))
7381 (when (not (zerop (length host)))
b96e6899
MA
7382 (concat
7383 (if (string-match tramp-ipv6-regexp host)
7384 (concat tramp-prefix-ipv6-format host tramp-postfix-ipv6-format)
7385 host)
7386 tramp-postfix-host-format))
00d6fd04
MA
7387 (when localname localname)))
7388
7389(defun tramp-make-copy-program-file-name (vec)
7390 "Create a file name suitable to be passed to `rcp' and workalikes."
7391 (let ((user (tramp-file-name-user vec))
0f205eee 7392 (host (tramp-file-name-real-host vec))
00d6fd04
MA
7393 (localname (tramp-shell-quote-argument
7394 (tramp-file-name-localname vec))))
7395 (if (not (zerop (length user)))
7396 (format "%s@%s:%s" user host localname)
7397 (format "%s:%s" host localname))))
7398
7399(defun tramp-method-out-of-band-p (vec)
38c65fca 7400 "Return t if this is an out-of-band method, nil otherwise."
00d6fd04 7401 (tramp-get-method-parameter (tramp-file-name-method vec) 'tramp-copy-program))
fb7933a3 7402
0f205eee
MA
7403(defun tramp-local-host-p (vec)
7404 "Return t if this points to the local host, nil otherwise."
c992abdb
MA
7405 ;; We cannot use `tramp-file-name-real-host'. A port is an
7406 ;; indication for an ssh tunnel or alike.
7407 (let ((host (tramp-file-name-host vec)))
0f205eee
MA
7408 (and
7409 (stringp host)
b96e6899 7410 (string-match tramp-local-host-regexp host)
a0a5183a
MA
7411 ;; The local temp directory must be writable for the other user.
7412 (file-writable-p
7413 (tramp-make-tramp-file-name
7414 (tramp-file-name-method vec)
7415 (tramp-file-name-user vec)
7416 host
93c3eb7c
MA
7417 (tramp-compat-temporary-file-directory)))
7418 ;; On some systems, chown runs only for root.
7419 (or (zerop (user-uid))
7420 (zerop (tramp-get-remote-uid vec 'integer))))))
0f205eee 7421
fb7933a3
KG
7422;; Variables local to connection.
7423
f84638eb 7424(defun tramp-get-remote-path (vec)
70c11b0b
MA
7425 (with-connection-property
7426 ;; When `tramp-own-remote-path' is in `tramp-remote-path', we
7427 ;; cache the result for the session only. Otherwise, the result
7428 ;; is cached persistently.
7429 (if (memq 'tramp-own-remote-path tramp-remote-path)
7430 (tramp-get-connection-process vec)
7431 vec)
7432 "remote-path"
9e6ab520 7433 (let* ((remote-path (tramp-compat-copy-tree tramp-remote-path))
70c11b0b
MA
7434 (elt1 (memq 'tramp-default-remote-path remote-path))
7435 (elt2 (memq 'tramp-own-remote-path remote-path))
f84638eb 7436 (default-remote-path
70c11b0b 7437 (when elt1
f84638eb 7438 (condition-case nil
70c11b0b
MA
7439 (tramp-send-command-and-read
7440 vec "echo \\\"`getconf PATH`\\\"")
f84638eb
MA
7441 ;; Default if "getconf" is not available.
7442 (error
7443 (tramp-message
7444 vec 3
7445 "`getconf PATH' not successful, using default value \"%s\"."
7446 "/bin:/usr/bin")
70c11b0b
MA
7447 "/bin:/usr/bin"))))
7448 (own-remote-path
7449 (when elt2
7450 (condition-case nil
7451 (tramp-send-command-and-read vec "echo \\\"$PATH\\\"")
7452 ;; Default if "getconf" is not available.
7453 (error
7454 (tramp-message
7455 vec 3 "$PATH not set, ignoring `tramp-own-remote-path'.")
7456 nil)))))
7457
7458 ;; Replace place holder `tramp-default-remote-path'.
7459 (when elt1
7460 (setcdr elt1
f84638eb 7461 (append
70c11b0b
MA
7462 (tramp-compat-split-string default-remote-path ":")
7463 (cdr elt1)))
f84638eb
MA
7464 (setq remote-path (delq 'tramp-default-remote-path remote-path)))
7465
70c11b0b
MA
7466 ;; Replace place holder `tramp-own-remote-path'.
7467 (when elt2
7468 (setcdr elt2
7469 (append
7470 (tramp-compat-split-string own-remote-path ":")
7471 (cdr elt2)))
7472 (setq remote-path (delq 'tramp-own-remote-path remote-path)))
7473
7474 ;; Remove double entries.
7475 (setq elt1 remote-path)
7476 (while (consp elt1)
7477 (while (and (car elt1) (setq elt2 (member (car elt1) (cdr elt1))))
7478 (setcar elt2 nil))
7479 (setq elt1 (cdr elt1)))
7480
f84638eb
MA
7481 ;; Remove non-existing directories.
7482 (delq
7483 nil
7484 (mapcar
7485 (lambda (x)
7486 (and
70c11b0b
MA
7487 (stringp x)
7488 (file-directory-p
7489 (tramp-make-tramp-file-name
7490 (tramp-file-name-method vec)
7491 (tramp-file-name-user vec)
7492 (tramp-file-name-host vec)
7493 x))
f84638eb
MA
7494 x))
7495 remote-path)))))
7496
a4aeb9a4
MA
7497(defun tramp-get-remote-tmpdir (vec)
7498 (with-connection-property vec "tmp-directory"
7499 (let ((dir (tramp-shell-quote-argument "/tmp")))
7500 (if (and (zerop
7501 (tramp-send-command-and-check
7502 vec (format "%s -d %s" (tramp-get-test-command vec) dir)))
7503 (zerop
7504 (tramp-send-command-and-check
7505 vec (format "%s -w %s" (tramp-get-test-command vec) dir))))
7506 dir
7507 (tramp-error vec 'file-error "Directory %s not accessible" dir)))))
7508
00d6fd04
MA
7509(defun tramp-get-ls-command (vec)
7510 (with-connection-property vec "ls"
946a5aeb
MA
7511 (tramp-message vec 5 "Finding a suitable `ls' command")
7512 (or
7513 (catch 'ls-found
7514 (dolist (cmd '("ls" "gnuls" "gls"))
7515 (let ((dl (tramp-get-remote-path vec))
7516 result)
7517 (while (and dl (setq result (tramp-find-executable vec cmd dl t t)))
7518 ;; Check parameter.
7519 (when (zerop (tramp-send-command-and-check
7520 vec (format "%s -lnd /" result)))
7521 (throw 'ls-found result))
7522 (setq dl (cdr dl))))))
7523 (tramp-error vec 'file-error "Couldn't find a proper `ls' command"))))
00d6fd04 7524
8e754ea2
MA
7525(defun tramp-get-ls-command-with-dired (vec)
7526 (save-match-data
7527 (with-connection-property vec "ls-dired"
7528 (tramp-message vec 5 "Checking, whether `ls --dired' works")
7529 (zerop (tramp-send-command-and-check
7530 vec (format "%s --diredd /" (tramp-get-ls-command vec)))))))
7531
00d6fd04
MA
7532(defun tramp-get-test-command (vec)
7533 (with-connection-property vec "test"
946a5aeb
MA
7534 (tramp-message vec 5 "Finding a suitable `test' command")
7535 (if (zerop (tramp-send-command-and-check vec "test 0"))
7536 "test"
7537 (tramp-find-executable vec "test" (tramp-get-remote-path vec)))))
00d6fd04
MA
7538
7539(defun tramp-get-test-nt-command (vec)
7540 ;; Does `test A -nt B' work? Use abominable `find' construct if it
7541 ;; doesn't. BSD/OS 4.0 wants the parentheses around the command,
7542 ;; for otherwise the shell crashes.
7543 (with-connection-property vec "test-nt"
7544 (or
7545 (progn
7546 (tramp-send-command
7547 vec (format "( %s / -nt / )" (tramp-get-test-command vec)))
7548 (with-current-buffer (tramp-get-buffer vec)
7549 (goto-char (point-min))
a0a5183a 7550 (when (looking-at (regexp-quote tramp-end-of-output))
00d6fd04
MA
7551 (format "%s %%s -nt %%s" (tramp-get-test-command vec)))))
7552 (progn
7553 (tramp-send-command
7554 vec
7555 (format
7556 "tramp_test_nt () {\n%s -n \"`find $1 -prune -newer $2 -print`\"\n}"
7557 (tramp-get-test-command vec)))
7558 "tramp_test_nt %s %s"))))
7559
7560(defun tramp-get-file-exists-command (vec)
7561 (with-connection-property vec "file-exists"
946a5aeb
MA
7562 (tramp-message vec 5 "Finding command to check if file exists")
7563 (tramp-find-file-exists-command vec)))
00d6fd04
MA
7564
7565(defun tramp-get-remote-ln (vec)
7566 (with-connection-property vec "ln"
946a5aeb
MA
7567 (tramp-message vec 5 "Finding a suitable `ln' command")
7568 (tramp-find-executable vec "ln" (tramp-get-remote-path vec))))
00d6fd04
MA
7569
7570(defun tramp-get-remote-perl (vec)
7571 (with-connection-property vec "perl"
946a5aeb
MA
7572 (tramp-message vec 5 "Finding a suitable `perl' command")
7573 (or (tramp-find-executable vec "perl5" (tramp-get-remote-path vec))
7574 (tramp-find-executable vec "perl" (tramp-get-remote-path vec)))))
00d6fd04
MA
7575
7576(defun tramp-get-remote-stat (vec)
7577 (with-connection-property vec "stat"
946a5aeb
MA
7578 (tramp-message vec 5 "Finding a suitable `stat' command")
7579 (let ((result (tramp-find-executable
7580 vec "stat" (tramp-get-remote-path vec)))
7581 tmp)
7582 ;; Check whether stat(1) returns usable syntax. %s does not
7583 ;; work on older AIX systems.
7584 (when result
7585 (setq tmp
7586 ;; We don't want to display an error message.
7587 (with-temp-message (or (current-message) "")
7588 (condition-case nil
7589 (tramp-send-command-and-read
7590 vec (format "%s -c '(\"%%N\" %%s)' /" result))
7591 (error nil))))
7592 (unless (and (listp tmp) (stringp (car tmp))
7593 (string-match "^./.$" (car tmp))
7594 (integerp (cadr tmp)))
7595 (setq result nil)))
7596 result)))
fb7933a3 7597
00d6fd04
MA
7598(defun tramp-get-remote-id (vec)
7599 (with-connection-property vec "id"
946a5aeb
MA
7600 (tramp-message vec 5 "Finding POSIX `id' command")
7601 (or
7602 (catch 'id-found
7603 (let ((dl (tramp-get-remote-path vec))
7604 result)
7605 (while (and dl (setq result (tramp-find-executable vec "id" dl t t)))
7606 ;; Check POSIX parameter.
7607 (when (zerop (tramp-send-command-and-check
7608 vec (format "%s -u" result)))
7609 (throw 'id-found result))
7610 (setq dl (cdr dl)))))
7611 (tramp-error vec 'file-error "Couldn't find a POSIX `id' command"))))
00d6fd04
MA
7612
7613(defun tramp-get-remote-uid (vec id-format)
7614 (with-connection-property vec (format "uid-%s" id-format)
7615 (let ((res (tramp-send-command-and-read
7616 vec
7617 (format "%s -u%s %s"
7618 (tramp-get-remote-id vec)
7619 (if (equal id-format 'integer) "" "n")
7620 (if (equal id-format 'integer)
7621 "" "| sed -e s/^/\\\"/ -e s/\$/\\\"/")))))
7622 ;; The command might not always return a number.
7623 (if (and (equal id-format 'integer) (not (integerp res))) -1 res))))
7624
7625(defun tramp-get-remote-gid (vec id-format)
7626 (with-connection-property vec (format "gid-%s" id-format)
7627 (let ((res (tramp-send-command-and-read
7628 vec
7629 (format "%s -g%s %s"
7630 (tramp-get-remote-id vec)
7631 (if (equal id-format 'integer) "" "n")
7632 (if (equal id-format 'integer)
7633 "" "| sed -e s/^/\\\"/ -e s/\$/\\\"/")))))
7634 ;; The command might not always return a number.
7635 (if (and (equal id-format 'integer) (not (integerp res))) -1 res))))
fb7933a3 7636
8d60099b
MA
7637(defun tramp-get-local-uid (id-format)
7638 (if (equal id-format 'integer) (user-uid) (user-login-name)))
7639
7640(defun tramp-get-local-gid (id-format)
9e6ab520 7641 (nth 3 (tramp-compat-file-attributes "~/" id-format)))
8d60099b 7642
00d6fd04
MA
7643;; Some predefined connection properties.
7644(defun tramp-get-remote-coding (vec prop)
7645 ;; Local coding handles properties like remote coding. So we could
7646 ;; call it without pain.
7647 (let ((ret (tramp-get-local-coding vec prop)))
7648 ;; The connection property might have been cached. So we must send
7649 ;; the script - maybe.
1d7e9a01 7650 (when (and ret (symbolp ret))
00d6fd04
MA
7651 (let ((name (symbol-name ret)))
7652 (while (string-match (regexp-quote "-") name)
7653 (setq name (replace-match "_" nil t name)))
7654 (tramp-maybe-send-script vec (symbol-value ret) name)
7655 (setq ret name)))
7656 ;; Return the value.
7657 ret))
7658
7659(defun tramp-get-local-coding (vec prop)
bf0503cb 7660 (or
00d6fd04
MA
7661 (tramp-get-connection-property vec prop nil)
7662 (progn
7663 (tramp-find-inline-encoding vec)
7664 (tramp-get-connection-property vec prop nil))))
fb7933a3 7665
00d6fd04 7666(defun tramp-get-method-parameter (method param)
c951aecb 7667 "Return the method parameter PARAM.
00d6fd04
MA
7668If the `tramp-methods' entry does not exist, return NIL."
7669 (let ((entry (assoc param (assoc method tramp-methods))))
7670 (when entry (cadr entry))))
90f8dc03 7671
fb7933a3
KG
7672;; Auto saving to a special directory.
7673
00cec167 7674(defun tramp-exists-file-name-handler (operation &rest args)
00d6fd04
MA
7675 "Checks whether OPERATION runs a file name handler."
7676 ;; The file name handler is determined on base of either an
7677 ;; argument, `buffer-file-name', or `default-directory'.
7678 (condition-case nil
7679 (let* ((buffer-file-name "/")
7680 (default-directory "/")
7681 (fnha file-name-handler-alist)
7682 (check-file-name-operation operation)
7683 (file-name-handler-alist
7684 (list
7685 (cons "/"
7686 '(lambda (operation &rest args)
7687 "Returns OPERATION if it is the one to be checked."
7688 (if (equal check-file-name-operation operation)
7689 operation
7690 (let ((file-name-handler-alist fnha))
7691 (apply operation args))))))))
7692 (equal (apply operation args) operation))
7693 (error nil)))
c1105d05
MA
7694
7695(unless (tramp-exists-file-name-handler 'make-auto-save-file-name)
7696 (defadvice make-auto-save-file-name
7697 (around tramp-advice-make-auto-save-file-name () activate)
00d6fd04 7698 "Invoke `tramp-handle-make-auto-save-file-name' for Tramp files."
c1105d05 7699 (if (and (buffer-file-name) (tramp-tramp-file-p (buffer-file-name)))
00cec167 7700 (setq ad-return-value (tramp-handle-make-auto-save-file-name))
a69c01a0
MA
7701 ad-do-it))
7702 (add-hook 'tramp-unload-hook
7703 '(lambda () (ad-unadvise 'make-auto-save-file-name))))
fb7933a3 7704
340b8d4f
MA
7705;; In Emacs < 22 and XEmacs < 21.5 autosaved remote files have
7706;; permission 0666 minus umask. This is a security threat.
414da5ab
MA
7707
7708(defun tramp-set-auto-save-file-modes ()
7709 "Set permissions of autosaved remote files to the original permissions."
7710 (let ((bfn (buffer-file-name)))
7711 (when (and (stringp bfn)
7712 (tramp-tramp-file-p bfn)
b50dd0d2 7713 (buffer-modified-p)
414da5ab 7714 (stringp buffer-auto-save-file-name)
340b8d4f
MA
7715 (not (equal bfn buffer-auto-save-file-name)))
7716 (unless (file-exists-p buffer-auto-save-file-name)
7717 (write-region "" nil buffer-auto-save-file-name))
7718 ;; Permissions should be set always, because there might be an old
7719 ;; auto-saved file belonging to another original file. This could
7720 ;; be a security threat.
7177e2a3 7721 (set-file-modes buffer-auto-save-file-name
11948172 7722 (or (file-modes bfn) (tramp-octal-to-decimal "0600"))))))
414da5ab
MA
7723
7724(unless (or (> emacs-major-version 21)
7725 (and (featurep 'xemacs)
7726 (= emacs-major-version 21)
340b8d4f 7727 (> emacs-minor-version 4)))
a69c01a0
MA
7728 (add-hook 'auto-save-hook 'tramp-set-auto-save-file-modes)
7729 (add-hook 'tramp-unload-hook
7730 '(lambda ()
7731 (remove-hook 'auto-save-hook 'tramp-set-auto-save-file-modes))))
414da5ab 7732
fb7933a3
KG
7733(defun tramp-subst-strs-in-string (alist string)
7734 "Replace all occurrences of the string FROM with TO in STRING.
7735ALIST is of the form ((FROM . TO) ...)."
7736 (save-match-data
7737 (while alist
7738 (let* ((pr (car alist))
7739 (from (car pr))
7740 (to (cdr pr)))
7741 (while (string-match (regexp-quote from) string)
7742 (setq string (replace-match to t t string)))
7743 (setq alist (cdr alist))))
7744 string))
7745
fb7933a3
KG
7746;; ------------------------------------------------------------
7747;; -- Compatibility functions section --
7748;; ------------------------------------------------------------
7749
00d6fd04 7750(defun tramp-read-passwd (proc &optional prompt)
fb7933a3 7751 "Read a password from user (compat function).
5615d63f 7752Consults the auth-source package.
5ec2cc41 7753Invokes `password-read' if available, `read-passwd' else."
00d6fd04
MA
7754 (let* ((key (tramp-make-tramp-file-name
7755 tramp-current-method tramp-current-user
7756 tramp-current-host ""))
7757 (pw-prompt
7758 (or prompt
7759 (with-current-buffer (process-buffer proc)
7760 (tramp-check-for-regexp proc tramp-password-prompt-regexp)
7761 (format "%s for %s " (capitalize (match-string 1)) key)))))
5c7043a2
MA
7762 (prog1
7763 (or
7764 ;; See if auth-sources contains something useful, if it's bound.
7765 (and (boundp 'auth-sources)
7766 (tramp-get-connection-property proc "first-password-request" nil)
7767 ;; Try with Tramp's current method.
7768 (funcall (symbol-function 'auth-source-user-or-password)
7769 "password" tramp-current-host tramp-current-method))
7770 ;; Try the password cache.
cb85dcd0
MA
7771 (when (functionp 'password-read)
7772 (unless (tramp-get-connection-property
7773 proc "first-password-request" nil)
7774 (funcall (symbol-function 'password-cache-remove) key))
7775 (let ((password
7776 (funcall (symbol-function 'password-read) pw-prompt key)))
7777 (funcall (symbol-function 'password-cache-add) key password)
7778 password))
5c7043a2
MA
7779 ;; Else, get the password interactively.
7780 (read-passwd pw-prompt))
7781 (tramp-set-connection-property proc "first-password-request" nil))))
00d6fd04 7782
9c13938d
MA
7783(defun tramp-clear-passwd (vec)
7784 "Clear password cache for connection related to VEC."
00d6fd04 7785 (when (functionp 'password-cache-remove)
9c13938d
MA
7786 (funcall
7787 (symbol-function 'password-cache-remove)
7788 (tramp-make-tramp-file-name
7789 (tramp-file-name-method vec)
7790 (tramp-file-name-user vec)
7791 (tramp-file-name-host vec)
7792 ""))))
00d6fd04
MA
7793
7794;; Snarfed code from time-date.el and parse-time.el
7795
7796(defconst tramp-half-a-year '(241 17024)
7797"Evaluated by \"(days-to-time 183)\".")
7798
7799(defconst tramp-parse-time-months
7800 '(("jan" . 1) ("feb" . 2) ("mar" . 3)
7801 ("apr" . 4) ("may" . 5) ("jun" . 6)
7802 ("jul" . 7) ("aug" . 8) ("sep" . 9)
7803 ("oct" . 10) ("nov" . 11) ("dec" . 12))
7804 "Alist mapping month names to integers.")
7805
7806(defun tramp-time-less-p (t1 t2)
7807 "Say whether time value T1 is less than time value T2."
7808 (unless t1 (setq t1 '(0 0)))
7809 (unless t2 (setq t2 '(0 0)))
7810 (or (< (car t1) (car t2))
7811 (and (= (car t1) (car t2))
7812 (< (nth 1 t1) (nth 1 t2)))))
7813
7814(defun tramp-time-subtract (t1 t2)
7815 "Subtract two time values.
7816Return the difference in the format of a time value."
7817 (unless t1 (setq t1 '(0 0)))
7818 (unless t2 (setq t2 '(0 0)))
7819 (let ((borrow (< (cadr t1) (cadr t2))))
7820 (list (- (car t1) (car t2) (if borrow 1 0))
7821 (- (+ (if borrow 65536 0) (cadr t1)) (cadr t2)))))
fb7933a3
KG
7822
7823(defun tramp-time-diff (t1 t2)
7824 "Return the difference between the two times, in seconds.
1a762140 7825T1 and T2 are time values (as returned by `current-time' for example)."
fb7933a3 7826 ;; Pacify byte-compiler with `symbol-function'.
ea9d1443
KG
7827 (cond ((and (fboundp 'subtract-time)
7828 (fboundp 'float-time))
7829 (funcall (symbol-function 'float-time)
7830 (funcall (symbol-function 'subtract-time) t1 t2)))
7831 ((and (fboundp 'subtract-time)
7832 (fboundp 'time-to-seconds))
7833 (funcall (symbol-function 'time-to-seconds)
7834 (funcall (symbol-function 'subtract-time) t1 t2)))
fb7933a3 7835 ((fboundp 'itimer-time-difference)
1a762140
MA
7836 (funcall (symbol-function 'itimer-time-difference)
7837 (if (< (length t1) 3) (append t1 '(0)) t1)
7838 (if (< (length t2) 3) (append t2 '(0)) t2)))
fb7933a3 7839 (t
00d6fd04 7840 (let ((time (tramp-time-subtract t1 t2)))
ea9d1443
KG
7841 (+ (* (car time) 65536.0)
7842 (cadr time)
7843 (/ (or (nth 2 time) 0) 1000000.0))))))
fb7933a3
KG
7844
7845(defun tramp-coding-system-change-eol-conversion (coding-system eol-type)
7846 "Return a coding system like CODING-SYSTEM but with given EOL-TYPE.
7847EOL-TYPE can be one of `dos', `unix', or `mac'."
7848 (cond ((fboundp 'coding-system-change-eol-conversion)
9e6ab520
MA
7849 (funcall (symbol-function 'coding-system-change-eol-conversion)
7850 coding-system eol-type))
fb7933a3 7851 ((fboundp 'subsidiary-coding-system)
9e6ab520
MA
7852 (funcall (symbol-function 'subsidiary-coding-system)
7853 coding-system
7854 (cond ((eq eol-type 'dos) 'crlf)
7855 ((eq eol-type 'unix) 'lf)
7856 ((eq eol-type 'mac) 'cr)
7857 (t
7858 (error "Unknown EOL-TYPE `%s', must be %s"
7859 eol-type
7860 "`dos', `unix', or `mac'")))))
fb7933a3
KG
7861 (t (error "Can't change EOL conversion -- is MULE missing?"))))
7862
19a87064
MA
7863(defun tramp-set-process-query-on-exit-flag (process flag)
7864 "Specify if query is needed for process when Emacs is exited.
7865If the second argument flag is non-nil, Emacs will query the user before
7866exiting if process is running."
7867 (if (fboundp 'set-process-query-on-exit-flag)
00d6fd04
MA
7868 (funcall (symbol-function 'set-process-query-on-exit-flag) process flag)
7869 (funcall (symbol-function 'process-kill-without-query) process flag)))
19a87064 7870
19a87064 7871
bf247b6e
KS
7872;; ------------------------------------------------------------
7873;; -- Kludges section --
7874;; ------------------------------------------------------------
fb7933a3
KG
7875
7876;; Currently (as of Emacs 20.5), the function `shell-quote-argument'
7877;; does not deal well with newline characters. Newline is replaced by
7878;; backslash newline. But if, say, the string `a backslash newline b'
7879;; is passed to a shell, the shell will expand this into "ab",
7880;; completely omitting the newline. This is not what was intended.
7881;; It does not appear to be possible to make the function
7882;; `shell-quote-argument' work with newlines without making it
7883;; dependent on the shell used. But within this package, we know that
7884;; we will always use a Bourne-like shell, so we use an approach which
7885;; groks newlines.
7886;;
7887;; The approach is simple: we call `shell-quote-argument', then
7888;; massage the newline part of the result.
7889;;
7890;; This function should produce a string which is grokked by a Unix
7891;; shell, even if the Emacs is running on Windows. Since this is the
7892;; kludges section, we bind `system-type' in such a way that
7893;; `shell-quote-arguments' behaves as if on Unix.
7894;;
7895;; Thanks to Mario DeWeerd for the hint that it is sufficient for this
7896;; function to work with Bourne-like shells.
7897;;
7898;; CCC: This function should be rewritten so that
7899;; `shell-quote-argument' is not used. This way, we are safe from
7900;; changes in `shell-quote-argument'.
7901(defun tramp-shell-quote-argument (s)
7902 "Similar to `shell-quote-argument', but groks newlines.
7903Only works for Bourne-like shells."
7904 (let ((system-type 'not-windows))
7905 (save-match-data
7906 (let ((result (shell-quote-argument s))
7907 (nl (regexp-quote (format "\\%s" tramp-rsh-end-of-line))))
7908 (when (and (>= (length result) 2)
7909 (string= (substring result 0 2) "\\~"))
7910 (setq result (substring result 1)))
7911 (while (string-match nl result)
7912 (setq result (replace-match (format "'%s'" tramp-rsh-end-of-line)
7913 t t result)))
7914 result))))
7915
16674e4f
KG
7916;; We currently (sometimes) use "[" and "]" in the filename format.
7917;; This means that Emacs wants to expand wildcards if
fb7933a3
KG
7918;; `find-file-wildcards' is non-nil, and then barfs because no
7919;; expansion could be found. We detect this situation and do
7920;; something really awful: we have `file-expand-wildcards' return the
7921;; original filename if it can't expand anything. Let's just hope
7922;; that this doesn't break anything else.
16674e4f
KG
7923;; CCC: This check is now also really awful; we should search all
7924;; of the filename format, not just the prefix.
7925(when (string-match "\\[" tramp-prefix-format)
1834b39f
MA
7926 (defadvice file-expand-wildcards
7927 (around tramp-advice-file-expand-wildcards activate)
d2a2c17f
MA
7928 (let ((name (ad-get-arg 0)))
7929 (if (tramp-tramp-file-p name)
7930 ;; If it's a Tramp file, dissect it and look if wildcards
7931 ;; need to be expanded at all.
1834b39f
MA
7932 (if (string-match
7933 "[[*?]"
7934 (tramp-file-name-localname (tramp-dissect-file-name name)))
7935 (setq ad-return-value (or ad-do-it (list name)))
7936 (setq ad-return-value (list name)))
d2a2c17f 7937 ;; If it is not a Tramp file, just run the original function.
1834b39f 7938 (setq ad-return-value (or ad-do-it (list name))))))
a69c01a0
MA
7939 (add-hook 'tramp-unload-hook
7940 '(lambda () (ad-unadvise 'file-expand-wildcards))))
fb7933a3 7941
a69c01a0
MA
7942;; Checklist for `tramp-unload-hook'
7943;; - Unload all `tramp-*' packages
7944;; - Reset `file-name-handler-alist'
7945;; - Cleanup hooks where Tramp functions are in
7946;; - Cleanup advised functions
7947;; - Cleanup autoloads
7948;;;###autoload
7949(defun tramp-unload-tramp ()
08b1eb21 7950 "Discard Tramp from loading remote files."
a69c01a0
MA
7951 (interactive)
7952 ;; When Tramp is not loaded yet, its autoloads are still active.
8c04e197 7953 (tramp-unload-file-name-handlers)
a69c01a0
MA
7954 ;; ange-ftp settings must be enabled.
7955 (when (functionp 'tramp-ftp-enable-ange-ftp)
7956 (funcall (symbol-function 'tramp-ftp-enable-ange-ftp)))
00d6fd04
MA
7957 ;; Maybe its not loaded yet.
7958 (condition-case nil
7959 (unload-feature 'tramp 'force)
a69c01a0
MA
7960 (error nil)))
7961
dea31ca6
MA
7962(when (and load-in-progress
7963 (string-match "Loading tramp..." (or (current-message) "")))
ccb4a481
MA
7964 (message "Loading tramp...done"))
7965
fb7933a3
KG
7966(provide 'tramp)
7967
fb7933a3
KG
7968;;; TODO:
7969
4007ba5b 7970;; * Handle nonlocal exits such as C-g.
00d6fd04
MA
7971;; * But it would probably be better to use with-local-quit at the
7972;; place where it's actually needed: around any potentially
7973;; indefinitely blocking piece of code. In this case it would be
7974;; within Tramp around one of its calls to accept-process-output (or
7975;; around one of the loops that calls accept-process-output)
d037d501 7976;; (Stefan Monnier).
fb7933a3 7977;; * Rewrite `tramp-shell-quote-argument' to abstain from using
b1d06e75 7978;; `shell-quote-argument'.
fb7933a3
KG
7979;; * In Emacs 21, `insert-directory' shows total number of bytes used
7980;; by the files in that directory. Add this here.
7981;; * Avoid screen blanking when hitting `g' in dired. (Eli Tziperman)
7982;; * Make ffap.el grok Tramp filenames. (Eli Tziperman)
fb7933a3 7983;; * Case-insensitive filename completion. (Norbert Goevert.)
fb7933a3
KG
7984;; * Don't use globbing for directories with many files, as this is
7985;; likely to produce long command lines, and some shells choke on
7986;; long command lines.
fb7933a3
KG
7987;; * `vc-directory' does not work. It never displays any files, even
7988;; if it does show files when run locally.
fb7933a3 7989;; * How to deal with MULE in `insert-file-contents' and `write-region'?
fb7933a3
KG
7990;; * Grok `append' parameter for `write-region'.
7991;; * Test remote ksh or bash for tilde expansion in `tramp-find-shell'?
7992;; * abbreviate-file-name
8e754ea2 7993;; * Better error checking. At least whenever we see something
fb7933a3
KG
7994;; strange when doing zerop, we should kill the process and start
7995;; again. (Greg Stark)
fb7933a3
KG
7996;; * Provide a local cache of old versions of remote files for the rsync
7997;; transfer method to use. (Greg Stark)
7998;; * Remove unneeded parameters from methods.
7999;; * Invoke rsync once for copying a whole directory hierarchy.
cdd44874 8000;; (Francesco Potortì)
fb7933a3
KG
8001;; * Make it work for different encodings, and for different file name
8002;; encodings, too. (Daniel Pittman)
fb7933a3 8003;; * Progress reports while copying files. (Michael Kifer)
fb7933a3
KG
8004;; * Don't search for perl5 and perl. Instead, only search for perl and
8005;; then look if it's the right version (with `perl -v').
8006;; * When editing a remote CVS controlled file as a different user, VC
8007;; gets confused about the file locking status. Try to find out why
8008;; the workaround doesn't work.
3cdaec13 8009;; * Username and hostname completion.
6c4e47fa 8010;; ** Try to avoid usage of `last-input-event' in `tramp-completion-mode-p'.
8daea7fc 8011;; ** Unify `tramp-parse-{rhosts,shosts,sconfig,hosts,passwd,netrc}'.
16674e4f 8012;; Code is nearly identical.
cfb5c0db
MA
8013;; * Allow out-of-band methods as _last_ multi-hop. Open a connection
8014;; until the last but one hop via `start-file-process'. Apply it
8015;; also for ftp and smb.
00d6fd04
MA
8016;; * WIBNI if we had a command "trampclient"? If I was editing in
8017;; some shell with root priviledges, it would be nice if I could
8018;; just call
8019;; trampclient filename.c
8020;; as an editor, and the _current_ shell would connect to an Emacs
8021;; server and would be used in an existing non-priviledged Emacs
8022;; session for doing the editing in question.
8023;; That way, I need not tell Emacs my password again and be afraid
8024;; that it makes it into core dumps or other ugly stuff (I had Emacs
8025;; once display a just typed password in the context of a keyboard
8026;; sequence prompt for a question immediately following in a shell
8027;; script run within Emacs -- nasty).
8028;; And if I have some ssh session running to a different computer,
8029;; having the possibility of passing a local file there to a local
8030;; Emacs session (in case I can arrange for a connection back) would
8031;; be nice.
a4aeb9a4 8032;; Likely the corresponding Tramp server should not allow the
00d6fd04
MA
8033;; equivalent of the emacsclient -eval option in order to make this
8034;; reasonably unproblematic. And maybe trampclient should have some
8035;; way of passing credentials, like by using an SSL socket or
8036;; something. (David Kastrup)
8037;; * Could Tramp reasonably look for a prompt after ^M rather than
8038;; only after ^J ? (Stefan Monnier)
00d6fd04
MA
8039;; * Reconnect directly to a compliant shell without first going
8040;; through the user's default shell. (Pete Forman)
00d6fd04 8041;; * Make `tramp-default-user' obsolete.
adb67129
MA
8042;; * Tramp shall reconnect automatically to its ssh connection when it
8043;; detects that the process "has died". (David Reitter)
11c71217
MA
8044;; * How can I interrupt the remote process with a signal
8045;; (interrupt-process seems not to work)? (Markus Triska)
2296b54d
MA
8046;; * Avoid the local shell entirely for starting remote processes. If
8047;; so, I think even a signal, when delivered directly to the local
8048;; SSH instance, would correctly be propagated to the remote process
8049;; automatically; possibly SSH would have to be started with
8050;; "-t". (Markus Triska)
ccb4a481
MA
8051;; * Set `tramp-copy-size-limit' to 0, when there is no remote
8052;; encoding routine.
dea31ca6
MA
8053;; * It makes me wonder if tramp couldn't fall back to ssh when scp
8054;; isn't on the remote host. (Mark A. Hershberger)
65a099b6
MA
8055;; * To improve the behavior in case of things like "git status", it
8056;; might be worthwhile to add some way to indicate that a particular
8057;; use of process-file is (supposed to be) free of side-effects.
8058;; (Stefan Monnier)
3e2fa353
MA
8059;; * Use lsh instead of ssh. (Alfred M. Szmidt)
8060;; * Implement a general server-local-variable mechanism, as there are
8061;; probably other variables that need different values for different
8062;; servers too. The user could then configure a variable (such as
8063;; tramp-server-local-variable-alist) to define any such variables
8064;; that they need to, which would then be let bound as appropriate
8065;; in tramp functions. (Jason Rumney)
946a5aeb
MA
8066;; * Optimize out-of-band copying, when both methods are scp-like (not
8067;; rsync).
8068;; * Keep a second connection open for out-of-band methods like scp or
8069;; rsync.
8070;; * Partial completion completes word constituents. I find it
8071;; acceptable if method completion works only after :, so that we
8072;; have "/s: TAB" offer completion for the method first, filenames
8073;; afterwards. (David Kastrup)
8074
fb7933a3
KG
8075
8076;; Functions for file-name-handler-alist:
8077;; diff-latest-backup-file -- in diff.el
fb7933a3 8078
cdd44874 8079;; arch-tag: 3a21a994-182b-48fa-b0cd-c1d9fede424a
fb7933a3 8080;;; tramp.el ends here
57671b72
MA
8081
8082;; Local Variables:
8083;; mode: Emacs-Lisp
8084;; coding: utf-8
8085;; End: