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