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