1 ;;; tramp.el --- Transparent Remote Access, Multiple Protocol
3 ;; Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004,
4 ;; 2005, 2006, 2007, 2008, 2009 Free Software Foundation, Inc.
6 ;; (copyright statements below in code to be updated with the above notice)
8 ;; Author: Kai Großjohann <kai.grossjohann@gmx.net>
9 ;; Michael Albinus <michael.albinus@gmx.de>
10 ;; Keywords: comm, processes
12 ;; This file is part of GNU Emacs.
14 ;; GNU Emacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
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.
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
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.
34 ;; For more detailed instructions, please see the info file.
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.)
43 ;; Also see the todo list at the bottom of this file.
45 ;; The current version of Tramp can be retrieved from the following URL:
46 ;; http://ftp.gnu.org/gnu/tramp/
48 ;; There's a mailing list for this, as well. Its name is:
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
53 ;; For the adventurous, the current development sources are available
54 ;; via CVS. You can find instructions about this at the following URL:
55 ;; http://savannah.gnu.org/projects/tramp/
56 ;; Click on "CVS" in the navigation bar near the top.
58 ;; Don't forget to put on your asbestos longjohns, first!
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..."))
69 ;; The Tramp version number and bug report address, as prepared by configure.
71 (add-hook 'tramp-unload-hook
73 (when (featurep 'trampver)
74 (unload-feature 'trampver 'force))))
76 (require 'tramp-compat)
77 (add-hook 'tramp-unload-hook
79 (when (featurep 'tramp-compat)
80 (unload-feature 'tramp-compat 'force))))
82 (require 'format-spec) ; from Gnus 5.8, also in tar ball
83 ;; As long as password.el is not part of (X)Emacs, it shouldn't
85 (if (featurep 'xemacs)
86 (load "password" 'noerror)
87 (or (require 'password-cache nil 'noerror)
88 (require 'password nil 'noerror))) ; from No Gnus, also in tar ball
94 (if (featurep 'xemacs)
95 (load "auth-source" 'noerror)
96 (require 'auth-source nil 'noerror)))
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")
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
109 (when (featurep 'tramp-cache)
110 (unload-feature 'tramp-cache 'force))))
112 (autoload 'tramp-uuencode-region "tramp-uu"
113 "Implementation of `uuencode' in Lisp.")
114 (add-hook 'tramp-unload-hook
116 (when (featurep 'tramp-uu)
117 (unload-feature 'tramp-uu 'force))))
119 (autoload 'uudecode-decode-region "uudecode")
121 ;; The following Tramp packages must be loaded after tramp.el, because
122 ;; they require it as well.
123 (eval-after-load "tramp"
128 ;; Tramp interactive commands.
131 ;; Load foreign FTP method.
132 (if (featurep 'xemacs) 'tramp-efs 'tramp-ftp)
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)
140 ;; Load foreign FISH method.
143 ;; tramp-gvfs needs D-Bus messages. Available since Emacs 23
144 ;; on some system types.
145 (when (and (featurep 'dbusbind)
146 (tramp-compat-process-running-p "gvfs-fuse-daemon"))
149 ;; Load gateways. It needs `make-network-process' from Emacs 22.
150 (when (functionp 'make-network-process) 'tramp-gw)))
153 ;; We have used just some basic tests, whether a package shall
154 ;; be added. There might still be other errors during loading,
155 ;; which we will catch here.
156 (catch 'tramp-loading
158 (add-hook 'tramp-unload-hook
160 (when (featurep (quote ,feature))
161 (unload-feature (quote ,feature) 'force)))))
162 (unless (featurep feature)
163 (message "Loading %s failed, ignoring this package" feature)))))
165 ;;; User Customizable Internal Variables:
168 "Edit remote files with a combination of rsh and rcp or similar programs."
172 ;; Maybe we need once a real Tramp mode, with key bindings etc.
174 (defcustom tramp-mode t
175 "*Whether Tramp is enabled.
176 If it is set to nil, all remote file names are used literally."
180 (defcustom tramp-verbose 3
181 "*Verbosity level for Tramp.
182 Any level x includes messages for all levels 1 .. x-1. The levels are
184 0 silent (no tramp messages at all)
187 3 connection to remote hosts (default level)
190 6 sent and received strings
192 8 connection properties
199 (when (boundp 'backup-directory-alist)
200 (defcustom tramp-backup-directory-alist nil
201 "Alist of filename patterns and backup directory names.
202 Each element looks like (REGEXP . DIRECTORY), with the same meaning like
203 in `backup-directory-alist'. If a Tramp file is backed up, and DIRECTORY
204 is a local file name, the backup directory is prepended with Tramp file
205 name prefix \(method, user, host\) of file.
207 \(setq tramp-backup-directory-alist backup-directory-alist\)
209 gives the same backup policy for Tramp files on their hosts like the
210 policy for local files."
212 :type '(repeat (cons (regexp :tag "Regexp matching filename")
213 (directory :tag "Backup directory name"))))))
215 ;; XEmacs case. We cannot check for `bkup-backup-directory-info', because
216 ;; the package "backup-dir" might not be loaded yet.
218 (when (featurep 'xemacs)
219 (defcustom tramp-bkup-backup-directory-info nil
220 "*Alist of (FILE-REGEXP BACKUP-DIR OPTIONS ...))
221 It has the same meaning like `bkup-backup-directory-info' from package
222 `backup-dir'. If a Tramp file is backed up, and BACKUP-DIR is a local
223 file name, the backup directory is prepended with Tramp file name prefix
224 \(method, user, host\) of file.
226 \(setq tramp-bkup-backup-directory-info bkup-backup-directory-info\)
228 gives the same backup policy for Tramp files on their hosts like the
229 policy for local files."
231 (list (regexp :tag "File regexp")
232 (string :tag "Backup Dir")
237 (const search-upward))))
240 (defcustom tramp-auto-save-directory nil
241 "*Put auto-save files in this directory, if set.
242 The idea is to use a local directory so that auto-saving is faster."
244 :type '(choice (const nil) string))
246 (defcustom tramp-encoding-shell
247 (if (memq system-type '(windows-nt))
250 "*Use this program for encoding and decoding commands on the local host.
251 This shell is used to execute the encoding and decoding command on the
252 local host, so if you want to use `~' in those commands, you should
253 choose a shell here which groks tilde expansion. `/bin/sh' normally
254 does not understand tilde expansion.
256 For encoding and deocding, commands like the following are executed:
258 /bin/sh -c COMMAND < INPUT > OUTPUT
260 This variable can be used to change the \"/bin/sh\" part. See the
261 variable `tramp-encoding-command-switch' for the \"-c\" part.
263 Note that this variable is not used for remote commands. There are
264 mechanisms in tramp.el which automatically determine the right shell to
265 use for the remote host."
267 :type '(file :must-match t))
269 (defcustom tramp-encoding-command-switch
270 (if (string-match "cmd\\.exe" tramp-encoding-shell)
273 "*Use this switch together with `tramp-encoding-shell' for local commands.
274 See the variable `tramp-encoding-shell' for more information."
278 (defcustom tramp-copy-size-limit 10240
279 "*The maximum file size where inline copying is preferred over an out-of-the-band copy."
283 (defcustom tramp-terminal-type "dumb"
284 "*Value of TERM environment variable for logging in to remote host.
285 Because Tramp wants to parse the output of the remote shell, it is easily
286 confused by ANSI color escape sequences and suchlike. Often, shell init
287 files conditionalize this setup based on the TERM environment variable."
291 (defvar tramp-methods
292 `(("rcp" (tramp-login-program "rsh")
293 (tramp-login-args (("%h") ("-l" "%u")))
294 (tramp-remote-sh "/bin/sh")
295 (tramp-copy-program "rcp")
296 (tramp-copy-args (("-p" "%k")))
297 (tramp-copy-keep-date t)
298 (tramp-password-end-of-line nil))
299 ("scp" (tramp-login-program "ssh")
300 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
302 (tramp-remote-sh "/bin/sh")
303 (tramp-copy-program "scp")
304 (tramp-copy-args (("-P" "%p") ("-p" "%k") ("-q")))
305 (tramp-copy-keep-date t)
306 (tramp-password-end-of-line nil)
307 (tramp-gw-args (("-o"
308 "GlobalKnownHostsFile=/dev/null")
309 ("-o" "UserKnownHostsFile=/dev/null")
310 ("-o" "StrictHostKeyChecking=no")))
311 (tramp-default-port 22))
312 ("scp1" (tramp-login-program "ssh")
313 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
315 (tramp-remote-sh "/bin/sh")
316 (tramp-copy-program "scp")
317 (tramp-copy-args (("-1") ("-P" "%p") ("-p" "%k")
319 (tramp-copy-keep-date t)
320 (tramp-password-end-of-line nil)
321 (tramp-gw-args (("-o"
322 "GlobalKnownHostsFile=/dev/null")
323 ("-o" "UserKnownHostsFile=/dev/null")
324 ("-o" "StrictHostKeyChecking=no")))
325 (tramp-default-port 22))
326 ("scp2" (tramp-login-program "ssh")
327 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
329 (tramp-remote-sh "/bin/sh")
330 (tramp-copy-program "scp")
331 (tramp-copy-args (("-2") ("-P" "%p") ("-p" "%k")
333 (tramp-copy-keep-date t)
334 (tramp-password-end-of-line nil)
335 (tramp-gw-args (("-o"
336 "GlobalKnownHostsFile=/dev/null")
337 ("-o" "UserKnownHostsFile=/dev/null")
338 ("-o" "StrictHostKeyChecking=no")))
339 (tramp-default-port 22))
341 (tramp-login-program "ssh1")
342 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
344 (tramp-remote-sh "/bin/sh")
345 (tramp-copy-program "scp1")
346 (tramp-copy-args (("-p" "%k")))
347 (tramp-copy-keep-date t)
348 (tramp-password-end-of-line nil))
350 (tramp-login-program "ssh2")
351 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
353 (tramp-remote-sh "/bin/sh")
354 (tramp-copy-program "scp2")
355 (tramp-copy-args (("-p" "%k")))
356 (tramp-copy-keep-date t)
357 (tramp-password-end-of-line nil))
358 ("sftp" (tramp-login-program "ssh")
359 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
361 (tramp-remote-sh "/bin/sh")
362 (tramp-copy-program "sftp")
363 (tramp-copy-args nil)
364 (tramp-copy-keep-date nil)
365 (tramp-password-end-of-line nil))
366 ("rsync" (tramp-login-program "ssh")
367 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
369 (tramp-remote-sh "/bin/sh")
370 (tramp-copy-program "rsync")
371 (tramp-copy-args (("-e" "ssh") ("-t" "%k")))
372 (tramp-copy-keep-date t)
373 (tramp-password-end-of-line nil))
374 ("remcp" (tramp-login-program "remsh")
375 (tramp-login-args (("%h") ("-l" "%u")))
376 (tramp-remote-sh "/bin/sh")
377 (tramp-copy-program "rcp")
378 (tramp-copy-args (("-p" "%k")))
379 (tramp-copy-keep-date t)
380 (tramp-password-end-of-line nil))
381 ("rsh" (tramp-login-program "rsh")
382 (tramp-login-args (("%h") ("-l" "%u")))
383 (tramp-remote-sh "/bin/sh")
384 (tramp-copy-program nil)
385 (tramp-copy-args nil)
386 (tramp-copy-keep-date nil)
387 (tramp-password-end-of-line nil))
388 ("ssh" (tramp-login-program "ssh")
389 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
391 (tramp-remote-sh "/bin/sh")
392 (tramp-copy-program nil)
393 (tramp-copy-args nil)
394 (tramp-copy-keep-date nil)
395 (tramp-password-end-of-line nil)
396 (tramp-gw-args (("-o"
397 "GlobalKnownHostsFile=/dev/null")
398 ("-o" "UserKnownHostsFile=/dev/null")
399 ("-o" "StrictHostKeyChecking=no")))
400 (tramp-default-port 22))
401 ("ssh1" (tramp-login-program "ssh")
402 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
404 (tramp-remote-sh "/bin/sh")
405 (tramp-copy-program nil)
406 (tramp-copy-args nil)
407 (tramp-copy-keep-date nil)
408 (tramp-password-end-of-line nil)
409 (tramp-gw-args (("-o"
410 "GlobalKnownHostsFile=/dev/null")
411 ("-o" "UserKnownHostsFile=/dev/null")
412 ("-o" "StrictHostKeyChecking=no")))
413 (tramp-default-port 22))
414 ("ssh2" (tramp-login-program "ssh")
415 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
417 (tramp-remote-sh "/bin/sh")
418 (tramp-copy-program nil)
419 (tramp-copy-args nil)
420 (tramp-copy-keep-date nil)
421 (tramp-password-end-of-line nil)
422 (tramp-gw-args (("-o"
423 "GlobalKnownHostsFile=/dev/null")
424 ("-o" "UserKnownHostsFile=/dev/null")
425 ("-o" "StrictHostKeyChecking=no")))
426 (tramp-default-port 22))
428 (tramp-login-program "ssh1")
429 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
431 (tramp-remote-sh "/bin/sh")
432 (tramp-copy-program nil)
433 (tramp-copy-args nil)
434 (tramp-copy-keep-date nil)
435 (tramp-password-end-of-line nil))
437 (tramp-login-program "ssh2")
438 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
440 (tramp-remote-sh "/bin/sh")
441 (tramp-copy-program nil)
442 (tramp-copy-args nil)
443 (tramp-copy-keep-date nil)
444 (tramp-password-end-of-line nil))
445 ("remsh" (tramp-login-program "remsh")
446 (tramp-login-args (("%h") ("-l" "%u")))
447 (tramp-remote-sh "/bin/sh")
448 (tramp-copy-program nil)
449 (tramp-copy-args nil)
450 (tramp-copy-keep-date nil)
451 (tramp-password-end-of-line nil))
453 (tramp-login-program "telnet")
454 (tramp-login-args (("%h") ("%p")))
455 (tramp-remote-sh "/bin/sh")
456 (tramp-copy-program nil)
457 (tramp-copy-args nil)
458 (tramp-copy-keep-date nil)
459 (tramp-password-end-of-line nil)
460 (tramp-default-port 23))
461 ("su" (tramp-login-program "su")
462 (tramp-login-args (("-") ("%u")))
463 (tramp-remote-sh "/bin/sh")
464 (tramp-copy-program nil)
465 (tramp-copy-args nil)
466 (tramp-copy-keep-date nil)
467 (tramp-password-end-of-line nil))
468 ("sudo" (tramp-login-program "sudo")
469 (tramp-login-args (("-u" "%u")
470 ("-s") ("-H") ("-p" "Password:")))
471 (tramp-remote-sh "/bin/sh")
472 (tramp-copy-program nil)
473 (tramp-copy-args nil)
474 (tramp-copy-keep-date nil)
475 (tramp-password-end-of-line nil))
476 ("scpc" (tramp-login-program "ssh")
477 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
478 ("-o" "ControlPath=%t.%%r@%%h:%%p")
479 ("-o" "ControlMaster=yes")
481 (tramp-remote-sh "/bin/sh")
482 (tramp-copy-program "scp")
483 (tramp-copy-args (("-P" "%p") ("-p" "%k") ("-q")
484 ("-o" "ControlPath=%t.%%r@%%h:%%p")
485 ("-o" "ControlMaster=auto")))
486 (tramp-copy-keep-date t)
487 (tramp-password-end-of-line nil)
488 (tramp-gw-args (("-o"
489 "GlobalKnownHostsFile=/dev/null")
490 ("-o" "UserKnownHostsFile=/dev/null")
491 ("-o" "StrictHostKeyChecking=no")))
492 (tramp-default-port 22))
493 ("scpx" (tramp-login-program "ssh")
494 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
495 ("-e" "none" "-t" "-t" "/bin/sh")))
496 (tramp-remote-sh "/bin/sh")
497 (tramp-copy-program "scp")
498 (tramp-copy-args (("-p" "%k")))
499 (tramp-copy-keep-date t)
500 (tramp-password-end-of-line nil)
501 (tramp-gw-args (("-o"
502 "GlobalKnownHostsFile=/dev/null")
503 ("-o" "UserKnownHostsFile=/dev/null")
504 ("-o" "StrictHostKeyChecking=no")))
505 (tramp-default-port 22))
506 ("sshx" (tramp-login-program "ssh")
507 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
508 ("-e" "none" "-t" "-t" "/bin/sh")))
509 (tramp-remote-sh "/bin/sh")
510 (tramp-copy-program nil)
511 (tramp-copy-args nil)
512 (tramp-copy-keep-date nil)
513 (tramp-password-end-of-line nil)
514 (tramp-gw-args (("-o"
515 "GlobalKnownHostsFile=/dev/null")
516 ("-o" "UserKnownHostsFile=/dev/null")
517 ("-o" "StrictHostKeyChecking=no")))
518 (tramp-default-port 22))
520 (tramp-login-program "krlogin")
521 (tramp-login-args (("%h") ("-l" "%u") ("-x")))
522 (tramp-remote-sh "/bin/sh")
523 (tramp-copy-program nil)
524 (tramp-copy-args nil)
525 (tramp-copy-keep-date nil)
526 (tramp-password-end-of-line nil))
527 ("plink" (tramp-login-program "plink")
528 (tramp-login-args (("%h") ("-l" "%u") ("-P" "%p")
530 (tramp-remote-sh "/bin/sh")
531 (tramp-copy-program nil)
532 (tramp-copy-args nil)
533 (tramp-copy-keep-date nil)
534 (tramp-password-end-of-line "xy") ;see docstring for "xy"
535 (tramp-default-port 22))
537 (tramp-login-program "plink")
538 (tramp-login-args (("%h") ("-l" "%u") ("-P" "%p")
540 (tramp-remote-sh "/bin/sh")
541 (tramp-copy-program nil)
542 (tramp-copy-args nil)
543 (tramp-copy-keep-date nil)
544 (tramp-password-end-of-line "xy") ;see docstring for "xy"
545 (tramp-default-port 22))
547 (tramp-login-program "plink")
548 ;; ("%h") must be a single element, see
549 ;; `tramp-compute-multi-hops'.
550 (tramp-login-args (("-load") ("%h") ("-t")
552 "env 'TERM=%s' 'PROMPT_COMMAND=' 'PS1=$ '"
553 tramp-terminal-type))
555 (tramp-remote-sh "/bin/sh")
556 (tramp-copy-program nil)
557 (tramp-copy-args nil)
558 (tramp-copy-keep-date nil)
559 (tramp-password-end-of-line nil))
560 ("pscp" (tramp-login-program "plink")
561 (tramp-login-args (("%h") ("-l" "%u") ("-P" "%p")
563 (tramp-remote-sh "/bin/sh")
564 (tramp-copy-program "pscp")
565 (tramp-copy-args (("-P" "%p") ("-scp") ("-p" "%k")))
566 (tramp-copy-keep-date t)
567 (tramp-password-end-of-line "xy") ;see docstring for "xy"
568 (tramp-default-port 22))
569 ("psftp" (tramp-login-program "plink")
570 (tramp-login-args (("%h") ("-l" "%u") ("-P" "%p")
572 (tramp-remote-sh "/bin/sh")
573 (tramp-copy-program "pscp")
574 (tramp-copy-args (("-P" "%p") ("-sftp") ("-p" "%k")))
575 (tramp-copy-keep-date t)
576 (tramp-password-end-of-line "xy")) ;see docstring for "xy"
577 ("fcp" (tramp-login-program "fsh")
578 (tramp-login-args (("%h") ("-l" "%u") ("sh" "-i")))
579 (tramp-remote-sh "/bin/sh -i")
580 (tramp-copy-program "fcp")
581 (tramp-copy-args (("-p" "%k")))
582 (tramp-copy-keep-date t)
583 (tramp-password-end-of-line nil)))
584 "*Alist of methods for remote files.
585 This is a list of entries of the form (NAME PARAM1 PARAM2 ...).
586 Each NAME stands for a remote access method. Each PARAM is a
587 pair of the form (KEY VALUE). The following KEYs are defined:
589 This specifies the Bourne shell to use on the remote host. This
590 MUST be a Bourne-like shell. It is normally not necessary to set
591 this to any value other than \"/bin/sh\": Tramp wants to use a shell
592 which groks tilde expansion, but it can search for it. Also note
593 that \"/bin/sh\" exists on all Unixen, this might not be true for
594 the value that you decide to use. You Have Been Warned.
595 * `tramp-login-program'
596 This specifies the name of the program to use for logging in to the
597 remote host. This may be the name of rsh or a workalike program,
598 or the name of telnet or a workalike, or the name of su or a workalike.
600 This specifies the list of arguments to pass to the above
601 mentioned program. Please note that this is a list of list of arguments,
602 that is, normally you don't want to put \"-a -b\" or \"-f foo\"
603 here. Instead, you want a list (\"-a\" \"-b\"), or (\"-f\" \"foo\").
604 There are some patterns: \"%h\" in this list is replaced by the host
605 name, \"%u\" is replaced by the user name, \"%p\" is replaced by the
606 port number, and \"%%\" can be used to obtain a literal percent character.
607 If a list containing \"%h\", \"%u\" or \"%p\" is unchanged during
608 expansion (i.e. no host or no user specified), this list is not used as
609 argument. By this, arguments like (\"-l\" \"%u\") are optional.
610 \"%t\" is replaced by the temporary file name produced with
611 `tramp-make-tramp-temp-file'. \"%k\" indicates the keep-date
612 parameter of a program, if exists.
613 * `tramp-copy-program'
614 This specifies the name of the program to use for remotely copying
615 the file; this might be the absolute filename of rcp or the name of
618 This specifies the list of parameters to pass to the above mentioned
619 program, the hints for `tramp-login-args' also apply here.
620 * `tramp-copy-keep-date'
621 This specifies whether the copying program when the preserves the
622 timestamp of the original file.
623 * `tramp-default-port'
624 The default port of a method is needed in case of gateway connections.
625 Additionally, it is used as indication which method is prepared for
628 As the attribute name says, additional arguments are specified here
629 when a method is applied via a gateway.
630 * `tramp-password-end-of-line'
631 This specifies the string to use for terminating the line after
632 submitting the password. If this method parameter is nil, then the
633 value of the normal variable `tramp-default-password-end-of-line'
634 is used. This parameter is necessary because the \"plink\" program
635 requires any two characters after sending the password. These do
636 not have to be newline or carriage return characters. Other login
637 programs are happy with just one character, the newline character.
638 We use \"xy\" as the value for methods using \"plink\".
640 What does all this mean? Well, you should specify `tramp-login-program'
641 for all methods; this program is used to log in to the remote site. Then,
642 there are two ways to actually transfer the files between the local and the
643 remote side. One way is using an additional rcp-like program. If you want
644 to do this, set `tramp-copy-program' in the method.
646 Another possibility for file transfer is inline transfer, i.e. the
647 file is passed through the same buffer used by `tramp-login-program'. In
648 this case, the file contents need to be protected since the
649 `tramp-login-program' might use escape codes or the connection might not
650 be eight-bit clean. Therefore, file contents are encoded for transit.
651 See the variables `tramp-local-coding-commands' and
652 `tramp-remote-coding-commands' for details.
654 So, to summarize: if the method is an out-of-band method, then you
655 must specify `tramp-copy-program' and `tramp-copy-args'. If it is an
656 inline method, then these two parameters should be nil. Methods which
657 are fit for gateways must have `tramp-default-port' at least.
661 When using `su' or `sudo' the phrase `open connection to a remote
662 host' sounds strange, but it is used nevertheless, for consistency.
663 No connection is opened to a remote host, but `su' or `sudo' is
664 started on the local host. You should specify a remote host
665 `localhost' or the name of the local host. Another host name is
666 useful only in combination with `tramp-default-proxies-alist'.")
668 (defcustom tramp-default-method
669 ;; An external copy method seems to be preferred, because it is much
670 ;; more performant for large files, and it hasn't too serious delays
671 ;; for small files. But it must be ensured that there aren't
672 ;; permanent password queries. Either a password agent like
673 ;; "ssh-agent" or "Pageant" shall run, or the optional password.el
674 ;; package shall be active for password caching. "scpc" would be
675 ;; another good choice because of the "ControlMaster" option, but
676 ;; this is a more modern alternative in OpenSSH 4, which cannot be
679 ;; PuTTY is installed.
680 ((executable-find "pscp")
681 (if (or (fboundp 'password-read)
682 ;; Pageant is running.
683 (tramp-compat-process-running-p "Pageant"))
686 ;; There is an ssh installation.
687 ((executable-find "scp")
688 (if (or (fboundp 'password-read)
689 ;; ssh-agent is running.
690 (getenv "SSH_AUTH_SOCK")
691 (getenv "SSH_AGENT_PID"))
696 "*Default method to use for transferring files.
697 See `tramp-methods' for possibilities.
698 Also see `tramp-default-method-alist'."
702 (defcustom tramp-default-method-alist
703 '(("\\`localhost\\'" "\\`root\\'" "su"))
704 "*Default method to use for specific host/user pairs.
705 This is an alist of items (HOST USER METHOD). The first matching item
706 specifies the method to use for a file name which does not specify a
707 method. HOST and USER are regular expressions or nil, which is
708 interpreted as a regular expression which always matches. If no entry
709 matches, the variable `tramp-default-method' takes effect.
711 If the file name does not specify the user, lookup is done using the
712 empty string for the user name.
714 See `tramp-methods' for a list of possibilities for METHOD."
716 :type '(repeat (list (regexp :tag "Host regexp")
717 (regexp :tag "User regexp")
718 (string :tag "Method"))))
720 (defcustom tramp-default-user
722 "*Default user to use for transferring files.
723 It is nil by default; otherwise settings in configuration files like
724 \"~/.ssh/config\" would be overwritten. Also see `tramp-default-user-alist'.
726 This variable is regarded as obsolete, and will be removed soon."
728 :type '(choice (const nil) string))
730 (defcustom tramp-default-user-alist
731 `(("\\`su\\(do\\)?\\'" nil "root")
732 ("\\`r\\(em\\)?\\(cp\\|sh\\)\\|telnet\\|plink1?\\'"
733 nil ,(user-login-name)))
734 "*Default user to use for specific method/host pairs.
735 This is an alist of items (METHOD HOST USER). The first matching item
736 specifies the user to use for a file name which does not specify a
737 user. METHOD and USER are regular expressions or nil, which is
738 interpreted as a regular expression which always matches. If no entry
739 matches, the variable `tramp-default-user' takes effect.
741 If the file name does not specify the method, lookup is done using the
742 empty string for the method name."
744 :type '(repeat (list (regexp :tag "Method regexp")
745 (regexp :tag "Host regexp")
746 (string :tag "User"))))
748 (defcustom tramp-default-host
750 "*Default host to use for transferring files.
751 Useful for su and sudo methods mostly."
755 (defcustom tramp-default-proxies-alist nil
756 "*Route to be followed for specific host/user pairs.
757 This is an alist of items (HOST USER PROXY). The first matching
758 item specifies the proxy to be passed for a file name located on
759 a remote target matching USER@HOST. HOST and USER are regular
760 expressions. PROXY must be a Tramp filename without a localname
761 part. Method and user name on PROXY are optional, which is
762 interpreted with the default values. PROXY can contain the
763 patterns %h and %u, which are replaced by the strings matching
764 HOST or USER, respectively.
766 HOST, USER or PROXY could also be Lisp forms, which will be
767 evaluated. The result must be a string or nil, which is
768 interpreted as a regular expression which always matches."
770 :type '(repeat (list (choice :tag "Host regexp" regexp sexp)
771 (choice :tag "User regexp" regexp sexp)
772 (choice :tag "Proxy remote name" string (const nil)))))
774 (defconst tramp-local-host-regexp
776 "^" (regexp-opt (list "localhost" (system-name) "127\.0\.0\.1" "::1") t) "$")
777 "*Host names which are regarded as local host.")
779 (defconst tramp-completion-function-alist-rsh
780 '((tramp-parse-rhosts "/etc/hosts.equiv")
781 (tramp-parse-rhosts "~/.rhosts"))
782 "Default list of (FUNCTION FILE) pairs to be examined for rsh methods.")
784 (defconst tramp-completion-function-alist-ssh
785 '((tramp-parse-rhosts "/etc/hosts.equiv")
786 (tramp-parse-rhosts "/etc/shosts.equiv")
787 (tramp-parse-shosts "/etc/ssh_known_hosts")
788 (tramp-parse-sconfig "/etc/ssh_config")
789 (tramp-parse-shostkeys "/etc/ssh2/hostkeys")
790 (tramp-parse-sknownhosts "/etc/ssh2/knownhosts")
791 (tramp-parse-rhosts "~/.rhosts")
792 (tramp-parse-rhosts "~/.shosts")
793 (tramp-parse-shosts "~/.ssh/known_hosts")
794 (tramp-parse-sconfig "~/.ssh/config")
795 (tramp-parse-shostkeys "~/.ssh2/hostkeys")
796 (tramp-parse-sknownhosts "~/.ssh2/knownhosts"))
797 "Default list of (FUNCTION FILE) pairs to be examined for ssh methods.")
799 (defconst tramp-completion-function-alist-telnet
800 '((tramp-parse-hosts "/etc/hosts"))
801 "Default list of (FUNCTION FILE) pairs to be examined for telnet methods.")
803 (defconst tramp-completion-function-alist-su
804 '((tramp-parse-passwd "/etc/passwd"))
805 "Default list of (FUNCTION FILE) pairs to be examined for su methods.")
807 (defconst tramp-completion-function-alist-putty
809 "HKEY_CURRENT_USER\\Software\\SimonTatham\\PuTTY\\Sessions"))
810 "Default list of (FUNCTION REGISTRY) pairs to be examined for putty methods.")
812 (defvar tramp-completion-function-alist nil
813 "*Alist of methods for remote files.
814 This is a list of entries of the form (NAME PAIR1 PAIR2 ...).
815 Each NAME stands for a remote access method. Each PAIR is of the form
816 \(FUNCTION FILE). FUNCTION is responsible to extract user names and host
817 names from FILE for completion. The following predefined FUNCTIONs exists:
819 * `tramp-parse-rhosts' for \"~/.rhosts\" like files,
820 * `tramp-parse-shosts' for \"~/.ssh/known_hosts\" like files,
821 * `tramp-parse-sconfig' for \"~/.ssh/config\" like files,
822 * `tramp-parse-shostkeys' for \"~/.ssh2/hostkeys/*\" like files,
823 * `tramp-parse-sknownhosts' for \"~/.ssh2/knownhosts/*\" like files,
824 * `tramp-parse-hosts' for \"/etc/hosts\" like files,
825 * `tramp-parse-passwd' for \"/etc/passwd\" like files.
826 * `tramp-parse-netrc' for \"~/.netrc\" like files.
827 * `tramp-parse-putty' for PuTTY registry keys.
829 FUNCTION can also be a customer defined function. For more details see
832 (eval-after-load "tramp"
834 (tramp-set-completion-function
835 "rcp" tramp-completion-function-alist-rsh)
836 (tramp-set-completion-function
837 "scp" tramp-completion-function-alist-ssh)
838 (tramp-set-completion-function
839 "scp1" tramp-completion-function-alist-ssh)
840 (tramp-set-completion-function
841 "scp2" tramp-completion-function-alist-ssh)
842 (tramp-set-completion-function
843 "scp1_old" tramp-completion-function-alist-ssh)
844 (tramp-set-completion-function
845 "scp2_old" tramp-completion-function-alist-ssh)
846 (tramp-set-completion-function
847 "rsync" tramp-completion-function-alist-ssh)
848 (tramp-set-completion-function
849 "remcp" tramp-completion-function-alist-rsh)
850 (tramp-set-completion-function
851 "rsh" tramp-completion-function-alist-rsh)
852 (tramp-set-completion-function
853 "ssh" tramp-completion-function-alist-ssh)
854 (tramp-set-completion-function
855 "ssh1" tramp-completion-function-alist-ssh)
856 (tramp-set-completion-function
857 "ssh2" tramp-completion-function-alist-ssh)
858 (tramp-set-completion-function
859 "ssh1_old" tramp-completion-function-alist-ssh)
860 (tramp-set-completion-function
861 "ssh2_old" tramp-completion-function-alist-ssh)
862 (tramp-set-completion-function
863 "remsh" tramp-completion-function-alist-rsh)
864 (tramp-set-completion-function
865 "telnet" tramp-completion-function-alist-telnet)
866 (tramp-set-completion-function
867 "su" tramp-completion-function-alist-su)
868 (tramp-set-completion-function
869 "sudo" tramp-completion-function-alist-su)
870 (tramp-set-completion-function
871 "scpx" tramp-completion-function-alist-ssh)
872 (tramp-set-completion-function
873 "sshx" tramp-completion-function-alist-ssh)
874 (tramp-set-completion-function
875 "krlogin" tramp-completion-function-alist-rsh)
876 (tramp-set-completion-function
877 "plink" tramp-completion-function-alist-ssh)
878 (tramp-set-completion-function
879 "plink1" tramp-completion-function-alist-ssh)
880 (tramp-set-completion-function
881 "plinkx" tramp-completion-function-alist-putty)
882 (tramp-set-completion-function
883 "pscp" tramp-completion-function-alist-ssh)
884 (tramp-set-completion-function
885 "fcp" tramp-completion-function-alist-ssh)))
887 (defconst tramp-echo-mark-marker "_echo"
888 "String marker to surround echoed commands.")
890 (defconst tramp-echo-mark "_echo\b\b\b\b\b"
891 "String mark to be transmitted around shell commands.
892 Used to separate their echo from the output they produce. This
893 will only be used if we cannot disable remote echo via stty.
894 This string must have no effect on the remote shell except for
895 producing some echo which can later be detected by
896 `tramp-echoed-echo-mark-regexp'. Using `tramp-echo-mark-marker',
897 followed by an equal number of backspaces to erase them will
900 (defconst tramp-echoed-echo-mark-regexp "_echo\\(\b\\( \b\\)?\\)\\{5\\}"
901 "Regexp which matches `tramp-echo-mark' as it gets echoed by
904 (defcustom tramp-rsh-end-of-line "\n"
905 "*String used for end of line in rsh connections.
906 I don't think this ever needs to be changed, so please tell me about it
907 if you need to change this.
908 Also see the method parameter `tramp-password-end-of-line' and the normal
909 variable `tramp-default-password-end-of-line'."
913 (defcustom tramp-default-password-end-of-line
914 tramp-rsh-end-of-line
915 "*String used for end of line after sending a password.
916 This variable provides the default value for the method parameter
917 `tramp-password-end-of-line', see `tramp-methods' for more details.
919 It seems that people using plink under Windows need to send
920 \"\\r\\n\" (carriage-return, then newline) after a password, but just
921 \"\\n\" after all other lines. This variable can be used for the
922 password, see `tramp-rsh-end-of-line' for the other cases.
924 The default value is to use the same value as `tramp-rsh-end-of-line'."
928 ;; "getconf PATH" yields:
929 ;; HP-UX: /usr/bin:/usr/ccs/bin:/opt/ansic/bin:/opt/langtools/bin:/opt/fortran/bin
930 ;; Solaris: /usr/xpg4/bin:/usr/ccs/bin:/usr/bin:/opt/SUNWspro/bin
931 ;; GNU/Linux (Debian, Suse): /bin:/usr/bin
932 ;; FreeBSD: /usr/bin:/bin:/usr/sbin:/sbin: - beware trailing ":"!
933 (defcustom tramp-remote-path
934 '(tramp-default-remote-path "/usr/sbin" "/usr/local/bin"
935 "/local/bin" "/local/freeware/bin" "/local/gnu/bin"
936 "/usr/freeware/bin" "/usr/pkg/bin" "/usr/contrib/bin")
937 "*List of directories to search for executables on remote host.
938 For every remote host, this variable will be set buffer local,
939 keeping the list of existing directories on that host.
941 You can use `~' in this list, but when searching for a shell which groks
942 tilde expansion, all directory names starting with `~' will be ignored.
944 `Default Directories' represent the list of directories given by
945 the command \"getconf PATH\". It is recommended to use this
946 entry on top of this list, because these are the default
947 directories for POSIX compatible commands.
949 `Private Directories' are the settings of the $PATH environment,
950 as given in your `~/.profile'."
952 :type '(repeat (choice
953 (const :tag "Default Directories" tramp-default-remote-path)
954 (const :tag "Private Directories" tramp-own-remote-path)
955 (string :tag "Directory"))))
957 (defcustom tramp-remote-process-environment
958 `("HISTFILE=$HOME/.tramp_history" "HISTSIZE=1" "LC_ALL=C"
959 ,(concat "TERM=" tramp-terminal-type)
960 "EMACS=t" ;; Deprecated.
961 ,(format "INSIDE_EMACS=%s,tramp:%s" emacs-version tramp-version)
962 "CDPATH=" "HISTORY=" "MAIL=" "MAILCHECK=" "MAILPATH="
963 "autocorrect=" "correct=")
965 "*List of environment variables to be set on the remote host.
967 Each element should be a string of the form ENVVARNAME=VALUE. An
968 entry ENVVARNAME= diables the corresponding environment variable,
969 which might have been set in the init files like ~/.profile.
971 Special handling is applied to the PATH environment, which should
972 not be set here. Instead of, it should be set via `tramp-remote-path'."
974 :type '(repeat string))
976 (defcustom tramp-login-prompt-regexp
977 ".*ogin\\( .*\\)?: *"
978 "*Regexp matching login-like prompts.
979 The regexp should match at end of buffer.
981 Sometimes the prompt is reported to look like \"login as:\"."
985 (defcustom tramp-shell-prompt-pattern
986 "^[^#$%>\n]*[#$%>] *\\(\e\\[[0-9;]*[a-zA-Z] *\\)*"
987 "Regexp to match prompts from remote shell.
988 Normally, Tramp expects you to configure `shell-prompt-pattern'
989 correctly, but sometimes it happens that you are connecting to a
990 remote host which sends a different kind of shell prompt. Therefore,
991 Tramp recognizes things matched by `shell-prompt-pattern' as prompt,
992 and also things matched by this variable. The default value of this
993 variable is similar to the default value of `shell-prompt-pattern',
994 which should work well in many cases."
998 (defcustom tramp-password-prompt-regexp
999 "^.*\\([pP]assword\\|[pP]assphrase\\).*:\^@? *"
1000 "*Regexp matching password-like prompts.
1001 The regexp should match at end of buffer.
1003 The `sudo' program appears to insert a `^@' character into the prompt."
1007 (defcustom tramp-wrong-passwd-regexp
1009 ;; These strings should be on the last line
1010 (regexp-opt '("Permission denied"
1013 "Connection refused"
1016 "Name or service not known"
1017 "Host key verification failed."
1018 "No supported authentication methods left to try!") t)
1022 ;; Here comes a list of regexes, separated by \\|
1023 "Received signal [0-9]+"
1025 "*Regexp matching a `login failed' message.
1026 The regexp should match at end of buffer."
1030 (defcustom tramp-yesno-prompt-regexp
1032 (regexp-opt '("Are you sure you want to continue connecting (yes/no)?") t)
1034 "Regular expression matching all yes/no queries which need to be confirmed.
1035 The confirmation should be done with yes or no.
1036 The regexp should match at end of buffer.
1037 See also `tramp-yn-prompt-regexp'."
1041 (defcustom tramp-yn-prompt-regexp
1043 (regexp-opt '("Store key in cache? (y/n)"
1044 "Update cached key? (y/n, Return cancels connection)") t)
1046 "Regular expression matching all y/n queries which need to be confirmed.
1047 The confirmation should be done with y or n.
1048 The regexp should match at end of buffer.
1049 See also `tramp-yesno-prompt-regexp'."
1053 (defcustom tramp-terminal-prompt-regexp
1057 "Terminal type\\? \\[.*\\]"
1059 "Regular expression matching all terminal setting prompts.
1060 The regexp should match at end of buffer.
1061 The answer will be provided by `tramp-action-terminal', which see."
1065 (defcustom tramp-operation-not-permitted-regexp
1066 (concat "\\(" "preserving times.*" "\\|" "set mode" "\\)" ":\\s-*"
1067 (regexp-opt '("Operation not permitted") t))
1068 "Regular expression matching keep-date problems in (s)cp operations.
1069 Copying has been performed successfully already, so this message can
1074 (defcustom tramp-copy-failed-regexp
1076 (regexp-opt '("Permission denied"
1077 "not a regular file"
1079 "No such file or directory") t)
1081 "Regular expression matching copy problems in (s)cp operations."
1085 (defcustom tramp-process-alive-regexp
1087 "Regular expression indicating a process has finished.
1088 In fact this expression is empty by intention, it will be used only to
1089 check regularly the status of the associated process.
1090 The answer will be provided by `tramp-action-process-alive',
1091 `tramp-action-out-of-band', which see."
1095 (defcustom tramp-temp-name-prefix "tramp."
1096 "*Prefix to use for temporary files.
1097 If this is a relative file name (such as \"tramp.\"), it is considered
1098 relative to the directory name returned by the function
1099 `tramp-compat-temporary-file-directory' (which see). It may also be an
1100 absolute file name; don't forget to include a prefix for the filename
1105 (defconst tramp-temp-buffer-name " *tramp temp*"
1106 "Buffer name for a temporary buffer.
1107 It shall be used in combination with `generate-new-buffer-name'.")
1109 (defcustom tramp-sh-extra-args '(("/bash\\'" . "-norc -noprofile"))
1110 "*Alist specifying extra arguments to pass to the remote shell.
1111 Entries are (REGEXP . ARGS) where REGEXP is a regular expression
1112 matching the shell file name and ARGS is a string specifying the
1115 This variable is only used when Tramp needs to start up another shell
1116 for tilde expansion. The extra arguments should typically prevent the
1117 shell from reading its init file."
1119 ;; This might be the wrong way to test whether the widget type
1120 ;; `alist' is available. Who knows the right way to test it?
1121 :type (if (get 'alist 'widget-type)
1122 '(alist :key-type string :value-type string)
1123 '(repeat (cons string string))))
1125 ;; XEmacs is distributed with few Lisp packages. Further packages are
1126 ;; installed using EFS. If we use a unified filename format, then
1127 ;; Tramp is required in addition to EFS. (But why can't Tramp just
1128 ;; disable EFS when Tramp is loaded? Then XEmacs can ship with EFS
1129 ;; just like before.) Another reason for using a separate filename
1130 ;; syntax on XEmacs is that EFS hooks into XEmacs in many places, but
1131 ;; Tramp only knows how to deal with `file-name-handler-alist', not
1132 ;; the other places.
1134 ;; Currently, we have the choice between 'ftp, 'sep, and 'url.
1136 (defcustom tramp-syntax
1137 (if (featurep 'xemacs) 'sep 'ftp)
1138 "Tramp filename syntax to be used.
1140 It can have the following values:
1142 'ftp -- Ange-FTP respective EFS like syntax (GNU Emacs default)
1143 'sep -- Syntax as defined for XEmacs (not available yet for GNU Emacs)
1144 'url -- URL-like syntax."
1146 :type (if (featurep 'xemacs)
1147 '(choice (const :tag "EFS" ftp)
1148 (const :tag "XEmacs" sep)
1149 (const :tag "URL" url))
1150 '(choice (const :tag "Ange-FTP" ftp)
1151 (const :tag "URL" url))))
1153 (defconst tramp-prefix-format
1154 (cond ((equal tramp-syntax 'ftp) "/")
1155 ((equal tramp-syntax 'sep) "/[")
1156 ((equal tramp-syntax 'url) "/")
1157 (t (error "Wrong `tramp-syntax' defined")))
1158 "*String matching the very beginning of Tramp file names.
1159 Used in `tramp-make-tramp-file-name'.")
1161 (defconst tramp-prefix-regexp
1162 (concat "^" (regexp-quote tramp-prefix-format))
1163 "*Regexp matching the very beginning of Tramp file names.
1164 Should always start with \"^\". Derived from `tramp-prefix-format'.")
1166 (defconst tramp-method-regexp
1168 "*Regexp matching methods identifiers.")
1170 (defconst tramp-postfix-method-format
1171 (cond ((equal tramp-syntax 'ftp) ":")
1172 ((equal tramp-syntax 'sep) "/")
1173 ((equal tramp-syntax 'url) "://")
1174 (t (error "Wrong `tramp-syntax' defined")))
1175 "*String matching delimeter between method and user or host names.
1176 Used in `tramp-make-tramp-file-name'.")
1178 (defconst tramp-postfix-method-regexp
1179 (regexp-quote tramp-postfix-method-format)
1180 "*Regexp matching delimeter between method and user or host names.
1181 Derived from `tramp-postfix-method-format'.")
1183 (defconst tramp-user-regexp
1185 "*Regexp matching user names.")
1187 (defconst tramp-prefix-domain-format "%"
1188 "*String matching delimeter between user and domain names.")
1190 (defconst tramp-prefix-domain-regexp
1191 (regexp-quote tramp-prefix-domain-format)
1192 "*Regexp matching delimeter between user and domain names.
1193 Derived from `tramp-prefix-domain-format'.")
1195 (defconst tramp-domain-regexp
1197 "*Regexp matching domain names.")
1199 (defconst tramp-user-with-domain-regexp
1200 (concat "\\(" tramp-user-regexp "\\)"
1201 tramp-prefix-domain-regexp
1202 "\\(" tramp-domain-regexp "\\)")
1203 "*Regexp matching user names with domain names.")
1205 (defconst tramp-postfix-user-format
1207 "*String matching delimeter between user and host names.
1208 Used in `tramp-make-tramp-file-name'.")
1210 (defconst tramp-postfix-user-regexp
1211 (regexp-quote tramp-postfix-user-format)
1212 "*Regexp matching delimeter between user and host names.
1213 Derived from `tramp-postfix-user-format'.")
1215 (defconst tramp-host-regexp
1217 "*Regexp matching host names.")
1219 (defconst tramp-prefix-ipv6-format
1220 (cond ((equal tramp-syntax 'ftp) "[")
1221 ((equal tramp-syntax 'sep) "")
1222 ((equal tramp-syntax 'url) "[")
1223 (t (error "Wrong `tramp-syntax' defined")))
1224 "*String matching left hand side of IPv6 addresses.
1225 Used in `tramp-make-tramp-file-name'.")
1227 (defconst tramp-prefix-ipv6-regexp
1228 (regexp-quote tramp-prefix-ipv6-format)
1229 "*Regexp matching left hand side of IPv6 addresses.
1230 Derived from `tramp-prefix-ipv6-format'.")
1232 ;; The following regexp is a bit sloppy. But it shall serve our
1233 ;; purposes. It covers also IPv4 mapped IPv6 addresses, like in
1234 ;; "::ffff:192.168.0.1".
1235 (defconst tramp-ipv6-regexp
1236 "\\(?:\\(?:[a-zA-Z0-9]+\\)?:\\)+[a-zA-Z0-9.]+"
1237 "*Regexp matching IPv6 addresses.")
1239 (defconst tramp-postfix-ipv6-format
1240 (cond ((equal tramp-syntax 'ftp) "]")
1241 ((equal tramp-syntax 'sep) "")
1242 ((equal tramp-syntax 'url) "]")
1243 (t (error "Wrong `tramp-syntax' defined")))
1244 "*String matching right hand side of IPv6 addresses.
1245 Used in `tramp-make-tramp-file-name'.")
1247 (defconst tramp-postfix-ipv6-regexp
1248 (regexp-quote tramp-postfix-ipv6-format)
1249 "*Regexp matching right hand side of IPv6 addresses.
1250 Derived from `tramp-postfix-ipv6-format'.")
1252 (defconst tramp-prefix-port-format
1253 (cond ((equal tramp-syntax 'ftp) "#")
1254 ((equal tramp-syntax 'sep) "#")
1255 ((equal tramp-syntax 'url) ":")
1256 (t (error "Wrong `tramp-syntax' defined")))
1257 "*String matching delimeter between host names and port numbers.")
1259 (defconst tramp-prefix-port-regexp
1260 (regexp-quote tramp-prefix-port-format)
1261 "*Regexp matching delimeter between host names and port numbers.
1262 Derived from `tramp-prefix-port-format'.")
1264 (defconst tramp-port-regexp
1266 "*Regexp matching port numbers.")
1268 (defconst tramp-host-with-port-regexp
1269 (concat "\\(" tramp-host-regexp "\\)"
1270 tramp-prefix-port-regexp
1271 "\\(" tramp-port-regexp "\\)")
1272 "*Regexp matching host names with port numbers.")
1274 (defconst tramp-postfix-host-format
1275 (cond ((equal tramp-syntax 'ftp) ":")
1276 ((equal tramp-syntax 'sep) "]")
1277 ((equal tramp-syntax 'url) "")
1278 (t (error "Wrong `tramp-syntax' defined")))
1279 "*String matching delimeter between host names and localnames.
1280 Used in `tramp-make-tramp-file-name'.")
1282 (defconst tramp-postfix-host-regexp
1283 (regexp-quote tramp-postfix-host-format)
1284 "*Regexp matching delimeter between host names and localnames.
1285 Derived from `tramp-postfix-host-format'.")
1287 (defconst tramp-localname-regexp
1289 "*Regexp matching localnames.")
1291 ;; File name format.
1293 (defconst tramp-file-name-structure
1297 "\\(" "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp "\\)?"
1298 "\\(" "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp "\\)?"
1299 "\\(" "\\(" tramp-host-regexp
1301 tramp-prefix-ipv6-regexp tramp-ipv6-regexp
1302 tramp-postfix-ipv6-regexp "\\)"
1303 "\\(" tramp-prefix-port-regexp tramp-port-regexp "\\)?" "\\)?"
1304 tramp-postfix-host-regexp
1305 "\\(" tramp-localname-regexp "\\)")
1308 "*List of five elements (REGEXP METHOD USER HOST FILE), detailing \
1309 the Tramp file name structure.
1311 The first element REGEXP is a regular expression matching a Tramp file
1312 name. The regex should contain parentheses around the method name,
1313 the user name, the host name, and the file name parts.
1315 The second element METHOD is a number, saying which pair of
1316 parentheses matches the method name. The third element USER is
1317 similar, but for the user name. The fourth element HOST is similar,
1318 but for the host name. The fifth element FILE is for the file name.
1319 These numbers are passed directly to `match-string', which see. That
1320 means the opening parentheses are counted to identify the pair.
1322 See also `tramp-file-name-regexp'.")
1325 (defconst tramp-file-name-regexp-unified
1326 "\\`/\\([^[/:]+\\|[^/]+]\\):"
1327 "Value for `tramp-file-name-regexp' for unified remoting.
1328 Emacs (not XEmacs) uses a unified filename syntax for Ange-FTP and
1329 Tramp. See `tramp-file-name-structure' for more explanations.")
1332 (defconst tramp-file-name-regexp-separate
1334 "Value for `tramp-file-name-regexp' for separate remoting.
1335 XEmacs uses a separate filename syntax for Tramp and EFS.
1336 See `tramp-file-name-structure' for more explanations.")
1339 (defconst tramp-file-name-regexp-url
1341 "Value for `tramp-file-name-regexp' for URL-like remoting.
1342 See `tramp-file-name-structure' for more explanations.")
1345 (defconst tramp-file-name-regexp
1346 (cond ((equal tramp-syntax 'ftp) tramp-file-name-regexp-unified)
1347 ((equal tramp-syntax 'sep) tramp-file-name-regexp-separate)
1348 ((equal tramp-syntax 'url) tramp-file-name-regexp-url)
1349 (t (error "Wrong `tramp-syntax' defined")))
1350 "*Regular expression matching file names handled by Tramp.
1351 This regexp should match Tramp file names but no other file names.
1352 \(When tramp.el is loaded, this regular expression is prepended to
1353 `file-name-handler-alist', and that is searched sequentially. Thus,
1354 if the Tramp entry appears rather early in the `file-name-handler-alist'
1355 and is a bit too general, then some files might be considered Tramp
1356 files which are not really Tramp files.
1358 Please note that the entry in `file-name-handler-alist' is made when
1359 this file (tramp.el) is loaded. This means that this variable must be set
1360 before loading tramp.el. Alternatively, `file-name-handler-alist' can be
1361 updated after changing this variable.
1363 Also see `tramp-file-name-structure'.")
1366 (defconst tramp-root-regexp
1367 (if (memq system-type '(cygwin windows-nt))
1368 "^\\([a-zA-Z]:\\)?/"
1370 "Beginning of an incomplete Tramp file name.
1371 Usually, it is just \"^/\". On W32 systems, there might be a
1372 volume letter, which will be removed by `tramp-drop-volume-letter'.")
1375 (defconst tramp-completion-file-name-regexp-unified
1376 (concat tramp-root-regexp "[^/]*$")
1377 "Value for `tramp-completion-file-name-regexp' for unified remoting.
1378 GNU Emacs uses a unified filename syntax for Tramp and Ange-FTP.
1379 See `tramp-file-name-structure' for more explanations.")
1382 (defconst tramp-completion-file-name-regexp-separate
1383 (concat tramp-root-regexp "\\([[][^]]*\\)?$")
1384 "Value for `tramp-completion-file-name-regexp' for separate remoting.
1385 XEmacs uses a separate filename syntax for Tramp and EFS.
1386 See `tramp-file-name-structure' for more explanations.")
1389 (defconst tramp-completion-file-name-regexp-url
1390 (concat tramp-root-regexp "[^/:]+\\(:\\(/\\(/[^/]*\\)?\\)?\\)?$")
1391 "Value for `tramp-completion-file-name-regexp' for URL-like remoting.
1392 See `tramp-file-name-structure' for more explanations.")
1395 (defconst tramp-completion-file-name-regexp
1396 (cond ((equal tramp-syntax 'ftp) tramp-completion-file-name-regexp-unified)
1397 ((equal tramp-syntax 'sep) tramp-completion-file-name-regexp-separate)
1398 ((equal tramp-syntax 'url) tramp-completion-file-name-regexp-url)
1399 (t (error "Wrong `tramp-syntax' defined")))
1400 "*Regular expression matching file names handled by Tramp completion.
1401 This regexp should match partial Tramp file names only.
1403 Please note that the entry in `file-name-handler-alist' is made when
1404 this file (tramp.el) is loaded. This means that this variable must be set
1405 before loading tramp.el. Alternatively, `file-name-handler-alist' can be
1406 updated after changing this variable.
1408 Also see `tramp-file-name-structure'.")
1410 (defconst tramp-actions-before-shell
1411 '((tramp-login-prompt-regexp tramp-action-login)
1412 (tramp-password-prompt-regexp tramp-action-password)
1413 (tramp-wrong-passwd-regexp tramp-action-permission-denied)
1414 (shell-prompt-pattern tramp-action-succeed)
1415 (tramp-shell-prompt-pattern tramp-action-succeed)
1416 (tramp-yesno-prompt-regexp tramp-action-yesno)
1417 (tramp-yn-prompt-regexp tramp-action-yn)
1418 (tramp-terminal-prompt-regexp tramp-action-terminal)
1419 (tramp-process-alive-regexp tramp-action-process-alive))
1420 "List of pattern/action pairs.
1421 Whenever a pattern matches, the corresponding action is performed.
1422 Each item looks like (PATTERN ACTION).
1424 The PATTERN should be a symbol, a variable. The value of this
1425 variable gives the regular expression to search for. Note that the
1426 regexp must match at the end of the buffer, \"\\'\" is implicitly
1429 The ACTION should also be a symbol, but a function. When the
1430 corresponding PATTERN matches, the ACTION function is called.")
1432 (defconst tramp-actions-copy-out-of-band
1433 '((tramp-password-prompt-regexp tramp-action-password)
1434 (tramp-wrong-passwd-regexp tramp-action-permission-denied)
1435 (tramp-copy-failed-regexp tramp-action-permission-denied)
1436 (tramp-process-alive-regexp tramp-action-out-of-band))
1437 "List of pattern/action pairs.
1438 This list is used for copying/renaming with out-of-band methods.
1440 See `tramp-actions-before-shell' for more info.")
1442 ;; Chunked sending kludge. We set this to 500 for black-listed constellations
1443 ;; known to have a bug in `process-send-string'; some ssh connections appear
1444 ;; to drop bytes when data is sent too quickly. There is also a connection
1445 ;; buffer local variable, which is computed depending on remote host properties
1446 ;; when `tramp-chunksize' is zero or nil.
1447 (defcustom tramp-chunksize
1448 (when (and (not (featurep 'xemacs))
1449 (memq system-type '(hpux)))
1451 ;; Parentheses in docstring starting at beginning of line are escaped.
1452 ;; Fontification is messed up when
1453 ;; `open-paren-in-column-0-is-defun-start' set to t.
1454 "*If non-nil, chunksize for sending input to local process.
1455 It is necessary only on systems which have a buggy `process-send-string'
1456 implementation. The necessity, whether this variable must be set, can be
1457 checked via the following code:
1460 (let* ((user \"xxx\") (host \"yyy\")
1462 (sent init) (received init))
1463 (while (= sent received)
1464 (setq sent (+ sent step))
1466 (let ((proc (start-process (buffer-name) (current-buffer)
1467 \"ssh\" \"-l\" user host \"wc\" \"-c\")))
1468 (when (memq (process-status proc) '(run open))
1469 (process-send-string proc (make-string sent ?\\ ))
1470 (process-send-eof proc)
1471 (process-send-eof proc))
1472 (while (not (progn (goto-char (point-min))
1473 (re-search-forward \"\\\\w+\" (point-max) t)))
1474 (accept-process-output proc 1))
1475 (when (memq (process-status proc) '(run open))
1476 (setq received (string-to-number (match-string 0)))
1477 (delete-process proc)
1478 (message \"Bytes sent: %s\\tBytes received: %s\" sent received)
1480 (if (> sent (+ init step))
1481 (message \"You should set `tramp-chunksize' to a maximum of %s\"
1483 (message \"Test does not work\")
1484 (display-buffer (current-buffer))
1487 In the Emacs normally running Tramp, evaluate the above code
1488 \(replace \"xxx\" and \"yyy\" by the remote user and host name,
1489 respectively). You can do this, for example, by pasting it into
1490 the `*scratch*' buffer and then hitting C-j with the cursor after the
1491 last closing parenthesis. Note that it works only if you have configured
1492 \"ssh\" to run without password query, see ssh-agent(1).
1494 You will see the number of bytes sent successfully to the remote host.
1495 If that number exceeds 1000, you can stop the execution by hitting
1496 C-g, because your Emacs is likely clean.
1498 When it is necessary to set `tramp-chunksize', you might consider to
1499 use an out-of-the-band method (like \"scp\") instead of an internal one
1500 \(like \"ssh\"), because setting `tramp-chunksize' to non-nil decreases
1503 If your Emacs is buggy, the code stops and gives you an indication
1504 about the value `tramp-chunksize' should be set. Maybe you could just
1505 experiment a bit, e.g. changing the values of `init' and `step'
1506 in the third line of the code.
1508 Please raise a bug report via \"M-x tramp-bug\" if your system needs
1509 this variable to be set as well."
1511 :type '(choice (const nil) integer))
1513 ;; Logging in to a remote host normally requires obtaining a pty. But
1514 ;; Emacs on MacOS X has process-connection-type set to nil by default,
1515 ;; so on those systems Tramp doesn't obtain a pty. Here, we allow
1516 ;; for an override of the system default.
1517 (defcustom tramp-process-connection-type t
1518 "Overrides `process-connection-type' for connections from Tramp.
1519 Tramp binds process-connection-type to the value given here before
1520 opening a connection to a remote host."
1522 :type '(choice (const nil) (const t) (const pty)))
1524 (defcustom tramp-completion-reread-directory-timeout 10
1525 "Defines seconds since last remote command before rereading a directory.
1526 A remote directory might have changed its contents. In order to
1527 make it visible during file name completion in the minibuffer,
1528 Tramp flushes its cache and rereads the directory contents when
1529 more than `tramp-completion-reread-directory-timeout' seconds
1530 have been gone since last remote command execution. A value of 0
1531 would require an immediate reread during filename completion, nil
1532 means to use always cached values for the directory contents."
1534 :type '(choice (const nil) integer))
1536 ;;; Internal Variables:
1538 (defvar tramp-end-of-output
1541 (md5 (concat (prin1-to-string process-environment) (current-time-string))))
1542 "String used to recognize end of output.
1543 The '$' character at the end is quoted; the string cannot be
1544 detected as prompt when being sent on echoing hosts, therefore.")
1546 (defvar tramp-current-method nil
1547 "Connection method for this *tramp* buffer.")
1549 (defvar tramp-current-user nil
1550 "Remote login name for this *tramp* buffer.")
1552 (defvar tramp-current-host nil
1553 "Remote host for this *tramp* buffer.")
1555 (defconst tramp-uudecode
1556 "(echo begin 600 /tmp/tramp.$$; tail +2) | uudecode
1558 rm -f /tmp/tramp.$$"
1559 "Shell function to implement `uudecode' to standard output.
1560 Many systems support `uudecode -o /dev/stdout' or `uudecode -o -'
1561 for this or `uudecode -p', but some systems don't, and for them
1562 we have this shell function.")
1564 ;; Perl script to implement `file-attributes' in a Lisp `read'able
1565 ;; output. If you are hacking on this, note that you get *no* output
1566 ;; unless this spits out a complete line, including the '\n' at the
1568 ;; The device number is returned as "-1", because there will be a virtual
1569 ;; device number set in `tramp-handle-file-attributes'.
1570 (defconst tramp-perl-file-attributes
1572 @stat = lstat($ARGV[0]);
1573 if (($stat[2] & 0170000) == 0120000)
1575 $type = readlink($ARGV[0]);
1576 $type = \"\\\"$type\\\"\";
1578 elsif (($stat[2] & 0170000) == 040000)
1586 $uid = ($ARGV[1] eq \"integer\") ? $stat[4] : \"\\\"\" . getpwuid($stat[4]) . \"\\\"\";
1587 $gid = ($ARGV[1] eq \"integer\") ? $stat[5] : \"\\\"\" . getgrgid($stat[5]) . \"\\\"\";
1589 \"(%%s %%u %%s %%s (%%u %%u) (%%u %%u) (%%u %%u) %%u.0 %%u t (%%u . %%u) -1)\\n\",
1594 $stat[8] >> 16 & 0xffff,
1596 $stat[9] >> 16 & 0xffff,
1598 $stat[10] >> 16 & 0xffff,
1602 $stat[1] >> 16 & 0xffff,
1604 );' \"$1\" \"$2\" \"$3\" 2>/dev/null"
1605 "Perl script to produce output suitable for use with `file-attributes'
1606 on the remote file system.
1607 Escape sequence %s is replaced with name of Perl binary.
1608 This string is passed to `format', so percent characters need to be doubled.")
1610 (defconst tramp-perl-directory-files-and-attributes
1612 chdir($ARGV[0]) or printf(\"\\\"Cannot change to $ARGV[0]: $''!''\\\"\\n\"), exit();
1613 opendir(DIR,\".\") or printf(\"\\\"Cannot open directory $ARGV[0]: $''!''\\\"\\n\"), exit();
1614 @list = readdir(DIR);
1618 for($i = 0; $i < $n; $i++)
1620 $filename = $list[$i];
1621 @stat = lstat($filename);
1622 if (($stat[2] & 0170000) == 0120000)
1624 $type = readlink($filename);
1625 $type = \"\\\"$type\\\"\";
1627 elsif (($stat[2] & 0170000) == 040000)
1635 $uid = ($ARGV[1] eq \"integer\") ? $stat[4] : \"\\\"\" . getpwuid($stat[4]) . \"\\\"\";
1636 $gid = ($ARGV[1] eq \"integer\") ? $stat[5] : \"\\\"\" . getgrgid($stat[5]) . \"\\\"\";
1638 \"(\\\"%%s\\\" %%s %%u %%s %%s (%%u %%u) (%%u %%u) (%%u %%u) %%u.0 %%u t (%%u . %%u) (%%u . %%u))\\n\",
1644 $stat[8] >> 16 & 0xffff,
1646 $stat[9] >> 16 & 0xffff,
1648 $stat[10] >> 16 & 0xffff,
1652 $stat[1] >> 16 & 0xffff,
1654 $stat[0] >> 16 & 0xffff,
1657 printf(\")\\n\");' \"$1\" \"$2\" \"$3\" 2>/dev/null"
1658 "Perl script implementing `directory-files-attributes' as Lisp `read'able
1660 Escape sequence %s is replaced with name of Perl binary.
1661 This string is passed to `format', so percent characters need to be doubled.")
1663 ;; ;; These two use uu encoding.
1664 ;; (defvar tramp-perl-encode "%s -e'\
1665 ;; print qq(begin 644 xxx\n);
1668 ;; while (read(STDIN, $s, 45)) {
1669 ;; print pack(q(u), $s);
1674 ;; "Perl program to use for encoding a file.
1675 ;; Escape sequence %s is replaced with name of Perl binary.")
1677 ;; (defvar tramp-perl-decode "%s -ne '
1678 ;; print unpack q(u), $_;
1680 ;; "Perl program to use for decoding a file.
1681 ;; Escape sequence %s is replaced with name of Perl binary.")
1683 ;; These two use base64 encoding.
1684 (defconst tramp-perl-encode-with-module
1685 "%s -MMIME::Base64 -0777 -ne 'print encode_base64($_)' 2>/dev/null"
1686 "Perl program to use for encoding a file.
1687 Escape sequence %s is replaced with name of Perl binary.
1688 This string is passed to `format', so percent characters need to be doubled.
1689 This implementation requires the MIME::Base64 Perl module to be installed
1690 on the remote host.")
1692 (defconst tramp-perl-decode-with-module
1693 "%s -MMIME::Base64 -0777 -ne 'print decode_base64($_)' 2>/dev/null"
1694 "Perl program to use for decoding a file.
1695 Escape sequence %s is replaced with name of Perl binary.
1696 This string is passed to `format', so percent characters need to be doubled.
1697 This implementation requires the MIME::Base64 Perl module to be installed
1698 on the remote host.")
1700 (defconst tramp-perl-encode
1702 # This script contributed by Juanma Barranquero <lektu@terra.es>.
1703 # Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009
1704 # Free Software Foundation, Inc.
1709 map {(substr(unpack(q(B8), chr $i++), 2, 6), $_)}
1710 split //, q(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/);
1715 # We read in chunks of 54 bytes, to generate output lines
1716 # of 72 chars (plus end of line)
1719 while (my $data = <STDIN>) {
1722 # Only for the last chunk, and only if did not fill the last three-byte packet
1724 my $mod = length($data) %% 3;
1725 $pad = q(=) x (3 - $mod) if $mod;
1728 # Not the fastest method, but it is simple: unpack to binary string, split
1729 # by groups of 6 bits and convert back from binary to byte; then map into
1730 # the translation table
1734 (substr(unpack(q(B*), $data) . q(00000), 0, 432) =~ /....../g)),
1738 "Perl program to use for encoding a file.
1739 Escape sequence %s is replaced with name of Perl binary.
1740 This string is passed to `format', so percent characters need to be doubled.")
1742 (defconst tramp-perl-decode
1744 # This script contributed by Juanma Barranquero <lektu@terra.es>.
1745 # Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009
1746 # Free Software Foundation, Inc.
1751 map {($_, substr(unpack(q(B8), chr $i++), 2, 6))}
1752 split //, q(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/)
1755 my %%bytes = map {(unpack(q(B8), chr $_), chr $_)} 0 .. 255;
1759 # We are going to accumulate into $pending to accept any line length
1760 # (we do not check they are <= 76 chars as the RFC says)
1763 while (my $data = <STDIN>) {
1766 # If we find one or two =, we have reached the end and
1767 # any following data is to be discarded
1768 my $finished = $data =~ s/(==?).*/$1/;
1771 my $len = length($pending);
1772 my $chunk = substr($pending, 0, $len & ~3);
1773 $pending = substr($pending, $len & ~3 + 1);
1775 # Easy method: translate from chars to (pregenerated) six-bit packets, join,
1776 # split in 8-bit chunks and convert back to char.
1779 ((join q(), map {$trans{$_} || q()} split //, $chunk) =~ /......../g);
1783 "Perl program to use for decoding a file.
1784 Escape sequence %s is replaced with name of Perl binary.
1785 This string is passed to `format', so percent characters need to be doubled.")
1787 (defconst tramp-file-mode-type-map
1788 '((0 . "-") ; Normal file (SVID-v2 and XPG2)
1790 (2 . "c") ; character device
1791 (3 . "m") ; multiplexed character device (v7)
1792 (4 . "d") ; directory
1793 (5 . "?") ; Named special file (XENIX)
1794 (6 . "b") ; block device
1795 (7 . "?") ; multiplexed block device (v7)
1796 (8 . "-") ; regular file
1797 (9 . "n") ; network special file (HP-UX)
1798 (10 . "l") ; symlink
1799 (11 . "?") ; ACL shadow inode (Solaris, not userspace)
1801 (13 . "D") ; door special (Solaris)
1802 (14 . "w")) ; whiteout (BSD)
1803 "A list of file types returned from the `stat' system call.
1804 This is used to map a mode number to a permission string.")
1806 ;; New handlers should be added here. The following operations can be
1807 ;; handled using the normal primitives: file-name-sans-versions,
1809 (defconst tramp-file-name-handler-alist
1810 '((load . tramp-handle-load)
1811 (make-symbolic-link . tramp-handle-make-symbolic-link)
1812 (file-name-as-directory . tramp-handle-file-name-as-directory)
1813 (file-name-directory . tramp-handle-file-name-directory)
1814 (file-name-nondirectory . tramp-handle-file-name-nondirectory)
1815 (file-truename . tramp-handle-file-truename)
1816 (file-exists-p . tramp-handle-file-exists-p)
1817 (file-directory-p . tramp-handle-file-directory-p)
1818 (file-executable-p . tramp-handle-file-executable-p)
1819 (file-readable-p . tramp-handle-file-readable-p)
1820 (file-regular-p . tramp-handle-file-regular-p)
1821 (file-symlink-p . tramp-handle-file-symlink-p)
1822 (file-writable-p . tramp-handle-file-writable-p)
1823 (file-ownership-preserved-p . tramp-handle-file-ownership-preserved-p)
1824 (file-newer-than-file-p . tramp-handle-file-newer-than-file-p)
1825 (file-attributes . tramp-handle-file-attributes)
1826 (file-modes . tramp-handle-file-modes)
1827 (directory-files . tramp-handle-directory-files)
1828 (directory-files-and-attributes . tramp-handle-directory-files-and-attributes)
1829 (file-name-all-completions . tramp-handle-file-name-all-completions)
1830 (file-name-completion . tramp-handle-file-name-completion)
1831 (add-name-to-file . tramp-handle-add-name-to-file)
1832 (copy-file . tramp-handle-copy-file)
1833 (rename-file . tramp-handle-rename-file)
1834 (set-file-modes . tramp-handle-set-file-modes)
1835 (set-file-times . tramp-handle-set-file-times)
1836 (make-directory . tramp-handle-make-directory)
1837 (delete-directory . tramp-handle-delete-directory)
1838 (delete-file . tramp-handle-delete-file)
1839 (directory-file-name . tramp-handle-directory-file-name)
1840 ;; `executable-find' is not official yet.
1841 (executable-find . tramp-handle-executable-find)
1842 (start-file-process . tramp-handle-start-file-process)
1843 (process-file . tramp-handle-process-file)
1844 (shell-command . tramp-handle-shell-command)
1845 (insert-directory . tramp-handle-insert-directory)
1846 (expand-file-name . tramp-handle-expand-file-name)
1847 (substitute-in-file-name . tramp-handle-substitute-in-file-name)
1848 (file-local-copy . tramp-handle-file-local-copy)
1849 (file-remote-p . tramp-handle-file-remote-p)
1850 (insert-file-contents . tramp-handle-insert-file-contents)
1851 (insert-file-contents-literally
1852 . tramp-handle-insert-file-contents-literally)
1853 (write-region . tramp-handle-write-region)
1854 (find-backup-file-name . tramp-handle-find-backup-file-name)
1855 (make-auto-save-file-name . tramp-handle-make-auto-save-file-name)
1856 (unhandled-file-name-directory . tramp-handle-unhandled-file-name-directory)
1857 (dired-compress-file . tramp-handle-dired-compress-file)
1858 (dired-recursive-delete-directory
1859 . tramp-handle-dired-recursive-delete-directory)
1860 (dired-uncache . tramp-handle-dired-uncache)
1861 (set-visited-file-modtime . tramp-handle-set-visited-file-modtime)
1862 (verify-visited-file-modtime . tramp-handle-verify-visited-file-modtime)
1863 (vc-registered . tramp-handle-vc-registered))
1864 "Alist of handler functions.
1865 Operations not mentioned here will be handled by the normal Emacs functions.")
1867 ;; Handlers for partial Tramp file names. For Emacs just
1868 ;; `file-name-all-completions' is needed.
1870 (defconst tramp-completion-file-name-handler-alist
1871 '((file-name-all-completions . tramp-completion-handle-file-name-all-completions)
1872 (file-name-completion . tramp-completion-handle-file-name-completion))
1873 "Alist of completion handler functions.
1874 Used for file names matching `tramp-file-name-regexp'. Operations not
1875 mentioned here will be handled by `tramp-file-name-handler-alist' or the
1876 normal Emacs functions.")
1878 ;; Handlers for foreign methods, like FTP or SMB, shall be plugged here.
1879 (defvar tramp-foreign-file-name-handler-alist
1880 ;; (identity . tramp-sh-file-name-handler) should always be the last
1881 ;; entry, since `identity' always matches.
1882 '((identity . tramp-sh-file-name-handler))
1883 "Alist of elements (FUNCTION . HANDLER) for foreign methods handled specially.
1884 If (FUNCTION FILENAME) returns non-nil, then all I/O on that file is done by
1887 ;;; Internal functions which must come first:
1889 (defsubst tramp-debug-message (vec fmt-string &rest args)
1890 "Append message to debug buffer.
1891 Message is formatted with FMT-STRING as control string and the remaining
1892 ARGS to actually emit the message (if applicable)."
1893 (when (get-buffer (tramp-buffer-name vec))
1894 (with-current-buffer (tramp-get-debug-buffer vec)
1895 (goto-char (point-max))
1900 ";; %sEmacs: %s Tramp: %s -*- mode: outline; -*-"
1901 (if (featurep 'sxemacs) "SX" (if (featurep 'xemacs) "X" "GNU "))
1902 emacs-version tramp-version)))
1906 (let ((now (current-time)))
1907 (insert (format-time-string "%T." now))
1908 (insert (format "%06d " (nth 2 now))))
1909 ;; Calling function.
1910 (let ((btn 1) btf fn)
1912 (setq btf (nth 1 (backtrace-frame btn)))
1916 (setq fn (symbol-name btf))
1917 (unless (and (string-match "^tramp" fn)
1919 "^tramp\\(-debug\\)?\\(-message\\|-error\\)$"
1922 (setq btn (1+ btn))))
1923 ;; The following code inserts filename and line number.
1924 ;; Should be deactivated by default, because it is time
1926 ; (let ((ffn (find-function-noselect (intern fn))))
1930 ; (file-name-nondirectory (buffer-file-name (car ffn)))
1931 ; (with-current-buffer (car ffn)
1932 ; (1+ (count-lines (point-min) (cdr ffn)))))))
1933 (insert (format "%s " fn)))
1935 (insert (apply 'format fmt-string args)))))
1937 (defsubst tramp-message (vec-or-proc level fmt-string &rest args)
1938 "Emit a message depending on verbosity level.
1939 VEC-OR-PROC identifies the Tramp buffer to use. It can be either a
1940 vector or a process. LEVEL says to be quiet if `tramp-verbose' is
1941 less than LEVEL. The message is emitted only if `tramp-verbose' is
1942 greater than or equal to LEVEL.
1944 The message is also logged into the debug buffer when `tramp-verbose'
1945 is greater than or equal 4.
1947 Calls functions `message' and `tramp-debug-message' with FMT-STRING as
1948 control string and the remaining ARGS to actually emit the message (if
1951 (when (<= level tramp-verbose)
1952 ;; Match data must be preserved!
1954 ;; Display only when there is a minimum level.
1961 ((= level 2) "Warning: ")
1965 ;; Log only when there is a minimum level.
1966 (when (>= tramp-verbose 4)
1967 (when (and vec-or-proc
1968 (processp vec-or-proc)
1969 (buffer-name (process-buffer vec-or-proc)))
1970 (with-current-buffer (process-buffer vec-or-proc)
1971 ;; Translate proc to vec.
1972 (setq vec-or-proc (tramp-dissect-file-name default-directory))))
1973 (when (and vec-or-proc (vectorp vec-or-proc))
1974 (apply 'tramp-debug-message
1976 (concat (format "(%d) # " level) fmt-string)
1978 ;; Suppress all errors.
1981 (defsubst tramp-error (vec-or-proc signal fmt-string &rest args)
1983 VEC-OR-PROC identifies the connection to use, SIGNAL is the
1984 signal identifier to be raised, remaining args passed to
1985 `tramp-message'. Finally, signal SIGNAL is raised."
1988 (error-message-string
1989 (list signal (get signal 'error-message) (apply 'format fmt-string args))))
1990 (signal signal (list (apply 'format fmt-string args))))
1992 (defsubst tramp-error-with-buffer
1993 (buffer vec-or-proc signal fmt-string &rest args)
1994 "Emit an error, and show BUFFER.
1995 If BUFFER is nil, show the connection buffer. Wait for 30\", or until
1996 an input event arrives. The other arguments are passed to `tramp-error'."
1997 (save-window-excursion
1999 (apply 'tramp-error vec-or-proc signal fmt-string args)
2000 (when (and vec-or-proc (not (zerop tramp-verbose)))
2001 (let ((enable-recursive-minibuffers t))
2003 (or (and (bufferp buffer) buffer)
2004 (and (processp vec-or-proc) (process-buffer vec-or-proc))
2005 (tramp-get-buffer vec-or-proc)))
2008 (defmacro with-parsed-tramp-file-name (filename var &rest body)
2009 "Parse a Tramp filename and make components available in the body.
2011 First arg FILENAME is evaluated and dissected into its components.
2012 Second arg VAR is a symbol. It is used as a variable name to hold
2013 the filename structure. It is also used as a prefix for the variables
2014 holding the components. For example, if VAR is the symbol `foo', then
2015 `foo' will be bound to the whole structure, `foo-method' will be bound to
2016 the method component, and so on for `foo-user', `foo-host', `foo-localname'.
2018 Remaining args are Lisp expressions to be evaluated (inside an implicit
2021 If VAR is nil, then we bind `v' to the structure and `method', `user',
2022 `host', `localname' to the components."
2023 `(let* ((,(or var 'v) (tramp-dissect-file-name ,filename))
2024 (,(if var (intern (concat (symbol-name var) "-method")) 'method)
2025 (tramp-file-name-method ,(or var 'v)))
2026 (,(if var (intern (concat (symbol-name var) "-user")) 'user)
2027 (tramp-file-name-user ,(or var 'v)))
2028 (,(if var (intern (concat (symbol-name var) "-host")) 'host)
2029 (tramp-file-name-host ,(or var 'v)))
2030 (,(if var (intern (concat (symbol-name var) "-localname")) 'localname)
2031 (tramp-file-name-localname ,(or var 'v))))
2034 (put 'with-parsed-tramp-file-name 'lisp-indent-function 2)
2035 (put 'with-parsed-tramp-file-name 'edebug-form-spec '(form symbolp body))
2036 (font-lock-add-keywords 'emacs-lisp-mode '("\\<with-parsed-tramp-file-name\\>"))
2038 (defmacro with-file-property (vec file property &rest body)
2039 "Check in Tramp cache for PROPERTY, otherwise execute BODY and set cache.
2040 FILE must be a local file name on a connection identified via VEC."
2041 `(if (file-name-absolute-p ,file)
2042 (let ((value (tramp-get-file-property ,vec ,file ,property 'undef)))
2043 (when (eq value 'undef)
2044 ;; We cannot pass @body as parameter to
2045 ;; `tramp-set-file-property' because it mangles our
2047 (setq value (progn ,@body))
2048 (tramp-set-file-property ,vec ,file ,property value))
2052 (put 'with-file-property 'lisp-indent-function 3)
2053 (put 'with-file-property 'edebug-form-spec t)
2054 (font-lock-add-keywords 'emacs-lisp-mode '("\\<with-file-property\\>"))
2056 (defmacro with-connection-property (key property &rest body)
2057 "Checks in Tramp for property PROPERTY, otherwise executes BODY and set."
2058 `(let ((value (tramp-get-connection-property ,key ,property 'undef)))
2059 (when (eq value 'undef)
2060 ;; We cannot pass ,@body as parameter to
2061 ;; `tramp-set-connection-property' because it mangles our debug
2063 (setq value (progn ,@body))
2064 (tramp-set-connection-property ,key ,property value))
2067 (put 'with-connection-property 'lisp-indent-function 2)
2068 (put 'with-connection-property 'edebug-form-spec t)
2069 (font-lock-add-keywords 'emacs-lisp-mode '("\\<with-connection-property\\>"))
2071 (eval-and-compile ; silence compiler
2072 (if (memq system-type '(cygwin windows-nt))
2073 (defun tramp-drop-volume-letter (name)
2074 "Cut off unnecessary drive letter from file NAME.
2075 The function `tramp-handle-expand-file-name' calls `expand-file-name'
2076 locally on a remote file name. When the local system is a W32 system
2077 but the remote system is Unix, this introduces a superfluous drive
2078 letter into the file name. This function removes it."
2080 (if (string-match tramp-root-regexp name)
2081 (replace-match "/" nil t name)
2084 (defalias 'tramp-drop-volume-letter 'identity)))
2086 (defsubst tramp-make-tramp-temp-file (vec)
2087 "Create a temporary file on the remote host identified by VEC.
2088 Return the local name of the temporary file."
2090 (tramp-make-tramp-file-name
2091 (tramp-file-name-method vec)
2092 (tramp-file-name-user vec)
2093 (tramp-file-name-host vec)
2094 (tramp-drop-volume-letter
2096 tramp-temp-name-prefix (tramp-get-remote-tmpdir vec)))))
2099 ;; `make-temp-file' would be the natural choice for
2100 ;; implementation. But it calls `write-region' internally,
2101 ;; which also needs a temporary file - we would end in an
2103 (setq result (make-temp-name prefix))
2104 (if (file-exists-p result)
2106 ;; This creates the file by side effect.
2107 (set-file-times result)
2108 (set-file-modes result (tramp-octal-to-decimal "0700"))))
2110 ;; Return the local part.
2111 (with-parsed-tramp-file-name result nil localname)))
2114 ;;; Config Manipulation Functions:
2116 (defun tramp-set-completion-function (method function-list)
2117 "Sets the list of completion functions for METHOD.
2118 FUNCTION-LIST is a list of entries of the form (FUNCTION FILE).
2119 The FUNCTION is intended to parse FILE according its syntax.
2120 It might be a predefined FUNCTION, or a user defined FUNCTION.
2121 Predefined FUNCTIONs are `tramp-parse-rhosts', `tramp-parse-shosts',
2122 `tramp-parse-sconfig', `tramp-parse-hosts', `tramp-parse-passwd',
2123 and `tramp-parse-netrc'.
2127 (tramp-set-completion-function
2129 '((tramp-parse-sconfig \"/etc/ssh_config\")
2130 (tramp-parse-sconfig \"~/.ssh/config\")))"
2132 (let ((r function-list)
2134 (setq tramp-completion-function-alist
2135 (delete (assoc method tramp-completion-function-alist)
2136 tramp-completion-function-alist))
2139 ;; Remove double entries.
2140 (when (member (car v) (cdr v))
2141 (setcdr v (delete (car v) (cdr v))))
2142 ;; Check for function and file or registry key.
2143 (unless (and (functionp (nth 0 (car v)))
2144 (if (string-match "^HKEY_CURRENT_USER" (nth 1 (car v)))
2145 ;; Windows registry.
2146 (and (memq system-type '(cygwin windows-nt))
2148 (tramp-local-call-process
2149 "reg" nil nil nil "query" (nth 1 (car v)))))
2150 ;; Configuration file.
2151 (file-exists-p (nth 1 (car v)))))
2152 (setq r (delete (car v) r)))
2156 (add-to-list 'tramp-completion-function-alist
2159 (defun tramp-get-completion-function (method)
2160 "Returns a list of completion functions for METHOD.
2161 For definition of that list see `tramp-set-completion-function'."
2163 ;; Hosts visited once shall be remembered.
2164 `(tramp-parse-connection-properties ,method)
2165 ;; The method related defaults.
2166 (cdr (assoc method tramp-completion-function-alist))))
2169 ;;; Fontification of `read-file-name':
2171 ;; rfn-eshadow.el is part of Emacs 22. It is autoloaded.
2172 (defvar tramp-rfn-eshadow-overlay)
2173 (make-variable-buffer-local 'tramp-rfn-eshadow-overlay)
2175 (defun tramp-rfn-eshadow-setup-minibuffer ()
2176 "Set up a minibuffer for `file-name-shadow-mode'.
2177 Adds another overlay hiding filename parts according to Tramp's
2178 special handling of `substitute-in-file-name'."
2179 (when (symbol-value 'minibuffer-completing-file-name)
2180 (setq tramp-rfn-eshadow-overlay
2181 (funcall (symbol-function 'make-overlay)
2182 (funcall (symbol-function 'minibuffer-prompt-end))
2183 (funcall (symbol-function 'minibuffer-prompt-end))))
2184 ;; Copy rfn-eshadow-overlay properties.
2185 (let ((props (funcall (symbol-function 'overlay-properties)
2186 (symbol-value 'rfn-eshadow-overlay))))
2188 (funcall (symbol-function 'overlay-put)
2189 tramp-rfn-eshadow-overlay (pop props) (pop props))))))
2191 (when (boundp 'rfn-eshadow-setup-minibuffer-hook)
2192 (add-hook 'rfn-eshadow-setup-minibuffer-hook
2193 'tramp-rfn-eshadow-setup-minibuffer)
2194 (add-hook 'tramp-unload-hook
2196 (remove-hook 'rfn-eshadow-setup-minibuffer-hook
2197 'tramp-rfn-eshadow-setup-minibuffer))))
2199 (defun tramp-rfn-eshadow-update-overlay ()
2200 "Update `rfn-eshadow-overlay' to cover shadowed part of minibuffer input.
2201 This is intended to be used as a minibuffer `post-command-hook' for
2202 `file-name-shadow-mode'; the minibuffer should have already
2203 been set up by `rfn-eshadow-setup-minibuffer'."
2204 ;; In remote files name, there is a shadowing just for the local part.
2205 (let ((end (or (funcall (symbol-function 'overlay-end)
2206 (symbol-value 'rfn-eshadow-overlay))
2207 (funcall (symbol-function 'minibuffer-prompt-end)))))
2208 (when (file-remote-p (buffer-substring-no-properties end (point-max)))
2212 (1+ (or (string-match "/" (buffer-string) end) end)) (point-max))
2213 (let ((rfn-eshadow-overlay tramp-rfn-eshadow-overlay)
2214 (rfn-eshadow-update-overlay-hook nil))
2215 (move-overlay rfn-eshadow-overlay (point-max) (point-max))
2216 (funcall (symbol-function 'rfn-eshadow-update-overlay))))))))
2218 (when (boundp 'rfn-eshadow-update-overlay-hook)
2219 (add-hook 'rfn-eshadow-update-overlay-hook
2220 'tramp-rfn-eshadow-update-overlay))
2223 ;;; File Name Handler Functions:
2225 (defun tramp-handle-make-symbolic-link
2226 (filename linkname &optional ok-if-already-exists)
2227 "Like `make-symbolic-link' for Tramp files.
2228 If LINKNAME is a non-Tramp file, it is used verbatim as the target of
2229 the symlink. If LINKNAME is a Tramp file, only the localname component is
2230 used as the target of the symlink.
2232 If LINKNAME is a Tramp file and the localname component is relative, then
2233 it is expanded first, before the localname component is taken. Note that
2234 this can give surprising results if the user/host for the source and
2235 target of the symlink differ."
2236 (with-parsed-tramp-file-name linkname l
2237 (let ((ln (tramp-get-remote-ln l))
2238 (cwd (tramp-run-real-handler
2239 'file-name-directory (list l-localname))))
2243 "Making a symbolic link. ln(1) does not exist on the remote host."))
2245 ;; Do the 'confirm if exists' thing.
2246 (when (file-exists-p linkname)
2248 (if (or (null ok-if-already-exists) ; not allowed to exist
2249 (and (numberp ok-if-already-exists)
2252 "File %s already exists; make it a link anyway? "
2255 l 'file-already-exists "File %s already exists" l-localname)
2256 (delete-file linkname)))
2258 ;; If FILENAME is a Tramp name, use just the localname component.
2259 (when (tramp-tramp-file-p filename)
2261 (tramp-file-name-localname
2262 (tramp-dissect-file-name (expand-file-name filename)))))
2264 ;; Right, they are on the same host, regardless of user, method, etc.
2265 ;; We now make the link on the remote machine. This will occur as the user
2266 ;; that FILENAME belongs to.
2268 (tramp-send-command-and-check
2269 l (format "cd %s && %s -sf %s %s" cwd ln filename l-localname) t)))))
2271 (defun tramp-handle-load (file &optional noerror nomessage nosuffix must-suffix)
2272 "Like `load' for Tramp files."
2273 (with-parsed-tramp-file-name (expand-file-name file) nil
2275 (cond ((file-exists-p (concat file ".elc"))
2276 (setq file (concat file ".elc")))
2277 ((file-exists-p (concat file ".el"))
2278 (setq file (concat file ".el")))))
2280 ;; The first condition is always true for absolute file names.
2281 ;; Included for safety's sake.
2282 (unless (or (file-name-directory file)
2283 (string-match "\\.elc?\\'" file))
2286 "File `%s' does not include a `.el' or `.elc' suffix" file)))
2288 (when (not (file-exists-p file))
2289 (tramp-error v 'file-error "Cannot load nonexistent file `%s'" file)))
2290 (if (not (file-exists-p file))
2292 (unless nomessage (tramp-message v 0 "Loading %s..." file))
2293 (let ((local-copy (file-local-copy file)))
2294 ;; MUST-SUFFIX doesn't exist on XEmacs, so let it default to nil.
2296 (load local-copy noerror t t)
2297 (delete-file local-copy)))
2298 (unless nomessage (tramp-message v 0 "Loading %s...done" file))
2301 ;; Localname manipulation functions that grok Tramp localnames...
2302 (defun tramp-handle-file-name-as-directory (file)
2303 "Like `file-name-as-directory' but aware of Tramp files."
2304 ;; `file-name-as-directory' would be sufficient except localname is
2305 ;; the empty string.
2306 (let ((v (tramp-dissect-file-name file t)))
2307 ;; Run the command on the localname portion only.
2308 (tramp-make-tramp-file-name
2309 (tramp-file-name-method v)
2310 (tramp-file-name-user v)
2311 (tramp-file-name-host v)
2312 (tramp-run-real-handler
2313 'file-name-as-directory (list (or (tramp-file-name-localname v) ""))))))
2315 (defun tramp-handle-file-name-directory (file)
2316 "Like `file-name-directory' but aware of Tramp files."
2317 ;; Everything except the last filename thing is the directory. We
2318 ;; cannot apply `with-parsed-tramp-file-name', because this expands
2319 ;; the remote file name parts. This is a problem when we are in
2320 ;; file name completion.
2321 (let ((v (tramp-dissect-file-name file t)))
2322 ;; Run the command on the localname portion only.
2323 (tramp-make-tramp-file-name
2324 (tramp-file-name-method v)
2325 (tramp-file-name-user v)
2326 (tramp-file-name-host v)
2327 (tramp-run-real-handler
2328 'file-name-directory (list (or (tramp-file-name-localname v) ""))))))
2330 (defun tramp-handle-file-name-nondirectory (file)
2331 "Like `file-name-nondirectory' but aware of Tramp files."
2332 (with-parsed-tramp-file-name file nil
2333 (tramp-run-real-handler 'file-name-nondirectory (list localname))))
2335 (defun tramp-handle-file-truename (filename &optional counter prev-dirs)
2336 "Like `file-truename' for Tramp files."
2337 (with-parsed-tramp-file-name (expand-file-name filename) nil
2338 (with-file-property v localname "file-truename"
2339 (let* ((directory-sep-char ?/) ; for XEmacs
2340 (steps (tramp-compat-split-string localname "/"))
2341 (localnamedir (tramp-run-real-handler
2342 'file-name-as-directory (list localname)))
2343 (is-dir (string= localname localnamedir))
2346 ;; Don't make the following value larger than necessary.
2347 ;; People expect an error message in a timely fashion when
2348 ;; something is wrong; otherwise they might think that Emacs
2349 ;; is hung. Of course, correctness has to come first.
2351 (result nil) ;result steps in reverse order
2353 (tramp-message v 4 "Finding true name for `%s'" filename)
2354 (while (and steps (< numchase numchase-limit))
2355 (setq thisstep (pop steps))
2358 (mapconcat 'identity
2359 (append '("") (reverse result) (list thisstep))
2361 (setq symlink-target
2362 (nth 0 (file-attributes
2363 (tramp-make-tramp-file-name
2365 (mapconcat 'identity
2370 (cond ((string= "." thisstep)
2371 (tramp-message v 5 "Ignoring step `.'"))
2372 ((string= ".." thisstep)
2373 (tramp-message v 5 "Processing step `..'")
2375 ((stringp symlink-target)
2376 ;; It's a symlink, follow it.
2377 (tramp-message v 5 "Follow symlink to %s" symlink-target)
2378 (setq numchase (1+ numchase))
2379 (when (file-name-absolute-p symlink-target)
2381 ;; If the symlink was absolute, we'll get a string like
2382 ;; "/user@host:/some/target"; extract the
2383 ;; "/some/target" part from it.
2384 (when (tramp-tramp-file-p symlink-target)
2385 (unless (tramp-equal-remote filename symlink-target)
2388 "Symlink target `%s' on wrong host" symlink-target))
2389 (setq symlink-target localname))
2391 (append (tramp-compat-split-string symlink-target "/")
2395 (setq result (cons thisstep result)))))
2396 (when (>= numchase numchase-limit)
2399 "Maximum number (%d) of symlinks exceeded" numchase-limit))
2400 (setq result (reverse result))
2401 ;; Combine list to form string.
2404 (mapconcat 'identity (cons "" result) "/")
2406 (when (and is-dir (or (string= "" result)
2407 (not (string= (substring result -1) "/"))))
2408 (setq result (concat result "/")))
2409 (tramp-message v 4 "True name of `%s' is `%s'" filename result)
2410 (tramp-make-tramp-file-name method user host result)))))
2414 (defun tramp-handle-file-exists-p (filename)
2415 "Like `file-exists-p' for Tramp files."
2416 (with-parsed-tramp-file-name filename nil
2417 (with-file-property v localname "file-exists-p"
2418 (zerop (tramp-send-command-and-check
2422 (tramp-get-file-exists-command v)
2423 (tramp-shell-quote-argument localname)))))))
2425 ;; Inodes don't exist for some file systems. Therefore we must
2426 ;; generate virtual ones. Used in `find-buffer-visiting'. The method
2427 ;; applied might be not so efficient (Ange-FTP uses hashes). But
2428 ;; performance isn't the major issue given that file transfer will
2430 (defvar tramp-inodes nil
2431 "Keeps virtual inodes numbers.")
2433 ;; Devices must distinguish physical file systems. The device numbers
2434 ;; provided by "lstat" aren't unique, because we operate on different hosts.
2435 ;; So we use virtual device numbers, generated by Tramp. Both Ange-FTP and
2436 ;; EFS use device number "-1". In order to be different, we use device number
2437 ;; (-1 . x), whereby "x" is unique for a given (method user host).
2438 (defvar tramp-devices nil
2439 "Keeps virtual device numbers.")
2441 ;; CCC: This should check for an error condition and signal failure
2442 ;; when something goes wrong.
2443 ;; Daniel Pittman <daniel@danann.net>
2444 (defun tramp-handle-file-attributes (filename &optional id-format)
2445 "Like `file-attributes' for Tramp files."
2446 (unless id-format (setq id-format 'integer))
2447 (with-parsed-tramp-file-name (expand-file-name filename) nil
2448 (with-file-property v localname (format "file-attributes-%s" id-format)
2449 (when (file-exists-p filename)
2450 ;; file exists, find out stuff
2452 (tramp-convert-file-attributes
2454 (if (tramp-get-remote-stat v)
2455 (tramp-handle-file-attributes-with-stat v localname id-format)
2456 (if (tramp-get-remote-perl v)
2457 (tramp-handle-file-attributes-with-perl v localname id-format)
2458 (tramp-handle-file-attributes-with-ls
2459 v localname id-format)))))))))
2461 (defun tramp-handle-file-attributes-with-ls (vec localname &optional id-format)
2462 "Implement `file-attributes' for Tramp files using the ls(1) command."
2464 res-inode res-filemodes res-numlinks
2465 res-uid res-gid res-size res-symlink-target)
2466 (tramp-message vec 5 "file attributes with ls: %s" localname)
2470 (tramp-get-ls-command vec)
2471 (if (eq id-format 'integer) "-ildn" "-ild")
2472 (tramp-shell-quote-argument localname)))
2473 ;; parse `ls -l' output ...
2474 (with-current-buffer (tramp-get-buffer vec)
2475 (goto-char (point-min))
2479 (read (current-buffer))
2480 (invalid-read-syntax
2481 (when (and (equal (cadr err)
2482 "Integer constant overflow in reader")
2484 "^[0-9]+\\([0-9][0-9][0-9][0-9][0-9]\\)\\'"
2486 (let* ((big (read (substring (car (cddr err)) 0
2487 (match-beginning 1))))
2488 (small (read (match-string 1 (car (cddr err)))))
2489 (twiddle (/ small 65536)))
2490 (cons (+ big twiddle)
2491 (- small (* twiddle 65536))))))))
2492 ;; ... file mode flags
2493 (setq res-filemodes (symbol-name (read (current-buffer))))
2495 (setq res-numlinks (read (current-buffer)))
2497 (setq res-uid (read (current-buffer)))
2498 (setq res-gid (read (current-buffer)))
2499 (if (eq id-format 'integer)
2501 (unless (numberp res-uid) (setq res-uid -1))
2502 (unless (numberp res-gid) (setq res-gid -1)))
2504 (unless (stringp res-uid) (setq res-uid (symbol-name res-uid)))
2505 (unless (stringp res-gid) (setq res-gid (symbol-name res-gid)))))
2507 (setq res-size (read (current-buffer)))
2508 ;; From the file modes, figure out other stuff.
2509 (setq symlinkp (eq ?l (aref res-filemodes 0)))
2510 (setq dirp (eq ?d (aref res-filemodes 0)))
2511 ;; if symlink, find out file name pointed to
2513 (search-forward "-> ")
2514 (setq res-symlink-target
2515 (buffer-substring (point) (tramp-compat-line-end-position))))
2516 ;; return data gathered
2518 ;; 0. t for directory, string (name linked to) for symbolic
2520 (or dirp res-symlink-target)
2521 ;; 1. Number of links to file.
2527 ;; 4. Last access time, as a list of two integers. First
2528 ;; integer has high-order 16 bits of time, second has low 16
2530 ;; 5. Last modification time, likewise.
2531 ;; 6. Last status change time, likewise.
2532 '(0 0) '(0 0) '(0 0) ;CCC how to find out?
2533 ;; 7. Size in bytes (-1, if number is out of range).
2535 ;; 8. File modes, as a string of ten letters or dashes as in ls -l.
2537 ;; 9. t if file's gid would change if file were deleted and
2538 ;; recreated. Will be set in `tramp-convert-file-attributes'
2540 ;; 10. inode number.
2542 ;; 11. Device number. Will be replaced by a virtual device number.
2546 (defun tramp-handle-file-attributes-with-perl
2547 (vec localname &optional id-format)
2548 "Implement `file-attributes' for Tramp files using a Perl script."
2549 (tramp-message vec 5 "file attributes with perl: %s" localname)
2550 (tramp-maybe-send-script
2551 vec tramp-perl-file-attributes "tramp_perl_file_attributes")
2552 (tramp-send-command-and-read
2554 (format "tramp_perl_file_attributes %s %s"
2555 (tramp-shell-quote-argument localname) id-format)))
2557 (defun tramp-handle-file-attributes-with-stat
2558 (vec localname &optional id-format)
2559 "Implement `file-attributes' for Tramp files using stat(1) command."
2560 (tramp-message vec 5 "file attributes with stat: %s" localname)
2561 (tramp-send-command-and-read
2564 "%s -c '((\"%%N\") %%h %s %s %%X.0 %%Y.0 %%Z.0 %%s.0 \"%%A\" t %%i.0 -1)' %s"
2565 (tramp-get-remote-stat vec)
2566 (if (eq id-format 'integer) "%u" "\"%U\"")
2567 (if (eq id-format 'integer) "%g" "\"%G\"")
2568 (tramp-shell-quote-argument localname))))
2570 (defun tramp-handle-set-visited-file-modtime (&optional time-list)
2571 "Like `set-visited-file-modtime' for Tramp files."
2572 (unless (buffer-file-name)
2573 (error "Can't set-visited-file-modtime: buffer `%s' not visiting a file"
2576 (tramp-run-real-handler 'set-visited-file-modtime (list time-list))
2577 (let ((f (buffer-file-name))
2579 (with-parsed-tramp-file-name f nil
2580 (let* ((attr (file-attributes f))
2581 ;; '(-1 65535) means file doesn't exists yet.
2582 (modtime (or (nth 5 attr) '(-1 65535))))
2583 (when (boundp 'last-coding-system-used)
2584 (setq coding-system-used (symbol-value 'last-coding-system-used)))
2585 ;; We use '(0 0) as a don't-know value. See also
2586 ;; `tramp-handle-file-attributes-with-ls'.
2587 (if (not (equal modtime '(0 0)))
2588 (tramp-run-real-handler 'set-visited-file-modtime (list modtime))
2592 (format "%s -ild %s"
2593 (tramp-get-ls-command v)
2594 (tramp-shell-quote-argument localname)))
2595 (setq attr (buffer-substring (point)
2596 (progn (end-of-line) (point)))))
2597 (tramp-set-file-property
2598 v localname "visited-file-modtime-ild" attr))
2599 (when (boundp 'last-coding-system-used)
2600 (set 'last-coding-system-used coding-system-used))
2603 ;; This function makes the same assumption as
2604 ;; `tramp-handle-set-visited-file-modtime'.
2605 (defun tramp-handle-verify-visited-file-modtime (buf)
2606 "Like `verify-visited-file-modtime' for Tramp files.
2607 At the time `verify-visited-file-modtime' calls this function, we
2608 already know that the buffer is visiting a file and that
2609 `visited-file-modtime' does not return 0. Do not call this
2610 function directly, unless those two cases are already taken care
2612 (with-current-buffer buf
2613 ;; There is no file visiting the buffer, or the buffer has no
2614 ;; recorded last modification time.
2615 (if (or (not (buffer-file-name))
2616 (eq (visited-file-modtime) 0))
2618 (let ((f (buffer-file-name)))
2619 (with-parsed-tramp-file-name f nil
2620 (tramp-flush-file-property v localname)
2621 (let* ((attr (file-attributes f))
2622 (modtime (nth 5 attr))
2623 (mt (visited-file-modtime)))
2626 ;; File exists, and has a known modtime.
2627 ((and attr (not (equal modtime '(0 0))))
2628 (< (abs (tramp-time-diff
2630 ;; For compatibility, deal with both the old
2631 ;; (HIGH . LOW) and the new (HIGH LOW) return
2632 ;; values of `visited-file-modtime'.
2634 (list (car mt) (cdr mt))
2637 ;; Modtime has the don't know value.
2641 (format "%s -ild %s"
2642 (tramp-get-ls-command v)
2643 (tramp-shell-quote-argument localname)))
2644 (with-current-buffer (tramp-get-buffer v)
2645 (setq attr (buffer-substring
2646 (point) (progn (end-of-line) (point)))))
2649 (tramp-get-file-property
2650 v localname "visited-file-modtime-ild" "")))
2651 ;; If file does not exist, say it is not modified if and
2652 ;; only if that agrees with the buffer's record.
2653 (t (equal mt '(-1 65535))))))))))
2655 (defun tramp-handle-set-file-modes (filename mode)
2656 "Like `set-file-modes' for Tramp files."
2657 (with-parsed-tramp-file-name filename nil
2658 (tramp-flush-file-property v localname)
2659 (unless (zerop (tramp-send-command-and-check
2661 (format "chmod %s %s"
2662 (tramp-decimal-to-octal mode)
2663 (tramp-shell-quote-argument localname))))
2664 ;; FIXME: extract the proper text from chmod's stderr.
2666 v 'file-error "Error while changing file's mode %s" filename))))
2668 (defun tramp-handle-set-file-times (filename &optional time)
2669 "Like `set-file-times' for Tramp files."
2671 (if (file-remote-p filename)
2672 (with-parsed-tramp-file-name filename nil
2673 (tramp-flush-file-property v localname)
2674 (let ((time (if (or (null time) (equal time '(0 0)))
2678 ;; With GNU Emacs, `format-time-string' has an
2679 ;; optional parameter UNIVERSAL. This is preferred,
2680 ;; because we could handle the case when the remote
2681 ;; host is located in a different time zone as the
2683 (and (functionp 'subr-arity)
2684 (subrp (symbol-function 'format-time-string))
2685 (= 3 (cdr (funcall (symbol-function 'subr-arity)
2687 'format-time-string)))))))
2688 (tramp-send-command-and-check
2689 v (format "%s touch -t %s %s"
2690 (if utc "TZ=UTC; export TZ;" "")
2692 (format-time-string "%Y%m%d%H%M.%S" time t)
2693 (format-time-string "%Y%m%d%H%M.%S" time))
2694 (tramp-shell-quote-argument localname)))))
2696 ;; We handle also the local part, because in older Emacsen,
2697 ;; without `set-file-times', this function is an alias for this.
2698 ;; We are local, so we don't need the UTC settings.
2699 (tramp-local-call-process
2700 "touch" nil nil nil "-t"
2701 (format-time-string "%Y%m%d%H%M.%S" time)
2702 (tramp-shell-quote-argument filename)))))
2704 (defun tramp-set-file-uid-gid (filename &optional uid gid)
2705 "Set the ownership for FILENAME.
2706 If UID and GID are provided, these values are used; otherwise uid
2707 and gid of the corresponding user is taken. Both parameters must be integers."
2708 ;; Modern Unices allow chown only for root. So we might need
2709 ;; another implementation, see `dired-do-chown'. OTOH, it is mostly
2710 ;; working with su(do)? when it is needed, so it shall succeed in
2711 ;; the majority of cases.
2712 (if (file-remote-p filename)
2713 (with-parsed-tramp-file-name filename nil
2714 (if (and (zerop (user-uid)) (tramp-local-host-p v))
2715 ;; If we are root on the local host, we can do it directly.
2716 (tramp-set-file-uid-gid localname uid gid)
2717 (let ((uid (or (and (integerp uid) uid)
2718 (tramp-get-remote-uid v 'integer)))
2719 (gid (or (and (integerp gid) gid)
2720 (tramp-get-remote-gid v 'integer))))
2723 "chown %d:%d %s" uid gid
2724 (tramp-shell-quote-argument localname))))))
2726 ;; We handle also the local part, because there doesn't exist
2727 ;; `set-file-uid-gid'. On W32 "chown" might not work.
2728 (let ((uid (or (and (integerp uid) uid) (tramp-get-local-uid 'integer)))
2729 (gid (or (and (integerp gid) gid) (tramp-get-local-gid 'integer))))
2730 (tramp-local-call-process
2732 (format "%d:%d" uid gid) (tramp-shell-quote-argument filename)))))
2734 ;; Simple functions using the `test' command.
2736 (defun tramp-handle-file-executable-p (filename)
2737 "Like `file-executable-p' for Tramp files."
2738 (with-parsed-tramp-file-name filename nil
2739 (with-file-property v localname "file-executable-p"
2740 (zerop (tramp-run-test "-x" filename)))))
2742 (defun tramp-handle-file-readable-p (filename)
2743 "Like `file-readable-p' for Tramp files."
2744 (with-parsed-tramp-file-name filename nil
2745 (with-file-property v localname "file-readable-p"
2746 (zerop (tramp-run-test "-r" filename)))))
2748 ;; When the remote shell is started, it looks for a shell which groks
2749 ;; tilde expansion. Here, we assume that all shells which grok tilde
2750 ;; expansion will also provide a `test' command which groks `-nt' (for
2751 ;; newer than). If this breaks, tell me about it and I'll try to do
2752 ;; something smarter about it.
2753 (defun tramp-handle-file-newer-than-file-p (file1 file2)
2754 "Like `file-newer-than-file-p' for Tramp files."
2755 (cond ((not (file-exists-p file1))
2757 ((not (file-exists-p file2))
2759 ;; We are sure both files exist at this point.
2762 ;; We try to get the mtime of both files. If they are not
2763 ;; equal to the "dont-know" value, then we subtract the times
2764 ;; and obtain the result.
2765 (let ((fa1 (file-attributes file1))
2766 (fa2 (file-attributes file2)))
2767 (if (and (not (equal (nth 5 fa1) '(0 0)))
2768 (not (equal (nth 5 fa2) '(0 0))))
2769 (> 0 (tramp-time-diff (nth 5 fa2) (nth 5 fa1)))
2770 ;; If one of them is the dont-know value, then we can
2771 ;; still try to run a shell command on the remote host.
2772 ;; However, this only works if both files are Tramp
2773 ;; files and both have the same method, same user, same
2775 (unless (tramp-equal-remote file1 file2)
2776 (with-parsed-tramp-file-name
2777 (if (tramp-tramp-file-p file1) file1 file2) nil
2780 "Files %s and %s must have same method, user, host"
2782 (with-parsed-tramp-file-name file1 nil
2783 (zerop (tramp-run-test2
2784 (tramp-get-test-nt-command v) file1 file2)))))))))
2786 ;; Functions implemented using the basic functions above.
2788 (defun tramp-handle-file-modes (filename)
2789 "Like `file-modes' for Tramp files."
2790 (let ((truename (or (file-truename filename) filename)))
2791 (when (file-exists-p truename)
2792 (tramp-mode-string-to-int (nth 8 (file-attributes truename))))))
2794 (defun tramp-default-file-modes (filename)
2795 "Return file modes of FILENAME as integer.
2796 If the file modes of FILENAME cannot be determined, return the
2797 value of `default-file-modes', without execute permissions."
2798 (or (file-modes filename)
2799 (logand (default-file-modes) (tramp-octal-to-decimal "0666"))))
2801 (defun tramp-handle-file-directory-p (filename)
2802 "Like `file-directory-p' for Tramp files."
2803 ;; Care must be taken that this function returns `t' for symlinks
2804 ;; pointing to directories. Surely the most obvious implementation
2805 ;; would be `test -d', but that returns false for such symlinks.
2806 ;; CCC: Stefan Monnier says that `test -d' follows symlinks. And
2807 ;; I now think he's right. So we could be using `test -d', couldn't
2810 ;; Alternatives: `cd %s', `test -d %s'
2811 (with-parsed-tramp-file-name filename nil
2812 (with-file-property v localname "file-directory-p"
2813 (zerop (tramp-run-test "-d" filename)))))
2815 (defun tramp-handle-file-regular-p (filename)
2816 "Like `file-regular-p' for Tramp files."
2817 (and (file-exists-p filename)
2818 (eq ?- (aref (nth 8 (file-attributes filename)) 0))))
2820 (defun tramp-handle-file-symlink-p (filename)
2821 "Like `file-symlink-p' for Tramp files."
2822 (with-parsed-tramp-file-name filename nil
2823 (let ((x (car (file-attributes filename))))
2825 ;; When Tramp is running on VMS, then `file-name-absolute-p'
2826 ;; might do weird things.
2827 (if (file-name-absolute-p x)
2828 (tramp-make-tramp-file-name method user host x)
2831 (defun tramp-handle-file-writable-p (filename)
2832 "Like `file-writable-p' for Tramp files."
2833 (with-parsed-tramp-file-name filename nil
2834 (with-file-property v localname "file-writable-p"
2835 (if (file-exists-p filename)
2836 ;; Existing files must be writable.
2837 (zerop (tramp-run-test "-w" filename))
2838 ;; If file doesn't exist, check if directory is writable.
2839 (and (zerop (tramp-run-test
2840 "-d" (file-name-directory filename)))
2841 (zerop (tramp-run-test
2842 "-w" (file-name-directory filename))))))))
2844 (defun tramp-handle-file-ownership-preserved-p (filename)
2845 "Like `file-ownership-preserved-p' for Tramp files."
2846 (with-parsed-tramp-file-name filename nil
2847 (with-file-property v localname "file-ownership-preserved-p"
2848 (let ((attributes (file-attributes filename)))
2849 ;; Return t if the file doesn't exist, since it's true that no
2850 ;; information would be lost by an (attempted) delete and create.
2851 (or (null attributes)
2852 (= (nth 2 attributes) (tramp-get-remote-uid v 'integer)))))))
2854 ;; Other file name ops.
2856 (defun tramp-handle-directory-file-name (directory)
2857 "Like `directory-file-name' for Tramp files."
2858 ;; If localname component of filename is "/", leave it unchanged.
2859 ;; Otherwise, remove any trailing slash from localname component.
2860 ;; Method, host, etc, are unchanged. Does it make sense to try
2861 ;; to avoid parsing the filename?
2862 (with-parsed-tramp-file-name directory nil
2863 (if (and (not (zerop (length localname)))
2864 (eq (aref localname (1- (length localname))) ?/)
2865 (not (string= localname "/")))
2866 (substring directory 0 -1)
2869 ;; Directory listings.
2871 (defun tramp-handle-directory-files
2872 (directory &optional full match nosort files-only)
2873 "Like `directory-files' for Tramp files."
2874 ;; FILES-ONLY is valid for XEmacs only.
2875 (when (file-directory-p directory)
2876 (setq directory (expand-file-name directory))
2877 (let ((temp (nreverse (file-name-all-completions "" directory)))
2881 (setq item (directory-file-name (pop temp)))
2882 (when (and (or (null match) (string-match match item))
2883 (or (null files-only)
2885 (and (equal files-only t) (file-regular-p item))
2887 (file-directory-p item)))
2888 (push (if full (expand-file-name item directory) item)
2892 (defun tramp-handle-directory-files-and-attributes
2893 (directory &optional full match nosort id-format)
2894 "Like `directory-files-and-attributes' for Tramp files."
2895 (unless id-format (setq id-format 'integer))
2896 (when (file-directory-p directory)
2897 (setq directory (expand-file-name directory))
2899 (tramp-compat-copy-tree
2900 (with-parsed-tramp-file-name directory nil
2903 (format "directory-files-and-attributes-%s" id-format)
2908 (tramp-convert-file-attributes v (cdr x))))
2909 (if (tramp-get-remote-stat v)
2910 (tramp-handle-directory-files-and-attributes-with-stat
2911 v localname id-format)
2912 (if (tramp-get-remote-perl v)
2913 (tramp-handle-directory-files-and-attributes-with-perl
2914 v localname id-format)))))))))
2918 (setq item (pop temp))
2919 (when (or (null match) (string-match match (car item)))
2921 (setcar item (expand-file-name (car item) directory)))
2922 (push item result)))
2926 (sort result (lambda (x y) (string< (car x) (car y))))))))
2928 (defun tramp-handle-directory-files-and-attributes-with-perl
2929 (vec localname &optional id-format)
2930 "Implement `directory-files-and-attributes' for Tramp files using a Perl script."
2931 (tramp-message vec 5 "directory-files-and-attributes with perl: %s" localname)
2932 (tramp-maybe-send-script
2933 vec tramp-perl-directory-files-and-attributes
2934 "tramp_perl_directory_files_and_attributes")
2936 (tramp-send-command-and-read
2938 (format "tramp_perl_directory_files_and_attributes %s %s"
2939 (tramp-shell-quote-argument localname) id-format))))
2940 (when (stringp object) (tramp-error vec 'file-error object))
2943 (defun tramp-handle-directory-files-and-attributes-with-stat
2944 (vec localname &optional id-format)
2945 "Implement `directory-files-and-attributes' for Tramp files using stat(1) command."
2946 (tramp-message vec 5 "directory-files-and-attributes with stat: %s" localname)
2947 (tramp-send-command-and-read
2951 ;; We must care about filenames with spaces, or starting with
2952 ;; "-"; this would confuse xargs. "ls -aQ" might be a solution,
2953 ;; but it does not work on all remote systems. Therefore, we
2954 ;; quote the filenames via sed.
2955 "cd %s; echo \"(\"; (%s -a | sed -e s/\\$/\\\"/g -e s/^/\\\"/g | xargs "
2956 "%s -c '(\"%%n\" (\"%%N\") %%h %s %s %%X.0 %%Y.0 %%Z.0 %%s.0 \"%%A\" t %%i.0 -1)'); "
2958 (tramp-shell-quote-argument localname)
2959 (tramp-get-ls-command vec)
2960 (tramp-get-remote-stat vec)
2961 (if (eq id-format 'integer) "%u" "\"%U\"")
2962 (if (eq id-format 'integer) "%g" "\"%G\""))))
2964 ;; This function should return "foo/" for directories and "bar" for
2966 (defun tramp-handle-file-name-all-completions (filename directory)
2967 "Like `file-name-all-completions' for Tramp files."
2968 (unless (save-match-data (string-match "/" filename))
2969 (with-parsed-tramp-file-name (expand-file-name directory) nil
2970 ;; Flush the directory cache. There could be changed directory
2972 (when (and (integerp tramp-completion-reread-directory-timeout)
2975 (tramp-get-file-property
2976 v localname "last-completion" '(0 0 0)))
2977 tramp-completion-reread-directory-timeout))
2978 (tramp-flush-file-property v localname))
2984 (with-file-property v localname "file-name-all-completions"
2986 (tramp-barf-unless-okay
2988 (format "cd %s" (tramp-shell-quote-argument localname))
2989 "tramp-handle-file-name-all-completions: Couldn't `cd %s'"
2990 (tramp-shell-quote-argument localname))
2992 ;; Get a list of directories and files, including reliably
2993 ;; tagging the directories with a trailing '/'. Because I
2994 ;; rock. --daniel@danann.net
2997 (format (concat "%s -a 2>/dev/null | while read f; do "
2998 "if %s -d \"$f\" 2>/dev/null; "
2999 "then echo \"$f/\"; else echo \"$f\"; fi; done")
3000 (tramp-get-ls-command v)
3001 (tramp-get-test-command v)))
3003 ;; Now grab the output.
3004 (with-current-buffer (tramp-get-buffer v)
3005 (goto-char (point-max))
3006 (while (zerop (forward-line -1))
3007 (push (buffer-substring
3008 (point) (tramp-compat-line-end-position))
3011 (tramp-set-file-property
3012 v localname "last-completion" (current-time))
3015 ;; The following isn't needed for Emacs 20 but for 19.34?
3016 (defun tramp-handle-file-name-completion
3017 (filename directory &optional predicate)
3018 "Like `file-name-completion' for Tramp files."
3019 (unless (tramp-tramp-file-p directory)
3021 "tramp-handle-file-name-completion invoked on non-tramp directory `%s'"
3025 (mapcar 'list (file-name-all-completions filename directory))
3027 (lambda (x) (funcall predicate (expand-file-name (car x) directory))))))
3031 (defun tramp-handle-add-name-to-file
3032 (filename newname &optional ok-if-already-exists)
3033 "Like `add-name-to-file' for Tramp files."
3034 (unless (tramp-equal-remote filename newname)
3035 (with-parsed-tramp-file-name
3036 (if (tramp-tramp-file-p filename) filename newname) nil
3039 "add-name-to-file: %s"
3040 "only implemented for same method, same user, same host")))
3041 (with-parsed-tramp-file-name filename v1
3042 (with-parsed-tramp-file-name newname v2
3043 (let ((ln (when v1 (tramp-get-remote-ln v1))))
3044 (when (and (not ok-if-already-exists)
3045 (file-exists-p newname)
3046 (not (numberp ok-if-already-exists))
3049 "File %s already exists; make it a new name anyway? "
3053 "add-name-to-file: file %s already exists" newname))
3054 (tramp-flush-file-property v2 v2-localname)
3055 (tramp-barf-unless-okay
3057 (format "%s %s %s" ln (tramp-shell-quote-argument v1-localname)
3058 (tramp-shell-quote-argument v2-localname))
3059 "error with add-name-to-file, see buffer `%s' for details"
3062 (defun tramp-handle-copy-file
3063 (filename newname &optional ok-if-already-exists keep-date preserve-uid-gid)
3064 "Like `copy-file' for Tramp files."
3065 ;; Check if both files are local -- invoke normal copy-file.
3066 ;; Otherwise, use Tramp from local system.
3067 (setq filename (expand-file-name filename))
3068 (setq newname (expand-file-name newname))
3070 ;; At least one file a Tramp file?
3071 ((or (tramp-tramp-file-p filename)
3072 (tramp-tramp-file-p newname))
3073 (tramp-do-copy-or-rename-file
3074 'copy filename newname ok-if-already-exists keep-date preserve-uid-gid))
3077 (tramp-run-real-handler
3079 (list filename newname ok-if-already-exists keep-date preserve-uid-gid)))
3081 (tramp-run-real-handler
3082 'copy-file (list filename newname ok-if-already-exists keep-date)))))
3084 (defun tramp-handle-rename-file
3085 (filename newname &optional ok-if-already-exists)
3086 "Like `rename-file' for Tramp files."
3087 ;; Check if both files are local -- invoke normal rename-file.
3088 ;; Otherwise, use Tramp from local system.
3089 (setq filename (expand-file-name filename))
3090 (setq newname (expand-file-name newname))
3091 ;; At least one file a Tramp file?
3092 (if (or (tramp-tramp-file-p filename)
3093 (tramp-tramp-file-p newname))
3094 (tramp-do-copy-or-rename-file
3095 'rename filename newname ok-if-already-exists t t)
3096 (tramp-run-real-handler
3097 'rename-file (list filename newname ok-if-already-exists))))
3099 (defun tramp-do-copy-or-rename-file
3100 (op filename newname &optional ok-if-already-exists keep-date preserve-uid-gid)
3101 "Copy or rename a remote file.
3102 OP must be `copy' or `rename' and indicates the operation to perform.
3103 FILENAME specifies the file to copy or rename, NEWNAME is the name of
3104 the new file (for copy) or the new name of the file (for rename).
3105 OK-IF-ALREADY-EXISTS means don't barf if NEWNAME exists already.
3106 KEEP-DATE means to make sure that NEWNAME has the same timestamp
3107 as FILENAME. PRESERVE-UID-GID, when non-nil, instructs to keep
3108 the uid and gid if both files are on the same host.
3110 This function is invoked by `tramp-handle-copy-file' and
3111 `tramp-handle-rename-file'. It is an error if OP is neither of `copy'
3112 and `rename'. FILENAME and NEWNAME must be absolute file names."
3113 (unless (memq op '(copy rename))
3114 (error "Unknown operation `%s', must be `copy' or `rename'" op))
3115 (let ((t1 (tramp-tramp-file-p filename))
3116 (t2 (tramp-tramp-file-p newname)))
3118 (when (and (not ok-if-already-exists) (file-exists-p newname))
3119 (with-parsed-tramp-file-name (if t1 filename newname) nil
3121 v 'file-already-exists "File %s already exists" newname)))
3123 (with-parsed-tramp-file-name (if t1 filename newname) nil
3124 (tramp-message v 0 "Transferring %s to %s..." filename newname))
3128 ;; Both are Tramp files.
3130 (with-parsed-tramp-file-name filename v1
3131 (with-parsed-tramp-file-name newname v2
3133 ;; Shortcut: if method, host, user are the same for both
3134 ;; files, we invoke `cp' or `mv' on the remote host
3136 ((tramp-equal-remote filename newname)
3137 (tramp-do-copy-or-rename-file-directly
3139 ok-if-already-exists keep-date preserve-uid-gid))
3141 ;; Try out-of-band operation.
3142 ((and (tramp-method-out-of-band-p v1)
3143 (> (nth 7 (file-attributes filename))
3144 tramp-copy-size-limit))
3145 (tramp-do-copy-or-rename-file-out-of-band
3146 op filename newname keep-date))
3148 ;; No shortcut was possible. So we copy the
3149 ;; file first. If the operation was `rename', we go
3150 ;; back and delete the original file (if the copy was
3151 ;; successful). The approach is simple-minded: we
3152 ;; create a new buffer, insert the contents of the
3153 ;; source file into it, then write out the buffer to
3154 ;; the target file. The advantage is that it doesn't
3155 ;; matter which filename handlers are used for the
3156 ;; source and target file.
3158 (tramp-do-copy-or-rename-file-via-buffer
3159 op filename newname keep-date))))))
3161 ;; One file is a Tramp file, the other one is local.
3163 (with-parsed-tramp-file-name (if t1 filename newname) nil
3165 ;; Fast track on local machine.
3166 ((tramp-local-host-p v)
3167 (tramp-do-copy-or-rename-file-directly
3169 ok-if-already-exists keep-date preserve-uid-gid))
3171 ;; If the Tramp file has an out-of-band method, the corresponding
3172 ;; copy-program can be invoked.
3173 ((and (tramp-method-out-of-band-p v)
3174 (> (nth 7 (file-attributes filename))
3175 tramp-copy-size-limit))
3176 (tramp-do-copy-or-rename-file-out-of-band
3177 op filename newname keep-date))
3179 ;; Use the inline method via a Tramp buffer.
3180 (t (tramp-do-copy-or-rename-file-via-buffer
3181 op filename newname keep-date)))))
3184 ;; One of them must be a Tramp file.
3185 (error "Tramp implementation says this cannot happen")))
3187 ;; In case of `rename', we must flush the cache of the source file.
3188 (when (and t1 (eq op 'rename))
3189 (with-parsed-tramp-file-name filename nil
3190 (tramp-flush-file-property v localname)))
3192 ;; When newname did exist, we have wrong cached values.
3194 (with-parsed-tramp-file-name newname nil
3195 (tramp-flush-file-property v localname)))
3197 (with-parsed-tramp-file-name (if t1 filename newname) nil
3198 (tramp-message v 0 "Transferring %s to %s...done" filename newname)))))
3200 (defun tramp-do-copy-or-rename-file-via-buffer (op filename newname keep-date)
3201 "Use an Emacs buffer to copy or rename a file.
3202 First arg OP is either `copy' or `rename' and indicates the operation.
3203 FILENAME is the source file, NEWNAME the target file.
3204 KEEP-DATE is non-nil if NEWNAME should have the same timestamp as FILENAME."
3206 ;; We must disable multibyte, because binary data shall not be
3208 (set-buffer-multibyte nil)
3209 (let ((coding-system-for-read 'binary)
3210 (jka-compr-inhibit t))
3211 (insert-file-contents-literally filename))
3212 ;; We don't want the target file to be compressed, so we let-bind
3213 ;; `jka-compr-inhibit' to t.
3214 (let ((coding-system-for-write 'binary)
3215 (jka-compr-inhibit t))
3216 (write-region (point-min) (point-max) newname)))
3217 ;; KEEP-DATE handling.
3218 (when keep-date (set-file-times newname (nth 5 (file-attributes filename))))
3220 (set-file-modes newname (tramp-default-file-modes filename))
3221 ;; If the operation was `rename', delete the original file.
3222 (unless (eq op 'copy) (delete-file filename)))
3224 (defun tramp-do-copy-or-rename-file-directly
3225 (op filename newname ok-if-already-exists keep-date preserve-uid-gid)
3226 "Invokes `cp' or `mv' on the remote system.
3227 OP must be one of `copy' or `rename', indicating `cp' or `mv',
3228 respectively. FILENAME specifies the file to copy or rename,
3229 NEWNAME is the name of the new file (for copy) or the new name of
3230 the file (for rename). Both files must reside on the same host.
3231 KEEP-DATE means to make sure that NEWNAME has the same timestamp
3232 as FILENAME. PRESERVE-UID-GID, when non-nil, instructs to keep
3233 the uid and gid from FILENAME."
3234 (let ((t1 (tramp-tramp-file-p filename))
3235 (t2 (tramp-tramp-file-p newname))
3236 (file-times (nth 5 (file-attributes filename)))
3237 (file-modes (tramp-default-file-modes filename)))
3238 (with-parsed-tramp-file-name (if t1 filename newname) nil
3239 (let* ((cmd (cond ((and (eq op 'copy) preserve-uid-gid) "cp -f -p")
3240 ((eq op 'copy) "cp -f")
3241 ((eq op 'rename) "mv -f")
3244 "Unknown operation `%s', must be `copy' or `rename'"
3247 (if t1 (tramp-handle-file-remote-p filename 'localname) filename))
3249 (if t2 (tramp-handle-file-remote-p newname 'localname) newname))
3250 (prefix (file-remote-p (if t1 filename newname))))
3253 ;; Both files are on a remote host, with same user.
3257 (format "%s %s %s" cmd
3258 (tramp-shell-quote-argument localname1)
3259 (tramp-shell-quote-argument localname2)))
3260 (with-current-buffer (tramp-get-buffer v)
3261 (goto-char (point-min))
3265 ;; Mask cp -f error.
3267 tramp-operation-not-permitted-regexp nil t))
3268 (zerop (tramp-send-command-and-check v nil)))
3269 (tramp-error-with-buffer
3271 "Copying directly failed, see buffer `%s' for details."
3274 ;; We are on the local host.
3277 ;; We can do it directly.
3278 ((let (file-name-handler-alist)
3279 (and (file-readable-p localname1)
3280 (file-writable-p (file-name-directory localname2))
3281 (or (file-directory-p localname2)
3282 (file-writable-p localname2))))
3284 (tramp-compat-copy-file
3285 localname1 localname2 ok-if-already-exists
3286 keep-date preserve-uid-gid)
3287 (tramp-run-real-handler
3288 'rename-file (list localname1 localname2 ok-if-already-exists))))
3290 ;; We can do it directly with `tramp-send-command'
3291 ((let (file-name-handler-alist)
3292 (and (file-readable-p (concat prefix localname1))
3294 (file-name-directory (concat prefix localname2)))))
3295 (tramp-do-copy-or-rename-file-directly
3296 op (concat prefix localname1) (concat prefix localname2)
3297 ok-if-already-exists keep-date t)
3298 ;; We must change the ownership to the local user.
3299 (tramp-set-file-uid-gid
3300 (concat prefix localname2)
3301 (tramp-get-local-uid 'integer)
3302 (tramp-get-local-gid 'integer)))
3304 ;; We need a temporary file in between.
3306 ;; Create the temporary file.
3307 (let ((tmpfile (tramp-compat-make-temp-file localname1)))
3314 (tramp-send-command-and-check
3317 (tramp-shell-quote-argument localname1)
3318 (tramp-shell-quote-argument tmpfile))))
3319 (tramp-error-with-buffer
3321 "Copying directly failed, see buffer `%s' for details."
3322 (tramp-get-buffer v)))
3323 ;; We must change the ownership as remote user.
3324 ;; Since this does not work reliable, we also
3325 ;; give read permissions.
3327 (concat prefix tmpfile) (tramp-octal-to-decimal "0777"))
3328 (tramp-set-file-uid-gid
3329 (concat prefix tmpfile)
3330 (tramp-get-local-uid 'integer)
3331 (tramp-get-local-gid 'integer)))
3334 (tramp-compat-copy-file
3335 localname1 tmpfile t
3336 keep-date preserve-uid-gid)
3337 (tramp-run-real-handler
3339 (list localname1 tmpfile t)))
3340 ;; We must change the ownership as local user.
3341 ;; Since this does not work reliable, we also
3342 ;; give read permissions.
3343 (set-file-modes tmpfile (tramp-octal-to-decimal "0777"))
3344 (tramp-set-file-uid-gid
3346 (tramp-get-remote-uid v 'integer)
3347 (tramp-get-remote-gid v 'integer))))
3349 ;; Move the temporary file to its destination.
3354 (tramp-send-command-and-check
3357 (tramp-shell-quote-argument tmpfile)
3358 (tramp-shell-quote-argument localname2))))
3359 (tramp-error-with-buffer
3361 "Copying directly failed, see buffer `%s' for details."
3362 (tramp-get-buffer v))))
3364 (tramp-run-real-handler
3366 (list tmpfile localname2 ok-if-already-exists)))))
3370 (delete-file tmpfile)
3373 ;; Set the time and mode. Mask possible errors.
3376 (set-file-times newname file-times)
3377 (set-file-modes newname file-modes))
3380 (defun tramp-do-copy-or-rename-file-out-of-band (op filename newname keep-date)
3381 "Invoke rcp program to copy.
3382 The method used must be an out-of-band method."
3383 (let ((t1 (tramp-tramp-file-p filename))
3384 (t2 (tramp-tramp-file-p newname))
3385 copy-program copy-args copy-keep-date port spec
3388 (with-parsed-tramp-file-name (if t1 filename newname) nil
3391 ;; Both are Tramp files. We shall optimize it, when the
3392 ;; methods for filename and newname are the same.
3393 (let ((tmpfile (tramp-compat-make-temp-file localname)))
3396 (tramp-do-copy-or-rename-file-out-of-band
3397 op filename tmpfile keep-date)
3398 (tramp-do-copy-or-rename-file-out-of-band
3399 'rename tmpfile newname keep-date))
3402 (delete-file tmpfile)
3405 ;; Expand hops. Might be necessary for gateway methods.
3406 (setq v (car (tramp-compute-multi-hops v)))
3407 (aset v 3 localname)
3409 ;; Check which ones of source and target are Tramp files.
3410 (setq source (if t1 (tramp-make-copy-program-file-name v) filename)
3411 target (if t2 (tramp-make-copy-program-file-name v) newname))
3413 ;; Check for port number. Until now, there's no need for handling
3414 ;; like method, user, host.
3415 (setq host (tramp-file-name-real-host v)
3416 port (tramp-file-name-port v)
3417 port (or (and port (number-to-string port)) ""))
3419 ;; Compose copy command.
3420 (setq spec `((?h . ,host) (?u . ,user) (?p . ,port)
3421 (?t . ,(tramp-get-connection-property
3422 (tramp-get-connection-process v) "temp-file" ""))
3423 (?k . ,(if keep-date " " "")))
3424 copy-program (tramp-get-method-parameter
3425 method 'tramp-copy-program)
3426 copy-keep-date (tramp-get-method-parameter
3427 method 'tramp-copy-keep-date)
3435 ;; " " is indication for keep-date argument.
3436 (delete " " (mapcar '(lambda (y) (format-spec y spec)) x)))
3437 (unless (member "" x) (mapconcat 'identity x " ")))
3438 (tramp-get-method-parameter method 'tramp-copy-args))))
3440 ;; Check for program.
3441 (when (and (fboundp 'executable-find)
3442 (not (let ((default-directory
3443 (tramp-compat-temporary-file-directory)))
3444 (executable-find copy-program))))
3446 v 'file-error "Cannot find copy program: %s" copy-program))
3450 ;; The default directory must be remote.
3451 (let ((default-directory
3452 (file-name-directory (if t1 filename newname))))
3453 ;; Set the transfer process properties.
3454 (tramp-set-connection-property
3455 v "process-name" (buffer-name (current-buffer)))
3456 (tramp-set-connection-property
3457 v "process-buffer" (current-buffer))
3459 ;; Use an asynchronous process. By this, password can
3460 ;; be handled. The default directory must be local, in
3461 ;; order to apply the correct `copy-program'. We don't
3462 ;; set a timeout, because the copying of large files can
3463 ;; last longer than 60 secs.
3464 (let ((p (let ((default-directory
3465 (tramp-compat-temporary-file-directory)))
3466 (apply 'start-process
3467 (tramp-get-connection-property
3468 v "process-name" nil)
3469 (tramp-get-connection-property
3470 v "process-buffer" nil)
3472 (append copy-args (list source target))))))
3474 v 6 "%s" (mapconcat 'identity (process-command p) " "))
3475 (tramp-set-process-query-on-exit-flag p nil)
3476 (tramp-process-actions p v tramp-actions-copy-out-of-band))))
3478 ;; Reset the transfer process properties.
3479 (tramp-set-connection-property v "process-name" nil)
3480 (tramp-set-connection-property v "process-buffer" nil))
3482 ;; Handle KEEP-DATE argument.
3483 (when (and keep-date (not copy-keep-date))
3484 (set-file-times newname (nth 5 (file-attributes filename))))
3487 (unless (and keep-date copy-keep-date)
3488 (set-file-modes newname (tramp-default-file-modes filename))))
3490 ;; If the operation was `rename', delete the original file.
3491 (unless (eq op 'copy)
3492 (delete-file filename)))))
3494 (defun tramp-handle-make-directory (dir &optional parents)
3495 "Like `make-directory' for Tramp files."
3496 (setq dir (expand-file-name dir))
3497 (with-parsed-tramp-file-name dir nil
3499 (tramp-barf-unless-okay
3502 (if parents "mkdir -p" "mkdir")
3503 (tramp-shell-quote-argument localname))
3504 "Couldn't make directory %s" dir))))
3506 (defun tramp-handle-delete-directory (directory)
3507 "Like `delete-directory' for Tramp files."
3508 (setq directory (expand-file-name directory))
3509 (with-parsed-tramp-file-name directory nil
3510 (tramp-flush-directory-property v localname)
3511 (unless (zerop (tramp-send-command-and-check
3513 (format "rmdir %s" (tramp-shell-quote-argument localname))))
3514 (tramp-error v 'file-error "Couldn't delete %s" directory))))
3516 (defun tramp-handle-delete-file (filename)
3517 "Like `delete-file' for Tramp files."
3518 (setq filename (expand-file-name filename))
3519 (with-parsed-tramp-file-name filename nil
3520 (tramp-flush-file-property v localname)
3521 (unless (zerop (tramp-send-command-and-check
3524 (tramp-shell-quote-argument localname))))
3525 (tramp-error v 'file-error "Couldn't delete %s" filename))))
3529 ;; CCC: This does not seem to be enough. Something dies when
3530 ;; we try and delete two directories under Tramp :/
3531 (defun tramp-handle-dired-recursive-delete-directory (filename)
3532 "Recursively delete the directory given.
3533 This is like `dired-recursive-delete-directory' for Tramp files."
3534 (with-parsed-tramp-file-name filename nil
3535 (tramp-flush-directory-property v localname)
3536 ;; Run a shell command 'rm -r <localname>'
3537 ;; Code shamelessly stolen from the dired implementation and, um, hacked :)
3538 (unless (file-exists-p filename)
3539 (tramp-error v 'file-error "No such directory: %s" filename))
3540 ;; Which is better, -r or -R? (-r works for me <daniel@danann.net>)
3543 (format "rm -rf %s" (tramp-shell-quote-argument localname))
3544 ;; Don't read the output, do it explicitely.
3546 ;; Wait for the remote system to return to us...
3547 ;; This might take a while, allow it plenty of time.
3548 (tramp-wait-for-output (tramp-get-connection-process v) 120)
3549 ;; Make sure that it worked...
3550 (and (file-exists-p filename)
3552 v 'file-error "Failed to recursively delete %s" filename))))
3554 (defun tramp-handle-dired-compress-file (file &rest ok-flag)
3555 "Like `dired-compress-file' for Tramp files."
3556 ;; OK-FLAG is valid for XEmacs only, but not implemented.
3557 ;; Code stolen mainly from dired-aux.el.
3558 (with-parsed-tramp-file-name file nil
3559 (tramp-flush-file-property v localname)
3562 (if (not (featurep 'xemacs))
3564 (symbol-value 'dired-compress-file-suffixes)
3565 ;; XEmacs has `dired-compression-method-alist', which is
3566 ;; transformed into `dired-compress-file-suffixes' structure.
3569 (list (concat (regexp-quote (nth 1 x)) "\\'")
3571 (mapconcat 'identity (nth 3 x) " ")))
3572 (symbol-value 'dired-compression-method-alist))))
3574 ;; See if any suffix rule matches this file name.
3576 (let (case-fold-search)
3577 (if (string-match (car (car suffixes)) localname)
3578 (setq suffix (car suffixes) suffixes nil))
3579 (setq suffixes (cdr suffixes))))
3581 (cond ((file-symlink-p file)
3583 ((and suffix (nth 2 suffix))
3584 ;; We found an uncompression rule.
3585 (tramp-message v 0 "Uncompressing %s..." file)
3586 (when (zerop (tramp-send-command-and-check
3587 v (concat (nth 2 suffix) " " localname)))
3588 (tramp-message v 0 "Uncompressing %s...done" file)
3589 ;; `dired-remove-file' is not defined in XEmacs
3590 (funcall (symbol-function 'dired-remove-file) file)
3591 (string-match (car suffix) file)
3592 (concat (substring file 0 (match-beginning 0)))))
3594 ;; We don't recognize the file as compressed, so compress it.
3596 (tramp-message v 0 "Compressing %s..." file)
3597 (when (zerop (tramp-send-command-and-check
3598 v (concat "gzip -f " localname)))
3599 (tramp-message v 0 "Compressing %s...done" file)
3600 ;; `dired-remove-file' is not defined in XEmacs
3601 (funcall (symbol-function 'dired-remove-file) file)
3602 (cond ((file-exists-p (concat file ".gz"))
3603 (concat file ".gz"))
3604 ((file-exists-p (concat file ".z"))
3608 (defun tramp-handle-dired-uncache (dir)
3609 "Like `dired-uncache' for Tramp files."
3610 (with-parsed-tramp-file-name dir nil
3611 (tramp-flush-file-property v localname)))
3613 ;; Pacify byte-compiler. The function is needed on XEmacs only. I'm
3614 ;; not sure at all that this is the right way to do it, but let's hope
3615 ;; it works for now, and wait for a guru to point out the Right Way to
3617 ;;(eval-when-compile
3618 ;; (unless (fboundp 'dired-insert-set-properties)
3619 ;; (fset 'dired-insert-set-properties 'ignore)))
3620 ;; Gerd suggests this:
3621 (eval-when-compile (require 'dired))
3622 ;; Note that dired is required at run-time, too, when it is needed.
3623 ;; It is only needed on XEmacs for the function
3624 ;; `dired-insert-set-properties'.
3626 (defun tramp-handle-insert-directory
3627 (filename switches &optional wildcard full-directory-p)
3628 "Like `insert-directory' for Tramp files."
3629 (setq filename (expand-file-name filename))
3630 (with-parsed-tramp-file-name filename nil
3631 (if (and (featurep 'ls-lisp)
3632 (not (symbol-value 'ls-lisp-use-insert-directory-program)))
3633 (tramp-run-real-handler
3634 'insert-directory (list filename switches wildcard full-directory-p))
3635 ;; For the moment, we assume that the remote "ls" program does not
3636 ;; grok "--dired". In the future, we should detect this on
3637 ;; connection setup.
3638 (when (string-match "^--dired\\s-+" switches)
3639 (setq switches (replace-match "" nil t switches)))
3641 v 4 "Inserting directory `ls %s %s', wildcard %s, fulldir %s"
3642 switches filename (if wildcard "yes" "no")
3643 (if full-directory-p "yes" "no"))
3645 (setq wildcard (tramp-run-real-handler
3646 'file-name-nondirectory (list localname)))
3647 (setq localname (tramp-run-real-handler
3648 'file-name-directory (list localname))))
3649 (when (listp switches)
3650 (setq switches (mapconcat 'identity switches " ")))
3651 (unless full-directory-p
3652 (setq switches (concat "-d " switches)))
3654 (setq switches (concat switches " " wildcard)))
3655 ;; If `full-directory-p', we just say `ls -l FILENAME'.
3656 ;; Else we chdir to the parent directory, then say `ls -ld BASENAME'.
3657 (if full-directory-p
3661 (tramp-get-ls-command v)
3665 (tramp-shell-quote-argument (concat localname ".")))))
3666 (tramp-barf-unless-okay
3668 (format "cd %s" (tramp-shell-quote-argument
3669 (tramp-run-real-handler
3670 'file-name-directory (list localname))))
3672 (tramp-shell-quote-argument
3673 (tramp-run-real-handler 'file-name-directory (list localname))))
3677 (tramp-get-ls-command v)
3681 (tramp-run-real-handler
3682 'file-name-nondirectory (list localname)))))
3684 (tramp-shell-quote-argument
3685 (tramp-run-real-handler
3686 'file-name-nondirectory (list localname)))))))
3687 ;; We cannot use `insert-buffer-substring' because the Tramp buffer
3688 ;; changes its contents before insertion due to calling
3689 ;; `expand-file' and alike.
3691 (with-current-buffer (tramp-get-buffer v)
3692 (buffer-string))))))
3694 (defun tramp-handle-unhandled-file-name-directory (filename)
3695 "Like `unhandled-file-name-directory' for Tramp files."
3696 ;; With Emacs 23, we could simply return `nil'. But we must keep it
3697 ;; for backward compatibility.
3698 (expand-file-name "~/"))
3700 ;; Canonicalization of file names.
3702 (defun tramp-handle-expand-file-name (name &optional dir)
3703 "Like `expand-file-name' for Tramp files.
3704 If the localname part of the given filename starts with \"/../\" then
3705 the result will be a local, non-Tramp, filename."
3706 ;; If DIR is not given, use DEFAULT-DIRECTORY or "/".
3707 (setq dir (or dir default-directory "/"))
3708 ;; Unless NAME is absolute, concat DIR and NAME.
3709 (unless (file-name-absolute-p name)
3710 (setq name (concat (file-name-as-directory dir) name)))
3711 ;; If NAME is not a Tramp file, run the real handler.
3712 (if (not (tramp-tramp-file-p name))
3713 (tramp-run-real-handler 'expand-file-name (list name nil))
3715 (with-parsed-tramp-file-name name nil
3716 (unless (tramp-run-real-handler 'file-name-absolute-p (list localname))
3717 (setq localname (concat "~/" localname)))
3718 ;; Tilde expansion if necessary. This needs a shell which
3719 ;; groks tilde expansion! The function `tramp-find-shell' is
3720 ;; supposed to find such a shell on the remote host. Please
3721 ;; tell me about it when this doesn't work on your system.
3722 (when (string-match "\\`\\(~[^/]*\\)\\(.*\\)\\'" localname)
3723 (let ((uname (match-string 1 localname))
3724 (fname (match-string 2 localname)))
3725 ;; We cannot simply apply "~/", because under sudo "~/" is
3726 ;; expanded to the local user home directory but to the
3727 ;; root home directory. On the other hand, using always
3728 ;; the default user name for tilde expansion is not
3729 ;; appropriate either, because ssh and companions might
3730 ;; use a user name from the config file.
3731 (when (and (string-equal uname "~")
3732 (string-match "\\`su\\(do\\)?\\'" method))
3733 (setq uname (concat uname user)))
3735 (with-connection-property v uname
3736 (tramp-send-command v (format "cd %s; pwd" uname))
3737 (with-current-buffer (tramp-get-buffer v)
3738 (goto-char (point-min))
3739 (buffer-substring (point) (tramp-compat-line-end-position)))))
3740 (setq localname (concat uname fname))))
3741 ;; There might be a double slash, for example when "~/"
3742 ;; expands to "/". Remove this.
3743 (while (string-match "//" localname)
3744 (setq localname (replace-match "/" t t localname)))
3745 ;; No tilde characters in file name, do normal
3746 ;; expand-file-name (this does "/./" and "/../"). We bind
3747 ;; `directory-sep-char' here for XEmacs on Windows, which
3748 ;; would otherwise use backslash. `default-directory' is
3749 ;; bound, because on Windows there would be problems with UNC
3750 ;; shares or Cygwin mounts.
3751 (let ((directory-sep-char ?/)
3752 (default-directory (tramp-compat-temporary-file-directory)))
3753 (tramp-make-tramp-file-name
3755 (tramp-drop-volume-letter
3756 (tramp-run-real-handler
3757 'expand-file-name (list localname))))))))
3759 (defun tramp-replace-environment-variables (filename)
3760 "Replace environment variables in FILENAME.
3761 Return the string with the replaced variables."
3763 (let ((idx (string-match "$\\w+" filename)))
3764 ;; `$' is coded as `$$'.
3765 (when (and idx (or (zerop idx) (not (eq ?$ (aref filename (1- idx))))))
3768 (substitute-in-file-name (match-string 0 filename))
3772 (defun tramp-handle-substitute-in-file-name (filename)
3773 "Like `substitute-in-file-name' for Tramp files.
3774 \"//\" and \"/~\" substitute only in the local filename part.
3775 If the URL Tramp syntax is chosen, \"//\" as method delimeter and \"/~\" at
3776 beginning of local filename are not substituted."
3777 ;; First, we must replace environment variables.
3778 (setq filename (tramp-replace-environment-variables filename))
3779 (with-parsed-tramp-file-name filename nil
3780 (if (equal tramp-syntax 'url)
3781 ;; We need to check localname only. The other parts cannot contain
3783 (if (and (> (length localname) 1)
3784 (or (string-match "//" localname)
3785 (string-match "/~" localname 1)))
3786 (tramp-run-real-handler 'substitute-in-file-name (list filename))
3787 (tramp-make-tramp-file-name
3788 (when method (substitute-in-file-name method))
3789 (when user (substitute-in-file-name user))
3790 (when host (substitute-in-file-name host))
3792 (tramp-run-real-handler
3793 'substitute-in-file-name (list localname)))))
3794 ;; Ignore in LOCALNAME everything before "//" or "/~".
3795 (when (and (stringp localname) (string-match ".+?/\\(/\\|~\\)" localname))
3797 (concat (file-remote-p filename)
3798 (replace-match "\\1" nil nil localname)))
3799 ;; "/m:h:~" does not work for completion. We use "/m:h:~/".
3800 (when (string-match "~$" filename)
3801 (setq filename (concat filename "/"))))
3802 (tramp-run-real-handler 'substitute-in-file-name (list filename)))))
3804 ;; In XEmacs, electricity is implemented via a key map for ?/ and ?~,
3805 ;; which calls corresponding functions (see minibuf.el).
3806 (when (fboundp 'minibuffer-electric-separator)
3811 (around ,(intern (format "tramp-advice-%s" x)) activate)
3812 "Invoke `substitute-in-file-name' for Tramp files."
3813 (if (and (symbol-value 'minibuffer-electric-file-name-behavior)
3814 (tramp-tramp-file-p (buffer-substring)))
3815 ;; We don't need to handle `last-input-event', because
3816 ;; due to the key map we know it must be ?/ or ?~.
3817 (let ((s (concat (buffer-substring (point-min) (point))
3818 (string last-command-char))))
3819 (delete-region (point-min) (point))
3820 (insert (substitute-in-file-name s))
3821 (setq ad-return-value last-command-char))
3824 '(minibuffer-electric-separator
3825 minibuffer-electric-tilde)))
3828 ;;; Remote commands:
3830 (defun tramp-handle-executable-find (command)
3831 "Like `executable-find' for Tramp files."
3832 (with-parsed-tramp-file-name default-directory nil
3833 (tramp-find-executable v command (tramp-get-remote-path v) t)))
3835 ;; We use BUFFER also as connection buffer during setup. Because of
3836 ;; this, its original contents must be saved, and restored once
3837 ;; connection has been setup.
3838 (defun tramp-handle-start-file-process (name buffer program &rest args)
3839 "Like `start-file-process' for Tramp files."
3840 (with-parsed-tramp-file-name default-directory nil
3845 ;; BUFFER can be nil. We use a temporary buffer.
3846 (setq buffer (generate-new-buffer tramp-temp-buffer-name)))
3847 (while (get-process name1)
3848 ;; NAME must be unique as process name.
3850 name1 (format "%s<%d>" name i)))
3852 ;; Set the new process properties.
3853 (tramp-set-connection-property v "process-name" name)
3854 (tramp-set-connection-property v "process-buffer" buffer)
3855 ;; Activate narrowing in order to save BUFFER contents.
3856 ;; Clear also the modification time; otherwise we might be
3857 ;; interrupted by `verify-visited-file-modtime'.
3858 (with-current-buffer (tramp-get-connection-buffer v)
3859 (clear-visited-file-modtime)
3860 (narrow-to-region (point-max) (point-max)))
3861 ;; Goto working directory. `tramp-send-command' opens a new
3864 v (format "cd %s" (tramp-shell-quote-argument localname)))
3865 ;; Send the command.
3869 (mapconcat 'tramp-shell-quote-argument
3870 (cons program args) " "))
3872 ;; Set query flag for this process.
3873 (tramp-set-process-query-on-exit-flag
3874 (tramp-get-connection-process v) t)
3876 (tramp-get-connection-process v))
3878 (with-current-buffer (tramp-get-connection-buffer v)
3879 (if (string-match tramp-temp-buffer-name (buffer-name))
3881 (set-process-buffer (tramp-get-connection-process v) nil)
3882 (kill-buffer (current-buffer)))
3884 (goto-char (point-max))))
3885 (tramp-set-connection-property v "process-name" nil)
3886 (tramp-set-connection-property v "process-buffer" nil))))
3888 (defun tramp-handle-process-file
3889 (program &optional infile destination display &rest args)
3890 "Like `process-file' for Tramp files."
3891 ;; The implementation is not complete yet.
3892 (when (and (numberp destination) (zerop destination))
3893 (error "Implementation does not handle immediate return"))
3895 (with-parsed-tramp-file-name default-directory nil
3896 (let (command input tmpinput stderr tmpstderr outbuf ret)
3898 (setq command (mapconcat 'tramp-shell-quote-argument
3899 (cons program args) " "))
3902 (setq input "/dev/null")
3903 (setq infile (expand-file-name infile))
3904 (if (tramp-equal-remote default-directory infile)
3905 ;; INFILE is on the same remote host.
3906 (setq input (with-parsed-tramp-file-name infile nil localname))
3907 ;; INFILE must be copied to remote host.
3908 (setq input (tramp-make-tramp-temp-file v)
3909 tmpinput (tramp-make-tramp-file-name method user host input))
3910 (copy-file infile tmpinput t)))
3911 (when input (setq command (format "%s <%s" command input)))
3913 ;; Determine output.
3916 ((bufferp destination)
3917 (setq outbuf destination))
3919 ((stringp destination)
3920 (setq outbuf (get-buffer-create destination)))
3921 ;; (REAL-DESTINATION ERROR-DESTINATION)
3922 ((consp destination)
3925 ((bufferp (car destination))
3926 (setq outbuf (car destination)))
3927 ((stringp (car destination))
3928 (setq outbuf (get-buffer-create (car destination))))
3930 (setq outbuf (current-buffer))))
3933 ((stringp (cadr destination))
3934 (setcar (cdr destination) (expand-file-name (cadr destination)))
3935 (if (tramp-equal-remote default-directory (cadr destination))
3936 ;; stderr is on the same remote host.
3937 (setq stderr (with-parsed-tramp-file-name
3938 (cadr destination) nil localname))
3939 ;; stderr must be copied to remote host. The temporary
3940 ;; file must be deleted after execution.
3941 (setq stderr (tramp-make-tramp-temp-file v)
3942 tmpstderr (tramp-make-tramp-file-name
3943 method user host stderr))))
3944 ;; stderr to be discarded.
3945 ((null (cadr destination))
3946 (setq stderr "/dev/null"))))
3949 (setq outbuf (current-buffer))))
3950 (when stderr (setq command (format "%s 2>%s" command stderr)))
3952 ;; Goto working directory.
3954 v (format "cd %s" (tramp-shell-quote-argument localname)))
3955 ;; Send the command. It might not return in time, so we protect it.
3958 (tramp-send-command v command)
3959 ;; We should show the output anyway.
3961 (let ((output-string
3962 (with-current-buffer (tramp-get-connection-buffer v)
3963 (buffer-substring (point-min) (point-max)))))
3964 (with-current-buffer outbuf
3965 (insert output-string)))
3966 (when display (display-buffer outbuf))))
3967 ;; When the user did interrupt, we should do it also. We use
3968 ;; return code -1 as marker.
3970 (kill-buffer (tramp-get-connection-buffer v))
3974 (kill-buffer (tramp-get-connection-buffer v))
3977 ;; Check return code.
3978 (unless ret (setq ret (tramp-send-command-and-check v nil)))
3979 ;; Provide error file.
3980 (when tmpstderr (rename-file tmpstderr (cadr destination) t))
3981 ;; Cleanup. We remove all file cache values for the connection,
3982 ;; because the remote process could have changed them.
3983 (when tmpinput (delete-file tmpinput))
3984 (tramp-flush-directory-property v "")
3985 ;; Return exit status.
3990 (defun tramp-local-call-process
3991 (program &optional infile destination display &rest args)
3992 "Calls `call-process' on the local host.
3993 This is needed because for some Emacs flavors Tramp has
3994 defadviced `call-process' to behave like `process-file'. The
3995 Lisp error raised when PROGRAM is nil is trapped also, returning 1."
3996 (let ((default-directory
3997 (if (file-remote-p default-directory)
3998 (tramp-compat-temporary-file-directory)
3999 default-directory)))
4000 (if (executable-find program)
4001 (apply 'call-process program infile destination display args)
4004 (defun tramp-handle-call-process-region
4005 (start end program &optional delete buffer display &rest args)
4006 "Like `call-process-region' for Tramp files."
4007 (let ((tmpfile (tramp-compat-make-temp-file "")))
4008 (write-region start end tmpfile)
4009 (when delete (delete-region start end))
4011 (apply 'call-process program tmpfile buffer display args)
4012 (delete-file tmpfile))))
4014 (defun tramp-handle-shell-command
4015 (command &optional output-buffer error-buffer)
4016 "Like `shell-command' for Tramp files."
4017 (let* ((asynchronous (string-match "[ \t]*&[ \t]*\\'" command))
4018 ;; We cannot use `shell-file-name' and `shell-command-switch',
4019 ;; they are variables of the local host.
4020 (args (list "/bin/sh" "-c" (substring command 0 asynchronous)))
4024 ((bufferp output-buffer) output-buffer)
4025 ((stringp output-buffer) (get-buffer-create output-buffer))
4027 (setq current-buffer-p t)
4029 (t (get-buffer-create
4031 "*Async Shell Command*"
4032 "*Shell Command Output*")))))
4035 ((bufferp error-buffer) error-buffer)
4036 ((stringp error-buffer) (get-buffer-create error-buffer))))
4038 (if (and (not asynchronous) error-buffer)
4039 (with-parsed-tramp-file-name default-directory nil
4040 (list output-buffer (tramp-make-tramp-temp-file v)))
4042 (p (get-buffer-process output-buffer)))
4044 ;; Check whether there is another process running. Tramp does not
4045 ;; support 2 (asynchronous) processes in parallel.
4047 (if (yes-or-no-p "A command is running. Kill it? ")
4051 (error "Shell command in progress")))
4053 (if current-buffer-p
4055 (barf-if-buffer-read-only)
4057 (with-current-buffer output-buffer
4058 (setq buffer-read-only nil)
4061 (if (and (not current-buffer-p) (integerp asynchronous))
4064 (apply 'start-file-process "*Async Shell*" buffer args)
4066 (pop-to-buffer output-buffer)
4067 (setq mode-line-process '(":%s"))
4068 (require 'shell) (shell-mode))
4072 (apply 'process-file (car args) nil buffer nil (cdr args))
4073 ;; Insert error messages if they were separated.
4074 (when (listp buffer)
4075 (with-current-buffer error-buffer
4076 (insert-file-contents (cadr buffer)))
4077 (delete-file (cadr buffer)))
4078 (if current-buffer-p
4079 ;; This is like exchange-point-and-mark, but doesn't
4080 ;; activate the mark. It is cleaner to avoid activation,
4081 ;; even though the command loop would deactivate the mark
4082 ;; because we inserted text.
4083 (goto-char (prog1 (mark t)
4084 (set-marker (mark-marker) (point)
4086 ;; There's some output, display it.
4087 (when (with-current-buffer output-buffer (> (point-max) (point-min)))
4088 (if (functionp 'display-message-or-buffer)
4089 (funcall (symbol-function 'display-message-or-buffer)
4091 (pop-to-buffer output-buffer))))))))
4095 (defvar tramp-handle-file-local-copy-hook nil
4096 "Normal hook to be run at the end of `tramp-handle-file-local-copy'.")
4098 (defun tramp-handle-file-local-copy (filename)
4099 "Like `file-local-copy' for Tramp files."
4101 (with-parsed-tramp-file-name filename nil
4102 (unless (file-exists-p filename)
4105 "Cannot make local copy of non-existing file `%s'" filename))
4107 (let ((rem-enc (tramp-get-remote-coding v "remote-encoding"))
4108 (loc-dec (tramp-get-local-coding v "local-decoding"))
4109 (tmpfile (tramp-compat-make-temp-file filename)))
4113 ;; `copy-file' handles direct copy and out-of-band methods.
4114 ((or (tramp-local-host-p v)
4115 (and (tramp-method-out-of-band-p v)
4116 (> (nth 7 (file-attributes filename))
4117 tramp-copy-size-limit)))
4118 (copy-file filename tmpfile t t))
4120 ;; Use inline encoding for file transfer.
4123 (tramp-message v 5 "Encoding remote file %s..." filename)
4124 (tramp-barf-unless-okay
4126 (format "%s < %s" rem-enc (tramp-shell-quote-argument localname))
4127 "Encoding remote file failed")
4128 (tramp-message v 5 "Encoding remote file %s...done" filename)
4130 (if (and (symbolp loc-dec) (fboundp loc-dec))
4131 ;; If local decoding is a function, we call it. We
4132 ;; must disable multibyte, because
4133 ;; `uudecode-decode-region' doesn't handle it
4136 (set-buffer-multibyte nil)
4137 (insert-buffer-substring (tramp-get-buffer v))
4139 v 5 "Decoding remote file %s with function %s..."
4141 (funcall loc-dec (point-min) (point-max))
4142 (let ((coding-system-for-write 'binary))
4143 (write-region (point-min) (point-max) tmpfile)))
4145 ;; If tramp-decoding-function is not defined for this
4146 ;; method, we invoke tramp-decoding-command instead.
4147 (let ((tmpfile2 (tramp-compat-make-temp-file filename)))
4148 (let ((coding-system-for-write 'binary))
4149 (write-region (point-min) (point-max) tmpfile2))
4151 v 5 "Decoding remote file %s with command %s..."
4154 (tramp-call-local-coding-command loc-dec tmpfile2 tmpfile)
4155 (delete-file tmpfile2))))
4157 (tramp-message v 5 "Decoding remote file %s...done" filename)
4158 ;; Set proper permissions.
4159 (set-file-modes tmpfile (tramp-default-file-modes filename))
4160 ;; Set local user ownership.
4161 (tramp-set-file-uid-gid tmpfile)))
4163 ;; Oops, I don't know what to do.
4165 v 'file-error "Wrong method specification for `%s'" method)))
4169 (delete-file tmpfile)
4170 (signal (car err) (cdr err))))
4172 (run-hooks 'tramp-handle-file-local-copy-hook)
4175 (defun tramp-handle-file-remote-p (filename &optional identification connected)
4176 "Like `file-remote-p' for Tramp files."
4177 (when (tramp-tramp-file-p filename)
4178 (with-parsed-tramp-file-name filename nil
4179 (and (or (not connected)
4180 (let ((p (tramp-get-connection-process v)))
4181 (and p (processp p) (memq (process-status p) '(run open)))))
4183 ((eq identification 'method) method)
4184 ((eq identification 'user) user)
4185 ((eq identification 'host) host)
4186 ((eq identification 'localname) localname)
4187 (t (tramp-make-tramp-file-name method user host "")))))))
4189 (defun tramp-find-file-name-coding-system-alist (filename tmpname)
4190 "Like `find-operation-coding-system' for Tramp filenames.
4191 Tramp's `insert-file-contents' and `write-region' work over
4192 temporary file names. If `file-coding-system-alist' contains an
4193 expression, which matches more than the file name suffix, the
4194 coding system might not be determined. This function repairs it."
4196 (dolist (elt file-coding-system-alist result)
4197 (when (and (consp elt) (string-match (car elt) filename))
4198 ;; We found a matching entry in `file-coding-system-alist'.
4199 ;; So we add a similar entry, but with the temporary file name
4202 'result (cons (regexp-quote tmpname) (cdr elt)) 'append)))))
4204 (defun tramp-handle-insert-file-contents
4205 (filename &optional visit beg end replace)
4206 "Like `insert-file-contents' for Tramp files."
4207 (barf-if-buffer-read-only)
4208 (setq filename (expand-file-name filename))
4209 (let (coding-system-used result local-copy remote-copy)
4211 (with-parsed-tramp-file-name filename nil
4213 (if (not (file-exists-p filename))
4214 ;; We don't raise a Tramp error, because it might be
4215 ;; suppressed, like in `find-file-noselect-1'.
4217 (list "File not found on remote host" filename))
4219 (if (and (tramp-local-host-p v)
4220 (let (file-name-handler-alist)
4221 (file-readable-p localname)))
4222 ;; Short track: if we are on the local host, we can
4225 (tramp-run-real-handler
4226 'insert-file-contents
4227 (list localname visit beg end replace)))
4229 ;; When we shall insert only a part of the file, we copy
4232 (setq remote-copy (tramp-make-tramp-temp-file v))
4237 (format "tail -c +%d %s | head -c +%d >%s"
4238 (1+ beg) (tramp-shell-quote-argument localname)
4239 (- end beg) remote-copy))
4241 (format "tail -c +%d %s >%s"
4242 (1+ beg) (tramp-shell-quote-argument localname)
4245 (format "head -c +%d %s >%s"
4246 (1+ end) (tramp-shell-quote-argument localname)
4249 ;; `insert-file-contents-literally' takes care to avoid
4250 ;; calling jka-compr. By let-binding
4251 ;; `inhibit-file-name-operation', we propagate that care
4252 ;; to the `file-local-copy' operation.
4254 (let ((inhibit-file-name-operation
4255 (when (eq inhibit-file-name-operation
4256 'insert-file-contents)
4259 (if (stringp remote-copy)
4260 (tramp-make-tramp-file-name
4261 method user host remote-copy)
4264 v 4 "Inserting local temp file `%s'..." local-copy)
4266 ;; We must ensure that `file-coding-system-alist'
4267 ;; matches `local-copy'.
4268 (let ((file-coding-system-alist
4269 (tramp-find-file-name-coding-system-alist
4270 filename local-copy)))
4272 (insert-file-contents
4273 local-copy nil nil nil replace))
4274 ;; Now `last-coding-system-used' has right value.
4276 (when (boundp 'last-coding-system-used)
4277 (setq coding-system-used
4278 (symbol-value 'last-coding-system-used))))
4281 v 4 "Inserting local temp file `%s'...done" local-copy)
4282 (when (boundp 'last-coding-system-used)
4283 (set 'last-coding-system-used coding-system-used)))))
4288 (setq buffer-file-name filename)
4289 (setq buffer-read-only (not (file-writable-p filename)))
4290 (set-visited-file-modtime)
4291 (set-buffer-modified-p nil))
4292 (when (stringp local-copy)
4293 (delete-file local-copy))
4294 (when (stringp remote-copy)
4296 (tramp-make-tramp-file-name method user host remote-copy)))))
4299 (list (expand-file-name filename)
4302 ;; This is needed for XEmacs only. Code stolen from files.el.
4303 (defun tramp-handle-insert-file-contents-literally
4304 (filename &optional visit beg end replace)
4305 "Like `insert-file-contents-literally' for Tramp files."
4306 (let ((format-alist nil)
4307 (after-insert-file-functions nil)
4308 (coding-system-for-read 'no-conversion)
4309 (coding-system-for-write 'no-conversion)
4310 (find-buffer-file-type-function
4311 (if (fboundp 'find-buffer-file-type)
4312 (symbol-function 'find-buffer-file-type)
4314 (inhibit-file-name-handlers '(jka-compr-handler image-file-handler))
4315 (inhibit-file-name-operation 'insert-file-contents))
4318 (fset 'find-buffer-file-type (lambda (filename) t))
4319 (insert-file-contents filename visit beg end replace))
4321 (if find-buffer-file-type-function
4322 (fset 'find-buffer-file-type find-buffer-file-type-function)
4323 (fmakunbound 'find-buffer-file-type)))))
4325 (defun tramp-handle-find-backup-file-name (filename)
4326 "Like `find-backup-file-name' for Tramp files."
4327 (with-parsed-tramp-file-name filename nil
4328 ;; We set both variables. It doesn't matter whether it is
4330 (let ((backup-directory-alist
4332 (when (boundp 'backup-directory-alist)
4333 (if (symbol-value 'tramp-backup-directory-alist)
4338 (if (and (stringp (cdr x))
4339 (file-name-absolute-p (cdr x))
4340 (not (tramp-file-name-p (cdr x))))
4341 (tramp-make-tramp-file-name method user host (cdr x))
4343 (symbol-value 'tramp-backup-directory-alist))
4344 (symbol-value 'backup-directory-alist))))
4346 (bkup-backup-directory-info
4348 (when (boundp 'bkup-backup-directory-info)
4349 (if (symbol-value 'tramp-bkup-backup-directory-info)
4355 (if (and (stringp (car (cdr x)))
4356 (file-name-absolute-p (car (cdr x)))
4357 (not (tramp-file-name-p (car (cdr x)))))
4358 (tramp-make-tramp-file-name
4359 method user host (car (cdr x)))
4362 (symbol-value 'tramp-bkup-backup-directory-info))
4363 (symbol-value 'bkup-backup-directory-info)))))
4365 (tramp-run-real-handler 'find-backup-file-name (list filename)))))
4367 (defun tramp-handle-make-auto-save-file-name ()
4368 "Like `make-auto-save-file-name' for Tramp files.
4369 Returns a file name in `tramp-auto-save-directory' for autosaving this file."
4370 (let ((tramp-auto-save-directory tramp-auto-save-directory)
4372 (tramp-subst-strs-in-string
4379 (buffer-file-name))))
4380 ;; File name must be unique. This is ensured with Emacs 22 (see
4381 ;; UNIQUIFY element of `auto-save-file-name-transforms'); but for
4382 ;; all other cases we must do it ourselves.
4383 (when (boundp 'auto-save-file-name-transforms)
4386 (when (and (string-match (car x) buffer-file-name)
4387 (not (car (cddr x))))
4388 (setq tramp-auto-save-directory
4389 (or tramp-auto-save-directory
4390 (tramp-compat-temporary-file-directory)))))
4391 (symbol-value 'auto-save-file-name-transforms)))
4392 ;; Create directory.
4393 (when tramp-auto-save-directory
4394 (setq buffer-file-name
4395 (expand-file-name buffer-file-name tramp-auto-save-directory))
4396 (unless (file-exists-p tramp-auto-save-directory)
4397 (make-directory tramp-auto-save-directory t)))
4398 ;; Run plain `make-auto-save-file-name'. There might be an advice when
4399 ;; it is not a magic file name operation (since Emacs 22).
4400 ;; We must deactivate it temporarily.
4401 (if (not (ad-is-active 'make-auto-save-file-name))
4402 (tramp-run-real-handler 'make-auto-save-file-name nil)
4404 (ad-deactivate 'make-auto-save-file-name)
4406 (tramp-run-real-handler 'make-auto-save-file-name nil)
4407 (ad-activate 'make-auto-save-file-name)))))
4409 (defvar tramp-handle-write-region-hook nil
4410 "Normal hook to be run at the end of `tramp-handle-write-region'.")
4412 ;; CCC grok APPEND, LOCKNAME
4413 (defun tramp-handle-write-region
4414 (start end filename &optional append visit lockname confirm)
4415 "Like `write-region' for Tramp files."
4416 (setq filename (expand-file-name filename))
4417 (with-parsed-tramp-file-name filename nil
4418 (unless (null append)
4420 v 'file-error "Cannot append to file using Tramp (`%s')" filename))
4421 ;; Following part commented out because we don't know what to do about
4422 ;; file locking, and it does not appear to be a problem to ignore it.
4423 ;; Ange-ftp ignores it, too.
4424 ;; (when (and lockname (stringp lockname))
4425 ;; (setq lockname (expand-file-name lockname)))
4426 ;; (unless (or (eq lockname nil)
4427 ;; (string= lockname filename))
4429 ;; "tramp-handle-write-region: LOCKNAME must be nil or equal FILENAME"))
4431 ;; XEmacs takes a coding system as the seventh argument, not `confirm'.
4432 (when (and (not (featurep 'xemacs)) confirm (file-exists-p filename))
4433 (unless (y-or-n-p (format "File %s exists; overwrite anyway? " filename))
4434 (tramp-error v 'file-error "File not overwritten")))
4436 (let ((uid (or (nth 2 (tramp-compat-file-attributes filename 'integer))
4437 (tramp-get-remote-uid v 'integer)))
4438 (gid (or (nth 3 (tramp-compat-file-attributes filename 'integer))
4439 (tramp-get-remote-gid v 'integer))))
4441 (if (and (tramp-local-host-p v)
4442 ;; `file-writable-p' calls `file-expand-file-name'. We
4443 ;; cannot use `tramp-run-real-handler' therefore.
4444 (let (file-name-handler-alist)
4446 (file-writable-p (file-name-directory localname))
4447 (or (file-directory-p localname)
4448 (file-writable-p localname)))))
4449 ;; Short track: if we are on the local host, we can run directly.
4451 (tramp-run-real-handler
4453 (list start end localname append 'no-message lockname confirm))
4454 (tramp-flush-file-property v localname))
4456 (let ((rem-dec (tramp-get-remote-coding v "remote-decoding"))
4457 (loc-enc (tramp-get-local-coding v "local-encoding"))
4458 (modes (save-excursion (tramp-default-file-modes filename)))
4459 ;; We use this to save the value of
4460 ;; `last-coding-system-used' after writing the tmp file.
4461 ;; At the end of the function, we set
4462 ;; `last-coding-system-used' to this saved value. This
4463 ;; way, any intermediary coding systems used while
4464 ;; talking to the remote shell or suchlike won't hose
4465 ;; this variable. This approach was snarfed from
4468 ;; Write region into a tmp file. This isn't really
4469 ;; needed if we use an encoding function, but currently
4470 ;; we use it always because this makes the logic
4472 (tmpfile (tramp-compat-make-temp-file filename)))
4474 ;; We say `no-message' here because we don't want the
4475 ;; visited file modtime data to be clobbered from the temp
4476 ;; file. We call `set-visited-file-modtime' ourselves later
4477 ;; on. We must ensure that `file-coding-system-alist'
4478 ;; matches `tmpfile'.
4479 (let ((file-coding-system-alist
4480 (tramp-find-file-name-coding-system-alist filename tmpfile)))
4482 (tramp-run-real-handler
4484 (list start end tmpfile append 'no-message lockname confirm))
4486 (delete-file tmpfile)
4487 (signal (car err) (cdr err))))
4489 ;; Now, `last-coding-system-used' has the right value. Remember it.
4490 (when (boundp 'last-coding-system-used)
4491 (setq coding-system-used
4492 (symbol-value 'last-coding-system-used))))
4494 ;; The permissions of the temporary file should be set. If
4495 ;; filename does not exist (eq modes nil) it has been
4496 ;; renamed to the backup file. This case `save-buffer'
4497 ;; handles permissions.
4498 (when modes (set-file-modes tmpfile modes))
4500 ;; This is a bit lengthy due to the different methods
4501 ;; possible for file transfer. First, we check whether the
4502 ;; method uses an rcp program. If so, we call it.
4503 ;; Otherwise, both encoding and decoding command must be
4504 ;; specified. However, if the method _also_ specifies an
4505 ;; encoding function, then that is used for encoding the
4506 ;; contents of the tmp file.
4508 ;; `rename-file' handles direct copy and out-of-band methods.
4509 ((or (tramp-local-host-p v)
4510 (and (tramp-method-out-of-band-p v)
4511 (> (- (or end (point-max)) (or start (point-min)))
4512 tramp-copy-size-limit)))
4514 (rename-file tmpfile filename t)
4516 (delete-file tmpfile)
4517 (signal (car err) (cdr err)))))
4519 ;; Use inline file transfer.
4522 (tramp-message v 5 "Encoding region...")
4525 ;; Use encoding function or command.
4526 (if (and (symbolp loc-enc) (fboundp loc-enc))
4529 v 5 "Encoding region using function `%s'..."
4530 (symbol-name loc-enc))
4531 (let ((coding-system-for-read 'binary))
4532 (insert-file-contents-literally tmpfile))
4533 ;; The following `let' is a workaround for the
4534 ;; base64.el that comes with pgnus-0.84. If
4535 ;; both of the following conditions are
4536 ;; satisfied, it tries to write to a local
4537 ;; file in default-directory, but at this
4538 ;; point, default-directory is remote.
4539 ;; (`call-process-region' can't write to
4540 ;; remote files, it seems.) The file in
4541 ;; question is a tmp file anyway.
4542 (let ((default-directory
4543 (tramp-compat-temporary-file-directory)))
4544 (funcall loc-enc (point-min) (point-max))))
4547 v 5 "Encoding region using command `%s'..." loc-enc)
4548 (unless (equal 0 (tramp-call-local-coding-command
4552 "Cannot write to `%s', local encoding command `%s' failed"
4555 ;; Send buffer into remote decoding command which
4556 ;; writes to remote file. Because this happens on
4557 ;; the remote host, we cannot use the function.
4558 (goto-char (point-max))
4559 (unless (bolp) (newline))
4561 v 5 "Decoding region into remote file %s..." filename)
4565 "%s >%s <<'EOF'\n%sEOF"
4567 (tramp-shell-quote-argument localname)
4569 (tramp-barf-unless-okay
4571 "Couldn't write region to `%s', decode using `%s' failed"
4573 ;; When `file-precious-flag' is set, the region is
4574 ;; written to a temporary file. Check that the
4575 ;; checksum is equal to that from the local tmpfile.
4576 (when file-precious-flag
4579 ;; cksum runs locally, if possible.
4580 (zerop (tramp-local-call-process "cksum" tmpfile t))
4581 ;; cksum runs remotely.
4583 (tramp-send-command-and-check
4586 "cksum <%s" (tramp-shell-quote-argument localname))))
4587 ;; ... they are different.
4591 (with-current-buffer (tramp-get-buffer v)
4595 (concat "Couldn't write region to `%s',"
4596 " decode using `%s' failed")
4599 v 5 "Decoding region into remote file %s...done" filename)
4600 (tramp-flush-file-property v localname))
4603 (delete-file tmpfile)))
4605 ;; That's not expected.
4609 (concat "Method `%s' should specify both encoding and "
4610 "decoding command or an rcp program")
4613 ;; Make `last-coding-system-used' have the right value.
4614 (when coding-system-used
4615 (set 'last-coding-system-used coding-system-used))))
4617 ;; We must protect `last-coding-system-used', now we have set it
4618 ;; to its correct value.
4619 (let (last-coding-system-used)
4620 ;; Set file modification time.
4621 (when (or (eq visit t) (stringp visit))
4622 (set-visited-file-modtime
4623 ;; We must pass modtime explicitely, because filename can
4624 ;; be different from (buffer-file-name), f.e. if
4625 ;; `file-precious-flag' is set.
4626 (nth 5 (file-attributes filename))))
4628 ;; Set the ownership.
4629 (tramp-set-file-uid-gid filename uid gid)
4630 (when (or (eq visit t) (null visit) (stringp visit))
4631 (tramp-message v 0 "Wrote %s" filename))
4632 (run-hooks 'tramp-handle-write-region-hook)))))
4634 (defun tramp-handle-vc-registered (file)
4635 "Like `vc-registered' for Tramp files."
4636 ;; There could be new files, created by the vc backend. We disable
4637 ;; the file cache therefore.
4638 (let ((tramp-cache-inhibit-cache t))
4639 (tramp-run-real-handler 'vc-registered (list file))))
4642 (progn (defun tramp-run-real-handler (operation args)
4643 "Invoke normal file name handler for OPERATION.
4644 First arg specifies the OPERATION, second arg is a list of arguments to
4645 pass to the OPERATION."
4646 (let* ((inhibit-file-name-handlers
4647 `(tramp-file-name-handler
4648 tramp-completion-file-name-handler
4649 cygwin-mount-name-hook-function
4650 cygwin-mount-map-drive-hook-function
4652 ,(and (eq inhibit-file-name-operation operation)
4653 inhibit-file-name-handlers)))
4654 (inhibit-file-name-operation operation))
4655 (apply operation args))))
4658 (progn (defun tramp-completion-run-real-handler (operation args)
4659 "Invoke `tramp-file-name-handler' for OPERATION.
4660 First arg specifies the OPERATION, second arg is a list of arguments to
4661 pass to the OPERATION."
4662 (let* ((inhibit-file-name-handlers
4663 `(tramp-completion-file-name-handler
4664 cygwin-mount-name-hook-function
4665 cygwin-mount-map-drive-hook-function
4667 ,(and (eq inhibit-file-name-operation operation)
4668 inhibit-file-name-handlers)))
4669 (inhibit-file-name-operation operation))
4670 (apply operation args))))
4672 ;; We handle here all file primitives. Most of them have the file
4673 ;; name as first parameter; nevertheless we check for them explicitly
4674 ;; in order to be signaled if a new primitive appears. This
4675 ;; scenario is needed because there isn't a way to decide by
4676 ;; syntactical means whether a foreign method must be called. It would
4677 ;; ease the life if `file-name-handler-alist' would support a decision
4678 ;; function as well but regexp only.
4679 (defun tramp-file-name-for-operation (operation &rest args)
4680 "Return file name related to OPERATION file primitive.
4681 ARGS are the arguments OPERATION has been called with."
4683 ; FILE resp DIRECTORY
4685 (list 'access-file 'byte-compiler-base-file-name 'delete-directory
4686 'delete-file 'diff-latest-backup-file 'directory-file-name
4687 'directory-files 'directory-files-and-attributes
4688 'dired-compress-file 'dired-uncache
4689 'file-accessible-directory-p 'file-attributes
4690 'file-directory-p 'file-executable-p 'file-exists-p
4691 'file-local-copy 'file-remote-p 'file-modes
4692 'file-name-as-directory 'file-name-directory
4693 'file-name-nondirectory 'file-name-sans-versions
4694 'file-ownership-preserved-p 'file-readable-p
4695 'file-regular-p 'file-symlink-p 'file-truename
4696 'file-writable-p 'find-backup-file-name 'find-file-noselect
4697 'get-file-buffer 'insert-directory 'insert-file-contents
4698 'load 'make-directory 'make-directory-internal
4699 'set-file-modes 'substitute-in-file-name
4700 'unhandled-file-name-directory 'vc-registered
4704 'abbreviate-file-name 'create-file-buffer
4705 'dired-file-modtime 'dired-make-compressed-filename
4706 'dired-recursive-delete-directory 'dired-set-file-modtime
4707 'dired-shell-unhandle-file-name 'dired-uucode-file
4708 'insert-file-contents-literally 'make-temp-name 'recover-file
4709 'vm-imap-check-mail 'vm-pop-check-mail 'vm-spool-check-mail))
4710 (if (file-name-absolute-p (nth 0 args))
4712 (expand-file-name (nth 0 args))))
4713 ; FILE DIRECTORY resp FILE1 FILE2
4715 (list 'add-name-to-file 'copy-file 'expand-file-name
4716 'file-name-all-completions 'file-name-completion
4717 'file-newer-than-file-p 'make-symbolic-link 'rename-file
4719 'dired-make-relative-symlink
4720 'vm-imap-move-mail 'vm-pop-move-mail 'vm-spool-move-mail))
4723 ((string-match tramp-file-name-regexp (nth 0 args)) (nth 0 args))
4724 ((string-match tramp-file-name-regexp (nth 1 args)) (nth 1 args))
4725 (t (buffer-file-name (current-buffer))))))
4727 ((eq operation 'write-region)
4731 (list 'set-visited-file-modtime 'verify-visited-file-modtime
4732 ; since Emacs 22 only
4733 'make-auto-save-file-name
4737 (if (bufferp (nth 0 args)) (nth 0 args) (current-buffer))))
4740 (list ; not in Emacs 23
4744 ; since Emacs 22 only
4746 ; since Emacs 23 only
4749 'dired-print-file 'dired-shell-call-process
4751 'executable-find 'start-process 'call-process))
4753 ; unknown file primitive
4754 (t (error "unknown file I/O primitive: %s" operation))))
4756 (defun tramp-find-foreign-file-name-handler (filename)
4757 "Return foreign file name handler if exists."
4758 (when (and (stringp filename) (tramp-tramp-file-p filename))
4759 (let ((v (tramp-dissect-file-name filename t))
4760 (handler tramp-foreign-file-name-handler-alist)
4762 ;; When we are not fully sure that filename completion is safe,
4763 ;; we should not return a handler.
4764 (when (or (tramp-file-name-method v) (tramp-file-name-user v)
4765 (and (tramp-file-name-host v)
4766 (not (member (tramp-file-name-host v)
4767 (mapcar 'car tramp-methods))))
4768 (not (tramp-completion-mode-p)))
4770 (setq elt (car handler)
4771 handler (cdr handler))
4772 (when (funcall (car elt) filename)
4779 (defun tramp-file-name-handler (operation &rest args)
4780 "Invoke Tramp file name handler.
4781 Falls back to normal file name handler if no Tramp file name handler exists."
4785 (tramp-replace-environment-variables
4786 (apply 'tramp-file-name-for-operation operation args)))
4787 (completion (tramp-completion-mode-p))
4788 (foreign (tramp-find-foreign-file-name-handler filename)))
4789 (with-parsed-tramp-file-name filename nil
4791 ;; When we are in completion mode, some operations
4792 ;; shouldn't be handled by backend.
4793 ((and completion (zerop (length localname))
4794 (memq operation '(file-exists-p file-directory-p)))
4796 ((and completion (zerop (length localname))
4797 (memq operation '(file-name-as-directory)))
4799 ;; Call the backend function.
4800 (foreign (apply foreign operation args))
4801 ;; Nothing to do for us.
4802 (t (tramp-run-real-handler operation args))))))
4803 ;; When `tramp-mode' is not enabled, we don't do anything.
4804 (tramp-run-real-handler operation args)))
4806 ;; In Emacs, there is some concurrency due to timers. If a timer
4807 ;; interrupts Tramp and wishes to use the same connection buffer as
4808 ;; the "main" Emacs, then garbage might occur in the connection
4809 ;; buffer. Therefore, we need to make sure that a timer does not use
4810 ;; the same connection buffer as the "main" Emacs. We implement a
4811 ;; cheap global lock, instead of locking each connection buffer
4812 ;; separately. The global lock is based on two variables,
4813 ;; `tramp-locked' and `tramp-locker'. `tramp-locked' is set to true
4814 ;; (with setq) to indicate a lock. But Tramp also calls itself during
4815 ;; processing of a single file operation, so we need to allow
4816 ;; recursive calls. That's where the `tramp-locker' variable comes in
4817 ;; -- it is let-bound to t during the execution of the current
4818 ;; handler. So if `tramp-locked' is t and `tramp-locker' is also t,
4819 ;; then we should just proceed because we have been called
4820 ;; recursively. But if `tramp-locker' is nil, then we are a timer
4821 ;; interrupting the "main" Emacs, and then we signal an error.
4823 (defvar tramp-locked nil
4824 "If non-nil, then Tramp is currently busy.
4825 Together with `tramp-locker', this implements a locking mechanism
4826 preventing reentrant calls of Tramp.")
4828 (defvar tramp-locker nil
4829 "If non-nil, then a caller has locked Tramp.
4830 Together with `tramp-locked', this implements a locking mechanism
4831 preventing reentrant calls of Tramp.")
4833 (defun tramp-sh-file-name-handler (operation &rest args)
4834 "Invoke remote-shell Tramp file name handler.
4835 Fall back to normal file name handler if no Tramp handler exists."
4836 (when (and tramp-locked (not tramp-locker))
4837 (setq tramp-locked nil)
4838 (signal 'file-error (list "Forbidden reentrant call of Tramp")))
4839 (let ((tl tramp-locked))
4842 (setq tramp-locked t)
4843 (let ((tramp-locker t))
4845 (let ((fn (assoc operation tramp-file-name-handler-alist)))
4847 (apply (cdr fn) args)
4848 (tramp-run-real-handler operation args))))))
4849 (setq tramp-locked tl))))
4852 (progn (defun tramp-completion-file-name-handler (operation &rest args)
4853 "Invoke Tramp file name completion handler.
4854 Falls back to normal file name handler if no Tramp file name handler exists."
4855 ;; We bind `directory-sep-char' here for XEmacs on Windows, which
4856 ;; would otherwise use backslash.
4857 (let ((directory-sep-char ?/)
4858 (fn (assoc operation tramp-completion-file-name-handler-alist)))
4859 ;; When `tramp-mode' is not enabled, we don't do anything.
4860 (if (and fn tramp-mode)
4861 (save-match-data (apply (cdr fn) args))
4862 (tramp-completion-run-real-handler operation args)))))
4865 (defsubst tramp-register-file-name-handler ()
4866 "Add Tramp file name handler to `file-name-handler-alist'."
4867 ;; Remove autoloaded handler from file name handler alist. Useful,
4868 ;; if `tramp-syntax' has been changed.
4869 (let ((a1 (rassq 'tramp-file-name-handler file-name-handler-alist)))
4870 (setq file-name-handler-alist (delete a1 file-name-handler-alist)))
4872 (add-to-list 'file-name-handler-alist
4873 (cons tramp-file-name-regexp 'tramp-file-name-handler))
4874 ;; If jka-compr is already loaded, move it to the front of
4875 ;; `file-name-handler-alist'.
4876 (let ((jka (rassoc 'jka-compr-handler file-name-handler-alist)))
4878 (setq file-name-handler-alist
4879 (cons jka (delete jka file-name-handler-alist))))))
4881 ;; `tramp-file-name-handler' must be registered before evaluation of
4882 ;; site-start and init files, because there might exist remote files
4883 ;; already, f.e. files kept via recentf-mode.
4884 ;;;###autoload(tramp-register-file-name-handler)
4885 (tramp-register-file-name-handler)
4888 (defsubst tramp-register-completion-file-name-handler ()
4889 "Add Tramp completion file name handler to `file-name-handler-alist'."
4890 ;; Remove autoloaded handler from file name handler alist. Useful,
4891 ;; if `tramp-syntax' has been changed.
4893 'tramp-completion-file-name-handler file-name-handler-alist)))
4894 (setq file-name-handler-alist (delete a1 file-name-handler-alist)))
4895 ;; `partial-completion-mode' is unknown in XEmacs. So we should
4896 ;; load it unconditionally there. In the GNU Emacs case, method/
4897 ;; user/host name completion shall be bound to `partial-completion-mode'.
4898 ;; `ido-mode' and `icy-mode' are other packages which extend file
4900 (when (or (not (boundp 'partial-completion-mode))
4901 (symbol-value 'partial-completion-mode)
4903 (featurep 'icicles))
4904 (add-to-list 'file-name-handler-alist
4905 (cons tramp-completion-file-name-regexp
4906 'tramp-completion-file-name-handler))
4907 (put 'tramp-completion-file-name-handler 'safe-magic t))
4908 ;; If jka-compr is already loaded, move it to the front of
4909 ;; `file-name-handler-alist'.
4910 (let ((jka (rassoc 'jka-compr-handler file-name-handler-alist)))
4912 (setq file-name-handler-alist
4913 (cons jka (delete jka file-name-handler-alist))))))
4915 ;; During autoload, it shall be checked whether
4916 ;; `partial-completion-mode' is active. Therefore registering of
4917 ;; `tramp-completion-file-name-handler' will be delayed.
4918 ;;;###autoload(add-hook
4919 ;;;###autoload 'after-init-hook
4920 ;;;###autoload 'tramp-register-completion-file-name-handler)
4921 (tramp-register-completion-file-name-handler)
4924 (defun tramp-unload-file-name-handlers ()
4925 (setq file-name-handler-alist
4926 (delete (rassoc 'tramp-file-name-handler
4927 file-name-handler-alist)
4928 (delete (rassoc 'tramp-completion-file-name-handler
4929 file-name-handler-alist)
4930 file-name-handler-alist))))
4932 (add-hook 'tramp-unload-hook 'tramp-unload-file-name-handlers)
4934 ;;; File name handler functions for completion mode:
4936 (defvar tramp-completion-mode nil
4937 "If non-nil, external packages signal that they are in file name completion.
4939 This is necessary, because Tramp uses a heuristic depending on last
4940 input event. This fails when external packages use other characters
4941 but <TAB>, <SPACE> or ?\\? for file name completion. This variable
4942 should never be set globally, the intention is to let-bind it.")
4944 ;; Necessary because `tramp-file-name-regexp-unified' and
4945 ;; `tramp-completion-file-name-regexp-unified' aren't different. If
4946 ;; nil, `tramp-completion-run-real-handler' is called (i.e. forwarding
4947 ;; to `tramp-file-name-handler'). Otherwise, it takes
4948 ;; `tramp-run-real-handler'. Using `last-input-event' is a little bit
4949 ;; risky, because completing a file might require loading other files,
4950 ;; like "~/.netrc", and for them it shouldn't be decided based on that
4951 ;; variable. On the other hand, those files shouldn't have partial
4952 ;; Tramp file name syntax. Maybe another variable should be introduced
4953 ;; overwriting this check in such cases. Or we change Tramp file name
4954 ;; syntax in order to avoid ambiguities, like in XEmacs ...
4955 (defun tramp-completion-mode-p ()
4956 "Checks whether method / user name / host name completion is active."
4958 ;; Signal from outside.
4959 tramp-completion-mode
4961 (equal last-input-event 'tab)
4962 (and (natnump last-input-event)
4964 ;; ?\t has event-modifier 'control.
4965 (equal last-input-event ?\t)
4966 (and (not (event-modifiers last-input-event))
4967 (or (equal last-input-event ?\?)
4968 (equal last-input-event ?\ )))))
4970 (and (featurep 'xemacs)
4971 ;; `last-input-event' might be nil.
4972 (not (null last-input-event))
4973 ;; `last-input-event' may have no character approximation.
4974 (funcall (symbol-function 'event-to-character) last-input-event)
4976 ;; ?\t has event-modifier 'control.
4978 (funcall (symbol-function 'event-to-character)
4979 last-input-event) ?\t)
4980 (and (not (event-modifiers last-input-event))
4982 (funcall (symbol-function 'event-to-character)
4983 last-input-event) ?\?)
4985 (funcall (symbol-function 'event-to-character)
4986 last-input-event) ?\ )))))))
4988 ;; Method, host name and user name completion.
4989 ;; `tramp-completion-dissect-file-name' returns a list of
4990 ;; tramp-file-name structures. For all of them we return possible completions.
4992 (defun tramp-completion-handle-file-name-all-completions (filename directory)
4993 "Like `file-name-all-completions' for partial Tramp files."
4995 (let* ((fullname (tramp-drop-volume-letter
4996 (expand-file-name filename directory)))
4997 ;; Possible completion structures.
4998 (v (tramp-completion-dissect-file-name fullname))
5002 (let* ((car (car v))
5003 (method (tramp-file-name-method car))
5004 (user (tramp-file-name-user car))
5005 (host (tramp-file-name-host car))
5006 (localname (tramp-file-name-localname car))
5007 (m (tramp-find-method method user host))
5008 (tramp-current-user user) ; see `tramp-parse-passwd'
5011 (unless localname ;; Nothing to complete.
5015 ;; Method dependent user / host combinations.
5019 (setq all-user-hosts
5020 (append all-user-hosts
5021 (funcall (nth 0 x) (nth 1 x)))))
5022 (tramp-get-completion-function m))
5028 (tramp-get-completion-user-host
5029 method user host (nth 0 x) (nth 1 x)))
5030 (delq nil all-user-hosts)))))
5032 ;; Possible methods.
5034 (append result (tramp-get-completion-methods m)))))
5038 ;; Unify list, remove nil elements.
5040 (let ((car (car result)))
5044 (substring car (length (tramp-drop-volume-letter directory)))))
5045 (setq result (cdr result))))
5047 ;; Complete local parts.
5051 (tramp-completion-run-real-handler
5052 'file-name-all-completions (list filename directory))
5055 ;; Method, host name and user name completion for a file.
5057 (defun tramp-completion-handle-file-name-completion
5058 (filename directory &optional predicate)
5059 "Like `file-name-completion' for Tramp files."
5062 (mapcar 'list (file-name-all-completions filename directory))
5064 (lambda (x) (funcall predicate (expand-file-name (car x) directory))))))
5066 ;; I misuse a little bit the tramp-file-name structure in order to handle
5067 ;; completion possibilities for partial methods / user names / host names.
5068 ;; Return value is a list of tramp-file-name structures according to possible
5069 ;; completions. If "localname" is non-nil it means there
5070 ;; shouldn't be a completion anymore.
5072 ;; Expected results:
5074 ;; "/x" "/[x" "/x@" "/[x@" "/x@y" "/[x@y"
5075 ;; [nil nil "x" nil] [nil "x" nil nil] [nil "x" "y" nil]
5076 ;; [nil "x" nil nil]
5077 ;; ["x" nil nil nil]
5079 ;; "/x:" "/x:y" "/x:y:"
5080 ;; [nil nil "x" ""] [nil nil "x" "y"] ["x" nil "y" ""]
5082 ;; ["x" nil "" nil] ["x" nil "y" nil]
5083 ;; ["x" "" nil nil] ["x" "y" nil nil]
5085 ;; "/x:y@" "/x:y@z" "/x:y@z:"
5086 ;; [nil nil "x" "y@"] [nil nil "x" "y@z"] ["x" "y" "z" ""]
5087 ;; "/[x/y@" "/[x/y@z"
5088 ;; ["x" nil "y" nil] ["x" "y" "z" nil]
5089 (defun tramp-completion-dissect-file-name (name)
5090 "Returns a list of `tramp-file-name' structures.
5091 They are collected by `tramp-completion-dissect-file-name1'."
5095 (tramp-completion-ipv6-regexp
5098 (if (zerop (length tramp-postfix-ipv6-format))
5099 tramp-postfix-host-format
5100 tramp-postfix-ipv6-format)))
5101 ;; "/method" "/[method"
5102 (tramp-completion-file-name-structure1
5103 (list (concat tramp-prefix-regexp "\\(" tramp-method-regexp x-nil "\\)$")
5106 (tramp-completion-file-name-structure2
5107 (list (concat tramp-prefix-regexp "\\(" tramp-user-regexp x-nil "\\)$")
5110 (tramp-completion-file-name-structure3
5111 (list (concat tramp-prefix-regexp "\\(" tramp-host-regexp x-nil "\\)$")
5113 ;; "/[ipv6" "/[ipv6"
5114 (tramp-completion-file-name-structure4
5115 (list (concat tramp-prefix-regexp
5116 tramp-prefix-ipv6-regexp
5117 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
5119 ;; "/user@host" "/[user@host"
5120 (tramp-completion-file-name-structure5
5121 (list (concat tramp-prefix-regexp
5122 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
5123 "\\(" tramp-host-regexp x-nil "\\)$")
5125 ;; "/user@[ipv6" "/[user@ipv6"
5126 (tramp-completion-file-name-structure6
5127 (list (concat tramp-prefix-regexp
5128 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
5129 tramp-prefix-ipv6-regexp
5130 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
5132 ;; "/method:user" "/[method/user" "/method://user"
5133 (tramp-completion-file-name-structure7
5134 (list (concat tramp-prefix-regexp
5135 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
5136 "\\(" tramp-user-regexp x-nil "\\)$")
5138 ;; "/method:host" "/[method/host" "/method://host"
5139 (tramp-completion-file-name-structure8
5140 (list (concat tramp-prefix-regexp
5141 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
5142 "\\(" tramp-host-regexp x-nil "\\)$")
5144 ;; "/method:[ipv6" "/[method/ipv6" "/method://[ipv6"
5145 (tramp-completion-file-name-structure9
5146 (list (concat tramp-prefix-regexp
5147 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
5148 tramp-prefix-ipv6-regexp
5149 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
5151 ;; "/method:user@host" "/[method/user@host" "/method://user@host"
5152 (tramp-completion-file-name-structure10
5153 (list (concat tramp-prefix-regexp
5154 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
5155 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
5156 "\\(" tramp-host-regexp x-nil "\\)$")
5158 ;; "/method:user@[ipv6" "/[method/user@ipv6" "/method://user@[ipv6"
5159 (tramp-completion-file-name-structure11
5160 (list (concat tramp-prefix-regexp
5161 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
5162 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
5163 tramp-prefix-ipv6-regexp
5164 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
5166 ;; "/method: "/method:/"
5167 (tramp-completion-file-name-structure12
5169 (if (equal tramp-syntax 'url)
5170 (concat tramp-prefix-regexp
5171 "\\(" tramp-method-regexp "\\)"
5172 "\\(" (substring tramp-postfix-method-regexp 0 1)
5173 "\\|" (substring tramp-postfix-method-regexp 1 2) "\\)"
5175 ;; Should not match if not URL syntax.
5176 (concat tramp-prefix-regexp "/$"))
5178 ;; "/method: "/method:/"
5179 (tramp-completion-file-name-structure13
5181 (if (equal tramp-syntax 'url)
5182 (concat tramp-prefix-regexp
5183 "\\(" tramp-method-regexp "\\)"
5184 "\\(" (substring tramp-postfix-method-regexp 0 1)
5185 "\\|" (substring tramp-postfix-method-regexp 1 2) "\\)"
5187 ;; Should not match if not URL syntax.
5188 (concat tramp-prefix-regexp "/$"))
5191 (mapc (lambda (regexp)
5192 (add-to-list 'result
5193 (tramp-completion-dissect-file-name1 regexp name)))
5195 tramp-completion-file-name-structure1
5196 tramp-completion-file-name-structure2
5197 tramp-completion-file-name-structure3
5198 tramp-completion-file-name-structure4
5199 tramp-completion-file-name-structure5
5200 tramp-completion-file-name-structure6
5201 tramp-completion-file-name-structure7
5202 tramp-completion-file-name-structure8
5203 tramp-completion-file-name-structure9
5204 tramp-completion-file-name-structure10
5205 tramp-completion-file-name-structure11
5206 tramp-completion-file-name-structure12
5207 tramp-completion-file-name-structure13
5208 tramp-file-name-structure))
5212 (defun tramp-completion-dissect-file-name1 (structure name)
5213 "Returns a `tramp-file-name' structure matching STRUCTURE.
5214 The structure consists of remote method, remote user,
5215 remote host and localname (filename on remote host)."
5218 (when (string-match (nth 0 structure) name)
5219 (let ((method (and (nth 1 structure)
5220 (match-string (nth 1 structure) name)))
5221 (user (and (nth 2 structure)
5222 (match-string (nth 2 structure) name)))
5223 (host (and (nth 3 structure)
5224 (match-string (nth 3 structure) name)))
5225 (localname (and (nth 4 structure)
5226 (match-string (nth 4 structure) name))))
5227 (vector method user host localname)))))
5229 ;; This function returns all possible method completions, adding the
5230 ;; trailing method delimeter.
5231 (defun tramp-get-completion-methods (partial-method)
5232 "Returns all method completions for PARTIAL-METHOD."
5236 (string-match (concat "^" (regexp-quote partial-method)) method)
5237 (tramp-completion-make-tramp-file-name method nil nil nil)))
5238 (mapcar 'car tramp-methods)))
5240 ;; Compares partial user and host names with possible completions.
5241 (defun tramp-get-completion-user-host (method partial-user partial-host user host)
5242 "Returns the most expanded string for user and host name completion.
5243 PARTIAL-USER must match USER, PARTIAL-HOST must match HOST."
5246 ((and partial-user partial-host)
5248 (string-match (concat "^" (regexp-quote partial-host)) host)
5249 (string-equal partial-user (or user partial-user)))
5250 (setq user partial-user)
5257 (and user (string-match (concat "^" (regexp-quote partial-user)) user))
5263 (and host (string-match (concat "^" (regexp-quote partial-host)) host))
5269 (unless (zerop (+ (length user) (length host)))
5270 (tramp-completion-make-tramp-file-name method user host nil)))
5272 (defun tramp-parse-rhosts (filename)
5273 "Return a list of (user host) tuples allowed to access.
5274 Either user or host may be nil."
5275 ;; On Windows, there are problems in completion when
5276 ;; `default-directory' is remote.
5277 (let ((default-directory (tramp-compat-temporary-file-directory))
5279 (when (file-readable-p filename)
5281 (insert-file-contents filename)
5282 (goto-char (point-min))
5284 (push (tramp-parse-rhosts-group) res))))
5287 (defun tramp-parse-rhosts-group ()
5288 "Return a (user host) tuple allowed to access.
5289 Either user or host may be nil."
5293 "^\\(" tramp-host-regexp "\\)"
5294 "\\([ \t]+" "\\(" tramp-user-regexp "\\)" "\\)?")))
5295 (narrow-to-region (point) (tramp-compat-line-end-position))
5296 (when (re-search-forward regexp nil t)
5297 (setq result (append (list (match-string 3) (match-string 1)))))
5302 (defun tramp-parse-shosts (filename)
5303 "Return a list of (user host) tuples allowed to access.
5304 User is always nil."
5305 ;; On Windows, there are problems in completion when
5306 ;; `default-directory' is remote.
5307 (let ((default-directory (tramp-compat-temporary-file-directory))
5309 (when (file-readable-p filename)
5311 (insert-file-contents filename)
5312 (goto-char (point-min))
5314 (push (tramp-parse-shosts-group) res))))
5317 (defun tramp-parse-shosts-group ()
5318 "Return a (user host) tuple allowed to access.
5319 User is always nil."
5321 (regexp (concat "^\\(" tramp-host-regexp "\\)")))
5322 (narrow-to-region (point) (tramp-compat-line-end-position))
5323 (when (re-search-forward regexp nil t)
5324 (setq result (list nil (match-string 1))))
5327 (> (skip-chars-forward ",") 0)
5331 (defun tramp-parse-sconfig (filename)
5332 "Return a list of (user host) tuples allowed to access.
5333 User is always nil."
5334 ;; On Windows, there are problems in completion when
5335 ;; `default-directory' is remote.
5336 (let ((default-directory (tramp-compat-temporary-file-directory))
5338 (when (file-readable-p filename)
5340 (insert-file-contents filename)
5341 (goto-char (point-min))
5343 (push (tramp-parse-sconfig-group) res))))
5346 (defun tramp-parse-sconfig-group ()
5347 "Return a (user host) tuple allowed to access.
5348 User is always nil."
5350 (regexp (concat "^[ \t]*Host[ \t]+" "\\(" tramp-host-regexp "\\)")))
5351 (narrow-to-region (point) (tramp-compat-line-end-position))
5352 (when (re-search-forward regexp nil t)
5353 (setq result (list nil (match-string 1))))
5356 (> (skip-chars-forward ",") 0)
5360 (defun tramp-parse-shostkeys (dirname)
5361 "Return a list of (user host) tuples allowed to access.
5362 User is always nil."
5363 ;; On Windows, there are problems in completion when
5364 ;; `default-directory' is remote.
5365 (let* ((default-directory (tramp-compat-temporary-file-directory))
5366 (regexp (concat "^key_[0-9]+_\\(" tramp-host-regexp "\\)\\.pub$"))
5367 (files (when (file-directory-p dirname) (directory-files dirname)))
5370 (when (string-match regexp (car files))
5371 (push (list nil (match-string 1 (car files))) result))
5372 (setq files (cdr files)))
5375 (defun tramp-parse-sknownhosts (dirname)
5376 "Return a list of (user host) tuples allowed to access.
5377 User is always nil."
5378 ;; On Windows, there are problems in completion when
5379 ;; `default-directory' is remote.
5380 (let* ((default-directory (tramp-compat-temporary-file-directory))
5381 (regexp (concat "^\\(" tramp-host-regexp
5382 "\\)\\.ssh-\\(dss\\|rsa\\)\\.pub$"))
5383 (files (when (file-directory-p dirname) (directory-files dirname)))
5386 (when (string-match regexp (car files))
5387 (push (list nil (match-string 1 (car files))) result))
5388 (setq files (cdr files)))
5391 (defun tramp-parse-hosts (filename)
5392 "Return a list of (user host) tuples allowed to access.
5393 User is always nil."
5394 ;; On Windows, there are problems in completion when
5395 ;; `default-directory' is remote.
5396 (let ((default-directory (tramp-compat-temporary-file-directory))
5398 (when (file-readable-p filename)
5400 (insert-file-contents filename)
5401 (goto-char (point-min))
5403 (push (tramp-parse-hosts-group) res))))
5406 (defun tramp-parse-hosts-group ()
5407 "Return a (user host) tuple allowed to access.
5408 User is always nil."
5411 (concat "^\\(" tramp-ipv6-regexp "\\|" tramp-host-regexp "\\)")))
5412 (narrow-to-region (point) (tramp-compat-line-end-position))
5413 (when (re-search-forward regexp nil t)
5414 (setq result (list nil (match-string 1))))
5417 (> (skip-chars-forward " \t") 0)
5421 ;; For su-alike methods it would be desirable to return "root@localhost"
5422 ;; as default. Unfortunately, we have no information whether any user name
5423 ;; has been typed already. So we use `tramp-current-user' as indication,
5424 ;; assuming it is set in `tramp-completion-handle-file-name-all-completions'.
5425 (defun tramp-parse-passwd (filename)
5426 "Return a list of (user host) tuples allowed to access.
5427 Host is always \"localhost\"."
5428 ;; On Windows, there are problems in completion when
5429 ;; `default-directory' is remote.
5430 (let ((default-directory (tramp-compat-temporary-file-directory))
5432 (if (zerop (length tramp-current-user))
5434 (when (file-readable-p filename)
5436 (insert-file-contents filename)
5437 (goto-char (point-min))
5439 (push (tramp-parse-passwd-group) res))))
5442 (defun tramp-parse-passwd-group ()
5443 "Return a (user host) tuple allowed to access.
5444 Host is always \"localhost\"."
5446 (regexp (concat "^\\(" tramp-user-regexp "\\):")))
5447 (narrow-to-region (point) (tramp-compat-line-end-position))
5448 (when (re-search-forward regexp nil t)
5449 (setq result (list (match-string 1) "localhost")))
5454 (defun tramp-parse-netrc (filename)
5455 "Return a list of (user host) tuples allowed to access.
5457 ;; On Windows, there are problems in completion when
5458 ;; `default-directory' is remote.
5459 (let ((default-directory (tramp-compat-temporary-file-directory))
5461 (when (file-readable-p filename)
5463 (insert-file-contents filename)
5464 (goto-char (point-min))
5466 (push (tramp-parse-netrc-group) res))))
5469 (defun tramp-parse-netrc-group ()
5470 "Return a (user host) tuple allowed to access.
5475 "^[ \t]*machine[ \t]+" "\\(" tramp-host-regexp "\\)"
5476 "\\([ \t]+login[ \t]+" "\\(" tramp-user-regexp "\\)" "\\)?")))
5477 (narrow-to-region (point) (tramp-compat-line-end-position))
5478 (when (re-search-forward regexp nil t)
5479 (setq result (list (match-string 3) (match-string 1))))
5484 (defun tramp-parse-putty (registry)
5485 "Return a list of (user host) tuples allowed to access.
5486 User is always nil."
5487 ;; On Windows, there are problems in completion when
5488 ;; `default-directory' is remote.
5489 (let ((default-directory (tramp-compat-temporary-file-directory))
5492 (when (zerop (tramp-local-call-process "reg" nil t nil "query" registry))
5493 (goto-char (point-min))
5495 (push (tramp-parse-putty-group registry) res))))
5498 (defun tramp-parse-putty-group (registry)
5499 "Return a (user host) tuple allowed to access.
5500 User is always nil."
5502 (regexp (concat (regexp-quote registry) "\\\\\\(.+\\)")))
5503 (narrow-to-region (point) (tramp-compat-line-end-position))
5504 (when (re-search-forward regexp nil t)
5505 (setq result (list nil (match-string 1))))
5510 ;;; Internal Functions:
5512 (defun tramp-maybe-send-script (vec script name)
5513 "Define in remote shell function NAME implemented as SCRIPT.
5514 Only send the definition if it has not already been done."
5515 (let* ((p (tramp-get-connection-process vec))
5516 (scripts (tramp-get-connection-property p "scripts" nil)))
5517 (unless (member name scripts)
5518 (tramp-message vec 5 "Sending script `%s'..." name)
5519 ;; The script could contain a call of Perl. This is masked with `%s'.
5520 (tramp-send-command-and-check
5522 (format "%s () {\n%s\n}" name
5523 (format script (tramp-get-remote-perl vec))))
5524 (tramp-set-connection-property p "scripts" (cons name scripts))
5525 (tramp-message vec 5 "Sending script `%s'...done." name))))
5527 (defun tramp-set-auto-save ()
5528 (when (and ;; ange-ftp has its own auto-save mechanism
5529 (eq (tramp-find-foreign-file-name-handler (buffer-file-name))
5530 'tramp-sh-file-name-handler)
5532 (auto-save-mode 1)))
5533 (add-hook 'find-file-hooks 'tramp-set-auto-save t)
5534 (add-hook 'tramp-unload-hook
5536 (remove-hook 'find-file-hooks 'tramp-set-auto-save)))
5538 (defun tramp-run-test (switch filename)
5539 "Run `test' on the remote system, given a SWITCH and a FILENAME.
5540 Returns the exit code of the `test' program."
5541 (with-parsed-tramp-file-name filename nil
5542 (tramp-send-command-and-check
5546 (tramp-get-test-command v)
5548 (tramp-shell-quote-argument localname)))))
5550 (defun tramp-run-test2 (format-string file1 file2)
5551 "Run `test'-like program on the remote system, given FILE1, FILE2.
5552 FORMAT-STRING contains the program name, switches, and place holders.
5553 Returns the exit code of the `test' program. Barfs if the methods,
5554 hosts, or files, disagree."
5555 (unless (tramp-equal-remote file1 file2)
5556 (with-parsed-tramp-file-name (if (tramp-tramp-file-p file1) file1 file2) nil
5559 "tramp-run-test2 only implemented for same method, user, host")))
5560 (with-parsed-tramp-file-name file1 v1
5561 (with-parsed-tramp-file-name file1 v2
5562 (tramp-send-command-and-check
5564 (format format-string
5565 (tramp-shell-quote-argument v1-localname)
5566 (tramp-shell-quote-argument v2-localname))))))
5568 (defun tramp-buffer-name (vec)
5569 "A name for the connection buffer VEC."
5570 ;; We must use `tramp-file-name-real-host', because for gateway
5571 ;; methods the default port will be expanded later on, which would
5573 (let ((method (tramp-file-name-method vec))
5574 (user (tramp-file-name-user vec))
5575 (host (tramp-file-name-real-host vec)))
5576 (if (not (zerop (length user)))
5577 (format "*tramp/%s %s@%s*" method user host)
5578 (format "*tramp/%s %s*" method host))))
5580 (defun tramp-get-buffer (vec)
5581 "Get the connection buffer to be used for VEC."
5582 (or (get-buffer (tramp-buffer-name vec))
5583 (with-current-buffer (get-buffer-create (tramp-buffer-name vec))
5584 (setq buffer-undo-list t)
5585 (setq default-directory
5586 (tramp-make-tramp-file-name
5587 (tramp-file-name-method vec)
5588 (tramp-file-name-user vec)
5589 (tramp-file-name-host vec)
5593 (defun tramp-get-connection-buffer (vec)
5594 "Get the connection buffer to be used for VEC.
5595 In case a second asynchronous communication has been started, it is different
5596 from `tramp-get-buffer'."
5597 (or (tramp-get-connection-property vec "process-buffer" nil)
5598 (tramp-get-buffer vec)))
5600 (defun tramp-get-connection-process (vec)
5601 "Get the connection process to be used for VEC.
5602 In case a second asynchronous communication has been started, it is different
5603 from the default one."
5605 (or (tramp-get-connection-property vec "process-name" nil)
5606 (tramp-buffer-name vec))))
5608 (defun tramp-debug-buffer-name (vec)
5609 "A name for the debug buffer for VEC."
5610 ;; We must use `tramp-file-name-real-host', because for gateway
5611 ;; methods the default port will be expanded later on, which would
5613 (let ((method (tramp-file-name-method vec))
5614 (user (tramp-file-name-user vec))
5615 (host (tramp-file-name-real-host vec)))
5616 (if (not (zerop (length user)))
5617 (format "*debug tramp/%s %s@%s*" method user host)
5618 (format "*debug tramp/%s %s*" method host))))
5620 (defun tramp-get-debug-buffer (vec)
5621 "Get the debug buffer for VEC."
5622 (with-current-buffer
5623 (get-buffer-create (tramp-debug-buffer-name vec))
5625 (setq buffer-undo-list t)
5626 ;; Activate outline-mode. This runs `text-mode-hook' and
5627 ;; `outline-mode-hook'. We must prevent that local processes
5628 ;; die. Yes: I've seen `flyspell-mode', which starts "ispell"
5630 (let ((default-directory (tramp-compat-temporary-file-directory)))
5632 (set (make-local-variable 'outline-regexp)
5633 "[0-9]+:[0-9]+:[0-9]+\\.[0-9]+ [a-z0-9-]+ (\\([0-9]+\\)) #")
5634 ; (set (make-local-variable 'outline-regexp)
5635 ; "[a-z.-]+:[0-9]+: [a-z0-9-]+ (\\([0-9]+\\)) #")
5636 (set (make-local-variable 'outline-level) 'tramp-outline-level))
5639 (defun tramp-outline-level ()
5640 "Return the depth to which a statement is nested in the outline.
5641 Point must be at the beginning of a header line.
5643 The outline level is equal to the verbosity of the Tramp message."
5644 (1+ (string-to-number (match-string 1))))
5646 (defun tramp-find-executable
5647 (vec progname dirlist &optional ignore-tilde ignore-path)
5648 "Searches for PROGNAME in $PATH and all directories mentioned in DIRLIST.
5649 First arg VEC specifies the connection, PROGNAME is the program
5650 to search for, and DIRLIST gives the list of directories to
5651 search. If IGNORE-TILDE is non-nil, directory names starting
5652 with `~' will be ignored. If IGNORE-PATH is non-nil, searches
5655 Returns the absolute file name of PROGNAME, if found, and nil otherwise.
5657 This function expects to be in the right *tramp* buffer."
5658 (with-current-buffer (tramp-get-buffer vec)
5660 ;; Check whether the executable is in $PATH. "which(1)" does not
5661 ;; report always a correct error code; therefore we check the
5662 ;; number of words it returns.
5664 (tramp-send-command vec (format "which \\%s | wc -w" progname))
5665 (goto-char (point-min))
5666 (if (looking-at "^1$")
5667 (setq result (concat "\\" progname))))
5670 ;; Remove all ~/foo directories from dirlist. In Emacs 20,
5671 ;; `remove' is in CL, and we want to avoid CL dependencies.
5674 (setq d (car dirlist))
5675 (setq dirlist (cdr dirlist))
5676 (unless (char-equal ?~ (aref d 0))
5677 (setq newdl (cons d newdl))))
5678 (setq dirlist (nreverse newdl))))
5681 (format (concat "while read d; "
5682 "do if test -x $d/%s -a -f $d/%s; "
5683 "then echo tramp_executable $d/%s; "
5684 "break; fi; done <<'EOF'\n"
5686 progname progname progname (mapconcat 'identity dirlist "\n")))
5687 (goto-char (point-max))
5688 (when (search-backward "tramp_executable " nil t)
5689 (skip-chars-forward "^ ")
5690 (skip-chars-forward " ")
5691 (setq result (buffer-substring
5692 (point) (tramp-compat-line-end-position)))))
5695 (defun tramp-set-remote-path (vec)
5696 "Sets the remote environment PATH to existing directories.
5697 I.e., for each directory in `tramp-remote-path', it is tested
5698 whether it exists and if so, it is added to the environment
5700 (tramp-message vec 5 (format "Setting $PATH environment variable"))
5702 vec (format "PATH=%s; export PATH"
5703 (mapconcat 'identity (tramp-get-remote-path vec) ":"))))
5705 ;; ------------------------------------------------------------
5706 ;; -- Communication with external shell --
5707 ;; ------------------------------------------------------------
5709 (defun tramp-find-file-exists-command (vec)
5710 "Find a command on the remote host for checking if a file exists.
5711 Here, we are looking for a command which has zero exit status if the
5712 file exists and nonzero exit status otherwise."
5713 (let ((existing "/")
5715 (tramp-shell-quote-argument "/ this file does not exist "))
5717 ;; The algorithm is as follows: we try a list of several commands.
5718 ;; For each command, we first run `$cmd /' -- this should return
5719 ;; true, as the root directory always exists. And then we run
5720 ;; `$cmd /this\ file\ does\ not\ exist ', hoping that the file indeed
5721 ;; does not exist. This should return false. We use the first
5722 ;; command we find that seems to work.
5723 ;; The list of commands to try is as follows:
5724 ;; `ls -d' This works on most systems, but NetBSD 1.4
5725 ;; has a bug: `ls' always returns zero exit
5726 ;; status, even for files which don't exist.
5727 ;; `test -e' Some Bourne shells have a `test' builtin
5728 ;; which does not know the `-e' option.
5729 ;; `/bin/test -e' For those, the `test' binary on disk normally
5730 ;; provides the option. Alas, the binary
5731 ;; is sometimes `/bin/test' and sometimes it's
5733 ;; `/usr/bin/test -e' In case `/bin/test' does not exist.
5735 (and (setq result (format "%s -e" (tramp-get-test-command vec)))
5736 (zerop (tramp-send-command-and-check
5737 vec (format "%s %s" result existing)))
5738 (not (zerop (tramp-send-command-and-check
5739 vec (format "%s %s" result nonexisting)))))
5740 (and (setq result "/bin/test -e")
5741 (zerop (tramp-send-command-and-check
5742 vec (format "%s %s" result existing)))
5743 (not (zerop (tramp-send-command-and-check
5744 vec (format "%s %s" result nonexisting)))))
5745 (and (setq result "/usr/bin/test -e")
5746 (zerop (tramp-send-command-and-check
5747 vec (format "%s %s" result existing)))
5748 (not (zerop (tramp-send-command-and-check
5749 vec (format "%s %s" result nonexisting)))))
5750 (and (setq result (format "%s -d" (tramp-get-ls-command vec)))
5751 (zerop (tramp-send-command-and-check
5752 vec (format "%s %s" result existing)))
5753 (not (zerop (tramp-send-command-and-check
5754 vec (format "%s %s" result nonexisting))))))
5756 vec 'file-error "Couldn't find command to check if file exists"))
5759 ;; CCC test ksh or bash found for tilde expansion?
5760 (defun tramp-find-shell (vec)
5761 "Opens a shell on the remote host which groks tilde expansion."
5762 (unless (tramp-get-connection-property vec "remote-shell" nil)
5764 (with-current-buffer (tramp-get-buffer vec)
5765 (tramp-send-command vec "echo ~root" t)
5767 ((string-match "^~root$" (buffer-string))
5769 (or (tramp-find-executable
5770 vec "bash" (tramp-get-remote-path vec) t)
5771 (tramp-find-executable
5772 vec "ksh" (tramp-get-remote-path vec) t)))
5776 "Couldn't find a shell which groks tilde expansion"))
5777 ;; Find arguments for this shell.
5778 (let ((alist tramp-sh-extra-args)
5780 (while (and alist (null extra-args))
5781 (setq item (pop alist))
5782 (when (string-match (car item) shell)
5783 (setq extra-args (cdr item))))
5784 (when extra-args (setq shell (concat shell " " extra-args))))
5786 vec 5 "Starting remote shell `%s' for tilde expansion..." shell)
5787 (let ((tramp-end-of-output "$ "))
5790 (format "PROMPT_COMMAND='' PS1=%s PS2='' PS3='' exec %s"
5791 (shell-quote-argument tramp-end-of-output) shell)
5794 (tramp-message vec 5 "Setting remote shell prompt...")
5796 vec (format "PS1=%s" (shell-quote-argument tramp-end-of-output)) t)
5797 (tramp-send-command vec "PS2=''" t)
5798 (tramp-send-command vec "PS3=''" t)
5799 (tramp-send-command vec "PROMPT_COMMAND=''" t)
5800 (tramp-message vec 5 "Setting remote shell prompt...done"))
5803 vec 5 "Remote `%s' groks tilde expansion, good"
5804 (tramp-get-method-parameter
5805 (tramp-file-name-method vec) 'tramp-remote-sh))
5806 (tramp-set-connection-property
5808 (tramp-get-method-parameter
5809 (tramp-file-name-method vec) 'tramp-remote-sh))))))))
5811 ;; ------------------------------------------------------------
5812 ;; -- Functions for establishing connection --
5813 ;; ------------------------------------------------------------
5815 ;; The following functions are actions to be taken when seeing certain
5816 ;; prompts from the remote host. See the variable
5817 ;; `tramp-actions-before-shell' for usage of these functions.
5819 (defun tramp-action-login (proc vec)
5820 "Send the login name."
5821 (when (not (stringp tramp-current-user))
5822 (save-window-excursion
5823 (let ((enable-recursive-minibuffers t))
5824 (pop-to-buffer (tramp-get-connection-buffer vec))
5825 (setq tramp-current-user (read-string (match-string 0))))))
5826 (tramp-message vec 3 "Sending login name `%s'" tramp-current-user)
5827 (with-current-buffer (tramp-get-connection-buffer vec)
5828 (tramp-message vec 6 "\n%s" (buffer-string)))
5829 (tramp-send-string vec tramp-current-user))
5831 (defun tramp-action-password (proc vec)
5832 "Query the user for a password."
5833 (with-current-buffer (process-buffer proc)
5834 (tramp-check-for-regexp proc tramp-password-prompt-regexp)
5835 (tramp-message vec 3 "Sending %s" (match-string 1)))
5836 (tramp-enter-password proc))
5838 (defun tramp-action-succeed (proc vec)
5839 "Signal success in finding shell prompt."
5840 (throw 'tramp-action 'ok))
5842 (defun tramp-action-permission-denied (proc vec)
5843 "Signal permission denied."
5845 (throw 'tramp-action 'permission-denied))
5847 (defun tramp-action-yesno (proc vec)
5848 "Ask the user for confirmation using `yes-or-no-p'.
5849 Send \"yes\" to remote process on confirmation, abort otherwise.
5850 See also `tramp-action-yn'."
5851 (save-window-excursion
5852 (let ((enable-recursive-minibuffers t))
5853 (save-match-data (pop-to-buffer (tramp-get-connection-buffer vec)))
5854 (unless (yes-or-no-p (match-string 0))
5856 (throw 'tramp-action 'permission-denied))
5857 (with-current-buffer (tramp-get-connection-buffer vec)
5858 (tramp-message vec 6 "\n%s" (buffer-string)))
5859 (tramp-send-string vec "yes"))))
5861 (defun tramp-action-yn (proc vec)
5862 "Ask the user for confirmation using `y-or-n-p'.
5863 Send \"y\" to remote process on confirmation, abort otherwise.
5864 See also `tramp-action-yesno'."
5865 (save-window-excursion
5866 (let ((enable-recursive-minibuffers t))
5867 (save-match-data (pop-to-buffer (tramp-get-connection-buffer vec)))
5868 (unless (y-or-n-p (match-string 0))
5870 (throw 'tramp-action 'permission-denied))
5871 (with-current-buffer (tramp-get-connection-buffer vec)
5872 (tramp-message vec 6 "\n%s" (buffer-string)))
5873 (tramp-send-string vec "y"))))
5875 (defun tramp-action-terminal (proc vec)
5876 "Tell the remote host which terminal type to use.
5877 The terminal type can be configured with `tramp-terminal-type'."
5878 (tramp-message vec 5 "Setting `%s' as terminal type." tramp-terminal-type)
5879 (with-current-buffer (tramp-get-connection-buffer vec)
5880 (tramp-message vec 6 "\n%s" (buffer-string)))
5881 (tramp-send-string vec tramp-terminal-type))
5883 (defun tramp-action-process-alive (proc vec)
5884 "Check whether a process has finished."
5885 (unless (memq (process-status proc) '(run open))
5886 (throw 'tramp-action 'process-died)))
5888 (defun tramp-action-out-of-band (proc vec)
5889 "Check whether an out-of-band copy has finished."
5890 (cond ((and (memq (process-status proc) '(stop exit))
5891 (zerop (process-exit-status proc)))
5892 (tramp-message vec 3 "Process has finished.")
5893 (throw 'tramp-action 'ok))
5894 ((or (and (memq (process-status proc) '(stop exit))
5895 (not (zerop (process-exit-status proc))))
5896 (memq (process-status proc) '(signal)))
5897 ;; `scp' could have copied correctly, but set modes could have failed.
5898 ;; This can be ignored.
5899 (with-current-buffer (process-buffer proc)
5900 (goto-char (point-min))
5901 (if (re-search-forward tramp-operation-not-permitted-regexp nil t)
5903 (tramp-message vec 5 "'set mode' error ignored.")
5904 (tramp-message vec 3 "Process has finished.")
5905 (throw 'tramp-action 'ok))
5906 (tramp-message vec 3 "Process has died.")
5907 (throw 'tramp-action 'process-died))))
5910 ;; Functions for processing the actions.
5912 (defun tramp-process-one-action (proc vec actions)
5913 "Wait for output from the shell and perform one action."
5914 (let (found todo item pattern action)
5916 ;; Reread output once all actions have been performed.
5917 ;; Obviously, the output was not complete.
5918 (tramp-accept-process-output proc 1)
5921 (setq item (pop todo))
5922 (setq pattern (format "\\(%s\\)\\'" (symbol-value (nth 0 item))))
5923 (setq action (nth 1 item))
5925 vec 5 "Looking for regexp \"%s\" from remote shell" pattern)
5926 (when (tramp-check-for-regexp proc pattern)
5927 (tramp-message vec 5 "Call `%s'" (symbol-name action))
5928 (setq found (funcall action proc vec)))))
5931 (defun tramp-process-actions (proc vec actions &optional timeout)
5932 "Perform actions until success or TIMEOUT."
5933 ;; Enable auth-sorce and password-cache.
5934 (tramp-set-connection-property proc "first-password-request" t)
5937 (tramp-message proc 3 "Waiting for prompts from remote shell")
5939 (catch 'tramp-action
5941 (with-timeout (timeout)
5942 (tramp-process-one-action proc vec actions))
5943 (tramp-process-one-action proc vec actions)))))
5944 (with-current-buffer (tramp-get-connection-buffer vec)
5945 (tramp-message vec 6 "\n%s" (buffer-string)))
5946 (unless (eq exit 'ok)
5947 (tramp-clear-passwd vec)
5948 (tramp-error-with-buffer
5951 ((eq exit 'permission-denied) "Permission denied")
5952 ((eq exit 'process-died) "Process died")
5953 (t "Login failed"))))))
5955 ;; Utility functions.
5957 (defun tramp-accept-process-output (&optional proc timeout timeout-msecs)
5958 "Like `accept-process-output' for Tramp processes.
5959 This is needed in order to hide `last-coding-system-used', which is set
5960 for process communication also."
5961 (with-current-buffer (process-buffer proc)
5962 (tramp-message proc 10 "%s %s" proc (process-status proc))
5963 (let (buffer-read-only last-coding-system-used)
5964 ;; Under Windows XP, accept-process-output doesn't return
5965 ;; sometimes. So we add an additional timeout.
5966 (with-timeout ((or timeout 1))
5967 (accept-process-output proc timeout timeout-msecs)))
5968 (tramp-message proc 10 "\n%s" (buffer-string))))
5970 (defun tramp-check-for-regexp (proc regexp)
5971 "Check whether REGEXP is contained in process buffer of PROC.
5972 Erase echoed commands if exists."
5973 (with-current-buffer (process-buffer proc)
5974 (goto-char (point-min))
5976 ;; Check whether we need to remove echo output.
5977 (when (and (tramp-get-connection-property proc "check-remote-echo" nil)
5978 (re-search-forward tramp-echoed-echo-mark-regexp nil t))
5979 (let ((begin (match-beginning 0)))
5980 (when (re-search-forward tramp-echoed-echo-mark-regexp nil t)
5981 ;; Discard echo from remote output.
5982 (tramp-set-connection-property proc "check-remote-echo" nil)
5983 (tramp-message proc 5 "echo-mark found")
5985 (delete-region begin (point))
5986 (goto-char (point-min)))))
5988 (when (not (tramp-get-connection-property proc "check-remote-echo" nil))
5989 ;; No echo to be handled, now we can look for the regexp.
5990 (goto-char (point-min))
5991 (re-search-forward regexp nil t))))
5993 (defun tramp-wait-for-regexp (proc timeout regexp)
5994 "Wait for a REGEXP to appear from process PROC within TIMEOUT seconds.
5995 Expects the output of PROC to be sent to the current buffer. Returns
5996 the string that matched, or nil. Waits indefinitely if TIMEOUT is
5998 (with-current-buffer (process-buffer proc)
5999 (let ((found (tramp-check-for-regexp proc regexp))
6000 (start-time (current-time)))
6002 ;; Work around a bug in XEmacs 21, where the timeout
6003 ;; expires faster than it should. This degenerates
6004 ;; to polling for buggy XEmacsen, but oh, well.
6005 (while (and (not found)
6006 (< (tramp-time-diff (current-time) start-time)
6008 (with-timeout (timeout)
6010 (tramp-accept-process-output proc 1)
6011 (unless (memq (process-status proc) '(run open))
6012 (tramp-error-with-buffer
6013 nil proc 'file-error "Process has died"))
6014 (setq found (tramp-check-for-regexp proc regexp))))))
6017 (tramp-accept-process-output proc 1)
6018 (unless (memq (process-status proc) '(run open))
6019 (tramp-error-with-buffer
6020 nil proc 'file-error "Process has died"))
6021 (setq found (tramp-check-for-regexp proc regexp)))))
6022 (tramp-message proc 6 "\n%s" (buffer-string))
6026 proc 'file-error "[[Regexp `%s' not found in %d secs]]"
6028 (tramp-error proc 'file-error "[[Regexp `%s' not found]]" regexp)))
6031 (defun tramp-barf-if-no-shell-prompt (proc timeout &rest error-args)
6032 "Wait for shell prompt and barf if none appears.
6033 Looks at process PROC to see if a shell prompt appears in TIMEOUT
6034 seconds. If not, it produces an error message with the given ERROR-ARGS."
6036 (tramp-wait-for-regexp
6039 "\\(%s\\|%s\\)\\'" shell-prompt-pattern tramp-shell-prompt-pattern))
6040 (apply 'tramp-error-with-buffer nil proc 'file-error error-args)))
6042 ;; We don't call `tramp-send-string' in order to hide the password
6043 ;; from the debug buffer, and because end-of-line handling of the
6045 (defun tramp-enter-password (proc)
6046 "Prompt for a password and send it to the remote end."
6047 (process-send-string
6048 proc (concat (tramp-read-passwd proc)
6049 (or (tramp-get-method-parameter
6050 tramp-current-method
6051 'tramp-password-end-of-line)
6052 tramp-default-password-end-of-line))))
6054 (defun tramp-open-connection-setup-interactive-shell (proc vec)
6055 "Set up an interactive shell.
6056 Mainly sets the prompt and the echo correctly. PROC is the shell
6057 process to set up. VEC specifies the connection."
6058 (let ((tramp-end-of-output "$ "))
6059 ;; It is useful to set the prompt in the following command because
6060 ;; some people have a setting for $PS1 which /bin/sh doesn't know
6061 ;; about and thus /bin/sh will display a strange prompt. For
6062 ;; example, if $PS1 has "${CWD}" in the value, then ksh will
6063 ;; display the current working directory but /bin/sh will display
6064 ;; a dollar sign. The following command line sets $PS1 to a sane
6065 ;; value, and works under Bourne-ish shells as well as csh-like
6066 ;; shells. Daniel Pittman reports that the unusual positioning of
6067 ;; the single quotes makes it work under `rc', too. We also unset
6068 ;; the variable $ENV because that is read by some sh
6069 ;; implementations (eg, bash when called as sh) on startup; this
6070 ;; way, we avoid the startup file clobbering $PS1. $PROMP_COMMAND
6071 ;; is another way to set the prompt in /bin/bash, it must be
6072 ;; discarded as well.
6076 "exec env ENV='' PROMPT_COMMAND='' PS1=%s PS2='' PS3='' %s"
6077 (shell-quote-argument tramp-end-of-output)
6078 (tramp-get-method-parameter
6079 (tramp-file-name-method vec) 'tramp-remote-sh))
6083 (tramp-message vec 5 "Setting up remote shell environment")
6084 (tramp-send-command vec "stty -inlcr -echo kill '^U' erase '^H'" t)
6085 ;; Check whether the echo has really been disabled. Some
6086 ;; implementations, like busybox of embedded GNU/Linux, don't
6087 ;; support disabling.
6088 (tramp-send-command vec "echo foo" t)
6089 (with-current-buffer (process-buffer proc)
6090 (goto-char (point-min))
6091 (when (looking-at "echo foo")
6092 (tramp-set-connection-property proc "remote-echo" t)
6093 (tramp-message vec 5 "Remote echo still on. Ok.")
6094 ;; Make sure backspaces and their echo are enabled and no line
6095 ;; width magic interferes with them.
6096 (tramp-send-command vec "stty icanon erase ^H cols 32767" t))))
6098 (tramp-message vec 5 "Setting shell prompt")
6100 vec (format "PS1=%s" (shell-quote-argument tramp-end-of-output)) t)
6101 (tramp-send-command vec "PS2=''" t)
6102 (tramp-send-command vec "PS3=''" t)
6103 (tramp-send-command vec "PROMPT_COMMAND=''" t)
6105 ;; Try to set up the coding system correctly.
6106 ;; CCC this can't be the right way to do it. Hm.
6107 (tramp-message vec 5 "Determining coding system")
6108 (tramp-send-command vec "echo foo ; echo bar" t)
6109 (with-current-buffer (process-buffer proc)
6110 (goto-char (point-min))
6111 (if (featurep 'mule)
6112 ;; Use MULE to select the right EOL convention for communicating
6113 ;; with the process.
6114 (let* ((cs (or (funcall (symbol-function 'process-coding-system) proc)
6115 (cons 'undecided 'undecided)))
6116 cs-decode cs-encode)
6117 (when (symbolp cs) (setq cs (cons cs cs)))
6118 (setq cs-decode (car cs))
6119 (setq cs-encode (cdr cs))
6120 (unless cs-decode (setq cs-decode 'undecided))
6121 (unless cs-encode (setq cs-encode 'undecided))
6122 (setq cs-encode (tramp-coding-system-change-eol-conversion
6124 (when (search-forward "\r" nil t)
6125 (setq cs-decode (tramp-coding-system-change-eol-conversion
6127 (funcall (symbol-function 'set-buffer-process-coding-system)
6128 cs-decode cs-encode)
6130 vec 5 "Setting coding system to `%s' and `%s'" cs-decode cs-encode))
6131 ;; Look for ^M and do something useful if found.
6132 (when (search-forward "\r" nil t)
6133 ;; We have found a ^M but cannot frob the process coding system
6134 ;; because we're running on a non-MULE Emacs. Let's try
6136 (tramp-send-command vec "stty -onlcr" t))))
6137 (tramp-send-command vec "set +o vi +o emacs" t)
6139 ;; Check whether the output of "uname -sr" has been changed. If
6140 ;; yes, this is a strong indication that we must expire all
6141 ;; connection properties. We start again with
6142 ;; `tramp-maybe-open-connection', it will be catched there.
6143 (tramp-message vec 5 "Checking system information")
6144 (let ((old-uname (tramp-get-connection-property vec "uname" nil))
6146 (tramp-set-connection-property
6148 (tramp-send-command-and-read vec "echo \\\"`uname -sr`\\\""))))
6149 (when (and (stringp old-uname) (not (string-equal old-uname new-uname)))
6150 (with-current-buffer (tramp-get-debug-buffer vec)
6151 ;; Keep the debug buffer
6153 (generate-new-buffer-name tramp-temp-buffer-name) 'unique)
6154 (funcall (symbol-function 'tramp-cleanup-connection) vec)
6155 (if (= (point-min) (point-max))
6157 (rename-buffer (tramp-debug-buffer-name vec) 'unique))
6158 ;; We call `tramp-get-buffer' in order to keep the debug buffer.
6159 (tramp-get-buffer vec)
6162 "Connection reset, because remote host changed from `%s' to `%s'"
6163 old-uname new-uname)
6164 (throw 'uname-changed (tramp-maybe-open-connection vec)))))
6166 ;; Check whether the remote host suffers from buggy
6167 ;; `send-process-string'. This is known for FreeBSD (see comment in
6168 ;; `send_process', file process.c). I've tested sending 624 bytes
6169 ;; successfully, sending 625 bytes failed. Emacs makes a hack when
6170 ;; this host type is detected locally. It cannot handle remote
6172 (with-connection-property proc "chunksize"
6174 ((and (integerp tramp-chunksize) (> tramp-chunksize 0))
6178 vec 5 "Checking remote host type for `send-process-string' bug")
6180 "^FreeBSD" (tramp-get-connection-property vec "uname" ""))
6183 ;; Set remote PATH variable.
6184 (tramp-set-remote-path vec)
6186 ;; Search for a good shell before searching for a command which
6187 ;; checks if a file exists. This is done because Tramp wants to use
6188 ;; "test foo; echo $?" to check if various conditions hold, and
6189 ;; there are buggy /bin/sh implementations which don't execute the
6190 ;; "echo $?" part if the "test" part has an error. In particular,
6191 ;; the Solaris /bin/sh is a problem. I'm betting that all systems
6192 ;; with buggy /bin/sh implementations will have a working bash or
6194 (tramp-find-shell vec)
6196 ;; Disable unexpected output.
6197 (tramp-send-command vec "mesg n; biff n" t)
6199 ;; Set the environment.
6200 (tramp-message vec 5 "Setting default environment")
6202 ;; On OpenSolaris, there is a bug when HISTFILE is changed in place
6203 ;; <http://bugs.opensolaris.org/view_bug.do?bug_id=6834184>. We
6204 ;; apply the workaround.
6205 (if (string-equal (tramp-get-connection-property vec "uname" "") "SunOS 5.11")
6206 (tramp-send-command vec "unset HISTFILE"))
6208 (let ((env (copy-sequence tramp-remote-process-environment))
6211 (setq item (tramp-compat-split-string (car env) "="))
6212 (if (and (stringp (cadr item)) (not (string-equal (cadr item) "")))
6214 vec (format "%s=%s; export %s" (car item) (cadr item) (car item)) t)
6215 (push (car item) unset))
6216 (setq env (cdr env)))
6219 vec (format "unset %s" (mapconcat 'identity unset " "))))) t)
6221 ;; CCC: We should either implement a Perl version of base64 encoding
6222 ;; and decoding. Then we just use that in the last item. The other
6223 ;; alternative is to use the Perl version of UU encoding. But then
6224 ;; we need a Lisp version of uuencode.
6226 ;; Old text from documentation of tramp-methods:
6227 ;; Using a uuencode/uudecode inline method is discouraged, please use one
6228 ;; of the base64 methods instead since base64 encoding is much more
6229 ;; reliable and the commands are more standardized between the different
6230 ;; Unix versions. But if you can't use base64 for some reason, please
6231 ;; note that the default uudecode command does not work well for some
6232 ;; Unices, in particular AIX and Irix. For AIX, you might want to use
6233 ;; the following command for uudecode:
6235 ;; sed '/^begin/d;/^[` ]$/d;/^end/d' | iconv -f uucode -t ISO8859-1
6237 ;; For Irix, no solution is known yet.
6239 (defconst tramp-local-coding-commands
6240 '((b64 base64-encode-region base64-decode-region)
6241 (uu tramp-uuencode-region uudecode-decode-region)
6243 "perl -e 'binmode STDIN; binmode STDOUT; print pack(q{u*}, join q{}, <>)'"
6244 "perl -e 'binmode STDIN; binmode STDOUT; print unpack(q{u*}, join q{}, <>)'"))
6245 "List of local coding commands for inline transfer.
6246 Each item is a list that looks like this:
6248 \(FORMAT ENCODING DECODING)
6250 FORMAT is symbol describing the encoding/decoding format. It can be
6251 `b64' for base64 encoding, `uu' for uu encoding, or `pack' for simple packing.
6253 ENCODING and DECODING can be strings, giving commands, or symbols,
6254 giving functions. If they are strings, then they can contain
6255 the \"%s\" format specifier. If that specifier is present, the input
6256 filename will be put into the command line at that spot. If the
6257 specifier is not present, the input should be read from standard
6260 If they are functions, they will be called with two arguments, start
6261 and end of region, and are expected to replace the region contents
6262 with the encoded or decoded results, respectively.")
6264 (defconst tramp-remote-coding-commands
6265 '((b64 "base64" "base64 -d")
6266 (b64 "mimencode -b" "mimencode -u -b")
6267 (b64 "mmencode -b" "mmencode -u -b")
6268 (b64 "recode data..base64" "recode base64..data")
6269 (b64 tramp-perl-encode-with-module tramp-perl-decode-with-module)
6270 (b64 tramp-perl-encode tramp-perl-decode)
6271 (uu "uuencode xxx" "uudecode -o /dev/stdout")
6272 (uu "uuencode xxx" "uudecode -o -")
6273 (uu "uuencode xxx" "uudecode -p")
6274 (uu "uuencode xxx" tramp-uudecode)
6276 "perl -e 'binmode STDIN; binmode STDOUT; print pack(q{u*}, join q{}, <>)'"
6277 "perl -e 'binmode STDIN; binmode STDOUT; print unpack(q{u*}, join q{}, <>)'"))
6278 "List of remote coding commands for inline transfer.
6279 Each item is a list that looks like this:
6281 \(FORMAT ENCODING DECODING)
6283 FORMAT is symbol describing the encoding/decoding format. It can be
6284 `b64' for base64 encoding, `uu' for uu encoding, or `pack' for simple packing.
6286 ENCODING and DECODING can be strings, giving commands, or symbols,
6287 giving variables. If they are strings, then they can contain
6288 the \"%s\" format specifier. If that specifier is present, the input
6289 filename will be put into the command line at that spot. If the
6290 specifier is not present, the input should be read from standard
6293 If they are variables, this variable is a string containing a Perl
6294 implementation for this functionality. This Perl program will be transferred
6295 to the remote host, and it is avalible as shell function with the same name.")
6297 (defun tramp-find-inline-encoding (vec)
6298 "Find an inline transfer encoding that works.
6299 Goes through the list `tramp-local-coding-commands' and
6300 `tramp-remote-coding-commands'."
6302 (let ((local-commands tramp-local-coding-commands)
6304 loc-enc loc-dec rem-enc rem-dec litem ritem found)
6305 (while (and local-commands (not found))
6306 (setq litem (pop local-commands))
6307 (catch 'wont-work-local
6308 (let ((format (nth 0 litem))
6309 (remote-commands tramp-remote-coding-commands))
6310 (setq loc-enc (nth 1 litem))
6311 (setq loc-dec (nth 2 litem))
6312 ;; If the local encoder or decoder is a string, the
6313 ;; corresponding command has to work locally.
6314 (if (not (stringp loc-enc))
6316 vec 5 "Checking local encoding function `%s'" loc-enc)
6318 vec 5 "Checking local encoding command `%s' for sanity" loc-enc)
6319 (unless (zerop (tramp-call-local-coding-command
6321 (throw 'wont-work-local nil)))
6322 (if (not (stringp loc-dec))
6324 vec 5 "Checking local decoding function `%s'" loc-dec)
6326 vec 5 "Checking local decoding command `%s' for sanity" loc-dec)
6327 (unless (zerop (tramp-call-local-coding-command
6329 (throw 'wont-work-local nil)))
6330 ;; Search for remote coding commands with the same format
6331 (while (and remote-commands (not found))
6332 (setq ritem (pop remote-commands))
6333 (catch 'wont-work-remote
6334 (when (equal format (nth 0 ritem))
6335 (setq rem-enc (nth 1 ritem))
6336 (setq rem-dec (nth 2 ritem))
6337 ;; Check if remote encoding and decoding commands can be
6338 ;; called remotely with null input and output. This makes
6339 ;; sure there are no syntax errors and the command is really
6340 ;; found. Note that we do not redirect stdout to /dev/null,
6341 ;; for two reasons: when checking the decoding command, we
6342 ;; actually check the output it gives. And also, when
6343 ;; redirecting "mimencode" output to /dev/null, then as root
6344 ;; it might change the permissions of /dev/null!
6345 (when (not (stringp rem-enc))
6346 (let ((name (symbol-name rem-enc)))
6347 (while (string-match (regexp-quote "-") name)
6348 (setq name (replace-match "_" nil t name)))
6349 (tramp-maybe-send-script vec (symbol-value rem-enc) name)
6350 (setq rem-enc name)))
6353 "Checking remote encoding command `%s' for sanity" rem-enc)
6354 (unless (zerop (tramp-send-command-and-check
6355 vec (format "%s </dev/null" rem-enc) t))
6356 (throw 'wont-work-remote nil))
6358 (when (not (stringp rem-dec))
6359 (let ((name (symbol-name rem-dec)))
6360 (while (string-match (regexp-quote "-") name)
6361 (setq name (replace-match "_" nil t name)))
6362 (tramp-maybe-send-script vec (symbol-value rem-dec) name)
6363 (setq rem-dec name)))
6366 "Checking remote decoding command `%s' for sanity" rem-dec)
6367 (unless (zerop (tramp-send-command-and-check
6369 (format "echo %s | %s | %s"
6370 magic rem-enc rem-dec) t))
6371 (throw 'wont-work-remote nil))
6373 (with-current-buffer (tramp-get-buffer vec)
6374 (goto-char (point-min))
6375 (unless (looking-at (regexp-quote magic))
6376 (throw 'wont-work-remote nil)))
6378 ;; `rem-enc' and `rem-dec' could be a string meanwhile.
6379 (setq rem-enc (nth 1 ritem))
6380 (setq rem-dec (nth 2 ritem))
6381 (setq found t)))))))
6383 ;; Did we find something?
6385 (tramp-message vec 2 "Couldn't find an inline transfer encoding"))
6387 ;; Set connection properties.
6388 (tramp-message vec 5 "Using local encoding `%s'" loc-enc)
6389 (tramp-set-connection-property vec "local-encoding" loc-enc)
6390 (tramp-message vec 5 "Using local decoding `%s'" loc-dec)
6391 (tramp-set-connection-property vec "local-decoding" loc-dec)
6392 (tramp-message vec 5 "Using remote encoding `%s'" rem-enc)
6393 (tramp-set-connection-property vec "remote-encoding" rem-enc)
6394 (tramp-message vec 5 "Using remote decoding `%s'" rem-dec)
6395 (tramp-set-connection-property vec "remote-decoding" rem-dec))))
6397 (defun tramp-call-local-coding-command (cmd input output)
6398 "Call the local encoding or decoding command.
6399 If CMD contains \"%s\", provide input file INPUT there in command.
6400 Otherwise, INPUT is passed via standard input.
6401 INPUT can also be nil which means `/dev/null'.
6402 OUTPUT can be a string (which specifies a filename), or t (which
6403 means standard output and thus the current buffer), or nil (which
6405 (tramp-local-call-process
6406 tramp-encoding-shell
6407 (when (and input (not (string-match "%s" cmd))) input)
6408 (if (eq output t) t nil)
6410 tramp-encoding-command-switch
6412 (if (string-match "%s" cmd) (format cmd input) cmd)
6413 (if (stringp output) (concat "> " output) ""))))
6415 (defun tramp-compute-multi-hops (vec)
6416 "Expands VEC according to `tramp-default-proxies-alist'.
6417 Gateway hops are already opened."
6418 (let ((target-alist `(,vec))
6419 (choices tramp-default-proxies-alist)
6422 ;; Look for proxy hosts to be passed.
6424 (setq item (pop choices)
6425 proxy (eval (nth 2 item)))
6428 (string-match (or (eval (nth 0 item)) "")
6429 (or (tramp-file-name-host (car target-alist)) ""))
6431 (string-match (or (eval (nth 1 item)) "")
6432 (or (tramp-file-name-user (car target-alist)) "")))
6434 ;; No more hops needed.
6436 ;; Replace placeholders.
6440 `((?u . ,(or (tramp-file-name-user (car target-alist)) ""))
6441 (?h . ,(or (tramp-file-name-host (car target-alist)) "")))))
6442 (with-parsed-tramp-file-name proxy l
6444 (add-to-list 'target-alist l)
6445 ;; Start next search.
6446 (setq choices tramp-default-proxies-alist)))))
6449 (when (and (boundp 'tramp-gw-tunnel-method)
6450 (string-match (format
6452 (symbol-value 'tramp-gw-tunnel-method)
6453 (symbol-value 'tramp-gw-socks-method))
6454 (tramp-file-name-method (car target-alist))))
6455 (let ((gw (pop target-alist))
6456 (hop (pop target-alist)))
6457 ;; Is the method prepared for gateways?
6458 (unless (tramp-get-method-parameter
6459 (tramp-file-name-method hop) 'tramp-default-port)
6462 "Method `%s' is not supported for gateway access."
6463 (tramp-file-name-method hop)))
6464 ;; Add default port if needed.
6467 tramp-host-with-port-regexp (tramp-file-name-host hop))
6470 (tramp-file-name-host hop) tramp-prefix-port-format
6472 (tramp-get-method-parameter
6473 (tramp-file-name-method hop) 'tramp-default-port)))))
6474 ;; Open the gateway connection.
6478 (tramp-file-name-method hop) (tramp-file-name-user hop)
6479 (funcall (symbol-function 'tramp-gw-open-connection) vec gw hop) nil))
6480 ;; For the password prompt, we need the correct values.
6481 ;; Therefore, we must remember the gateway vector. But we
6482 ;; cannot do it as connection property, because it shouldn't
6483 ;; be persistent. And we have no started process yet either.
6484 (tramp-set-file-property (car target-alist) "" "gateway" hop)))
6486 ;; Foreign and out-of-band methods are not supported for multi-hops.
6487 (when (cdr target-alist)
6488 (setq choices target-alist)
6490 (setq item (pop choices))
6494 (tramp-get-method-parameter
6495 (tramp-file-name-method item) 'tramp-login-program))
6496 (tramp-get-method-parameter
6497 (tramp-file-name-method item) 'tramp-copy-program))
6500 "Method `%s' is not supported for multi-hops."
6501 (tramp-file-name-method item)))))
6503 ;; In case the host name is not used for the remote shell
6504 ;; command, the user could be misguided by applying a random
6506 (let* ((v (car target-alist))
6507 (method (tramp-file-name-method v))
6508 (host (tramp-file-name-host v)))
6511 ;; There are multi-hops.
6513 ;; The host name is used for the remote shell command.
6515 '("%h") (tramp-get-method-parameter method 'tramp-login-args))
6516 ;; The host is local. We cannot use `tramp-local-host-p'
6517 ;; here, because it opens a connection as well.
6518 (string-match tramp-local-host-regexp host))
6521 "Host `%s' looks like a remote host, `%s' can only use the local host"
6527 (defun tramp-maybe-open-connection (vec)
6528 "Maybe open a connection VEC.
6529 Does not do anything if a connection is already open, but re-opens the
6530 connection if a previous connection has died for some reason."
6531 (catch 'uname-changed
6532 (let ((p (tramp-get-connection-process vec))
6533 (process-environment (copy-sequence process-environment)))
6535 ;; If too much time has passed since last command was sent, look
6536 ;; whether process is still alive. If it isn't, kill it. When
6537 ;; using ssh, it can sometimes happen that the remote end has
6538 ;; hung up but the local ssh client doesn't recognize this until
6539 ;; it tries to send some data to the remote end. So that's why
6540 ;; we try to send a command from time to time, then look again
6541 ;; whether the process is really alive.
6543 (when (and (> (tramp-time-diff
6545 (tramp-get-connection-property
6546 p "last-cmd-time" '(0 0 0)))
6548 p (processp p) (memq (process-status p) '(run open)))
6549 (tramp-send-command vec "echo are you awake" t t)
6550 (unless (and (memq (process-status p) '(run open))
6551 (tramp-wait-for-output p 10))
6552 ;; The error will be catched locally.
6553 (tramp-error vec 'file-error "Awake did fail")))
6555 (tramp-flush-connection-property vec)
6556 (tramp-flush-connection-property p)
6560 ;; New connection must be opened.
6561 (unless (and p (processp p) (memq (process-status p) '(run open)))
6563 ;; We call `tramp-get-buffer' in order to get a debug buffer for
6564 ;; messages from the beginning.
6565 (tramp-get-buffer vec)
6566 (if (zerop (length (tramp-file-name-user vec)))
6568 vec 3 "Opening connection for %s using %s..."
6569 (tramp-file-name-host vec)
6570 (tramp-file-name-method vec))
6572 vec 3 "Opening connection for %s@%s using %s..."
6573 (tramp-file-name-user vec)
6574 (tramp-file-name-host vec)
6575 (tramp-file-name-method vec)))
6577 ;; Start new process.
6578 (when (and p (processp p))
6580 (setenv "TERM" tramp-terminal-type)
6581 (setenv "LC_ALL" "C")
6582 (setenv "PROMPT_COMMAND")
6584 (let* ((target-alist (tramp-compute-multi-hops vec))
6585 (process-connection-type tramp-process-connection-type)
6586 (process-adaptive-read-buffering nil)
6587 (coding-system-for-read nil)
6588 ;; This must be done in order to avoid our file name handler.
6589 (p (let ((default-directory
6590 (tramp-compat-temporary-file-directory)))
6592 (or (tramp-get-connection-property vec "process-name" nil)
6593 (tramp-buffer-name vec))
6594 (tramp-get-connection-buffer vec)
6595 tramp-encoding-shell))))
6598 vec 6 "%s" (mapconcat 'identity (process-command p) " "))
6600 ;; Check whether process is alive.
6601 (tramp-set-process-query-on-exit-flag p nil)
6602 (tramp-message vec 3 "Waiting 60s for local shell to come up...")
6603 (tramp-barf-if-no-shell-prompt
6604 p 60 "Couldn't find local shell prompt %s" tramp-encoding-shell)
6606 ;; Now do all the connections as specified.
6608 (let* ((hop (car target-alist))
6609 (l-method (tramp-file-name-method hop))
6610 (l-user (tramp-file-name-user hop))
6611 (l-host (tramp-file-name-host hop))
6614 (tramp-get-method-parameter l-method 'tramp-login-program))
6616 (tramp-get-method-parameter l-method 'tramp-login-args))
6618 (tramp-get-method-parameter l-method 'tramp-gw-args))
6619 (gw (tramp-get-file-property hop "" "gateway" nil))
6620 (g-method (and gw (tramp-file-name-method gw)))
6621 (g-user (and gw (tramp-file-name-user gw)))
6622 (g-host (and gw (tramp-file-name-host gw)))
6623 (command login-program)
6624 ;; We don't create the temporary file. In fact, it
6625 ;; is just a prefix for the ControlPath option of
6626 ;; ssh; the real temporary file has another name, and
6627 ;; it is created and protected by ssh. It is also
6628 ;; removed by ssh, when the connection is closed.
6630 (tramp-set-connection-property
6634 tramp-temp-name-prefix
6635 (tramp-compat-temporary-file-directory)))))
6638 ;; Add gateway arguments if necessary.
6639 (when (and gw gw-args)
6640 (setq login-args (append login-args gw-args)))
6642 ;; Check for port number. Until now, there's no need
6643 ;; for handling like method, user, host.
6644 (when (string-match tramp-host-with-port-regexp l-host)
6645 (setq l-port (match-string 2 l-host)
6646 l-host (match-string 1 l-host)))
6648 ;; Set variables for computing the prompt for reading
6649 ;; password. They can also be derived from a gateway.
6650 (setq tramp-current-method (or g-method l-method)
6651 tramp-current-user (or g-user l-user)
6652 tramp-current-host (or g-host l-host))
6654 ;; Replace login-args place holders.
6656 l-host (or l-host "")
6657 l-user (or l-user "")
6658 l-port (or l-port "")
6659 spec `((?h . ,l-host) (?u . ,l-user) (?p . ,l-port)
6666 (setq x (mapcar '(lambda (y) (format-spec y spec)) x))
6667 (unless (member "" x) (mapconcat 'identity x " ")))
6669 ;; Local shell could be a Windows COMSPEC. It doesn't
6670 ;; know the ";" syntax, but we must exit always for
6671 ;; `start-file-process'. "exec" does not work either.
6672 " && exit || exit"))
6674 ;; Send the command.
6675 (tramp-message vec 3 "Sending command `%s'" command)
6676 (tramp-send-command vec command t t)
6677 (tramp-process-actions p vec tramp-actions-before-shell 60)
6678 (tramp-message vec 3 "Found remote shell prompt on `%s'" l-host))
6680 (setq target-alist (cdr target-alist)))
6682 ;; Make initial shell settings.
6683 (tramp-open-connection-setup-interactive-shell p vec))))))
6685 (defun tramp-send-command (vec command &optional neveropen nooutput)
6686 "Send the COMMAND to connection VEC.
6687 Erases temporary buffer before sending the command. If optional
6688 arg NEVEROPEN is non-nil, never try to open the connection. This
6689 is meant to be used from `tramp-maybe-open-connection' only. The
6690 function waits for output unless NOOUTPUT is set."
6691 (unless neveropen (tramp-maybe-open-connection vec))
6692 (let ((p (tramp-get-connection-process vec)))
6693 (when (tramp-get-connection-property p "remote-echo" nil)
6694 ;; We mark the command string that it can be erased in the output buffer.
6695 (tramp-set-connection-property p "check-remote-echo" t)
6696 (setq command (format "%s%s%s" tramp-echo-mark command tramp-echo-mark)))
6697 (tramp-message vec 6 "%s" command)
6698 (tramp-send-string vec command)
6699 (unless nooutput (tramp-wait-for-output p))))
6701 (defun tramp-wait-for-output (proc &optional timeout)
6702 "Wait for output from remote rsh command."
6703 (with-current-buffer (process-buffer proc)
6704 (let* (;; Initially, `tramp-end-of-output' is "$ ". There might
6705 ;; be leading escape sequences, which must be ignored.
6706 (regexp (format "[^$\n]*%s\r?$" (regexp-quote tramp-end-of-output)))
6707 ;; Sometimes, the commands do not return a newline but a
6708 ;; null byte before the shell prompt, for example "git
6709 ;; ls-files -c -z ...".
6710 (regexp1 (format "\\(^\\|\000\\)%s" regexp))
6711 (found (tramp-wait-for-regexp proc timeout regexp1)))
6713 (let (buffer-read-only)
6714 (goto-char (point-max))
6715 (re-search-backward regexp nil t)
6716 (delete-region (point) (point-max)))
6720 "[[Remote prompt `%s' not found in %d secs]]"
6721 tramp-end-of-output timeout)
6724 "[[Remote prompt `%s' not found]]" tramp-end-of-output)))
6725 ;; Return value is whether end-of-output sentinel was found.
6728 (defun tramp-send-command-and-check (vec command &optional subshell)
6729 "Run COMMAND and check its exit status.
6730 Sends `echo $?' along with the COMMAND for checking the exit status. If
6731 COMMAND is nil, just sends `echo $?'. Returns the exit status found.
6733 If the optional argument SUBSHELL is non-nil, the command is executed in
6734 a subshell, ie surrounded by parentheses."
6737 (concat (if subshell "( " "")
6739 (if command " 2>/dev/null; " "")
6740 "echo tramp_exit_status $?"
6741 (if subshell " )" " ")))
6742 (with-current-buffer (tramp-get-connection-buffer vec)
6743 (goto-char (point-max))
6744 (unless (re-search-backward "tramp_exit_status [0-9]+" nil t)
6746 vec 'file-error "Couldn't find exit status of `%s'" command))
6747 (skip-chars-forward "^ ")
6749 (read (current-buffer))
6750 (let (buffer-read-only) (delete-region (match-beginning 0) (point-max))))))
6752 (defun tramp-barf-unless-okay (vec command fmt &rest args)
6753 "Run COMMAND, check exit status, throw error if exit status not okay.
6754 Similar to `tramp-send-command-and-check' but accepts two more arguments
6755 FMT and ARGS which are passed to `error'."
6756 (unless (zerop (tramp-send-command-and-check vec command))
6757 (apply 'tramp-error vec 'file-error fmt args)))
6759 (defun tramp-send-command-and-read (vec command)
6760 "Run COMMAND and return the output, which must be a Lisp expression.
6761 In case there is no valid Lisp expression, it raises an error"
6762 (tramp-barf-unless-okay vec command "`%s' returns with error" command)
6763 (with-current-buffer (tramp-get-connection-buffer vec)
6764 ;; Read the expression.
6765 (goto-char (point-min))
6767 (prog1 (read (current-buffer))
6769 (when (re-search-forward "\\S-" (tramp-compat-line-end-position) t)
6773 "`%s' does not return a valid Lisp expression: `%s'"
6774 command (buffer-string))))))
6776 ;; It seems that Tru64 Unix does not like it if long strings are sent
6777 ;; to it in one go. (This happens when sending the Perl
6778 ;; `file-attributes' implementation, for instance.) Therefore, we
6779 ;; have this function which sends the string in chunks.
6780 (defun tramp-send-string (vec string)
6781 "Send the STRING via connection VEC.
6783 The STRING is expected to use Unix line-endings, but the lines sent to
6784 the remote host use line-endings as defined in the variable
6785 `tramp-rsh-end-of-line'. The communication buffer is erased before sending."
6786 (let* ((p (tramp-get-connection-process vec))
6787 (chunksize (tramp-get-connection-property p "chunksize" nil)))
6790 vec 'file-error "Can't send string to remote host -- not logged in"))
6791 (tramp-set-connection-property p "last-cmd-time" (current-time))
6792 (tramp-message vec 10 "%s" string)
6793 (with-current-buffer (tramp-get-connection-buffer vec)
6794 ;; Clean up the buffer. We cannot call `erase-buffer' because
6795 ;; narrowing might be in effect.
6796 (let (buffer-read-only) (delete-region (point-min) (point-max)))
6797 ;; Replace "\n" by `tramp-rsh-end-of-line'.
6799 (mapconcat 'identity
6800 (tramp-compat-split-string string "\n")
6801 tramp-rsh-end-of-line))
6802 (unless (or (string= string "")
6803 (string-equal (substring string -1) tramp-rsh-end-of-line))
6804 (setq string (concat string tramp-rsh-end-of-line)))
6806 (if (and chunksize (not (zerop chunksize)))
6808 (end (length string)))
6811 vec 10 "Sending chunk from %s to %s"
6812 pos (min (+ pos chunksize) end))
6813 (process-send-string
6814 p (substring string pos (min (+ pos chunksize) end)))
6815 (setq pos (+ pos chunksize))))
6816 (process-send-string p string)))))
6818 (defun tramp-mode-string-to-int (mode-string)
6819 "Converts a ten-letter `drwxrwxrwx'-style mode string into mode bits."
6820 (let* (case-fold-search
6821 (mode-chars (string-to-vector mode-string))
6822 (owner-read (aref mode-chars 1))
6823 (owner-write (aref mode-chars 2))
6824 (owner-execute-or-setid (aref mode-chars 3))
6825 (group-read (aref mode-chars 4))
6826 (group-write (aref mode-chars 5))
6827 (group-execute-or-setid (aref mode-chars 6))
6828 (other-read (aref mode-chars 7))
6829 (other-write (aref mode-chars 8))
6830 (other-execute-or-sticky (aref mode-chars 9)))
6834 ((char-equal owner-read ?r) (tramp-octal-to-decimal "00400"))
6835 ((char-equal owner-read ?-) 0)
6836 (t (error "Second char `%c' must be one of `r-'" owner-read)))
6838 ((char-equal owner-write ?w) (tramp-octal-to-decimal "00200"))
6839 ((char-equal owner-write ?-) 0)
6840 (t (error "Third char `%c' must be one of `w-'" owner-write)))
6842 ((char-equal owner-execute-or-setid ?x)
6843 (tramp-octal-to-decimal "00100"))
6844 ((char-equal owner-execute-or-setid ?S)
6845 (tramp-octal-to-decimal "04000"))
6846 ((char-equal owner-execute-or-setid ?s)
6847 (tramp-octal-to-decimal "04100"))
6848 ((char-equal owner-execute-or-setid ?-) 0)
6849 (t (error "Fourth char `%c' must be one of `xsS-'"
6850 owner-execute-or-setid)))
6852 ((char-equal group-read ?r) (tramp-octal-to-decimal "00040"))
6853 ((char-equal group-read ?-) 0)
6854 (t (error "Fifth char `%c' must be one of `r-'" group-read)))
6856 ((char-equal group-write ?w) (tramp-octal-to-decimal "00020"))
6857 ((char-equal group-write ?-) 0)
6858 (t (error "Sixth char `%c' must be one of `w-'" group-write)))
6860 ((char-equal group-execute-or-setid ?x)
6861 (tramp-octal-to-decimal "00010"))
6862 ((char-equal group-execute-or-setid ?S)
6863 (tramp-octal-to-decimal "02000"))
6864 ((char-equal group-execute-or-setid ?s)
6865 (tramp-octal-to-decimal "02010"))
6866 ((char-equal group-execute-or-setid ?-) 0)
6867 (t (error "Seventh char `%c' must be one of `xsS-'"
6868 group-execute-or-setid)))
6870 ((char-equal other-read ?r)
6871 (tramp-octal-to-decimal "00004"))
6872 ((char-equal other-read ?-) 0)
6873 (t (error "Eighth char `%c' must be one of `r-'" other-read)))
6875 ((char-equal other-write ?w) (tramp-octal-to-decimal "00002"))
6876 ((char-equal other-write ?-) 0)
6877 (t (error "Nineth char `%c' must be one of `w-'" other-write)))
6879 ((char-equal other-execute-or-sticky ?x)
6880 (tramp-octal-to-decimal "00001"))
6881 ((char-equal other-execute-or-sticky ?T)
6882 (tramp-octal-to-decimal "01000"))
6883 ((char-equal other-execute-or-sticky ?t)
6884 (tramp-octal-to-decimal "01001"))
6885 ((char-equal other-execute-or-sticky ?-) 0)
6886 (t (error "Tenth char `%c' must be one of `xtT-'"
6887 other-execute-or-sticky)))))))
6889 (defun tramp-convert-file-attributes (vec attr)
6890 "Convert file-attributes ATTR generated by perl script, stat or ls.
6891 Convert file mode bits to string and set virtual device number.
6893 ;; Convert last access time.
6894 (unless (listp (nth 4 attr))
6895 (setcar (nthcdr 4 attr)
6896 (list (floor (nth 4 attr) 65536)
6897 (floor (mod (nth 4 attr) 65536)))))
6898 ;; Convert last modification time.
6899 (unless (listp (nth 5 attr))
6900 (setcar (nthcdr 5 attr)
6901 (list (floor (nth 5 attr) 65536)
6902 (floor (mod (nth 5 attr) 65536)))))
6903 ;; Convert last status change time.
6904 (unless (listp (nth 6 attr))
6905 (setcar (nthcdr 6 attr)
6906 (list (floor (nth 6 attr) 65536)
6907 (floor (mod (nth 6 attr) 65536)))))
6908 ;; Convert file size.
6909 (when (< (nth 7 attr) 0)
6910 (setcar (nthcdr 7 attr) -1))
6911 (when (and (floatp (nth 7 attr))
6912 (<= (nth 7 attr) (tramp-compat-most-positive-fixnum)))
6913 (setcar (nthcdr 7 attr) (round (nth 7 attr))))
6914 ;; Convert file mode bits to string.
6915 (unless (stringp (nth 8 attr))
6916 (setcar (nthcdr 8 attr) (tramp-file-mode-from-int (nth 8 attr)))
6917 (when (stringp (car attr))
6918 (aset (nth 8 attr) 0 ?l)))
6919 ;; Convert directory indication bit.
6920 (when (string-match "^d" (nth 8 attr))
6922 ;; Convert symlink from `tramp-handle-file-attributes-with-stat'.
6923 (when (consp (car attr))
6924 (if (and (stringp (caar attr))
6925 (string-match ".+ -> .\\(.+\\)." (caar attr)))
6926 (setcar attr (match-string 1 (caar attr)))
6928 ;; Set file's gid change bit.
6929 (setcar (nthcdr 9 attr)
6930 (if (numberp (nth 3 attr))
6931 (not (= (nth 3 attr)
6932 (tramp-get-remote-gid vec 'integer)))
6935 (tramp-get-remote-gid vec 'string)))))
6937 (unless (listp (nth 10 attr))
6938 (setcar (nthcdr 10 attr)
6940 (cons (floor (nth 10 attr) 65536)
6941 (floor (mod (nth 10 attr) 65536)))
6942 ;; Inodes can be incredible huge. We must hide this.
6943 (error (tramp-get-inode vec)))))
6944 ;; Set virtual device number.
6945 (setcar (nthcdr 11 attr)
6946 (tramp-get-device vec))
6949 (defun tramp-get-inode (vec)
6950 "Returns the virtual inode number.
6951 If it doesn't exist, generate a new one."
6952 (let ((string (tramp-make-tramp-file-name
6953 (tramp-file-name-method vec)
6954 (tramp-file-name-user vec)
6955 (tramp-file-name-host vec)
6957 (unless (assoc string tramp-inodes)
6958 (add-to-list 'tramp-inodes
6959 (list string (length tramp-inodes))))
6960 (nth 1 (assoc string tramp-inodes))))
6962 (defun tramp-get-device (vec)
6963 "Returns the virtual device number.
6964 If it doesn't exist, generate a new one."
6965 (let ((string (tramp-make-tramp-file-name
6966 (tramp-file-name-method vec)
6967 (tramp-file-name-user vec)
6968 (tramp-file-name-host vec)
6970 (unless (assoc string tramp-devices)
6971 (add-to-list 'tramp-devices
6972 (list string (length tramp-devices))))
6973 (cons -1 (nth 1 (assoc string tramp-devices)))))
6975 (defun tramp-file-mode-from-int (mode)
6976 "Turn an integer representing a file mode into an ls(1)-like string."
6977 (let ((type (cdr (assoc (logand (lsh mode -12) 15) tramp-file-mode-type-map)))
6978 (user (logand (lsh mode -6) 7))
6979 (group (logand (lsh mode -3) 7))
6980 (other (logand (lsh mode -0) 7))
6981 (suid (> (logand (lsh mode -9) 4) 0))
6982 (sgid (> (logand (lsh mode -9) 2) 0))
6983 (sticky (> (logand (lsh mode -9) 1) 0)))
6984 (setq user (tramp-file-mode-permissions user suid "s"))
6985 (setq group (tramp-file-mode-permissions group sgid "s"))
6986 (setq other (tramp-file-mode-permissions other sticky "t"))
6987 (concat type user group other)))
6989 (defun tramp-file-mode-permissions (perm suid suid-text)
6990 "Convert a permission bitset into a string.
6991 This is used internally by `tramp-file-mode-from-int'."
6992 (let ((r (> (logand perm 4) 0))
6993 (w (> (logand perm 2) 0))
6994 (x (> (logand perm 1) 0)))
6995 (concat (or (and r "r") "-")
6996 (or (and w "w") "-")
6997 (or (and suid x suid-text) ; suid, execute
6998 (and suid (upcase suid-text)) ; suid, !execute
6999 (and x "x") "-")))) ; !suid
7001 (defun tramp-decimal-to-octal (i)
7002 "Return a string consisting of the octal digits of I.
7003 Not actually used. Use `(format \"%o\" i)' instead?"
7004 (cond ((< i 0) (error "Cannot convert negative number to octal"))
7005 ((not (integerp i)) (error "Cannot convert non-integer to octal"))
7007 (t (concat (tramp-decimal-to-octal (/ i 8))
7008 (number-to-string (% i 8))))))
7010 ;; Kudos to Gerd Moellmann for this suggestion.
7011 (defun tramp-octal-to-decimal (ostr)
7012 "Given a string of octal digits, return a decimal number."
7013 (let ((x (or ostr "")))
7014 ;; `save-match' is in `tramp-mode-string-to-int' which calls this.
7015 (unless (string-match "\\`[0-7]*\\'" x)
7016 (error "Non-octal junk in string `%s'" x))
7017 (string-to-number ostr 8)))
7019 (defun tramp-shell-case-fold (string)
7020 "Converts STRING to shell glob pattern which ignores case."
7023 (if (equal (downcase c) (upcase c))
7025 (format "[%c%c]" (downcase c) (upcase c))))
7030 ;; ------------------------------------------------------------
7031 ;; -- Tramp file names --
7032 ;; ------------------------------------------------------------
7033 ;; Conversion functions between external representation and
7034 ;; internal data structure. Convenience functions for internal
7037 (defun tramp-file-name-p (vec)
7038 "Check whether VEC is a Tramp object."
7039 (and (vectorp vec) (= 4 (length vec))))
7041 (defun tramp-file-name-method (vec)
7042 "Return method component of VEC."
7043 (and (tramp-file-name-p vec) (aref vec 0)))
7045 (defun tramp-file-name-user (vec)
7046 "Return user component of VEC."
7047 (and (tramp-file-name-p vec) (aref vec 1)))
7049 (defun tramp-file-name-host (vec)
7050 "Return host component of VEC."
7051 (and (tramp-file-name-p vec) (aref vec 2)))
7053 (defun tramp-file-name-localname (vec)
7054 "Return localname component of VEC."
7055 (and (tramp-file-name-p vec) (aref vec 3)))
7057 ;; The user part of a Tramp file name vector can be of kind
7058 ;; "user%domain". Sometimes, we must extract these parts.
7059 (defun tramp-file-name-real-user (vec)
7060 "Return the user name of VEC without domain."
7061 (let ((user (tramp-file-name-user vec)))
7062 (if (and (stringp user)
7063 (string-match tramp-user-with-domain-regexp user))
7064 (match-string 1 user)
7067 (defun tramp-file-name-domain (vec)
7068 "Return the domain name of VEC."
7069 (let ((user (tramp-file-name-user vec)))
7071 (string-match tramp-user-with-domain-regexp user)
7072 (match-string 2 user))))
7074 ;; The host part of a Tramp file name vector can be of kind
7075 ;; "host#port". Sometimes, we must extract these parts.
7076 (defun tramp-file-name-real-host (vec)
7077 "Return the host name of VEC without port."
7078 (let ((host (tramp-file-name-host vec)))
7079 (if (and (stringp host)
7080 (string-match tramp-host-with-port-regexp host))
7081 (match-string 1 host)
7084 (defun tramp-file-name-port (vec)
7085 "Return the port number of VEC."
7086 (let ((host (tramp-file-name-host vec)))
7088 (string-match tramp-host-with-port-regexp host)
7089 (string-to-number (match-string 2 host)))))
7091 (defun tramp-tramp-file-p (name)
7092 "Return t if NAME is a Tramp file."
7094 (string-match tramp-file-name-regexp name)))
7096 (defun tramp-find-method (method user host)
7097 "Return the right method string to use.
7098 This is METHOD, if non-nil. Otherwise, do a lookup in
7099 `tramp-default-method-alist'."
7101 (let ((choices tramp-default-method-alist)
7104 (setq item (pop choices))
7105 (when (and (string-match (or (nth 0 item) "") (or host ""))
7106 (string-match (or (nth 1 item) "") (or user "")))
7107 (setq lmethod (nth 2 item))
7108 (setq choices nil)))
7110 tramp-default-method))
7112 (defun tramp-find-user (method user host)
7113 "Return the right user string to use.
7114 This is USER, if non-nil. Otherwise, do a lookup in
7115 `tramp-default-user-alist'."
7117 (let ((choices tramp-default-user-alist)
7120 (setq item (pop choices))
7121 (when (and (string-match (or (nth 0 item) "") (or method ""))
7122 (string-match (or (nth 1 item) "") (or host "")))
7123 (setq luser (nth 2 item))
7124 (setq choices nil)))
7126 tramp-default-user))
7128 (defun tramp-find-host (method user host)
7129 "Return the right host string to use.
7130 This is HOST, if non-nil. Otherwise, it is `tramp-default-host'."
7131 (or (and (> (length host) 0) host)
7132 tramp-default-host))
7134 (defun tramp-dissect-file-name (name &optional nodefault)
7135 "Return a `tramp-file-name' structure.
7136 The structure consists of remote method, remote user, remote host
7137 and localname (file name on remote host). If NODEFAULT is
7138 non-nil, the file name parts are not expanded to their default
7141 (let ((match (string-match (nth 0 tramp-file-name-structure) name)))
7142 (unless match (error "Not a Tramp file name: %s" name))
7143 (let ((method (match-string (nth 1 tramp-file-name-structure) name))
7144 (user (match-string (nth 2 tramp-file-name-structure) name))
7145 (host (match-string (nth 3 tramp-file-name-structure) name))
7146 (localname (match-string (nth 4 tramp-file-name-structure) name)))
7147 (when (member method '("multi" "multiu"))
7149 "`%s' method is no longer supported, see (info \"(tramp)Multi-hops\")"
7152 (when (string-match tramp-prefix-ipv6-regexp host)
7153 (setq host (replace-match "" nil t host)))
7154 (when (string-match tramp-postfix-ipv6-regexp host)
7155 (setq host (replace-match "" nil t host))))
7157 (vector method user host localname)
7159 (tramp-find-method method user host)
7160 (tramp-find-user method user host)
7161 (tramp-find-host method user host)
7164 (defun tramp-equal-remote (file1 file2)
7165 "Checks, whether the remote parts of FILE1 and FILE2 are identical.
7166 The check depends on method, user and host name of the files. If
7167 one of the components is missing, the default values are used.
7168 The local file name parts of FILE1 and FILE2 are not taken into
7173 (tramp-equal-remote \"/ssh::/etc\" \"/<your host name>:/home\")
7175 would yield `t'. On the other hand, the following check results in nil:
7177 (tramp-equal-remote \"/sudo::/etc\" \"/su::/etc\")"
7178 (and (stringp (file-remote-p file1))
7179 (stringp (file-remote-p file2))
7180 (string-equal (file-remote-p file1) (file-remote-p file2))))
7182 (defun tramp-make-tramp-file-name (method user host localname)
7183 "Constructs a Tramp file name from METHOD, USER, HOST and LOCALNAME."
7184 (concat tramp-prefix-format
7185 (when (not (zerop (length method)))
7186 (concat method tramp-postfix-method-format))
7187 (when (not (zerop (length user)))
7188 (concat user tramp-postfix-user-format))
7190 (if (string-match tramp-ipv6-regexp host)
7191 (concat tramp-prefix-ipv6-format host tramp-postfix-ipv6-format)
7193 tramp-postfix-host-format
7194 (when localname localname)))
7196 (defun tramp-completion-make-tramp-file-name (method user host localname)
7197 "Constructs a Tramp file name from METHOD, USER, HOST and LOCALNAME.
7198 It must not be a complete Tramp file name, but as long as there are
7199 necessary only. This function will be used in file name completion."
7200 (concat tramp-prefix-format
7201 (when (not (zerop (length method)))
7202 (concat method tramp-postfix-method-format))
7203 (when (not (zerop (length user)))
7204 (concat user tramp-postfix-user-format))
7205 (when (not (zerop (length host)))
7207 (if (string-match tramp-ipv6-regexp host)
7208 (concat tramp-prefix-ipv6-format host tramp-postfix-ipv6-format)
7210 tramp-postfix-host-format))
7211 (when localname localname)))
7213 (defun tramp-make-copy-program-file-name (vec)
7214 "Create a file name suitable to be passed to `rcp' and workalikes."
7215 (let ((user (tramp-file-name-user vec))
7216 (host (tramp-file-name-real-host vec))
7217 (localname (tramp-shell-quote-argument
7218 (tramp-file-name-localname vec))))
7219 (if (not (zerop (length user)))
7220 (format "%s@%s:%s" user host localname)
7221 (format "%s:%s" host localname))))
7223 (defun tramp-method-out-of-band-p (vec)
7224 "Return t if this is an out-of-band method, nil otherwise."
7225 (tramp-get-method-parameter (tramp-file-name-method vec) 'tramp-copy-program))
7227 (defun tramp-local-host-p (vec)
7228 "Return t if this points to the local host, nil otherwise."
7229 ;; We cannot use `tramp-file-name-real-host'. A port is an
7230 ;; indication for an ssh tunnel or alike.
7231 (let ((host (tramp-file-name-host vec)))
7234 (string-match tramp-local-host-regexp host)
7235 ;; The local temp directory must be writable for the other user.
7237 (tramp-make-tramp-file-name
7238 (tramp-file-name-method vec)
7239 (tramp-file-name-user vec)
7241 (tramp-compat-temporary-file-directory)))
7242 ;; On some systems, chown runs only for root.
7243 (or (zerop (user-uid))
7244 (zerop (tramp-get-remote-uid vec 'integer))))))
7246 ;; Variables local to connection.
7248 (defun tramp-get-remote-path (vec)
7249 (with-connection-property
7250 ;; When `tramp-own-remote-path' is in `tramp-remote-path', we
7251 ;; cache the result for the session only. Otherwise, the result
7252 ;; is cached persistently.
7253 (if (memq 'tramp-own-remote-path tramp-remote-path)
7254 (tramp-get-connection-process vec)
7257 (let* ((remote-path (tramp-compat-copy-tree tramp-remote-path))
7258 (elt1 (memq 'tramp-default-remote-path remote-path))
7259 (elt2 (memq 'tramp-own-remote-path remote-path))
7260 (default-remote-path
7263 (tramp-send-command-and-read
7264 vec "echo \\\"`getconf PATH`\\\"")
7265 ;; Default if "getconf" is not available.
7269 "`getconf PATH' not successful, using default value \"%s\"."
7275 (tramp-send-command-and-read vec "echo \\\"$PATH\\\"")
7276 ;; Default if "getconf" is not available.
7279 vec 3 "$PATH not set, ignoring `tramp-own-remote-path'.")
7282 ;; Replace place holder `tramp-default-remote-path'.
7286 (tramp-compat-split-string default-remote-path ":")
7288 (setq remote-path (delq 'tramp-default-remote-path remote-path)))
7290 ;; Replace place holder `tramp-own-remote-path'.
7294 (tramp-compat-split-string own-remote-path ":")
7296 (setq remote-path (delq 'tramp-own-remote-path remote-path)))
7298 ;; Remove double entries.
7299 (setq elt1 remote-path)
7301 (while (and (car elt1) (setq elt2 (member (car elt1) (cdr elt1))))
7303 (setq elt1 (cdr elt1)))
7305 ;; Remove non-existing directories.
7313 (tramp-make-tramp-file-name
7314 (tramp-file-name-method vec)
7315 (tramp-file-name-user vec)
7316 (tramp-file-name-host vec)
7321 (defun tramp-get-remote-tmpdir (vec)
7322 (with-connection-property vec "tmp-directory"
7323 (let ((dir (tramp-shell-quote-argument "/tmp")))
7325 (tramp-send-command-and-check
7326 vec (format "%s -d %s" (tramp-get-test-command vec) dir)))
7328 (tramp-send-command-and-check
7329 vec (format "%s -w %s" (tramp-get-test-command vec) dir))))
7331 (tramp-error vec 'file-error "Directory %s not accessible" dir)))))
7333 (defun tramp-get-ls-command (vec)
7334 (with-connection-property vec "ls"
7335 (with-current-buffer (tramp-get-buffer vec)
7336 (tramp-message vec 5 "Finding a suitable `ls' command")
7339 (dolist (cmd '("ls" "gnuls" "gls"))
7340 (let ((dl (tramp-get-remote-path vec))
7346 (tramp-find-executable vec cmd dl t t)))
7348 (when (zerop (tramp-send-command-and-check
7349 vec (format "%s -lnd /" result)))
7350 (throw 'ls-found result))
7351 (setq dl (cdr dl))))))
7352 (tramp-error vec 'file-error "Couldn't find a proper `ls' command")))))
7354 (defun tramp-get-test-command (vec)
7355 (with-connection-property vec "test"
7356 (with-current-buffer (tramp-get-buffer vec)
7357 (tramp-message vec 5 "Finding a suitable `test' command")
7358 (if (zerop (tramp-send-command-and-check vec "test 0"))
7360 (tramp-find-executable vec "test" (tramp-get-remote-path vec))))))
7362 (defun tramp-get-test-nt-command (vec)
7363 ;; Does `test A -nt B' work? Use abominable `find' construct if it
7364 ;; doesn't. BSD/OS 4.0 wants the parentheses around the command,
7365 ;; for otherwise the shell crashes.
7366 (with-connection-property vec "test-nt"
7370 vec (format "( %s / -nt / )" (tramp-get-test-command vec)))
7371 (with-current-buffer (tramp-get-buffer vec)
7372 (goto-char (point-min))
7373 (when (looking-at (regexp-quote tramp-end-of-output))
7374 (format "%s %%s -nt %%s" (tramp-get-test-command vec)))))
7379 "tramp_test_nt () {\n%s -n \"`find $1 -prune -newer $2 -print`\"\n}"
7380 (tramp-get-test-command vec)))
7381 "tramp_test_nt %s %s"))))
7383 (defun tramp-get-file-exists-command (vec)
7384 (with-connection-property vec "file-exists"
7385 (with-current-buffer (tramp-get-buffer vec)
7386 (tramp-message vec 5 "Finding command to check if file exists")
7387 (tramp-find-file-exists-command vec))))
7389 (defun tramp-get-remote-ln (vec)
7390 (with-connection-property vec "ln"
7391 (with-current-buffer (tramp-get-buffer vec)
7392 (tramp-message vec 5 "Finding a suitable `ln' command")
7393 (tramp-find-executable vec "ln" (tramp-get-remote-path vec)))))
7395 (defun tramp-get-remote-perl (vec)
7396 (with-connection-property vec "perl"
7397 (with-current-buffer (tramp-get-buffer vec)
7398 (tramp-message vec 5 "Finding a suitable `perl' command")
7399 (or (tramp-find-executable vec "perl5" (tramp-get-remote-path vec))
7400 (tramp-find-executable vec "perl" (tramp-get-remote-path vec))))))
7402 (defun tramp-get-remote-stat (vec)
7403 (with-connection-property vec "stat"
7404 (with-current-buffer (tramp-get-buffer vec)
7405 (tramp-message vec 5 "Finding a suitable `stat' command")
7406 (let ((result (tramp-find-executable
7407 vec "stat" (tramp-get-remote-path vec)))
7409 ;; Check whether stat(1) returns usable syntax. %s does not
7410 ;; work on older AIX systems.
7413 ;; We don't want to display an error message.
7414 (with-temp-message (or (current-message) "")
7416 (tramp-send-command-and-read
7417 vec (format "%s -c '(\"%%N\" %%s)' /" result))
7419 (unless (and (listp tmp) (stringp (car tmp))
7420 (string-match "^./.$" (car tmp))
7421 (integerp (cadr tmp)))
7425 (defun tramp-get-remote-id (vec)
7426 (with-connection-property vec "id"
7427 (with-current-buffer (tramp-get-buffer vec)
7428 (tramp-message vec 5 "Finding POSIX `id' command")
7431 (let ((dl (tramp-get-remote-path vec))
7437 (tramp-find-executable vec "id" dl t t)))
7438 ;; Check POSIX parameter.
7439 (when (zerop (tramp-send-command-and-check
7440 vec (format "%s -u" result)))
7441 (throw 'id-found result))
7442 (setq dl (cdr dl)))))
7443 (tramp-error vec 'file-error "Couldn't find a POSIX `id' command")))))
7445 (defun tramp-get-remote-uid (vec id-format)
7446 (with-connection-property vec (format "uid-%s" id-format)
7447 (let ((res (tramp-send-command-and-read
7449 (format "%s -u%s %s"
7450 (tramp-get-remote-id vec)
7451 (if (equal id-format 'integer) "" "n")
7452 (if (equal id-format 'integer)
7453 "" "| sed -e s/^/\\\"/ -e s/\$/\\\"/")))))
7454 ;; The command might not always return a number.
7455 (if (and (equal id-format 'integer) (not (integerp res))) -1 res))))
7457 (defun tramp-get-remote-gid (vec id-format)
7458 (with-connection-property vec (format "gid-%s" id-format)
7459 (let ((res (tramp-send-command-and-read
7461 (format "%s -g%s %s"
7462 (tramp-get-remote-id vec)
7463 (if (equal id-format 'integer) "" "n")
7464 (if (equal id-format 'integer)
7465 "" "| sed -e s/^/\\\"/ -e s/\$/\\\"/")))))
7466 ;; The command might not always return a number.
7467 (if (and (equal id-format 'integer) (not (integerp res))) -1 res))))
7469 (defun tramp-get-local-uid (id-format)
7470 (if (equal id-format 'integer) (user-uid) (user-login-name)))
7472 (defun tramp-get-local-gid (id-format)
7473 (nth 3 (tramp-compat-file-attributes "~/" id-format)))
7475 ;; Some predefined connection properties.
7476 (defun tramp-get-remote-coding (vec prop)
7477 ;; Local coding handles properties like remote coding. So we could
7478 ;; call it without pain.
7479 (let ((ret (tramp-get-local-coding vec prop)))
7480 ;; The connection property might have been cached. So we must send
7481 ;; the script - maybe.
7482 (when (and ret (symbolp ret))
7483 (let ((name (symbol-name ret)))
7484 (while (string-match (regexp-quote "-") name)
7485 (setq name (replace-match "_" nil t name)))
7486 (tramp-maybe-send-script vec (symbol-value ret) name)
7488 ;; Return the value.
7491 (defun tramp-get-local-coding (vec prop)
7493 (tramp-get-connection-property vec prop nil)
7495 (tramp-find-inline-encoding vec)
7496 (tramp-get-connection-property vec prop nil))))
7498 (defun tramp-get-method-parameter (method param)
7499 "Return the method parameter PARAM.
7500 If the `tramp-methods' entry does not exist, return NIL."
7501 (let ((entry (assoc param (assoc method tramp-methods))))
7502 (when entry (cadr entry))))
7504 ;; Auto saving to a special directory.
7506 (defun tramp-exists-file-name-handler (operation &rest args)
7507 "Checks whether OPERATION runs a file name handler."
7508 ;; The file name handler is determined on base of either an
7509 ;; argument, `buffer-file-name', or `default-directory'.
7511 (let* ((buffer-file-name "/")
7512 (default-directory "/")
7513 (fnha file-name-handler-alist)
7514 (check-file-name-operation operation)
7515 (file-name-handler-alist
7518 '(lambda (operation &rest args)
7519 "Returns OPERATION if it is the one to be checked."
7520 (if (equal check-file-name-operation operation)
7522 (let ((file-name-handler-alist fnha))
7523 (apply operation args))))))))
7524 (equal (apply operation args) operation))
7527 (unless (tramp-exists-file-name-handler 'make-auto-save-file-name)
7528 (defadvice make-auto-save-file-name
7529 (around tramp-advice-make-auto-save-file-name () activate)
7530 "Invoke `tramp-handle-make-auto-save-file-name' for Tramp files."
7531 (if (and (buffer-file-name) (tramp-tramp-file-p (buffer-file-name)))
7532 (setq ad-return-value (tramp-handle-make-auto-save-file-name))
7534 (add-hook 'tramp-unload-hook
7535 '(lambda () (ad-unadvise 'make-auto-save-file-name))))
7537 ;; In Emacs < 22 and XEmacs < 21.5 autosaved remote files have
7538 ;; permission 0666 minus umask. This is a security threat.
7540 (defun tramp-set-auto-save-file-modes ()
7541 "Set permissions of autosaved remote files to the original permissions."
7542 (let ((bfn (buffer-file-name)))
7543 (when (and (stringp bfn)
7544 (tramp-tramp-file-p bfn)
7546 (stringp buffer-auto-save-file-name)
7547 (not (equal bfn buffer-auto-save-file-name)))
7548 (unless (file-exists-p buffer-auto-save-file-name)
7549 (write-region "" nil buffer-auto-save-file-name))
7550 ;; Permissions should be set always, because there might be an old
7551 ;; auto-saved file belonging to another original file. This could
7552 ;; be a security threat.
7553 (set-file-modes buffer-auto-save-file-name
7554 (or (file-modes bfn) (tramp-octal-to-decimal "0600"))))))
7556 (unless (or (> emacs-major-version 21)
7557 (and (featurep 'xemacs)
7558 (= emacs-major-version 21)
7559 (> emacs-minor-version 4)))
7560 (add-hook 'auto-save-hook 'tramp-set-auto-save-file-modes)
7561 (add-hook 'tramp-unload-hook
7563 (remove-hook 'auto-save-hook 'tramp-set-auto-save-file-modes))))
7565 (defun tramp-subst-strs-in-string (alist string)
7566 "Replace all occurrences of the string FROM with TO in STRING.
7567 ALIST is of the form ((FROM . TO) ...)."
7570 (let* ((pr (car alist))
7573 (while (string-match (regexp-quote from) string)
7574 (setq string (replace-match to t t string)))
7575 (setq alist (cdr alist))))
7578 ;; ------------------------------------------------------------
7579 ;; -- Compatibility functions section --
7580 ;; ------------------------------------------------------------
7582 (defun tramp-read-passwd (proc &optional prompt)
7583 "Read a password from user (compat function).
7584 Consults the auth-source package.
7585 Invokes `password-read' if available, `read-passwd' else."
7586 (let* ((key (tramp-make-tramp-file-name
7587 tramp-current-method tramp-current-user
7588 tramp-current-host ""))
7591 (with-current-buffer (process-buffer proc)
7592 (tramp-check-for-regexp proc tramp-password-prompt-regexp)
7593 (format "%s for %s " (capitalize (match-string 1)) key)))))
7596 ;; See if auth-sources contains something useful, if it's bound.
7597 (and (boundp 'auth-sources)
7598 (tramp-get-connection-property proc "first-password-request" nil)
7599 ;; Try with Tramp's current method.
7600 (funcall (symbol-function 'auth-source-user-or-password)
7601 "password" tramp-current-host tramp-current-method))
7602 ;; Try the password cache.
7603 (when (functionp 'password-read)
7604 (unless (tramp-get-connection-property
7605 proc "first-password-request" nil)
7606 (funcall (symbol-function 'password-cache-remove) key))
7608 (funcall (symbol-function 'password-read) pw-prompt key)))
7609 (funcall (symbol-function 'password-cache-add) key password)
7611 ;; Else, get the password interactively.
7612 (read-passwd pw-prompt))
7613 (tramp-set-connection-property proc "first-password-request" nil))))
7615 (defun tramp-clear-passwd (vec)
7616 "Clear password cache for connection related to VEC."
7617 (when (functionp 'password-cache-remove)
7619 (symbol-function 'password-cache-remove)
7620 (tramp-make-tramp-file-name
7621 (tramp-file-name-method vec)
7622 (tramp-file-name-user vec)
7623 (tramp-file-name-host vec)
7626 ;; Snarfed code from time-date.el and parse-time.el
7628 (defconst tramp-half-a-year '(241 17024)
7629 "Evaluated by \"(days-to-time 183)\".")
7631 (defconst tramp-parse-time-months
7632 '(("jan" . 1) ("feb" . 2) ("mar" . 3)
7633 ("apr" . 4) ("may" . 5) ("jun" . 6)
7634 ("jul" . 7) ("aug" . 8) ("sep" . 9)
7635 ("oct" . 10) ("nov" . 11) ("dec" . 12))
7636 "Alist mapping month names to integers.")
7638 (defun tramp-time-less-p (t1 t2)
7639 "Say whether time value T1 is less than time value T2."
7640 (unless t1 (setq t1 '(0 0)))
7641 (unless t2 (setq t2 '(0 0)))
7642 (or (< (car t1) (car t2))
7643 (and (= (car t1) (car t2))
7644 (< (nth 1 t1) (nth 1 t2)))))
7646 (defun tramp-time-subtract (t1 t2)
7647 "Subtract two time values.
7648 Return the difference in the format of a time value."
7649 (unless t1 (setq t1 '(0 0)))
7650 (unless t2 (setq t2 '(0 0)))
7651 (let ((borrow (< (cadr t1) (cadr t2))))
7652 (list (- (car t1) (car t2) (if borrow 1 0))
7653 (- (+ (if borrow 65536 0) (cadr t1)) (cadr t2)))))
7655 (defun tramp-time-diff (t1 t2)
7656 "Return the difference between the two times, in seconds.
7657 T1 and T2 are time values (as returned by `current-time' for example)."
7658 ;; Pacify byte-compiler with `symbol-function'.
7659 (cond ((and (fboundp 'subtract-time)
7660 (fboundp 'float-time))
7661 (funcall (symbol-function 'float-time)
7662 (funcall (symbol-function 'subtract-time) t1 t2)))
7663 ((and (fboundp 'subtract-time)
7664 (fboundp 'time-to-seconds))
7665 (funcall (symbol-function 'time-to-seconds)
7666 (funcall (symbol-function 'subtract-time) t1 t2)))
7667 ((fboundp 'itimer-time-difference)
7668 (funcall (symbol-function 'itimer-time-difference)
7669 (if (< (length t1) 3) (append t1 '(0)) t1)
7670 (if (< (length t2) 3) (append t2 '(0)) t2)))
7672 (let ((time (tramp-time-subtract t1 t2)))
7673 (+ (* (car time) 65536.0)
7675 (/ (or (nth 2 time) 0) 1000000.0))))))
7677 (defun tramp-coding-system-change-eol-conversion (coding-system eol-type)
7678 "Return a coding system like CODING-SYSTEM but with given EOL-TYPE.
7679 EOL-TYPE can be one of `dos', `unix', or `mac'."
7680 (cond ((fboundp 'coding-system-change-eol-conversion)
7681 (funcall (symbol-function 'coding-system-change-eol-conversion)
7682 coding-system eol-type))
7683 ((fboundp 'subsidiary-coding-system)
7684 (funcall (symbol-function 'subsidiary-coding-system)
7686 (cond ((eq eol-type 'dos) 'crlf)
7687 ((eq eol-type 'unix) 'lf)
7688 ((eq eol-type 'mac) 'cr)
7690 (error "Unknown EOL-TYPE `%s', must be %s"
7692 "`dos', `unix', or `mac'")))))
7693 (t (error "Can't change EOL conversion -- is MULE missing?"))))
7695 (defun tramp-set-process-query-on-exit-flag (process flag)
7696 "Specify if query is needed for process when Emacs is exited.
7697 If the second argument flag is non-nil, Emacs will query the user before
7698 exiting if process is running."
7699 (if (fboundp 'set-process-query-on-exit-flag)
7700 (funcall (symbol-function 'set-process-query-on-exit-flag) process flag)
7701 (funcall (symbol-function 'process-kill-without-query) process flag)))
7704 ;; ------------------------------------------------------------
7705 ;; -- Kludges section --
7706 ;; ------------------------------------------------------------
7708 ;; Currently (as of Emacs 20.5), the function `shell-quote-argument'
7709 ;; does not deal well with newline characters. Newline is replaced by
7710 ;; backslash newline. But if, say, the string `a backslash newline b'
7711 ;; is passed to a shell, the shell will expand this into "ab",
7712 ;; completely omitting the newline. This is not what was intended.
7713 ;; It does not appear to be possible to make the function
7714 ;; `shell-quote-argument' work with newlines without making it
7715 ;; dependent on the shell used. But within this package, we know that
7716 ;; we will always use a Bourne-like shell, so we use an approach which
7719 ;; The approach is simple: we call `shell-quote-argument', then
7720 ;; massage the newline part of the result.
7722 ;; This function should produce a string which is grokked by a Unix
7723 ;; shell, even if the Emacs is running on Windows. Since this is the
7724 ;; kludges section, we bind `system-type' in such a way that
7725 ;; `shell-quote-arguments' behaves as if on Unix.
7727 ;; Thanks to Mario DeWeerd for the hint that it is sufficient for this
7728 ;; function to work with Bourne-like shells.
7730 ;; CCC: This function should be rewritten so that
7731 ;; `shell-quote-argument' is not used. This way, we are safe from
7732 ;; changes in `shell-quote-argument'.
7733 (defun tramp-shell-quote-argument (s)
7734 "Similar to `shell-quote-argument', but groks newlines.
7735 Only works for Bourne-like shells."
7736 (let ((system-type 'not-windows))
7738 (let ((result (shell-quote-argument s))
7739 (nl (regexp-quote (format "\\%s" tramp-rsh-end-of-line))))
7740 (when (and (>= (length result) 2)
7741 (string= (substring result 0 2) "\\~"))
7742 (setq result (substring result 1)))
7743 (while (string-match nl result)
7744 (setq result (replace-match (format "'%s'" tramp-rsh-end-of-line)
7748 ;; We currently (sometimes) use "[" and "]" in the filename format.
7749 ;; This means that Emacs wants to expand wildcards if
7750 ;; `find-file-wildcards' is non-nil, and then barfs because no
7751 ;; expansion could be found. We detect this situation and do
7752 ;; something really awful: we have `file-expand-wildcards' return the
7753 ;; original filename if it can't expand anything. Let's just hope
7754 ;; that this doesn't break anything else.
7755 ;; CCC: This check is now also really awful; we should search all
7756 ;; of the filename format, not just the prefix.
7757 (when (string-match "\\[" tramp-prefix-format)
7758 (defadvice file-expand-wildcards
7759 (around tramp-advice-file-expand-wildcards activate)
7760 (let ((name (ad-get-arg 0)))
7761 (if (tramp-tramp-file-p name)
7762 ;; If it's a Tramp file, dissect it and look if wildcards
7763 ;; need to be expanded at all.
7766 (tramp-file-name-localname (tramp-dissect-file-name name)))
7767 (setq ad-return-value (or ad-do-it (list name)))
7768 (setq ad-return-value (list name)))
7769 ;; If it is not a Tramp file, just run the original function.
7770 (setq ad-return-value (or ad-do-it (list name))))))
7771 (add-hook 'tramp-unload-hook
7772 '(lambda () (ad-unadvise 'file-expand-wildcards))))
7774 ;; Checklist for `tramp-unload-hook'
7775 ;; - Unload all `tramp-*' packages
7776 ;; - Reset `file-name-handler-alist'
7777 ;; - Cleanup hooks where Tramp functions are in
7778 ;; - Cleanup advised functions
7779 ;; - Cleanup autoloads
7781 (defun tramp-unload-tramp ()
7782 "Discard Tramp from loading remote files."
7784 ;; When Tramp is not loaded yet, its autoloads are still active.
7785 (tramp-unload-file-name-handlers)
7786 ;; ange-ftp settings must be enabled.
7787 (when (functionp 'tramp-ftp-enable-ange-ftp)
7788 (funcall (symbol-function 'tramp-ftp-enable-ange-ftp)))
7789 ;; Maybe its not loaded yet.
7791 (unload-feature 'tramp 'force)
7794 (when (and load-in-progress
7795 (string-match "Loading tramp..." (or (current-message) "")))
7796 (message "Loading tramp...done"))
7802 ;; * Handle nonlocal exits such as C-g.
7803 ;; * But it would probably be better to use with-local-quit at the
7804 ;; place where it's actually needed: around any potentially
7805 ;; indefinitely blocking piece of code. In this case it would be
7806 ;; within Tramp around one of its calls to accept-process-output (or
7807 ;; around one of the loops that calls accept-process-output)
7808 ;; (Stefan Monnier).
7809 ;; * Autodetect if remote `ls' groks the "--dired" switch.
7810 ;; * Rewrite `tramp-shell-quote-argument' to abstain from using
7811 ;; `shell-quote-argument'.
7812 ;; * In Emacs 21, `insert-directory' shows total number of bytes used
7813 ;; by the files in that directory. Add this here.
7814 ;; * Avoid screen blanking when hitting `g' in dired. (Eli Tziperman)
7815 ;; * Make ffap.el grok Tramp filenames. (Eli Tziperman)
7816 ;; * Case-insensitive filename completion. (Norbert Goevert.)
7817 ;; * Don't use globbing for directories with many files, as this is
7818 ;; likely to produce long command lines, and some shells choke on
7819 ;; long command lines.
7820 ;; * `vc-directory' does not work. It never displays any files, even
7821 ;; if it does show files when run locally.
7822 ;; * How to deal with MULE in `insert-file-contents' and `write-region'?
7823 ;; * Grok `append' parameter for `write-region'.
7824 ;; * Test remote ksh or bash for tilde expansion in `tramp-find-shell'?
7825 ;; * abbreviate-file-name
7826 ;; * better error checking. At least whenever we see something
7827 ;; strange when doing zerop, we should kill the process and start
7828 ;; again. (Greg Stark)
7829 ;; * Provide a local cache of old versions of remote files for the rsync
7830 ;; transfer method to use. (Greg Stark)
7831 ;; * Remove unneeded parameters from methods.
7832 ;; * Invoke rsync once for copying a whole directory hierarchy.
7833 ;; (Francesco Potortì)
7834 ;; * Make it work for different encodings, and for different file name
7835 ;; encodings, too. (Daniel Pittman)
7836 ;; * Progress reports while copying files. (Michael Kifer)
7837 ;; * Don't search for perl5 and perl. Instead, only search for perl and
7838 ;; then look if it's the right version (with `perl -v').
7839 ;; * When editing a remote CVS controlled file as a different user, VC
7840 ;; gets confused about the file locking status. Try to find out why
7841 ;; the workaround doesn't work.
7842 ;; * Username and hostname completion.
7843 ;; ** Try to avoid usage of `last-input-event' in `tramp-completion-mode-p'.
7844 ;; ** Unify `tramp-parse-{rhosts,shosts,sconfig,hosts,passwd,netrc}'.
7845 ;; Code is nearly identical.
7846 ;; * Allow out-of-band methods as _last_ multi-hop. Open a connection
7847 ;; until the last but one hop via `start-file-process'. Apply it
7848 ;; also for ftp and smb.
7849 ;; * WIBNI if we had a command "trampclient"? If I was editing in
7850 ;; some shell with root priviledges, it would be nice if I could
7852 ;; trampclient filename.c
7853 ;; as an editor, and the _current_ shell would connect to an Emacs
7854 ;; server and would be used in an existing non-priviledged Emacs
7855 ;; session for doing the editing in question.
7856 ;; That way, I need not tell Emacs my password again and be afraid
7857 ;; that it makes it into core dumps or other ugly stuff (I had Emacs
7858 ;; once display a just typed password in the context of a keyboard
7859 ;; sequence prompt for a question immediately following in a shell
7860 ;; script run within Emacs -- nasty).
7861 ;; And if I have some ssh session running to a different computer,
7862 ;; having the possibility of passing a local file there to a local
7863 ;; Emacs session (in case I can arrange for a connection back) would
7865 ;; Likely the corresponding Tramp server should not allow the
7866 ;; equivalent of the emacsclient -eval option in order to make this
7867 ;; reasonably unproblematic. And maybe trampclient should have some
7868 ;; way of passing credentials, like by using an SSL socket or
7869 ;; something. (David Kastrup)
7870 ;; * Could Tramp reasonably look for a prompt after ^M rather than
7871 ;; only after ^J ? (Stefan Monnier)
7872 ;; * Reconnect directly to a compliant shell without first going
7873 ;; through the user's default shell. (Pete Forman)
7874 ;; * Make `tramp-default-user' obsolete.
7875 ;; * Tramp shall reconnect automatically to its ssh connection when it
7876 ;; detects that the process "has died". (David Reitter)
7877 ;; * How can I interrupt the remote process with a signal
7878 ;; (interrupt-process seems not to work)? (Markus Triska)
7879 ;; * Avoid the local shell entirely for starting remote processes. If
7880 ;; so, I think even a signal, when delivered directly to the local
7881 ;; SSH instance, would correctly be propagated to the remote process
7882 ;; automatically; possibly SSH would have to be started with
7883 ;; "-t". (Markus Triska)
7884 ;; * Set `tramp-copy-size-limit' to 0, when there is no remote
7885 ;; encoding routine.
7886 ;; * It makes me wonder if tramp couldn't fall back to ssh when scp
7887 ;; isn't on the remote host. (Mark A. Hershberger)
7888 ;; * To improve the behavior in case of things like "git status", it
7889 ;; might be worthwhile to add some way to indicate that a particular
7890 ;; use of process-file is (supposed to be) free of side-effects.
7892 ;; * Use lsh instead of ssh. (Alfred M. Szmidt)
7893 ;; * Implement a general server-local-variable mechanism, as there are
7894 ;; probably other variables that need different values for different
7895 ;; servers too. The user could then configure a variable (such as
7896 ;; tramp-server-local-variable-alist) to define any such variables
7897 ;; that they need to, which would then be let bound as appropriate
7898 ;; in tramp functions. (Jason Rumney)
7899 ;; * Optimize out-of-band copying, when both methods are scp-like.
7901 ;; Functions for file-name-handler-alist:
7902 ;; diff-latest-backup-file -- in diff.el
7904 ;; arch-tag: 3a21a994-182b-48fa-b0cd-c1d9fede424a
7905 ;;; tramp.el ends here