Quote a few backticks in docstrings.
[emacs.git] / lisp / net / tramp.el
blobc4839e7f69775b8f52df3b668f3715e6eb5d3206
1 ;;; tramp.el --- Transparent Remote Access, Multiple Protocol -*- lexical-binding:t -*-
3 ;; Copyright (C) 1998-2018 Free Software Foundation, Inc.
5 ;; Author: Kai Großjohann <kai.grossjohann@gmx.net>
6 ;; Michael Albinus <michael.albinus@gmx.de>
7 ;; Maintainer: Michael Albinus <michael.albinus@gmx.de>
8 ;; Keywords: comm, processes
9 ;; Package: tramp
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
26 ;;; Commentary:
28 ;; This package provides remote file editing, similar to ange-ftp.
29 ;; The difference is that ange-ftp uses FTP to transfer files between
30 ;; the local and the remote host, whereas tramp.el uses a combination
31 ;; of rsh and rcp or other work-alike programs, such as ssh/scp.
33 ;; For more detailed instructions, please see the info file.
35 ;; Notes:
36 ;; -----
38 ;; This package only works for Emacs 24.1 and higher.
40 ;; Also see the todo list at the bottom of this file.
42 ;; The current version of Tramp can be retrieved from the following URL:
43 ;; https://ftp.gnu.org/gnu/tramp/
45 ;; There's a mailing list for this, as well. Its name is:
46 ;; tramp-devel@gnu.org
47 ;; You can use the Web to subscribe, under the following URL:
48 ;; https://lists.gnu.org/mailman/listinfo/tramp-devel
50 ;; For the adventurous, the current development sources are available
51 ;; via Git. You can find instructions about this at the following URL:
52 ;; https://savannah.gnu.org/projects/tramp/
54 ;; Don't forget to put on your asbestos longjohns, first!
56 ;;; Code:
58 (require 'tramp-compat)
60 ;; Pacify byte-compiler.
61 (require 'cl-lib)
62 (defvar auto-save-file-name-transforms)
63 (defvar eshell-path-env)
64 (defvar ls-lisp-use-insert-directory-program)
65 (defvar outline-regexp)
67 ;;; User Customizable Internal Variables:
69 (defgroup tramp nil
70 "Edit remote files with a combination of ssh, scp, etc."
71 :group 'files
72 :group 'comm
73 :link '(custom-manual "(tramp)Top")
74 :version "22.1")
76 ;; Maybe we need once a real Tramp mode, with key bindings etc.
77 ;;;###autoload
78 (defcustom tramp-mode t
79 "Whether Tramp is enabled.
80 If it is set to nil, all remote file names are used literally."
81 :group 'tramp
82 :type 'boolean
83 :require 'tramp)
85 (defcustom tramp-verbose 3
86 "Verbosity level for Tramp messages.
87 Any level x includes messages for all levels 1 .. x-1. The levels are
89 0 silent (no tramp messages at all)
90 1 errors
91 2 warnings
92 3 connection to remote hosts (default level)
93 4 activities
94 5 internal
95 6 sent and received strings
96 7 file caching
97 8 connection properties
98 9 test commands
99 10 traces (huge)."
100 :group 'tramp
101 :type 'integer
102 :require 'tramp)
104 (defcustom tramp-backup-directory-alist nil
105 "Alist of filename patterns and backup directory names.
106 Each element looks like (REGEXP . DIRECTORY), with the same meaning like
107 in `backup-directory-alist'. If a Tramp file is backed up, and DIRECTORY
108 is a local file name, the backup directory is prepended with Tramp file
109 name prefix \(method, user, host) of file.
111 \(setq tramp-backup-directory-alist backup-directory-alist)
113 gives the same backup policy for Tramp files on their hosts like the
114 policy for local files."
115 :group 'tramp
116 :type '(repeat (cons (regexp :tag "Regexp matching filename")
117 (directory :tag "Backup directory name")))
118 :require 'tramp)
120 (defcustom tramp-auto-save-directory nil
121 "Put auto-save files in this directory, if set.
122 The idea is to use a local directory so that auto-saving is faster.
123 This setting has precedence over `auto-save-file-name-transforms'."
124 :group 'tramp
125 :type '(choice (const :tag "Use default" nil)
126 (directory :tag "Auto save directory name"))
127 :require 'tramp)
129 (defcustom tramp-encoding-shell
130 (or (tramp-compat-funcall 'w32-shell-name) "/bin/sh")
131 "Use this program for encoding and decoding commands on the local host.
132 This shell is used to execute the encoding and decoding command on the
133 local host, so if you want to use `~' in those commands, you should
134 choose a shell here which groks tilde expansion. `/bin/sh' normally
135 does not understand tilde expansion.
137 For encoding and decoding, commands like the following are executed:
139 /bin/sh -c COMMAND < INPUT > OUTPUT
141 This variable can be used to change the \"/bin/sh\" part. See the
142 variable `tramp-encoding-command-switch' for the \"-c\" part.
144 If the shell must be forced to be interactive, see
145 `tramp-encoding-command-interactive'.
147 Note that this variable is not used for remote commands. There are
148 mechanisms in tramp.el which automatically determine the right shell to
149 use for the remote host."
150 :group 'tramp
151 :type '(file :must-match t)
152 :require 'tramp)
154 (defcustom tramp-encoding-command-switch
155 (if (tramp-compat-funcall 'w32-shell-dos-semantics) "/c" "-c")
156 "Use this switch together with `tramp-encoding-shell' for local commands.
157 See the variable `tramp-encoding-shell' for more information."
158 :group 'tramp
159 :type 'string
160 :require 'tramp)
162 (defcustom tramp-encoding-command-interactive
163 (unless (tramp-compat-funcall 'w32-shell-dos-semantics) "-i")
164 "Use this switch together with `tramp-encoding-shell' for interactive shells.
165 See the variable `tramp-encoding-shell' for more information."
166 :version "24.1"
167 :group 'tramp
168 :type '(choice (const nil) string)
169 :require 'tramp)
171 ;;;###tramp-autoload
172 (defvar tramp-methods nil
173 "Alist of methods for remote files.
174 This is a list of entries of the form (NAME PARAM1 PARAM2 ...).
175 Each NAME stands for a remote access method. Each PARAM is a
176 pair of the form (KEY VALUE). The following KEYs are defined:
177 * `tramp-remote-shell'
178 This specifies the shell to use on the remote host. This
179 MUST be a Bourne-like shell. It is normally not necessary to
180 set this to any value other than \"/bin/sh\": Tramp wants to
181 use a shell which groks tilde expansion, but it can search
182 for it. Also note that \"/bin/sh\" exists on all Unixen,
183 this might not be true for the value that you decide to use.
184 You Have Been Warned.
185 * `tramp-remote-shell-login'
186 This specifies the arguments to let `tramp-remote-shell' run
187 as a login shell. It defaults to (\"-l\"), but some shells,
188 like ksh, require another argument. See
189 `tramp-connection-properties' for a way to overwrite the
190 default value.
191 * `tramp-remote-shell-args'
192 For implementation of `shell-command', this specifies the
193 arguments to let `tramp-remote-shell' run a single command.
194 * `tramp-login-program'
195 This specifies the name of the program to use for logging in to the
196 remote host. This may be the name of rsh or a workalike program,
197 or the name of telnet or a workalike, or the name of su or a workalike.
198 * `tramp-login-args'
199 This specifies the list of arguments to pass to the above
200 mentioned program. Please note that this is a list of list of arguments,
201 that is, normally you don't want to put \"-a -b\" or \"-f foo\"
202 here. Instead, you want a list (\"-a\" \"-b\"), or (\"-f\" \"foo\").
203 There are some patterns: \"%h\" in this list is replaced by the host
204 name, \"%u\" is replaced by the user name, \"%p\" is replaced by the
205 port number, and \"%%\" can be used to obtain a literal percent character.
206 If a list containing \"%h\", \"%u\" or \"%p\" is unchanged during
207 expansion (i.e. no host or no user specified), this list is not used as
208 argument. By this, arguments like (\"-l\" \"%u\") are optional.
209 \"%t\" is replaced by the temporary file name produced with
210 `tramp-make-tramp-temp-file'. \"%k\" indicates the keep-date
211 parameter of a program, if exists. \"%c\" adds additional
212 `tramp-ssh-controlmaster-options' options for the first hop.
213 * `tramp-login-env'
214 A list of environment variables and their values, which will
215 be set when calling `tramp-login-program'.
216 * `tramp-async-args'
217 When an asynchronous process is started, we know already that
218 the connection works. Therefore, we can pass additional
219 parameters to suppress diagnostic messages, in order not to
220 tamper the process output.
221 * `tramp-copy-program'
222 This specifies the name of the program to use for remotely copying
223 the file; this might be the absolute filename of scp or the name of
224 a workalike program. It is always applied on the local host.
225 * `tramp-copy-args'
226 This specifies the list of parameters to pass to the above mentioned
227 program, the hints for `tramp-login-args' also apply here.
228 * `tramp-copy-env'
229 A list of environment variables and their values, which will
230 be set when calling `tramp-copy-program'.
231 * `tramp-remote-copy-program'
232 The listener program to be applied on remote side, if needed.
233 * `tramp-remote-copy-args'
234 The list of parameters to pass to the listener program, the hints
235 for `tramp-login-args' also apply here. Additionally, \"%r\" could
236 be used here and in `tramp-copy-args'. It denotes a randomly
237 chosen port for the remote listener.
238 * `tramp-copy-keep-date'
239 This specifies whether the copying program when the preserves the
240 timestamp of the original file.
241 * `tramp-copy-keep-tmpfile'
242 This specifies whether a temporary local file shall be kept
243 for optimization reasons (useful for \"rsync\" methods).
244 * `tramp-copy-recursive'
245 Whether the operation copies directories recursively.
246 * `tramp-default-port'
247 The default port of a method.
248 * `tramp-tmpdir'
249 A directory on the remote host for temporary files. If not
250 specified, \"/tmp\" is taken as default.
251 * `tramp-connection-timeout'
252 This is the maximum time to be spent for establishing a connection.
253 In general, the global default value shall be used, but for
254 some methods, like \"su\" or \"sudo\", a shorter timeout
255 might be desirable.
256 * `tramp-case-insensitive'
257 Whether the remote file system handles file names case insensitive.
258 Only a non-nil value counts, the default value nil means to
259 perform further checks on the remote host. See
260 `tramp-connection-properties' for a way to overwrite this.
262 What does all this mean? Well, you should specify `tramp-login-program'
263 for all methods; this program is used to log in to the remote site. Then,
264 there are two ways to actually transfer the files between the local and the
265 remote side. One way is using an additional scp-like program. If you want
266 to do this, set `tramp-copy-program' in the method.
268 Another possibility for file transfer is inline transfer, i.e. the
269 file is passed through the same buffer used by `tramp-login-program'. In
270 this case, the file contents need to be protected since the
271 `tramp-login-program' might use escape codes or the connection might not
272 be eight-bit clean. Therefore, file contents are encoded for transit.
273 See the variables `tramp-local-coding-commands' and
274 `tramp-remote-coding-commands' for details.
276 So, to summarize: if the method is an out-of-band method, then you
277 must specify `tramp-copy-program' and `tramp-copy-args'. If it is an
278 inline method, then these two parameters should be nil.
280 Notes:
282 When using `su' or `sudo' the phrase \"open connection to a remote
283 host\" sounds strange, but it is used nevertheless, for consistency.
284 No connection is opened to a remote host, but `su' or `sudo' is
285 started on the local host. You should specify a remote host
286 `localhost' or the name of the local host. Another host name is
287 useful only in combination with `tramp-default-proxies-alist'.")
289 (defcustom tramp-default-method
290 ;; An external copy method seems to be preferred, because it performs
291 ;; much better for large files, and it hasn't too serious delays
292 ;; for small files. But it must be ensured that there aren't
293 ;; permanent password queries. Either a password agent like
294 ;; "ssh-agent" or "Pageant" shall run, or the optional
295 ;; password-cache.el or auth-sources.el packages shall be active for
296 ;; password caching. If we detect that the user is running OpenSSH
297 ;; 4.0 or newer, we could reuse the connection, which calls also for
298 ;; an external method.
299 (cond
300 ;; PuTTY is installed. We don't take it, if it is installed on a
301 ;; non-windows system, or pscp from the pssh (parallel ssh) package
302 ;; is found.
303 ((and (eq system-type 'windows-nt) (executable-find "pscp")) "pscp")
304 ;; There is an ssh installation.
305 ((executable-find "scp") "scp")
306 ;; Fallback.
307 (t "ftp"))
308 "Default method to use for transferring files.
309 See `tramp-methods' for possibilities.
310 Also see `tramp-default-method-alist'."
311 :group 'tramp
312 :type 'string
313 :require 'tramp)
315 ;;;###tramp-autoload
316 (defcustom tramp-default-method-alist nil
317 "Default method to use for specific host/user pairs.
318 This is an alist of items (HOST USER METHOD). The first matching item
319 specifies the method to use for a file name which does not specify a
320 method. HOST and USER are regular expressions or nil, which is
321 interpreted as a regular expression which always matches. If no entry
322 matches, the variable `tramp-default-method' takes effect.
324 If the file name does not specify the user, lookup is done using the
325 empty string for the user name.
327 See `tramp-methods' for a list of possibilities for METHOD."
328 :group 'tramp
329 :type '(repeat (list (choice :tag "Host regexp" regexp sexp)
330 (choice :tag "User regexp" regexp sexp)
331 (choice :tag "Method name" string (const nil))))
332 :require 'tramp)
334 (defconst tramp-default-method-marker "-"
335 "Marker for default method in remote file names.")
337 (defcustom tramp-default-user nil
338 "Default user to use for transferring files.
339 It is nil by default; otherwise settings in configuration files like
340 \"~/.ssh/config\" would be overwritten. Also see `tramp-default-user-alist'.
342 This variable is regarded as obsolete, and will be removed soon."
343 :group 'tramp
344 :type '(choice (const nil) string)
345 :require 'tramp)
347 ;;;###tramp-autoload
348 (defcustom tramp-default-user-alist nil
349 "Default user to use for specific method/host pairs.
350 This is an alist of items (METHOD HOST USER). The first matching item
351 specifies the user to use for a file name which does not specify a
352 user. METHOD and USER are regular expressions or nil, which is
353 interpreted as a regular expression which always matches. If no entry
354 matches, the variable `tramp-default-user' takes effect.
356 If the file name does not specify the method, lookup is done using the
357 empty string for the method name."
358 :group 'tramp
359 :type '(repeat (list (choice :tag "Method regexp" regexp sexp)
360 (choice :tag " Host regexp" regexp sexp)
361 (choice :tag " User name" string (const nil))))
362 :require 'tramp)
364 (defcustom tramp-default-host (system-name)
365 "Default host to use for transferring files.
366 Useful for su and sudo methods mostly."
367 :group 'tramp
368 :type 'string
369 :require 'tramp)
371 ;;;###tramp-autoload
372 (defcustom tramp-default-host-alist nil
373 "Default host to use for specific method/user pairs.
374 This is an alist of items (METHOD USER HOST). The first matching item
375 specifies the host to use for a file name which does not specify a
376 host. METHOD and HOST are regular expressions or nil, which is
377 interpreted as a regular expression which always matches. If no entry
378 matches, the variable `tramp-default-host' takes effect.
380 If the file name does not specify the method, lookup is done using the
381 empty string for the method name."
382 :group 'tramp
383 :version "24.4"
384 :type '(repeat (list (choice :tag "Method regexp" regexp sexp)
385 (choice :tag " User regexp" regexp sexp)
386 (choice :tag " Host name" string (const nil))))
387 :require 'tramp)
389 (defcustom tramp-default-proxies-alist nil
390 "Route to be followed for specific host/user pairs.
391 This is an alist of items (HOST USER PROXY). The first matching
392 item specifies the proxy to be passed for a file name located on
393 a remote target matching USER@HOST. HOST and USER are regular
394 expressions. PROXY must be a Tramp filename without a localname
395 part. Method and user name on PROXY are optional, which is
396 interpreted with the default values. PROXY can contain the
397 patterns %h and %u, which are replaced by the strings matching
398 HOST or USER, respectively.
400 HOST, USER or PROXY could also be Lisp forms, which will be
401 evaluated. The result must be a string or nil, which is
402 interpreted as a regular expression which always matches."
403 :group 'tramp
404 :type '(repeat (list (choice :tag "Host regexp" regexp sexp)
405 (choice :tag "User regexp" regexp sexp)
406 (choice :tag " Proxy name" string (const nil))))
407 :require 'tramp)
409 (defcustom tramp-save-ad-hoc-proxies nil
410 "Whether to save ad-hoc proxies persistently."
411 :group 'tramp
412 :version "24.3"
413 :type 'boolean
414 :require 'tramp)
416 (defcustom tramp-restricted-shell-hosts-alist
417 (when (memq system-type '(windows-nt))
418 (list (concat "\\`" (regexp-quote (system-name)) "\\'")))
419 "List of hosts, which run a restricted shell.
420 This is a list of regular expressions, which denote hosts running
421 a registered shell like \"rbash\". Those hosts can be used as
422 proxies only, see `tramp-default-proxies-alist'. If the local
423 host runs a registered shell, it shall be added to this list, too."
424 :version "24.3"
425 :group 'tramp
426 :type '(repeat (regexp :tag "Host regexp"))
427 :require 'tramp)
429 ;;;###tramp-autoload
430 (defconst tramp-local-host-regexp
431 (concat
432 "\\`"
433 (regexp-opt
434 (list "localhost" "localhost6" (system-name) "127.0.0.1" "::1") t)
435 "\\'")
436 "Host names which are regarded as local host.")
438 (defvar tramp-completion-function-alist nil
439 "Alist of methods for remote files.
440 This is a list of entries of the form \(NAME PAIR1 PAIR2 ...).
441 Each NAME stands for a remote access method. Each PAIR is of the form
442 \(FUNCTION FILE). FUNCTION is responsible to extract user names and host
443 names from FILE for completion. The following predefined FUNCTIONs exists:
445 * `tramp-parse-rhosts' for \"~/.rhosts\" like files,
446 * `tramp-parse-shosts' for \"~/.ssh/known_hosts\" like files,
447 * `tramp-parse-sconfig' for \"~/.ssh/config\" like files,
448 * `tramp-parse-shostkeys' for \"~/.ssh2/hostkeys/*\" like files,
449 * `tramp-parse-sknownhosts' for \"~/.ssh2/knownhosts/*\" like files,
450 * `tramp-parse-hosts' for \"/etc/hosts\" like files,
451 * `tramp-parse-passwd' for \"/etc/passwd\" like files.
452 * `tramp-parse-etc-group' for \"/etc/group\" like files.
453 * `tramp-parse-netrc' for \"~/.netrc\" like files.
454 * `tramp-parse-putty' for PuTTY registered sessions.
456 FUNCTION can also be a user defined function. For more details see
457 the info pages.")
459 (defconst tramp-echo-mark-marker "_echo"
460 "String marker to surround echoed commands.")
462 (defconst tramp-echo-mark-marker-length (length tramp-echo-mark-marker)
463 "String length of `tramp-echo-mark-marker'.")
465 (defconst tramp-echo-mark
466 (concat tramp-echo-mark-marker
467 (make-string tramp-echo-mark-marker-length ?\b))
468 "String mark to be transmitted around shell commands.
469 Used to separate their echo from the output they produce. This
470 will only be used if we cannot disable remote echo via stty.
471 This string must have no effect on the remote shell except for
472 producing some echo which can later be detected by
473 `tramp-echoed-echo-mark-regexp'. Using `tramp-echo-mark-marker',
474 followed by an equal number of backspaces to erase them will
475 usually suffice.")
477 (defconst tramp-echoed-echo-mark-regexp
478 (format "%s\\(\b\\( \b\\)?\\)\\{%d\\}"
479 tramp-echo-mark-marker tramp-echo-mark-marker-length)
480 "Regexp which matches `tramp-echo-mark' as it gets echoed by
481 the remote shell.")
483 (defcustom tramp-local-end-of-line
484 (if (memq system-type '(windows-nt)) "\r\n" "\n")
485 "String used for end of line in local processes."
486 :version "24.1"
487 :group 'tramp
488 :type 'string
489 :require 'tramp)
491 (defcustom tramp-rsh-end-of-line "\n"
492 "String used for end of line in rsh connections.
493 I don't think this ever needs to be changed, so please tell me about it
494 if you need to change this."
495 :group 'tramp
496 :type 'string
497 :require 'tramp)
499 (defcustom tramp-login-prompt-regexp
500 ".*\\(user\\|login\\)\\( .*\\)?: *"
501 "Regexp matching login-like prompts.
502 The regexp should match at end of buffer.
504 Sometimes the prompt is reported to look like \"login as:\"."
505 :group 'tramp
506 :type 'regexp
507 :require 'tramp)
509 (defcustom tramp-shell-prompt-pattern
510 ;; Allow a prompt to start right after a ^M since it indeed would be
511 ;; displayed at the beginning of the line (and Zsh uses it). This
512 ;; regexp works only for GNU Emacs.
513 ;; Allow also [] style prompts. They can appear only during
514 ;; connection initialization; Tramp redefines the prompt afterwards.
515 (concat "\\(?:^\\|\r\\)"
516 "[^]#$%>\n]*#?[]#$%>] *\\(\e\\[[0-9;]*[a-zA-Z] *\\)*")
517 "Regexp to match prompts from remote shell.
518 Normally, Tramp expects you to configure `shell-prompt-pattern'
519 correctly, but sometimes it happens that you are connecting to a
520 remote host which sends a different kind of shell prompt. Therefore,
521 Tramp recognizes things matched by `shell-prompt-pattern' as prompt,
522 and also things matched by this variable. The default value of this
523 variable is similar to the default value of `shell-prompt-pattern',
524 which should work well in many cases.
526 This regexp must match both `tramp-initial-end-of-output' and
527 `tramp-end-of-output'."
528 :group 'tramp
529 :type 'regexp
530 :require 'tramp)
532 (defcustom tramp-password-prompt-regexp
533 (format "^.*\\(%s\\).*:\^@? *"
534 ;; `password-word-equivalents' has been introduced with Emacs 24.4.
535 (regexp-opt (or (bound-and-true-p password-word-equivalents)
536 '("password" "passphrase"))))
537 "Regexp matching password-like prompts.
538 The regexp should match at end of buffer.
540 The `sudo' program appears to insert a `^@' character into the prompt."
541 :version "24.4"
542 :group 'tramp
543 :type 'regexp
544 :require 'tramp)
546 (defcustom tramp-wrong-passwd-regexp
547 (concat "^.*"
548 ;; These strings should be on the last line
549 (regexp-opt '("Permission denied"
550 "Login incorrect"
551 "Login Incorrect"
552 "Connection refused"
553 "Connection closed"
554 "Timeout, server not responding."
555 "Sorry, try again."
556 "Name or service not known"
557 "Host key verification failed."
558 "No supported authentication methods left to try!")
560 ".*"
561 "\\|"
562 "^.*\\("
563 ;; Here comes a list of regexes, separated by \\|
564 "Received signal [0-9]+"
565 "\\).*")
566 "Regexp matching a `login failed' message.
567 The regexp should match at end of buffer."
568 :group 'tramp
569 :type 'regexp
570 :require 'tramp)
572 (defcustom tramp-yesno-prompt-regexp
573 (concat
574 (regexp-opt '("Are you sure you want to continue connecting (yes/no)?") t)
575 "\\s-*")
576 "Regular expression matching all yes/no queries which need to be confirmed.
577 The confirmation should be done with yes or no.
578 The regexp should match at end of buffer.
579 See also `tramp-yn-prompt-regexp'."
580 :group 'tramp
581 :type 'regexp
582 :require 'tramp)
584 (defcustom tramp-yn-prompt-regexp
585 (concat
586 (regexp-opt '("Store key in cache? (y/n)"
587 "Update cached key? (y/n, Return cancels connection)")
589 "\\s-*")
590 "Regular expression matching all y/n queries which need to be confirmed.
591 The confirmation should be done with y or n.
592 The regexp should match at end of buffer.
593 See also `tramp-yesno-prompt-regexp'."
594 :group 'tramp
595 :type 'regexp
596 :require 'tramp)
598 (defcustom tramp-terminal-prompt-regexp
599 (concat "\\("
600 "TERM = (.*)"
601 "\\|"
602 "Terminal type\\? \\[.*\\]"
603 "\\)\\s-*")
604 "Regular expression matching all terminal setting prompts.
605 The regexp should match at end of buffer.
606 The answer will be provided by `tramp-action-terminal', which see."
607 :group 'tramp
608 :type 'regexp
609 :require 'tramp)
611 (defcustom tramp-operation-not-permitted-regexp
612 (concat "\\(" "preserving times.*" "\\|" "set mode" "\\)" ":\\s-*"
613 (regexp-opt '("Operation not permitted") t))
614 "Regular expression matching keep-date problems in (s)cp operations.
615 Copying has been performed successfully already, so this message can
616 be ignored safely."
617 :group 'tramp
618 :type 'regexp
619 :require 'tramp)
621 (defcustom tramp-copy-failed-regexp
622 (concat "\\(.+: "
623 (regexp-opt '("Permission denied"
624 "not a regular file"
625 "is a directory"
626 "No such file or directory")
628 "\\)\\s-*")
629 "Regular expression matching copy problems in (s)cp operations."
630 :group 'tramp
631 :type 'regexp
632 :require 'tramp)
634 (defcustom tramp-process-alive-regexp
636 "Regular expression indicating a process has finished.
637 In fact this expression is empty by intention, it will be used only to
638 check regularly the status of the associated process.
639 The answer will be provided by `tramp-action-process-alive',
640 `tramp-action-out-of-band', which see."
641 :group 'tramp
642 :type 'regexp
643 :require 'tramp)
645 (defconst tramp-temp-name-prefix "tramp."
646 "Prefix to use for temporary files.
647 If this is a relative file name (such as \"tramp.\"), it is considered
648 relative to the directory name returned by the function
649 `tramp-compat-temporary-file-directory' (which see). It may also be an
650 absolute file name; don't forget to include a prefix for the filename
651 part, though.")
653 (defconst tramp-temp-buffer-name " *tramp temp*"
654 "Buffer name for a temporary buffer.
655 It shall be used in combination with `generate-new-buffer-name'.")
657 (defvar tramp-temp-buffer-file-name nil
658 "File name of a persistent local temporary file.
659 Useful for \"rsync\" like methods.")
660 (make-variable-buffer-local 'tramp-temp-buffer-file-name)
661 (put 'tramp-temp-buffer-file-name 'permanent-local t)
663 ;;;###tramp-autoload
664 (defcustom tramp-syntax 'default
665 "Tramp filename syntax to be used.
667 It can have the following values:
669 `default' -- Default syntax
670 `simplified' -- Ange-FTP like syntax
671 `separate' -- Syntax as defined for XEmacs originally
673 Do not change the value by `setq', it must be changed only via
674 Customize. See also `tramp-change-syntax'."
675 :group 'tramp
676 :version "26.1"
677 :package-version '(Tramp . "2.3.3")
678 :type '(choice (const :tag "Default" default)
679 (const :tag "Ange-FTP" simplified)
680 (const :tag "XEmacs" separate))
681 :require 'tramp
682 :initialize 'custom-initialize-set
683 :set 'tramp-set-syntax)
685 (defun tramp-set-syntax (symbol value)
686 "Set SYMBOL to value VALUE.
687 Used in user option `tramp-syntax'. There are further variables
688 to be set, depending on VALUE."
689 ;; Check allowed values.
690 (unless (memq value (tramp-syntax-values))
691 (tramp-compat-user-error "Wrong `tramp-syntax' %s" tramp-syntax))
692 ;; Cleanup existing buffers.
693 (unless (eq (symbol-value symbol) value)
694 (tramp-cleanup-all-buffers))
695 ;; Set the value:
696 (set-default symbol value)
697 ;; Reset the depending variables.
698 (with-no-warnings
699 (setq tramp-prefix-format (tramp-build-prefix-format)
700 tramp-prefix-regexp (tramp-build-prefix-regexp)
701 tramp-method-regexp (tramp-build-method-regexp)
702 tramp-postfix-method-format (tramp-build-postfix-method-format)
703 tramp-postfix-method-regexp (tramp-build-postfix-method-regexp)
704 tramp-prefix-ipv6-format (tramp-build-prefix-ipv6-format)
705 tramp-prefix-ipv6-regexp (tramp-build-prefix-ipv6-regexp)
706 tramp-postfix-ipv6-format (tramp-build-postfix-ipv6-format)
707 tramp-postfix-ipv6-regexp (tramp-build-postfix-ipv6-regexp)
708 tramp-postfix-host-format (tramp-build-postfix-host-format)
709 tramp-postfix-host-regexp (tramp-build-postfix-host-regexp)
710 tramp-remote-file-name-spec-regexp
711 (tramp-build-remote-file-name-spec-regexp)
712 tramp-file-name-structure (tramp-build-file-name-structure)
713 tramp-file-name-regexp (tramp-build-file-name-regexp)
714 tramp-completion-file-name-regexp
715 (tramp-build-completion-file-name-regexp)))
716 ;; Rearrange file name handlers.
717 (tramp-register-file-name-handlers))
719 ;; Initialize the Tramp syntax variables. We want to override initial
720 ;; value of `tramp-file-name-regexp'. Other Tramp syntax variables
721 ;; must be initialized as well to proper values. We do not call
722 ;; `custom-set-variable', this would load Tramp via custom.el.
723 (eval-after-load 'tramp
724 '(tramp-set-syntax 'tramp-syntax (tramp-compat-tramp-syntax)))
726 (defun tramp-syntax-values ()
727 "Return possible values of `tramp-syntax', a list"
728 (let ((values (cdr (get 'tramp-syntax 'custom-type))))
729 (setq values (mapcar 'last values)
730 values (mapcar 'car values))))
732 (defun tramp-lookup-syntax (alist)
733 "Look up a syntax string in ALIST according to `tramp-compat-tramp-syntax.'
734 Raise an error if `tramp-syntax' is invalid."
735 (or (cdr (assq (tramp-compat-tramp-syntax) alist))
736 (error "Wrong `tramp-syntax' %s" tramp-syntax)))
738 (defconst tramp-prefix-format-alist
739 '((default . "/")
740 (simplified . "/")
741 (separate . "/["))
742 "Alist mapping Tramp syntax to strings beginning Tramp file names.")
744 (defun tramp-build-prefix-format ()
745 (tramp-lookup-syntax tramp-prefix-format-alist))
747 (defvar tramp-prefix-format (tramp-build-prefix-format)
748 "String matching the very beginning of Tramp file names.
749 Used in `tramp-make-tramp-file-name'.")
751 (defun tramp-build-prefix-regexp ()
752 (concat "^" (regexp-quote tramp-prefix-format)))
754 (defvar tramp-prefix-regexp (tramp-build-prefix-regexp)
755 "Regexp matching the very beginning of Tramp file names.
756 Should always start with \"^\". Derived from `tramp-prefix-format'.")
758 (defconst tramp-method-regexp-alist
759 '((default . "[a-zA-Z0-9-]+")
760 (simplified . "")
761 (separate . "[a-zA-Z0-9-]*"))
762 "Alist mapping Tramp syntax to regexps matching methods identifiers.")
764 (defun tramp-build-method-regexp ()
765 (tramp-lookup-syntax tramp-method-regexp-alist))
767 (defvar tramp-method-regexp (tramp-build-method-regexp)
768 "Regexp matching methods identifiers.
769 The `ftp' syntax does not support methods.")
771 (defconst tramp-postfix-method-format-alist
772 '((default . ":")
773 (simplified . "")
774 (separate . "/"))
775 "Alist mapping Tramp syntax to the delimiter after the method.")
777 (defun tramp-build-postfix-method-format ()
778 (tramp-lookup-syntax tramp-postfix-method-format-alist))
780 (defvar tramp-postfix-method-format (tramp-build-postfix-method-format)
781 "String matching delimiter between method and user or host names.
782 The `ftp' syntax does not support methods.
783 Used in `tramp-make-tramp-file-name'.")
785 (defun tramp-build-postfix-method-regexp ()
786 (regexp-quote tramp-postfix-method-format))
788 (defvar tramp-postfix-method-regexp (tramp-build-postfix-method-regexp)
789 "Regexp matching delimiter between method and user or host names.
790 Derived from `tramp-postfix-method-format'.")
792 (defconst tramp-user-regexp "[^/|: \t]+"
793 "Regexp matching user names.")
795 ;;;###tramp-autoload
796 (defconst tramp-prefix-domain-format "%"
797 "String matching delimiter between user and domain names.")
799 ;;;###tramp-autoload
800 (defconst tramp-prefix-domain-regexp (regexp-quote tramp-prefix-domain-format)
801 "Regexp matching delimiter between user and domain names.
802 Derived from `tramp-prefix-domain-format'.")
804 (defconst tramp-domain-regexp "[a-zA-Z0-9_.-]+"
805 "Regexp matching domain names.")
807 (defconst tramp-user-with-domain-regexp
808 (concat "\\(" tramp-user-regexp "\\)"
809 tramp-prefix-domain-regexp
810 "\\(" tramp-domain-regexp "\\)")
811 "Regexp matching user names with domain names.")
813 (defconst tramp-postfix-user-format "@"
814 "String matching delimiter between user and host names.
815 Used in `tramp-make-tramp-file-name'.")
817 (defconst tramp-postfix-user-regexp (regexp-quote tramp-postfix-user-format)
818 "Regexp matching delimiter between user and host names.
819 Derived from `tramp-postfix-user-format'.")
821 (defconst tramp-host-regexp "[a-zA-Z0-9_.%-]+"
822 "Regexp matching host names.")
824 (defconst tramp-prefix-ipv6-format-alist
825 '((default . "[")
826 (simplified . "[")
827 (separate . ""))
828 "Alist mapping Tramp syntax to strings prefixing IPv6 addresses.")
830 (defun tramp-build-prefix-ipv6-format ()
831 (tramp-lookup-syntax tramp-prefix-ipv6-format-alist))
833 (defvar tramp-prefix-ipv6-format (tramp-build-prefix-ipv6-format)
834 "String matching left hand side of IPv6 addresses.
835 Used in `tramp-make-tramp-file-name'.")
837 (defun tramp-build-prefix-ipv6-regexp ()
838 (regexp-quote tramp-prefix-ipv6-format))
840 (defvar tramp-prefix-ipv6-regexp (tramp-build-prefix-ipv6-regexp)
841 "Regexp matching left hand side of IPv6 addresses.
842 Derived from `tramp-prefix-ipv6-format'.")
844 ;; The following regexp is a bit sloppy. But it shall serve our
845 ;; purposes. It covers also IPv4 mapped IPv6 addresses, like in
846 ;; "::ffff:192.168.0.1".
847 (defconst tramp-ipv6-regexp "\\(?:\\(?:[a-zA-Z0-9]+\\)?:\\)+[a-zA-Z0-9.]+"
848 "Regexp matching IPv6 addresses.")
850 (defconst tramp-postfix-ipv6-format-alist
851 '((default . "]")
852 (simplified . "]")
853 (separate . ""))
854 "Alist mapping Tramp syntax to suffix for IPv6 addresses.")
856 (defun tramp-build-postfix-ipv6-format ()
857 (tramp-lookup-syntax tramp-postfix-ipv6-format-alist))
859 (defvar tramp-postfix-ipv6-format (tramp-build-postfix-ipv6-format)
860 "String matching right hand side of IPv6 addresses.
861 Used in `tramp-make-tramp-file-name'.")
863 (defun tramp-build-postfix-ipv6-regexp ()
864 (regexp-quote tramp-postfix-ipv6-format))
866 (defvar tramp-postfix-ipv6-regexp (tramp-build-postfix-ipv6-regexp)
867 "Regexp matching right hand side of IPv6 addresses.
868 Derived from `tramp-postfix-ipv6-format'.")
870 (defconst tramp-prefix-port-format "#"
871 "String matching delimiter between host names and port numbers.")
873 (defconst tramp-prefix-port-regexp (regexp-quote tramp-prefix-port-format)
874 "Regexp matching delimiter between host names and port numbers.
875 Derived from `tramp-prefix-port-format'.")
877 (defconst tramp-port-regexp "[0-9]+"
878 "Regexp matching port numbers.")
880 (defconst tramp-host-with-port-regexp
881 (concat "\\(" tramp-host-regexp "\\)"
882 tramp-prefix-port-regexp
883 "\\(" tramp-port-regexp "\\)")
884 "Regexp matching host names with port numbers.")
886 (defconst tramp-postfix-hop-format "|"
887 "String matching delimiter after ad-hoc hop definitions.")
889 (defconst tramp-postfix-hop-regexp (regexp-quote tramp-postfix-hop-format)
890 "Regexp matching delimiter after ad-hoc hop definitions.
891 Derived from `tramp-postfix-hop-format'.")
893 (defconst tramp-postfix-host-format-alist
894 '((default . ":")
895 (simplified . ":")
896 (separate . "]"))
897 "Alist mapping Tramp syntax to strings between host and local names.")
899 (defun tramp-build-postfix-host-format ()
900 (tramp-lookup-syntax tramp-postfix-host-format-alist))
902 (defvar tramp-postfix-host-format (tramp-build-postfix-host-format)
903 "String matching delimiter between host names and localnames.
904 Used in `tramp-make-tramp-file-name'.")
906 (defun tramp-build-postfix-host-regexp ()
907 (regexp-quote tramp-postfix-host-format))
909 (defvar tramp-postfix-host-regexp (tramp-build-postfix-host-regexp)
910 "Regexp matching delimiter between host names and localnames.
911 Derived from `tramp-postfix-host-format'.")
913 (defconst tramp-localname-regexp ".*$"
914 "Regexp matching localnames.")
916 (defconst tramp-unknown-id-string "UNKNOWN"
917 "String used to denote an unknown user or group")
919 (defconst tramp-unknown-id-integer -1
920 "Integer used to denote an unknown user or group")
922 ;;; File name format:
924 (defun tramp-build-remote-file-name-spec-regexp ()
925 "Construct a regexp matching a Tramp file name for a Tramp syntax.
926 It is expected, that `tramp-syntax' has the proper value."
927 (concat
928 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
929 "\\(?:" "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp "\\)?"
930 "\\(" "\\(?:" tramp-host-regexp "\\|"
931 tramp-prefix-ipv6-regexp "\\(?:" tramp-ipv6-regexp "\\)?"
932 tramp-postfix-ipv6-regexp "\\)"
933 "\\(?:" tramp-prefix-port-regexp tramp-port-regexp "\\)?" "\\)?"))
935 (defvar tramp-remote-file-name-spec-regexp
936 (tramp-build-remote-file-name-spec-regexp)
937 "Regular expression matching a Tramp file name between prefix and postfix.")
939 (defun tramp-build-file-name-structure ()
940 "Construct the Tramp file name structure for a Tramp syntax.
941 It is expected, that `tramp-syntax' has the proper value.
942 See `tramp-file-name-structure'."
943 (list
944 (concat
945 tramp-prefix-regexp
946 "\\(" "\\(?:" tramp-remote-file-name-spec-regexp
947 tramp-postfix-hop-regexp "\\)+" "\\)?"
948 tramp-remote-file-name-spec-regexp tramp-postfix-host-regexp
949 "\\(" tramp-localname-regexp "\\)")
950 5 6 7 8 1))
952 (defvar tramp-file-name-structure (tramp-build-file-name-structure)
953 "List of six elements (REGEXP METHOD USER HOST FILE HOP), detailing \
954 the Tramp file name structure.
956 The first element REGEXP is a regular expression matching a Tramp file
957 name. The regex should contain parentheses around the method name,
958 the user name, the host name, and the file name parts.
960 The second element METHOD is a number, saying which pair of
961 parentheses matches the method name. The third element USER is
962 similar, but for the user name. The fourth element HOST is similar,
963 but for the host name. The fifth element FILE is for the file name.
964 The last element HOP is the ad-hoc hop definition, which could be a
965 cascade of several hops.
967 These numbers are passed directly to `match-string', which see. That
968 means the opening parentheses are counted to identify the pair.
970 See also `tramp-file-name-regexp'.")
972 (defun tramp-build-file-name-regexp ()
973 (car tramp-file-name-structure))
975 ;;;###autoload
976 (defconst tramp-initial-file-name-regexp "\\`/.+:.*:"
977 "Value for `tramp-file-name-regexp' for autoload.
978 It must match the initial `tramp-syntax' settings.")
980 ;;;###autoload
981 (defvar tramp-file-name-regexp tramp-initial-file-name-regexp
982 "Regular expression matching file names handled by Tramp.
983 This regexp should match Tramp file names but no other file
984 names. When calling `tramp-register-file-name-handlers', the
985 initial value is overwritten by the car of `tramp-file-name-structure'.")
987 (defconst tramp-completion-file-name-regexp-default
988 (concat
989 "\\`/\\("
990 ;; Optional multi hop.
991 "\\([^/|:]+:[^/|:]*|\\)*"
992 ;; Last hop.
993 (if (memq system-type '(cygwin windows-nt))
994 ;; The method is either "-", or at least two characters.
995 "\\(-\\|[^/|:]\\{2,\\}\\)"
996 ;; At least one character for method.
997 "[^/|:]+")
998 ;; Method separator, user name and host name.
999 "\\(:[^/|:]*\\)?"
1000 "\\)?\\'")
1001 "Value for `tramp-completion-file-name-regexp' for default remoting.
1002 See `tramp-file-name-structure' for more explanations.
1004 On W32 systems, the volume letter must be ignored.")
1006 (defconst tramp-completion-file-name-regexp-simplified
1007 (concat
1008 "\\`/\\("
1009 ;; Optional multi hop.
1010 "\\([^/|:]*|\\)*"
1011 ;; Last hop.
1012 (if (memq system-type '(cygwin windows-nt))
1013 ;; At least two characters.
1014 "[^/|:]\\{2,\\}"
1015 ;; At least one character.
1016 "[^/|:]+")
1017 "\\)?\\'")
1018 "Value for `tramp-completion-file-name-regexp' for simplified style remoting.
1019 See `tramp-file-name-structure' for more explanations.
1021 On W32 systems, the volume letter must be ignored.")
1023 (defconst tramp-completion-file-name-regexp-separate
1024 "\\`/\\(\\[[^]]*\\)?\\'"
1025 "Value for `tramp-completion-file-name-regexp' for separate remoting.
1026 See `tramp-file-name-structure' for more explanations.")
1028 (defconst tramp-completion-file-name-regexp-alist
1029 `((default . ,tramp-completion-file-name-regexp-default)
1030 (simplified . ,tramp-completion-file-name-regexp-simplified)
1031 (separate . ,tramp-completion-file-name-regexp-separate))
1032 "Alist mapping incomplete Tramp file names.")
1034 (defun tramp-build-completion-file-name-regexp ()
1035 (tramp-lookup-syntax tramp-completion-file-name-regexp-alist))
1037 (defvar tramp-completion-file-name-regexp
1038 (tramp-build-completion-file-name-regexp)
1039 "Regular expression matching file names handled by Tramp completion.
1040 This regexp should match partial Tramp file names only.
1042 Please note that the entry in `file-name-handler-alist' is made when
1043 this file \(tramp.el) is loaded. This means that this variable must be set
1044 before loading tramp.el. Alternatively, `file-name-handler-alist' can be
1045 updated after changing this variable.
1047 Also see `tramp-file-name-structure'.")
1049 ;;;###autoload
1050 (defconst tramp-autoload-file-name-regexp
1051 (concat
1052 "\\`/"
1053 (if (memq system-type '(cygwin windows-nt))
1054 ;; The method is either "-", or at least two characters.
1055 "\\(-\\|[^/|:]\\{2,\\}\\)"
1056 ;; At least one character for method.
1057 "[^/|:]+")
1058 ":")
1059 "Regular expression matching file names handled by Tramp autoload.
1060 It must match the initial `tramp-syntax' settings. It should not
1061 match file names at root of the underlying local file system,
1062 like \"/sys\" or \"/C:\".")
1064 ;; Chunked sending kludge. We set this to 500 for black-listed constellations
1065 ;; known to have a bug in `process-send-string'; some ssh connections appear
1066 ;; to drop bytes when data is sent too quickly. There is also a connection
1067 ;; buffer local variable, which is computed depending on remote host properties
1068 ;; when `tramp-chunksize' is zero or nil.
1069 (defcustom tramp-chunksize (when (memq system-type '(hpux)) 500)
1070 ;; Parentheses in docstring starting at beginning of line are escaped.
1071 ;; Fontification is messed up when
1072 ;; `open-paren-in-column-0-is-defun-start' set to t.
1073 "If non-nil, chunksize for sending input to local process.
1074 It is necessary only on systems which have a buggy `process-send-string'
1075 implementation. The necessity, whether this variable must be set, can be
1076 checked via the following code:
1078 (with-temp-buffer
1079 (let* ((user \"xxx\") (host \"yyy\")
1080 (init 0) (step 50)
1081 (sent init) (received init))
1082 (while (= sent received)
1083 (setq sent (+ sent step))
1084 (erase-buffer)
1085 (let ((proc (start-process (buffer-name) (current-buffer)
1086 \"ssh\" \"-l\" user host \"wc\" \"-c\")))
1087 (when (process-live-p proc)
1088 (process-send-string proc (make-string sent ?\\ ))
1089 (process-send-eof proc)
1090 (process-send-eof proc))
1091 (while (not (progn (goto-char (point-min))
1092 (re-search-forward \"\\\\w+\" (point-max) t)))
1093 (accept-process-output proc 1))
1094 (when (process-live-p proc)
1095 (setq received (string-to-number (match-string 0)))
1096 (delete-process proc)
1097 (message \"Bytes sent: %s\\tBytes received: %s\" sent received)
1098 (sit-for 0))))
1099 (if (> sent (+ init step))
1100 (message \"You should set `tramp-chunksize' to a maximum of %s\"
1101 (- sent step))
1102 (message \"Test does not work\")
1103 (display-buffer (current-buffer))
1104 (sit-for 30))))
1106 In the Emacs normally running Tramp, evaluate the above code
1107 \(replace \"xxx\" and \"yyy\" by the remote user and host name,
1108 respectively). You can do this, for example, by pasting it into
1109 the `*scratch*' buffer and then hitting C-j with the cursor after the
1110 last closing parenthesis. Note that it works only if you have configured
1111 \"ssh\" to run without password query, see ssh-agent(1).
1113 You will see the number of bytes sent successfully to the remote host.
1114 If that number exceeds 1000, you can stop the execution by hitting
1115 C-g, because your Emacs is likely clean.
1117 When it is necessary to set `tramp-chunksize', you might consider to
1118 use an out-of-the-band method \(like \"scp\") instead of an internal one
1119 \(like \"ssh\"), because setting `tramp-chunksize' to non-nil decreases
1120 performance.
1122 If your Emacs is buggy, the code stops and gives you an indication
1123 about the value `tramp-chunksize' should be set. Maybe you could just
1124 experiment a bit, e.g. changing the values of `init' and `step'
1125 in the third line of the code.
1127 Please raise a bug report via \"M-x tramp-bug\" if your system needs
1128 this variable to be set as well."
1129 :group 'tramp
1130 :type '(choice (const nil) integer)
1131 :require 'tramp)
1133 ;; Logging in to a remote host normally requires obtaining a pty. But
1134 ;; Emacs on macOS has process-connection-type set to nil by default,
1135 ;; so on those systems Tramp doesn't obtain a pty. Here, we allow
1136 ;; for an override of the system default.
1137 (defcustom tramp-process-connection-type t
1138 "Overrides `process-connection-type' for connections from Tramp.
1139 Tramp binds `process-connection-type' to the value given here before
1140 opening a connection to a remote host."
1141 :group 'tramp
1142 :type '(choice (const nil) (const t) (const pty))
1143 :require 'tramp)
1145 (defcustom tramp-connection-timeout 60
1146 "Defines the max time to wait for establishing a connection (in seconds).
1147 This can be overwritten for different connection types in `tramp-methods'.
1149 The timeout does not include the time reading a password."
1150 :group 'tramp
1151 :version "24.4"
1152 :type 'integer
1153 :require 'tramp)
1155 (defcustom tramp-connection-min-time-diff 5
1156 "Defines seconds between two consecutive connection attempts.
1157 This is necessary as self defense mechanism, in order to avoid
1158 yo-yo connection attempts when the remote host is unavailable.
1160 A value of 0 or nil suppresses this check. This might be
1161 necessary, when several out-of-order copy operations are
1162 performed, or when several asynchronous processes will be started
1163 in a short time frame. In those cases it is recommended to
1164 let-bind this variable."
1165 :group 'tramp
1166 :version "24.4"
1167 :type '(choice (const nil) integer)
1168 :require 'tramp)
1170 (defcustom tramp-completion-reread-directory-timeout 10
1171 "Defines seconds since last remote command before rereading a directory.
1172 A remote directory might have changed its contents. In order to
1173 make it visible during file name completion in the minibuffer,
1174 Tramp flushes its cache and rereads the directory contents when
1175 more than `tramp-completion-reread-directory-timeout' seconds
1176 have been gone since last remote command execution. A value of t
1177 would require an immediate reread during filename completion, nil
1178 means to use always cached values for the directory contents."
1179 :group 'tramp
1180 :type '(choice (const nil) (const t) integer)
1181 :require 'tramp)
1183 ;;; Internal Variables:
1185 (defvar tramp-current-method nil
1186 "Connection method for this *tramp* buffer.")
1188 (defvar tramp-current-user nil
1189 "Remote login name for this *tramp* buffer.")
1191 (defvar tramp-current-domain nil
1192 "Remote domain name for this *tramp* buffer.")
1194 (defvar tramp-current-host nil
1195 "Remote host for this *tramp* buffer.")
1197 (defvar tramp-current-port nil
1198 "Remote port for this *tramp* buffer.")
1200 (defvar tramp-current-connection nil
1201 "Last connection timestamp.")
1203 (defconst tramp-completion-file-name-handler-alist
1204 '((file-name-all-completions
1205 . tramp-completion-handle-file-name-all-completions)
1206 (file-name-completion . tramp-completion-handle-file-name-completion))
1207 "Alist of completion handler functions.
1208 Used for file names matching `tramp-completion-file-name-regexp'.
1209 Operations not mentioned here will be handled by Tramp's file
1210 name handler functions, or the normal Emacs functions.")
1212 ;; Handlers for foreign methods, like FTP or SMB, shall be plugged here.
1213 ;;;###tramp-autoload
1214 (defvar tramp-foreign-file-name-handler-alist nil
1215 "Alist of elements (FUNCTION . HANDLER) for foreign methods handled specially.
1216 If (FUNCTION FILENAME) returns non-nil, then all I/O on that file is done by
1217 calling HANDLER.")
1219 ;;; Internal functions which must come first:
1221 ;; Conversion functions between external representation and
1222 ;; internal data structure. Convenience functions for internal
1223 ;; data structure.
1225 ;; The basic structure for remote file names. We use a list :type,
1226 ;; in order to be compatible with Emacs 24 and 25.
1227 (cl-defstruct (tramp-file-name (:type list) :named)
1228 method user domain host port localname hop)
1230 (defun tramp-file-name-user-domain (vec)
1231 "Return user and domain components of VEC."
1232 (when (or (tramp-file-name-user vec) (tramp-file-name-domain vec))
1233 (concat (tramp-file-name-user vec)
1234 (and (tramp-file-name-domain vec)
1235 tramp-prefix-domain-format)
1236 (tramp-file-name-domain vec))))
1238 (defun tramp-file-name-host-port (vec)
1239 "Return host and port components of VEC."
1240 (when (or (tramp-file-name-host vec) (tramp-file-name-port vec))
1241 (concat (tramp-file-name-host vec)
1242 (and (tramp-file-name-port vec)
1243 tramp-prefix-port-format)
1244 (tramp-file-name-port vec))))
1246 (defun tramp-file-name-port-or-default (vec)
1247 "Return port component of VEC.
1248 If nil, return `tramp-default-port'."
1249 (or (tramp-file-name-port vec)
1250 (tramp-get-method-parameter vec 'tramp-default-port)))
1252 (defun tramp-file-name-equal-p (vec1 vec2)
1253 "Check, whether VEC1 and VEC2 denote the same `tramp-file-name'."
1254 (and (tramp-file-name-p vec1) (tramp-file-name-p vec2)
1255 (string-equal (tramp-file-name-method vec1)
1256 (tramp-file-name-method vec2))
1257 (string-equal (tramp-file-name-user-domain vec1)
1258 (tramp-file-name-user-domain vec2))
1259 (string-equal (tramp-file-name-host-port vec1)
1260 (tramp-file-name-host-port vec2))))
1262 (defun tramp-get-method-parameter (vec param)
1263 "Return the method parameter PARAM.
1264 If VEC is a vector, check first in connection properties.
1265 Afterwards, check in `tramp-methods'. If the `tramp-methods'
1266 entry does not exist, return nil."
1267 (let ((hash-entry
1268 (replace-regexp-in-string "^tramp-" "" (symbol-name param))))
1269 (if (tramp-connection-property-p vec hash-entry)
1270 ;; We use the cached property.
1271 (tramp-get-connection-property vec hash-entry nil)
1272 ;; Use the static value from `tramp-methods'.
1273 (let ((methods-entry
1274 (assoc param (assoc (tramp-file-name-method vec) tramp-methods))))
1275 (when methods-entry (cadr methods-entry))))))
1277 ;; The localname can be quoted with "/:". Extract this.
1278 (defun tramp-file-name-unquote-localname (vec)
1279 "Return unquoted localname component of VEC."
1280 (tramp-compat-file-name-unquote (tramp-file-name-localname vec)))
1282 ;;;###tramp-autoload
1283 (defun tramp-tramp-file-p (name)
1284 "Return t if NAME is a string with Tramp file name syntax."
1285 (and (stringp name)
1286 ;; No "/:" and "/c:". This is not covered by `tramp-file-name-regexp'.
1287 (not (string-match-p
1288 (if (memq system-type '(cygwin windows-nt))
1289 "^/[[:alpha:]]?:" "^/:")
1290 name))
1291 (string-match-p tramp-file-name-regexp name)
1294 (defun tramp-find-method (method user host)
1295 "Return the right method string to use.
1296 This is METHOD, if non-nil. Otherwise, do a lookup in
1297 `tramp-default-method-alist'."
1298 (when (and method
1299 (or (string-equal method "")
1300 (string-equal method tramp-default-method-marker)))
1301 (setq method nil))
1302 (let ((result
1303 (or method
1304 (let ((choices tramp-default-method-alist)
1305 lmethod item)
1306 (while choices
1307 (setq item (pop choices))
1308 (when (and (string-match (or (nth 0 item) "") (or host ""))
1309 (string-match (or (nth 1 item) "") (or user "")))
1310 (setq lmethod (nth 2 item))
1311 (setq choices nil)))
1312 lmethod)
1313 tramp-default-method)))
1314 ;; We must mark, whether a default value has been used.
1315 (if (or method (null result))
1316 result
1317 (propertize result 'tramp-default t))))
1319 (defun tramp-find-user (method user host)
1320 "Return the right user string to use.
1321 This is USER, if non-nil. Otherwise, do a lookup in
1322 `tramp-default-user-alist'."
1323 (let ((result
1324 (or user
1325 (let ((choices tramp-default-user-alist)
1326 luser item)
1327 (while choices
1328 (setq item (pop choices))
1329 (when (and (string-match (or (nth 0 item) "") (or method ""))
1330 (string-match (or (nth 1 item) "") (or host "")))
1331 (setq luser (nth 2 item))
1332 (setq choices nil)))
1333 luser)
1334 tramp-default-user)))
1335 ;; We must mark, whether a default value has been used.
1336 (if (or user (null result))
1337 result
1338 (propertize result 'tramp-default t))))
1340 (defun tramp-find-host (method user host)
1341 "Return the right host string to use.
1342 This is HOST, if non-nil. Otherwise, it is `tramp-default-host'."
1343 (or (and (> (length host) 0) host)
1344 (let ((choices tramp-default-host-alist)
1345 lhost item)
1346 (while choices
1347 (setq item (pop choices))
1348 (when (and (string-match (or (nth 0 item) "") (or method ""))
1349 (string-match (or (nth 1 item) "") (or user "")))
1350 (setq lhost (nth 2 item))
1351 (setq choices nil)))
1352 lhost)
1353 tramp-default-host))
1355 (defun tramp-dissect-file-name (name &optional nodefault)
1356 "Return a `tramp-file-name' structure.
1357 The structure consists of remote method, remote user, remote host,
1358 localname (file name on remote host) and hop. If NODEFAULT is
1359 non-nil, the file name parts are not expanded to their default
1360 values."
1361 (save-match-data
1362 (unless (tramp-tramp-file-p name)
1363 (tramp-compat-user-error nil "Not a Tramp file name: \"%s\"" name))
1364 (if (not (string-match (nth 0 tramp-file-name-structure) name))
1365 (error "`tramp-file-name-structure' didn't match!")
1366 (let ((method (match-string (nth 1 tramp-file-name-structure) name))
1367 (user (match-string (nth 2 tramp-file-name-structure) name))
1368 (host (match-string (nth 3 tramp-file-name-structure) name))
1369 (localname (match-string (nth 4 tramp-file-name-structure) name))
1370 (hop (match-string (nth 5 tramp-file-name-structure) name))
1371 domain port)
1372 (when user
1373 (when (string-match tramp-user-with-domain-regexp user)
1374 (setq domain (match-string 2 user)
1375 user (match-string 1 user))))
1377 (when host
1378 (when (string-match tramp-host-with-port-regexp host)
1379 (setq port (match-string 2 host)
1380 host (match-string 1 host)))
1381 (when (string-match tramp-prefix-ipv6-regexp host)
1382 (setq host (replace-match "" nil t host)))
1383 (when (string-match tramp-postfix-ipv6-regexp host)
1384 (setq host (replace-match "" nil t host))))
1386 (unless nodefault
1387 (setq method (tramp-find-method method user host)
1388 user (tramp-find-user method user host)
1389 host (tramp-find-host method user host)))
1391 (make-tramp-file-name
1392 :method method :user user :domain domain :host host :port port
1393 :localname (or localname "") :hop hop)))))
1395 (defun tramp-buffer-name (vec)
1396 "A name for the connection buffer VEC."
1397 (let ((method (tramp-file-name-method vec))
1398 (user-domain (tramp-file-name-user-domain vec))
1399 (host-port (tramp-file-name-host-port vec)))
1400 (if (not (zerop (length user-domain)))
1401 (format "*tramp/%s %s@%s*" method user-domain host-port)
1402 (format "*tramp/%s %s*" method host-port))))
1404 (defun tramp-make-tramp-file-name
1405 (method user domain host port localname &optional hop)
1406 "Constructs a Tramp file name from METHOD, USER, HOST and LOCALNAME.
1407 When not nil, optional DOMAIN, PORT and HOP are used."
1408 (concat tramp-prefix-format hop
1409 (unless (or (zerop (length method))
1410 (zerop (length tramp-postfix-method-format)))
1411 (concat method tramp-postfix-method-format))
1412 user
1413 (unless (zerop (length domain))
1414 (concat tramp-prefix-domain-format domain))
1415 (unless (zerop (length user))
1416 tramp-postfix-user-format)
1417 (when host
1418 (if (string-match tramp-ipv6-regexp host)
1419 (concat tramp-prefix-ipv6-format host tramp-postfix-ipv6-format)
1420 host))
1421 (unless (zerop (length port))
1422 (concat tramp-prefix-port-format port))
1423 tramp-postfix-host-format
1424 (when localname localname)))
1426 (defun tramp-completion-make-tramp-file-name (method user host localname)
1427 "Constructs a Tramp file name from METHOD, USER, HOST and LOCALNAME.
1428 It must not be a complete Tramp file name, but as long as there are
1429 necessary only. This function will be used in file name completion."
1430 (concat tramp-prefix-format
1431 (unless (or (zerop (length method))
1432 (zerop (length tramp-postfix-method-format)))
1433 (concat method tramp-postfix-method-format))
1434 (unless (zerop (length user))
1435 (concat user tramp-postfix-user-format))
1436 (unless (zerop (length host))
1437 (concat
1438 (if (string-match tramp-ipv6-regexp host)
1439 (concat
1440 tramp-prefix-ipv6-format host tramp-postfix-ipv6-format)
1441 host)
1442 tramp-postfix-host-format))
1443 (when localname localname)))
1445 (defun tramp-get-buffer (vec)
1446 "Get the connection buffer to be used for VEC."
1447 (or (get-buffer (tramp-buffer-name vec))
1448 (with-current-buffer (get-buffer-create (tramp-buffer-name vec))
1449 ;; We use the existence of connection property "process-buffer"
1450 ;; as indication, whether a connection is active.
1451 (tramp-set-connection-property
1452 vec "process-buffer"
1453 (tramp-get-connection-property vec "process-buffer" nil))
1454 (setq buffer-undo-list t)
1455 (setq default-directory
1456 (tramp-make-tramp-file-name
1457 (tramp-file-name-method vec)
1458 (tramp-file-name-user vec)
1459 (tramp-file-name-domain vec)
1460 (tramp-file-name-host vec)
1461 (tramp-file-name-port vec)
1462 "/"))
1463 (current-buffer))))
1465 (defun tramp-get-connection-buffer (vec)
1466 "Get the connection buffer to be used for VEC.
1467 In case a second asynchronous communication has been started, it is different
1468 from `tramp-get-buffer'."
1469 (or (tramp-get-connection-property vec "process-buffer" nil)
1470 (tramp-get-buffer vec)))
1472 (defun tramp-get-connection-name (vec)
1473 "Get the connection name to be used for VEC.
1474 In case a second asynchronous communication has been started, it is different
1475 from the default one."
1476 (or (tramp-get-connection-property vec "process-name" nil)
1477 (tramp-buffer-name vec)))
1479 (defun tramp-get-connection-process (vec)
1480 "Get the connection process to be used for VEC.
1481 In case a second asynchronous communication has been started, it is different
1482 from the default one."
1483 (and (tramp-file-name-p vec) (get-process (tramp-get-connection-name vec))))
1485 (defun tramp-set-connection-local-variables (vec)
1486 "Set connection-local variables in the connection buffer used for VEC.
1487 If connection-local variables are not supported by this Emacs
1488 version, the function does nothing."
1489 (with-current-buffer (tramp-get-connection-buffer vec)
1490 ;; `hack-connection-local-variables-apply' exists since Emacs 26.1.
1491 (tramp-compat-funcall
1492 'hack-connection-local-variables-apply
1493 `(:application tramp
1494 :protocol ,(tramp-file-name-method vec)
1495 :user ,(tramp-file-name-user-domain vec)
1496 :machine ,(tramp-file-name-host-port vec)))))
1498 (defun tramp-set-connection-local-variables-for-buffer ()
1499 "Set connection-local variables in the current buffer.
1500 If connection-local variables are not supported by this Emacs
1501 version, the function does nothing."
1502 (when (file-remote-p default-directory)
1503 ;; `hack-connection-local-variables-apply' exists since Emacs 26.1.
1504 (tramp-compat-funcall
1505 'hack-connection-local-variables-apply
1506 `(:application tramp
1507 :protocol ,(file-remote-p default-directory 'method)
1508 :user ,(file-remote-p default-directory 'user)
1509 :machine ,(file-remote-p default-directory 'host)))))
1511 (defun tramp-debug-buffer-name (vec)
1512 "A name for the debug buffer for VEC."
1513 (let ((method (tramp-file-name-method vec))
1514 (user-domain (tramp-file-name-user-domain vec))
1515 (host-port (tramp-file-name-host-port vec)))
1516 (if (not (zerop (length user-domain)))
1517 (format "*debug tramp/%s %s@%s*" method user-domain host-port)
1518 (format "*debug tramp/%s %s*" method host-port))))
1520 (defconst tramp-debug-outline-regexp
1521 "[0-9]+:[0-9]+:[0-9]+\\.[0-9]+ [a-z0-9-]+ (\\([0-9]+\\)) #"
1522 "Used for highlighting Tramp debug buffers in `outline-mode'.")
1524 (defun tramp-debug-outline-level ()
1525 "Return the depth to which a statement is nested in the outline.
1526 Point must be at the beginning of a header line.
1528 The outline level is equal to the verbosity of the Tramp message."
1529 (1+ (string-to-number (match-string 1))))
1531 (defun tramp-get-debug-buffer (vec)
1532 "Get the debug buffer for VEC."
1533 (with-current-buffer
1534 (get-buffer-create (tramp-debug-buffer-name vec))
1535 (when (bobp)
1536 (setq buffer-undo-list t)
1537 ;; So it does not get loaded while `outline-regexp' is let-bound.
1538 (require 'outline)
1539 ;; Activate `outline-mode'. This runs `text-mode-hook' and
1540 ;; `outline-mode-hook'. We must prevent that local processes
1541 ;; die. Yes: I've seen `flyspell-mode', which starts "ispell".
1542 ;; Furthermore, `outline-regexp' must have the correct value
1543 ;; already, because it is used by `font-lock-compile-keywords'.
1544 (let ((default-directory (tramp-compat-temporary-file-directory))
1545 (outline-regexp tramp-debug-outline-regexp))
1546 (outline-mode))
1547 (set (make-local-variable 'outline-regexp) tramp-debug-outline-regexp)
1548 (set (make-local-variable 'outline-level) 'tramp-debug-outline-level))
1549 (current-buffer)))
1551 (defsubst tramp-debug-message (vec fmt-string &rest arguments)
1552 "Append message to debug buffer.
1553 Message is formatted with FMT-STRING as control string and the remaining
1554 ARGUMENTS to actually emit the message (if applicable)."
1555 (with-current-buffer (tramp-get-debug-buffer vec)
1556 (goto-char (point-max))
1557 ;; Headline.
1558 (when (bobp)
1559 (insert
1560 (format
1561 ";; Emacs: %s Tramp: %s -*- mode: outline; -*-"
1562 emacs-version tramp-version))
1563 (when (>= tramp-verbose 10)
1564 (insert
1565 (format
1566 "\n;; Location: %s Git: %s"
1567 (locate-library "tramp") (tramp-repository-get-version)))))
1568 (unless (bolp)
1569 (insert "\n"))
1570 ;; Timestamp.
1571 (let ((now (current-time)))
1572 (insert (format-time-string "%T." now))
1573 (insert (format "%06d " (nth 2 now))))
1574 ;; Calling Tramp function. We suppress compat and trace functions
1575 ;; from being displayed.
1576 (let ((btn 1) btf fn)
1577 (while (not fn)
1578 (setq btf (nth 1 (backtrace-frame btn)))
1579 (if (not btf)
1580 (setq fn "")
1581 (when (symbolp btf)
1582 (setq fn (symbol-name btf))
1583 (unless
1584 (and
1585 (string-match "^tramp" fn)
1586 (not
1587 (string-match
1588 (concat
1590 (regexp-opt
1591 '("tramp-backtrace"
1592 "tramp-compat-funcall"
1593 "tramp-compat-user-error"
1594 "tramp-condition-case-unless-debug"
1595 "tramp-debug-message"
1596 "tramp-error"
1597 "tramp-error-with-buffer"
1598 "tramp-message")
1600 "$")
1601 fn)))
1602 (setq fn nil)))
1603 (setq btn (1+ btn))))
1604 ;; The following code inserts filename and line number. Should
1605 ;; be inactive by default, because it is time consuming.
1606 ; (let ((ffn (find-function-noselect (intern fn))))
1607 ; (insert
1608 ; (format
1609 ; "%s:%d: "
1610 ; (file-name-nondirectory (buffer-file-name (car ffn)))
1611 ; (with-current-buffer (car ffn)
1612 ; (1+ (count-lines (point-min) (cdr ffn)))))))
1613 (insert (format "%s " fn)))
1614 ;; The message.
1615 (insert (apply #'format-message fmt-string arguments))))
1617 (defvar tramp-message-show-message t
1618 "Show Tramp message in the minibuffer.
1619 This variable is used to disable messages from `tramp-error'.
1620 The messages are visible anyway, because an error is raised.")
1622 (defsubst tramp-message (vec-or-proc level fmt-string &rest arguments)
1623 "Emit a message depending on verbosity level.
1624 VEC-OR-PROC identifies the Tramp buffer to use. It can be either a
1625 vector or a process. LEVEL says to be quiet if `tramp-verbose' is
1626 less than LEVEL. The message is emitted only if `tramp-verbose' is
1627 greater than or equal to LEVEL.
1629 The message is also logged into the debug buffer when `tramp-verbose'
1630 is greater than or equal 4.
1632 Calls functions `message' and `tramp-debug-message' with FMT-STRING as
1633 control string and the remaining ARGUMENTS to actually emit the message (if
1634 applicable)."
1635 (ignore-errors
1636 (when (<= level tramp-verbose)
1637 ;; Match data must be preserved!
1638 (save-match-data
1639 ;; Display only when there is a minimum level.
1640 (when (and tramp-message-show-message (<= level 3))
1641 (apply 'message
1642 (concat
1643 (cond
1644 ((= level 0) "")
1645 ((= level 1) "")
1646 ((= level 2) "Warning: ")
1647 (t "Tramp: "))
1648 fmt-string)
1649 arguments))
1650 ;; Log only when there is a minimum level.
1651 (when (>= tramp-verbose 4)
1652 ;; Translate proc to vec.
1653 (when (processp vec-or-proc)
1654 (let ((tramp-verbose 0))
1655 (setq vec-or-proc
1656 (tramp-get-connection-property vec-or-proc "vector" nil))))
1657 ;; Append connection buffer for error messages.
1658 (when (= level 1)
1659 (let ((tramp-verbose 0))
1660 (with-current-buffer (tramp-get-connection-buffer vec-or-proc)
1661 (setq fmt-string (concat fmt-string "\n%s")
1662 arguments (append arguments (list (buffer-string)))))))
1663 ;; Do it.
1664 (when (tramp-file-name-p vec-or-proc)
1665 (apply 'tramp-debug-message
1666 vec-or-proc
1667 (concat (format "(%d) # " level) fmt-string)
1668 arguments)))))))
1670 (defsubst tramp-backtrace (&optional vec-or-proc)
1671 "Dump a backtrace into the debug buffer.
1672 If VEC-OR-PROC is nil, the buffer *debug tramp* is used. This
1673 function is meant for debugging purposes."
1674 (if vec-or-proc
1675 (tramp-message vec-or-proc 10 "\n%s" (with-output-to-string (backtrace)))
1676 (if (>= tramp-verbose 10)
1677 (with-output-to-temp-buffer "*debug tramp*" (backtrace)))))
1679 (defsubst tramp-error (vec-or-proc signal fmt-string &rest arguments)
1680 "Emit an error.
1681 VEC-OR-PROC identifies the connection to use, SIGNAL is the
1682 signal identifier to be raised, remaining arguments passed to
1683 `tramp-message'. Finally, signal SIGNAL is raised."
1684 (let (tramp-message-show-message)
1685 (tramp-backtrace vec-or-proc)
1686 (unless arguments
1687 ;; FMT-STRING could be just a file name, as in
1688 ;; `file-already-exists' errors. It could contain the ?\%
1689 ;; character, as in smb domain spec.
1690 (setq arguments (list fmt-string)
1691 fmt-string "%s"))
1692 (when vec-or-proc
1693 (tramp-message
1694 vec-or-proc 1 "%s"
1695 (error-message-string
1696 (list signal
1697 (get signal 'error-message)
1698 (apply #'format-message fmt-string arguments)))))
1699 (signal signal (list (apply #'format-message fmt-string arguments)))))
1701 (defsubst tramp-error-with-buffer
1702 (buf vec-or-proc signal fmt-string &rest arguments)
1703 "Emit an error, and show BUF.
1704 If BUF is nil, show the connection buf. Wait for 30\", or until
1705 an input event arrives. The other arguments are passed to `tramp-error'."
1706 (save-window-excursion
1707 (let* ((buf (or (and (bufferp buf) buf)
1708 (and (processp vec-or-proc) (process-buffer vec-or-proc))
1709 (and (tramp-file-name-p vec-or-proc)
1710 (tramp-get-connection-buffer vec-or-proc))))
1711 (vec (or (and (tramp-file-name-p vec-or-proc) vec-or-proc)
1712 (and buf (with-current-buffer buf
1713 (tramp-dissect-file-name default-directory))))))
1714 (unwind-protect
1715 (apply 'tramp-error vec-or-proc signal fmt-string arguments)
1716 ;; Save exit.
1717 (when (and buf
1718 tramp-message-show-message
1719 (not (zerop tramp-verbose))
1720 ;; Do not show when flagged from outside.
1721 (not (tramp-completion-mode-p))
1722 ;; Show only when Emacs has started already.
1723 (current-message))
1724 (let ((enable-recursive-minibuffers t))
1725 ;; `tramp-error' does not show messages. So we must do it
1726 ;; ourselves.
1727 (apply 'message fmt-string arguments)
1728 ;; Show buffer.
1729 (pop-to-buffer buf)
1730 (discard-input)
1731 (sit-for 30)))
1732 ;; Reset timestamp. It would be wrong after waiting for a while.
1733 (when (tramp-file-name-equal-p vec (car tramp-current-connection))
1734 (setcdr tramp-current-connection (current-time)))))))
1736 (defmacro tramp-with-demoted-errors (vec-or-proc format &rest body)
1737 "Execute BODY while redirecting the error message to `tramp-message'.
1738 BODY is executed like wrapped by `with-demoted-errors'. FORMAT
1739 is a format-string containing a %-sequence meaning to substitute
1740 the resulting error message."
1741 (declare (debug (symbolp body))
1742 (indent 2))
1743 (let ((err (make-symbol "err")))
1744 `(condition-case-unless-debug ,err
1745 (progn ,@body)
1746 (error (tramp-message ,vec-or-proc 3 ,format ,err) nil))))
1748 (defmacro with-parsed-tramp-file-name (filename var &rest body)
1749 "Parse a Tramp filename and make components available in the body.
1751 First arg FILENAME is evaluated and dissected into its components.
1752 Second arg VAR is a symbol. It is used as a variable name to hold
1753 the filename structure. It is also used as a prefix for the variables
1754 holding the components. For example, if VAR is the symbol `foo', then
1755 `foo' will be bound to the whole structure, `foo-method' will be bound to
1756 the method component, and so on for `foo-user', `foo-domain', `foo-host',
1757 `foo-port', `foo-localname', `foo-hop'.
1759 Remaining args are Lisp expressions to be evaluated (inside an implicit
1760 `progn').
1762 If VAR is nil, then we bind `v' to the structure and `method', `user',
1763 `domain', `host', `port', `localname', `hop' to the components."
1764 (let ((bindings
1765 (mapcar (lambda (elem)
1766 `(,(if var (intern (format "%s-%s" var elem)) elem)
1767 (,(intern (format "tramp-file-name-%s" elem))
1768 ,(or var 'v))))
1769 `,(tramp-compat-tramp-file-name-slots))))
1770 `(let* ((,(or var 'v) (tramp-dissect-file-name ,filename))
1771 ,@bindings)
1772 ;; We don't know which of those vars will be used, so we bind them all,
1773 ;; and then add here a dummy use of all those variables, so we don't get
1774 ;; flooded by warnings about those vars `body' didn't use.
1775 (ignore ,@(mapcar #'car bindings))
1776 ,@body)))
1778 (put 'with-parsed-tramp-file-name 'lisp-indent-function 2)
1779 (put 'with-parsed-tramp-file-name 'edebug-form-spec '(form symbolp body))
1780 (font-lock-add-keywords 'emacs-lisp-mode '("\\<with-parsed-tramp-file-name\\>"))
1782 (defun tramp-progress-reporter-update (reporter &optional value)
1783 "Report progress of an operation for Tramp."
1784 (let* ((parameters (cdr reporter))
1785 (message (aref parameters 3)))
1786 (when (string-match message (or (current-message) ""))
1787 (progress-reporter-update reporter value))))
1789 (defmacro with-tramp-progress-reporter (vec level message &rest body)
1790 "Executes BODY, spinning a progress reporter with MESSAGE.
1791 If LEVEL does not fit for visible messages, there are only traces
1792 without a visible progress reporter."
1793 (declare (indent 3) (debug t))
1794 `(progn
1795 (tramp-message ,vec ,level "%s..." ,message)
1796 (let ((cookie "failed")
1798 ;; We start a pulsing progress reporter after 3 seconds.
1799 (when (and tramp-message-show-message
1800 ;; Display only when there is a minimum level.
1801 (<= ,level (min tramp-verbose 3)))
1802 (let ((pr (make-progress-reporter ,message nil nil)))
1803 (when pr
1804 (run-at-time
1805 3 0.1 #'tramp-progress-reporter-update pr))))))
1806 (unwind-protect
1807 ;; Execute the body.
1808 (prog1 (progn ,@body) (setq cookie "done"))
1809 ;; Stop progress reporter.
1810 (if tm (cancel-timer tm))
1811 (tramp-message ,vec ,level "%s...%s" ,message cookie)))))
1813 (font-lock-add-keywords
1814 'emacs-lisp-mode '("\\<with-tramp-progress-reporter\\>"))
1816 (defmacro with-tramp-file-property (vec file property &rest body)
1817 "Check in Tramp cache for PROPERTY, otherwise execute BODY and set cache.
1818 FILE must be a local file name on a connection identified via VEC."
1819 `(if (file-name-absolute-p ,file)
1820 (let ((value (tramp-get-file-property ,vec ,file ,property 'undef)))
1821 (when (eq value 'undef)
1822 ;; We cannot pass @body as parameter to
1823 ;; `tramp-set-file-property' because it mangles our
1824 ;; debug messages.
1825 (setq value (progn ,@body))
1826 (tramp-set-file-property ,vec ,file ,property value))
1827 value)
1828 ,@body))
1830 (put 'with-tramp-file-property 'lisp-indent-function 3)
1831 (put 'with-tramp-file-property 'edebug-form-spec t)
1832 (font-lock-add-keywords 'emacs-lisp-mode '("\\<with-tramp-file-property\\>"))
1834 (defmacro with-tramp-connection-property (key property &rest body)
1835 "Check in Tramp for property PROPERTY, otherwise executes BODY and set."
1836 `(let ((value (tramp-get-connection-property ,key ,property 'undef)))
1837 (when (eq value 'undef)
1838 ;; We cannot pass ,@body as parameter to
1839 ;; `tramp-set-connection-property' because it mangles our debug
1840 ;; messages.
1841 (setq value (progn ,@body))
1842 (tramp-set-connection-property ,key ,property value))
1843 value))
1845 (put 'with-tramp-connection-property 'lisp-indent-function 2)
1846 (put 'with-tramp-connection-property 'edebug-form-spec t)
1847 (font-lock-add-keywords
1848 'emacs-lisp-mode '("\\<with-tramp-connection-property\\>"))
1850 (defun tramp-drop-volume-letter (name)
1851 "Cut off unnecessary drive letter from file NAME.
1852 The functions `tramp-*-handle-expand-file-name' call `expand-file-name'
1853 locally on a remote file name. When the local system is a W32 system
1854 but the remote system is Unix, this introduces a superfluous drive
1855 letter into the file name. This function removes it."
1856 (save-match-data
1857 (funcall
1858 (if (tramp-compat-file-name-quoted-p name)
1859 'tramp-compat-file-name-quote 'identity)
1860 (let ((name (tramp-compat-file-name-unquote name)))
1861 (if (string-match "\\`[a-zA-Z]:/" name)
1862 (replace-match "/" nil t name)
1863 name)))))
1865 ;;; Config Manipulation Functions:
1867 ;;;###tramp-autoload
1868 (defun tramp-set-completion-function (method function-list)
1869 "Sets the list of completion functions for METHOD.
1870 FUNCTION-LIST is a list of entries of the form (FUNCTION FILE).
1871 The FUNCTION is intended to parse FILE according its syntax.
1872 It might be a predefined FUNCTION, or a user defined FUNCTION.
1873 For the list of predefined FUNCTIONs see `tramp-completion-function-alist'.
1875 Example:
1877 (tramp-set-completion-function
1878 \"ssh\"
1879 \\='((tramp-parse-sconfig \"/etc/ssh_config\")
1880 (tramp-parse-sconfig \"~/.ssh/config\")))"
1882 (let ((r function-list)
1883 (v function-list))
1884 (setq tramp-completion-function-alist
1885 (delete (assoc method tramp-completion-function-alist)
1886 tramp-completion-function-alist))
1888 (while v
1889 ;; Remove double entries.
1890 (when (member (car v) (cdr v))
1891 (setcdr v (delete (car v) (cdr v))))
1892 ;; Check for function and file or registry key.
1893 (unless (and (functionp (nth 0 (car v)))
1894 (cond
1895 ;; Windows registry.
1896 ((string-match "^HKEY_CURRENT_USER" (nth 1 (car v)))
1897 (and (memq system-type '(cygwin windows-nt))
1898 (zerop
1899 (tramp-call-process
1900 v "reg" nil nil nil "query" (nth 1 (car v))))))
1901 ;; Zeroconf service type.
1902 ((string-match
1903 "^_[[:alpha:]]+\\._[[:alpha:]]+$" (nth 1 (car v))))
1904 ;; Configuration file.
1905 (t (file-exists-p (nth 1 (car v))))))
1906 (setq r (delete (car v) r)))
1907 (setq v (cdr v)))
1909 (when r
1910 (add-to-list 'tramp-completion-function-alist
1911 (cons method r)))))
1913 (defun tramp-get-completion-function (method)
1914 "Returns a list of completion functions for METHOD.
1915 For definition of that list see `tramp-set-completion-function'."
1916 (append
1917 `(;; Default settings are taken into account.
1918 (tramp-parse-default-user-host ,method)
1919 ;; Hosts visited once shall be remembered.
1920 (tramp-parse-connection-properties ,method))
1921 ;; The method related defaults.
1922 (cdr (assoc method tramp-completion-function-alist))))
1925 ;;; Fontification of `read-file-name':
1927 (defvar tramp-rfn-eshadow-overlay)
1928 (make-variable-buffer-local 'tramp-rfn-eshadow-overlay)
1930 (defun tramp-rfn-eshadow-setup-minibuffer ()
1931 "Set up a minibuffer for `file-name-shadow-mode'.
1932 Adds another overlay hiding filename parts according to Tramp's
1933 special handling of `substitute-in-file-name'."
1934 (when (symbol-value 'minibuffer-completing-file-name)
1935 (setq tramp-rfn-eshadow-overlay
1936 (make-overlay (minibuffer-prompt-end) (minibuffer-prompt-end)))
1937 ;; Copy rfn-eshadow-overlay properties.
1938 (let ((props (overlay-properties (symbol-value 'rfn-eshadow-overlay))))
1939 (while props
1940 ;; The `field' property prevents correct minibuffer
1941 ;; completion; we exclude it.
1942 (if (not (eq (car props) 'field))
1943 (overlay-put tramp-rfn-eshadow-overlay (pop props) (pop props))
1944 (pop props) (pop props))))))
1946 (add-hook 'rfn-eshadow-setup-minibuffer-hook
1947 'tramp-rfn-eshadow-setup-minibuffer)
1948 (add-hook 'tramp-unload-hook
1949 (lambda ()
1950 (remove-hook 'rfn-eshadow-setup-minibuffer-hook
1951 'tramp-rfn-eshadow-setup-minibuffer)))
1953 (defun tramp-rfn-eshadow-update-overlay-regexp ()
1954 (format "[^%s/~]*\\(/\\|~\\)" tramp-postfix-host-format))
1956 (defun tramp-rfn-eshadow-update-overlay ()
1957 "Update `rfn-eshadow-overlay' to cover shadowed part of minibuffer input.
1958 This is intended to be used as a minibuffer `post-command-hook' for
1959 `file-name-shadow-mode'; the minibuffer should have already
1960 been set up by `rfn-eshadow-setup-minibuffer'."
1961 ;; In remote files name, there is a shadowing just for the local part.
1962 (ignore-errors
1963 (let ((end (or (overlay-end (symbol-value 'rfn-eshadow-overlay))
1964 (minibuffer-prompt-end)))
1965 ;; We do not want to send any remote command.
1966 (non-essential t))
1967 (when
1968 (tramp-tramp-file-p
1969 (buffer-substring-no-properties end (point-max)))
1970 (save-excursion
1971 (save-restriction
1972 (narrow-to-region
1973 (1+ (or (string-match
1974 (tramp-rfn-eshadow-update-overlay-regexp)
1975 (buffer-string) end)
1976 end))
1977 (point-max))
1978 (let ((rfn-eshadow-overlay tramp-rfn-eshadow-overlay)
1979 (rfn-eshadow-update-overlay-hook nil)
1980 file-name-handler-alist)
1981 (move-overlay rfn-eshadow-overlay (point-max) (point-max))
1982 (rfn-eshadow-update-overlay))))))))
1984 (add-hook 'rfn-eshadow-update-overlay-hook
1985 'tramp-rfn-eshadow-update-overlay)
1986 (add-hook 'tramp-unload-hook
1987 (lambda ()
1988 (remove-hook 'rfn-eshadow-update-overlay-hook
1989 'tramp-rfn-eshadow-update-overlay)))
1991 ;; Inodes don't exist for some file systems. Therefore we must
1992 ;; generate virtual ones. Used in `find-buffer-visiting'. The method
1993 ;; applied might be not so efficient (Ange-FTP uses hashes). But
1994 ;; performance isn't the major issue given that file transfer will
1995 ;; take time.
1996 (defvar tramp-inodes 0
1997 "Keeps virtual inodes numbers.")
1999 ;; Devices must distinguish physical file systems. The device numbers
2000 ;; provided by "lstat" aren't unique, because we operate on different hosts.
2001 ;; So we use virtual device numbers, generated by Tramp. Both Ange-FTP and
2002 ;; EFS use device number "-1". In order to be different, we use device number
2003 ;; (-1 . x), whereby "x" is unique for a given (method user host).
2004 (defvar tramp-devices 0
2005 "Keeps virtual device numbers.")
2007 (defun tramp-default-file-modes (filename)
2008 "Return file modes of FILENAME as integer.
2009 If the file modes of FILENAME cannot be determined, return the
2010 value of `default-file-modes', without execute permissions."
2011 (or (file-modes filename)
2012 (logand (default-file-modes) (string-to-number "0666" 8))))
2014 (defun tramp-replace-environment-variables (filename)
2015 "Replace environment variables in FILENAME.
2016 Return the string with the replaced variables."
2017 (or (ignore-errors
2018 ;; Optional arg has been introduced with Emacs 24.4.
2019 (tramp-compat-funcall 'substitute-env-vars filename 'only-defined))
2020 ;; We need an own implementation.
2021 (save-match-data
2022 (let ((idx (string-match "$\\(\\w+\\)" filename)))
2023 ;; `$' is coded as `$$'.
2024 (when (and idx
2025 (or (zerop idx) (not (eq ?$ (aref filename (1- idx)))))
2026 (getenv (match-string 1 filename)))
2027 (setq filename
2028 (replace-match
2029 (substitute-in-file-name (match-string 0 filename))
2030 t nil filename)))
2031 filename))))
2033 (defun tramp-find-file-name-coding-system-alist (filename tmpname)
2034 "Like `find-operation-coding-system' for Tramp filenames.
2035 Tramp's `insert-file-contents' and `write-region' work over
2036 temporary file names. If `file-coding-system-alist' contains an
2037 expression, which matches more than the file name suffix, the
2038 coding system might not be determined. This function repairs it."
2039 (let (result)
2040 (dolist (elt file-coding-system-alist (nreverse result))
2041 (when (and (consp elt) (string-match (car elt) filename))
2042 ;; We found a matching entry in `file-coding-system-alist'.
2043 ;; So we add a similar entry, but with the temporary file name
2044 ;; as regexp.
2045 (push (cons (regexp-quote tmpname) (cdr elt)) result)))))
2047 (defun tramp-run-real-handler (operation args)
2048 "Invoke normal file name handler for OPERATION.
2049 First arg specifies the OPERATION, second arg is a list of arguments to
2050 pass to the OPERATION."
2051 (let* ((inhibit-file-name-handlers
2052 `(tramp-file-name-handler
2053 tramp-vc-file-name-handler
2054 tramp-completion-file-name-handler
2055 cygwin-mount-name-hook-function
2056 cygwin-mount-map-drive-hook-function
2058 ,(and (eq inhibit-file-name-operation operation)
2059 inhibit-file-name-handlers)))
2060 (inhibit-file-name-operation operation))
2061 (apply operation args)))
2063 ;; We handle here all file primitives. Most of them have the file
2064 ;; name as first parameter; nevertheless we check for them explicitly
2065 ;; in order to be signaled if a new primitive appears. This
2066 ;; scenario is needed because there isn't a way to decide by
2067 ;; syntactical means whether a foreign method must be called. It would
2068 ;; ease the life if `file-name-handler-alist' would support a decision
2069 ;; function as well but regexp only.
2070 (defun tramp-file-name-for-operation (operation &rest args)
2071 "Return file name related to OPERATION file primitive.
2072 ARGS are the arguments OPERATION has been called with."
2073 (cond
2074 ;; FILE resp DIRECTORY.
2075 ((member operation
2076 '(access-file byte-compiler-base-file-name delete-directory
2077 delete-file diff-latest-backup-file directory-file-name
2078 directory-files directory-files-and-attributes
2079 dired-compress-file dired-uncache file-acl
2080 file-accessible-directory-p file-attributes
2081 file-directory-p file-executable-p file-exists-p
2082 file-local-copy file-modes file-name-as-directory
2083 file-name-directory file-name-nondirectory
2084 file-name-sans-versions file-notify-add-watch
2085 file-ownership-preserved-p file-readable-p
2086 file-regular-p file-remote-p file-selinux-context
2087 file-symlink-p file-truename file-writable-p
2088 find-backup-file-name find-file-noselect get-file-buffer
2089 insert-directory insert-file-contents load
2090 make-directory make-directory-internal set-file-acl
2091 set-file-modes set-file-selinux-context set-file-times
2092 substitute-in-file-name unhandled-file-name-directory
2093 vc-registered
2094 ;; Emacs 26+ only.
2095 file-name-case-insensitive-p
2096 ;; Emacs 27+ only.
2097 file-system-info))
2098 (if (file-name-absolute-p (nth 0 args))
2099 (nth 0 args)
2100 default-directory))
2101 ;; FILE DIRECTORY resp FILE1 FILE2.
2102 ((member operation
2103 '(add-name-to-file copy-directory copy-file expand-file-name
2104 file-equal-p file-in-directory-p
2105 file-name-all-completions file-name-completion
2106 ;; Starting with Emacs 26.1, just the 2nd argument of
2107 ;; `make-symbolic-link' matters. For backward
2108 ;; compatibility, we still accept the first argument as
2109 ;; file name to be checked. Handled properly in
2110 ;; `tramp-handle-*-make-symbolic-link'.
2111 file-newer-than-file-p make-symbolic-link rename-file))
2112 (save-match-data
2113 (cond
2114 ((tramp-tramp-file-p (nth 0 args)) (nth 0 args))
2115 ((tramp-tramp-file-p (nth 1 args)) (nth 1 args))
2116 (t default-directory))))
2117 ;; START END FILE.
2118 ((eq operation 'write-region)
2119 (if (file-name-absolute-p (nth 2 args))
2120 (nth 2 args)
2121 default-directory))
2122 ;; BUFFER.
2123 ((member operation
2124 '(make-auto-save-file-name
2125 set-visited-file-modtime verify-visited-file-modtime))
2126 (buffer-file-name
2127 (if (bufferp (nth 0 args)) (nth 0 args) (current-buffer))))
2128 ;; COMMAND.
2129 ((member operation
2130 '(process-file shell-command start-file-process
2131 ;; Emacs 26+ only.
2132 make-nearby-temp-file temporary-file-directory))
2133 default-directory)
2134 ;; PROC.
2135 ((member operation
2136 '(file-notify-rm-watch
2137 ;; Emacs 25+ only.
2138 file-notify-valid-p))
2139 (when (processp (nth 0 args))
2140 (with-current-buffer (process-buffer (nth 0 args))
2141 default-directory)))
2142 ;; Unknown file primitive.
2143 (t (error "unknown file I/O primitive: %s" operation))))
2145 (defun tramp-find-foreign-file-name-handler (filename &optional _operation)
2146 "Return foreign file name handler if exists."
2147 (when (tramp-tramp-file-p filename)
2148 (let ((handler tramp-foreign-file-name-handler-alist)
2149 elt res)
2150 (while handler
2151 (setq elt (car handler)
2152 handler (cdr handler))
2153 (when (funcall (car elt) filename)
2154 (setq handler nil
2155 res (cdr elt))))
2156 res)))
2158 (defvar tramp-debug-on-error nil
2159 "Like `debug-on-error' but used Tramp internal.")
2161 (defmacro tramp-condition-case-unless-debug
2162 (var bodyform &rest handlers)
2163 "Like `condition-case-unless-debug' but `tramp-debug-on-error'."
2164 `(let ((debug-on-error tramp-debug-on-error))
2165 (condition-case-unless-debug ,var ,bodyform ,@handlers)))
2167 ;; In Emacs, there is some concurrency due to timers. If a timer
2168 ;; interrupts Tramp and wishes to use the same connection buffer as
2169 ;; the "main" Emacs, then garbage might occur in the connection
2170 ;; buffer. Therefore, we need to make sure that a timer does not use
2171 ;; the same connection buffer as the "main" Emacs. We implement a
2172 ;; cheap global lock, instead of locking each connection buffer
2173 ;; separately. The global lock is based on two variables,
2174 ;; `tramp-locked' and `tramp-locker'. `tramp-locked' is set to true
2175 ;; (with setq) to indicate a lock. But Tramp also calls itself during
2176 ;; processing of a single file operation, so we need to allow
2177 ;; recursive calls. That's where the `tramp-locker' variable comes in
2178 ;; -- it is let-bound to t during the execution of the current
2179 ;; handler. So if `tramp-locked' is t and `tramp-locker' is also t,
2180 ;; then we should just proceed because we have been called
2181 ;; recursively. But if `tramp-locker' is nil, then we are a timer
2182 ;; interrupting the "main" Emacs, and then we signal an error.
2184 (defvar tramp-locked nil
2185 "If non-nil, then Tramp is currently busy.
2186 Together with `tramp-locker', this implements a locking mechanism
2187 preventing reentrant calls of Tramp.")
2189 (defvar tramp-locker nil
2190 "If non-nil, then a caller has locked Tramp.
2191 Together with `tramp-locked', this implements a locking mechanism
2192 preventing reentrant calls of Tramp.")
2194 ;; Main function.
2195 (defun tramp-file-name-handler (operation &rest args)
2196 "Invoke Tramp file name handler.
2197 Falls back to normal file name handler if no Tramp file name handler exists."
2198 (let ((filename (apply 'tramp-file-name-for-operation operation args)))
2199 (if (and tramp-mode (tramp-tramp-file-p filename))
2200 (save-match-data
2201 (setq filename (tramp-replace-environment-variables filename))
2202 (with-parsed-tramp-file-name filename nil
2203 (let ((completion (tramp-completion-mode-p))
2204 (foreign
2205 (tramp-find-foreign-file-name-handler filename operation))
2206 result)
2207 ;; Call the backend function.
2208 (if foreign
2209 (tramp-condition-case-unless-debug err
2210 (let ((sf (symbol-function foreign)))
2211 ;; Some packages set the default directory to a
2212 ;; remote path, before respective Tramp packages
2213 ;; are already loaded. This results in
2214 ;; recursive loading. Therefore, we load the
2215 ;; Tramp packages locally.
2216 (when (autoloadp sf)
2217 (let ((default-directory
2218 (tramp-compat-temporary-file-directory)))
2219 (load (cadr sf) 'noerror 'nomessage)))
2220 ;; If `non-essential' is non-nil, Tramp shall
2221 ;; not open a new connection.
2222 ;; If Tramp detects that it shouldn't continue
2223 ;; to work, it throws the `suppress' event.
2224 ;; This could happen for example, when Tramp
2225 ;; tries to open the same connection twice in a
2226 ;; short time frame.
2227 ;; In both cases, we try the default handler then.
2228 (setq result
2229 (catch 'non-essential
2230 (catch 'suppress
2231 (when (and tramp-locked (not tramp-locker))
2232 (setq tramp-locked nil)
2233 (tramp-error
2234 (car-safe tramp-current-connection)
2235 'file-error
2236 "Forbidden reentrant call of Tramp"))
2237 (let ((tl tramp-locked))
2238 (setq tramp-locked t)
2239 (unwind-protect
2240 (let ((tramp-locker t))
2241 (apply foreign operation args))
2242 (setq tramp-locked tl))))))
2243 (cond
2244 ((eq result 'non-essential)
2245 (tramp-message
2246 v 5 "Non-essential received in operation %s"
2247 (cons operation args))
2248 (tramp-run-real-handler operation args))
2249 ((eq result 'suppress)
2250 (let (tramp-message-show-message)
2251 (tramp-message
2252 v 1 "Suppress received in operation %s"
2253 (cons operation args))
2254 (tramp-cleanup-connection v t)
2255 (tramp-run-real-handler operation args)))
2256 (t result)))
2258 ;; Trace that somebody has interrupted the operation.
2259 ((debug quit)
2260 (let (tramp-message-show-message)
2261 (tramp-message
2262 v 1 "Interrupt received in operation %s"
2263 (cons operation args)))
2264 ;; Propagate the quit signal.
2265 (signal (car err) (cdr err)))
2267 ;; When we are in completion mode, some failed
2268 ;; operations shall return at least a default
2269 ;; value in order to give the user a chance to
2270 ;; correct the file name in the minibuffer.
2271 ;; In order to get a full backtrace, one could apply
2272 ;; (setq tramp-debug-on-error t)
2273 (error
2274 (cond
2275 ((and completion (zerop (length localname))
2276 (memq operation '(file-exists-p file-directory-p)))
2278 ((and completion (zerop (length localname))
2279 (memq operation
2280 '(expand-file-name file-name-as-directory)))
2281 filename)
2282 ;; Propagate the error.
2283 (t (signal (car err) (cdr err))))))
2285 ;; Nothing to do for us. However, since we are in
2286 ;; `tramp-mode', we must suppress the volume letter on
2287 ;; MS Windows.
2288 (setq result (tramp-run-real-handler operation args))
2289 (if (stringp result)
2290 (tramp-drop-volume-letter result)
2291 result)))))
2293 ;; When `tramp-mode' is not enabled, or the file name is quoted,
2294 ;; we don't do anything.
2295 (tramp-run-real-handler operation args))))
2297 (defun tramp-completion-file-name-handler (operation &rest args)
2298 "Invoke Tramp file name completion handler.
2299 Falls back to normal file name handler if no Tramp file name handler exists."
2300 (let ((fn (assoc operation tramp-completion-file-name-handler-alist)))
2301 (if (and fn tramp-mode)
2302 (save-match-data (apply (cdr fn) args))
2303 (tramp-run-real-handler operation args))))
2305 ;;;###autoload
2306 (progn (defun tramp-autoload-file-name-handler (operation &rest args)
2307 "Load Tramp file name handler, and perform OPERATION."
2308 (if tramp-mode
2309 (let ((default-directory temporary-file-directory))
2310 (load "tramp" 'noerror 'nomessage))
2311 (tramp-unload-file-name-handlers))
2312 (apply operation args)))
2314 ;; `tramp-autoload-file-name-handler' must be registered before
2315 ;; evaluation of site-start and init files, because there might exist
2316 ;; remote files already, f.e. files kept via recentf-mode.
2317 ;;;###autoload
2318 (progn (defun tramp-register-autoload-file-name-handlers ()
2319 "Add Tramp file name handlers to `file-name-handler-alist' during autoload."
2320 (add-to-list 'file-name-handler-alist
2321 (cons tramp-autoload-file-name-regexp
2322 'tramp-autoload-file-name-handler))
2323 (put 'tramp-autoload-file-name-handler 'safe-magic t)))
2325 ;;;###autoload (tramp-register-autoload-file-name-handlers)
2327 (defun tramp-use-absolute-autoload-file-names ()
2328 "Change Tramp autoload objects to use absolute file names.
2329 This avoids problems during autoload, when `load-path' contains
2330 remote file names."
2331 ;; We expect all other Tramp files in the same directory as tramp.el.
2332 (let* ((dir (expand-file-name (file-name-directory (locate-library "tramp"))))
2333 (files-regexp
2334 (format
2335 "^%s$"
2336 (regexp-opt
2337 (mapcar
2338 'file-name-sans-extension
2339 (directory-files dir nil "^tramp.+\\.elc?$"))
2340 'paren))))
2341 (mapatoms
2342 (lambda (atom)
2343 (when (and (functionp atom)
2344 (autoloadp (symbol-function atom))
2345 (string-match files-regexp (cadr (symbol-function atom))))
2346 (ignore-errors
2347 (setf (cadr (symbol-function atom))
2348 (expand-file-name (cadr (symbol-function atom)) dir))))))))
2350 (eval-after-load 'tramp (tramp-use-absolute-autoload-file-names))
2352 (defun tramp-register-file-name-handlers ()
2353 "Add Tramp file name handlers to `file-name-handler-alist'."
2354 ;; Remove autoloaded handlers from file name handler alist. Useful,
2355 ;; if `tramp-syntax' has been changed.
2356 (dolist (fnh '(tramp-file-name-handler
2357 tramp-completion-file-name-handler
2358 tramp-autoload-file-name-handler))
2359 (let ((a1 (rassq fnh file-name-handler-alist)))
2360 (setq file-name-handler-alist (delq a1 file-name-handler-alist))))
2362 ;; Add the handlers. We do not add anything to the `operations'
2363 ;; property of `tramp-file-name-handler', this shall be done by the
2364 ;; respective foreign handlers.
2365 (add-to-list 'file-name-handler-alist
2366 (cons tramp-file-name-regexp 'tramp-file-name-handler))
2367 (put 'tramp-file-name-handler 'safe-magic t)
2369 (add-to-list 'file-name-handler-alist
2370 (cons tramp-completion-file-name-regexp
2371 'tramp-completion-file-name-handler))
2372 (put 'tramp-completion-file-name-handler 'safe-magic t)
2373 ;; Mark `operations' the handler is responsible for.
2374 (put 'tramp-completion-file-name-handler 'operations
2375 (mapcar 'car tramp-completion-file-name-handler-alist))
2377 ;; If jka-compr or epa-file are already loaded, move them to the
2378 ;; front of `file-name-handler-alist'.
2379 (dolist (fnh '(epa-file-handler jka-compr-handler))
2380 (let ((entry (rassoc fnh file-name-handler-alist)))
2381 (when entry
2382 (setq file-name-handler-alist
2383 (cons entry (delete entry file-name-handler-alist)))))))
2385 (eval-after-load 'tramp (tramp-register-file-name-handlers))
2387 ;;;###tramp-autoload
2388 (progn (defun tramp-register-foreign-file-name-handler
2389 (func handler &optional append)
2390 "Register (FUNC . HANDLER) in `tramp-foreign-file-name-handler-alist'.
2391 FUNC is the function, which determines whether HANDLER is to be called.
2392 Add operations defined in `HANDLER-alist' to `tramp-file-name-handler'."
2393 (add-to-list
2394 'tramp-foreign-file-name-handler-alist `(,func . ,handler) append)
2395 ;; Mark `operations' the handler is responsible for.
2396 (put 'tramp-file-name-handler
2397 'operations
2398 (delete-dups
2399 (append
2400 (get 'tramp-file-name-handler 'operations)
2401 (mapcar
2402 'car
2403 (symbol-value (intern (concat (symbol-name handler) "-alist")))))))))
2405 (defun tramp-exists-file-name-handler (operation &rest args)
2406 "Check, whether OPERATION runs a file name handler."
2407 ;; The file name handler is determined on base of either an
2408 ;; argument, `buffer-file-name', or `default-directory'.
2409 (ignore-errors
2410 (let* ((buffer-file-name "/")
2411 (default-directory "/")
2412 (fnha file-name-handler-alist)
2413 (check-file-name-operation operation)
2414 (file-name-handler-alist
2415 (list
2416 (cons "/"
2417 (lambda (operation &rest args)
2418 "Returns OPERATION if it is the one to be checked."
2419 (if (equal check-file-name-operation operation)
2420 operation
2421 (let ((file-name-handler-alist fnha))
2422 (apply operation args))))))))
2423 (equal (apply operation args) operation))))
2425 ;;;###autoload
2426 (progn (defun tramp-unload-file-name-handlers ()
2427 "Unload Tramp file name handlers from `file-name-handler-alist'."
2428 (dolist (fnh '(tramp-file-name-handler
2429 tramp-completion-file-name-handler
2430 tramp-autoload-file-name-handler))
2431 (let ((a1 (rassq fnh file-name-handler-alist)))
2432 (setq file-name-handler-alist (delq a1 file-name-handler-alist))))))
2434 (add-hook 'tramp-unload-hook 'tramp-unload-file-name-handlers)
2436 ;;; File name handler functions for completion mode:
2438 ;;;###autoload
2439 (defvar tramp-completion-mode nil
2440 "If non-nil, external packages signal that they are in file name completion.")
2441 (make-obsolete-variable 'tramp-completion-mode 'non-essential "26.1")
2443 (defun tramp-completion-mode-p ()
2444 "Check, whether method / user name / host name completion is active."
2446 ;; Signal from outside.
2447 non-essential
2448 ;; This variable has been obsoleted in Emacs 26.
2449 tramp-completion-mode))
2451 (defun tramp-connectable-p (filename)
2452 "Check, whether it is possible to connect the remote host w/o side-effects.
2453 This is true, if either the remote host is already connected, or if we are
2454 not in completion mode."
2455 (let (tramp-verbose)
2456 (and (tramp-tramp-file-p filename)
2457 (or (not (tramp-completion-mode-p))
2458 (process-live-p
2459 (tramp-get-connection-process
2460 (tramp-dissect-file-name filename)))))))
2462 ;; Method, host name and user name completion.
2463 ;; `tramp-completion-dissect-file-name' returns a list of
2464 ;; `tramp-file-name' structures. For all of them we return possible
2465 ;; completions.
2466 (defun tramp-completion-handle-file-name-all-completions (filename directory)
2467 "Like `file-name-all-completions' for partial Tramp files."
2469 (let ((fullname
2470 (tramp-drop-volume-letter (expand-file-name filename directory)))
2471 hop result result1)
2473 ;; Suppress hop from completion.
2474 (when (string-match
2475 (concat
2476 tramp-prefix-regexp
2477 "\\(" "\\(" tramp-remote-file-name-spec-regexp
2478 tramp-postfix-hop-regexp
2479 "\\)+" "\\)")
2480 fullname)
2481 (setq hop (match-string 1 fullname)
2482 fullname (replace-match "" nil nil fullname 1)))
2484 ;; Possible completion structures.
2485 (dolist (elt (tramp-completion-dissect-file-name fullname))
2486 (let* ((method (tramp-file-name-method elt))
2487 (user (tramp-file-name-user elt))
2488 (host (tramp-file-name-host elt))
2489 (localname (tramp-file-name-localname elt))
2490 (m (tramp-find-method method user host))
2491 (tramp-current-user user) ; see `tramp-parse-passwd'
2492 all-user-hosts)
2494 (unless localname ;; Nothing to complete.
2496 (if (or user host)
2498 ;; Method dependent user / host combinations.
2499 (progn
2500 (mapc
2501 (lambda (x)
2502 (setq all-user-hosts
2503 (append all-user-hosts
2504 (funcall (nth 0 x) (nth 1 x)))))
2505 (tramp-get-completion-function m))
2507 (setq result
2508 (append result
2509 (mapcar
2510 (lambda (x)
2511 (tramp-get-completion-user-host
2512 method user host (nth 0 x) (nth 1 x)))
2513 (delq nil all-user-hosts)))))
2515 ;; Possible methods.
2516 (setq result
2517 (append result (tramp-get-completion-methods m)))))))
2519 ;; Unify list, add hop, remove nil elements.
2520 (dolist (elt result)
2521 (when elt
2522 (string-match tramp-prefix-regexp elt)
2523 (setq elt (replace-match (concat tramp-prefix-format hop) nil nil elt))
2524 (push
2525 (substring elt (length (tramp-drop-volume-letter directory)))
2526 result1)))
2528 ;; Complete local parts.
2529 (append
2530 result1
2531 (ignore-errors
2532 (tramp-run-real-handler
2533 'file-name-all-completions (list filename directory))))))
2535 ;; Method, host name and user name completion for a file.
2536 (defun tramp-completion-handle-file-name-completion
2537 (filename directory &optional predicate)
2538 "Like `file-name-completion' for Tramp files."
2539 (try-completion
2540 filename
2541 (mapcar 'list (file-name-all-completions filename directory))
2542 (when (and predicate
2543 (tramp-connectable-p (expand-file-name filename directory)))
2544 (lambda (x) (funcall predicate (expand-file-name (car x) directory))))))
2546 ;; I misuse a little bit the `tramp-file-name' structure in order to
2547 ;; handle completion possibilities for partial methods / user names /
2548 ;; host names. Return value is a list of `tramp-file-name' structures
2549 ;; according to possible completions. If "localname" is non-nil it
2550 ;; means there shouldn't be a completion anymore.
2552 ;; Expected results:
2554 ;; "/x" "/[x"
2555 ;; ["x" nil nil nil]
2557 ;; "/x:" "/[x/" "/x:y" "/[x/y" "/x:y:" "/[x/y]"
2558 ;; ["x" nil "" nil] ["x" nil "y" nil] ["x" nil "y" ""]
2559 ;; ["x" "" nil nil] ["x" "y" nil nil]
2561 ;; "/x:y@""/[x/y@" "/x:y@z" "/[x/y@z" "/x:y@z:" "/[x/y@z]"
2562 ;;["x" "y" nil nil] ["x" "y" "z" nil] ["x" "y" "z" ""]
2563 (defun tramp-completion-dissect-file-name (name)
2564 "Returns a list of `tramp-file-name' structures.
2565 They are collected by `tramp-completion-dissect-file-name1'."
2567 (let* ((x-nil "\\|\\(\\)")
2568 (tramp-completion-ipv6-regexp
2569 (format
2570 "[^%s]*"
2571 (if (zerop (length tramp-postfix-ipv6-format))
2572 tramp-postfix-host-format
2573 tramp-postfix-ipv6-format)))
2574 ;; "/method" "/[method"
2575 (tramp-completion-file-name-structure1
2576 (list
2577 (concat
2578 tramp-prefix-regexp
2579 "\\(" tramp-method-regexp x-nil "\\)$")
2580 1 nil nil nil))
2581 ;; "/method:user" "/[method/user"
2582 (tramp-completion-file-name-structure2
2583 (list
2584 (concat
2585 tramp-prefix-regexp
2586 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
2587 "\\(" tramp-user-regexp x-nil "\\)$")
2588 1 2 nil nil))
2589 ;; "/method:host" "/[method/host"
2590 (tramp-completion-file-name-structure3
2591 (list
2592 (concat
2593 tramp-prefix-regexp
2594 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
2595 "\\(" tramp-host-regexp x-nil "\\)$")
2596 1 nil 2 nil))
2597 ;; "/method:[ipv6" "/[method/ipv6"
2598 (tramp-completion-file-name-structure4
2599 (list
2600 (concat
2601 tramp-prefix-regexp
2602 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
2603 tramp-prefix-ipv6-regexp
2604 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
2605 1 nil 2 nil))
2606 ;; "/method:user@host" "/[method/user@host"
2607 (tramp-completion-file-name-structure5
2608 (list
2609 (concat
2610 tramp-prefix-regexp
2611 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
2612 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
2613 "\\(" tramp-host-regexp x-nil "\\)$")
2614 1 2 3 nil))
2615 ;; "/method:user@[ipv6" "/[method/user@ipv6"
2616 (tramp-completion-file-name-structure6
2617 (list
2618 (concat
2619 tramp-prefix-regexp
2620 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
2621 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
2622 tramp-prefix-ipv6-regexp
2623 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
2624 1 2 3 nil)))
2625 (delq
2627 (mapcar
2628 (lambda (structure) (tramp-completion-dissect-file-name1 structure name))
2629 (list
2630 tramp-completion-file-name-structure1
2631 tramp-completion-file-name-structure2
2632 tramp-completion-file-name-structure3
2633 tramp-completion-file-name-structure4
2634 tramp-completion-file-name-structure5
2635 tramp-completion-file-name-structure6)))))
2637 (defun tramp-completion-dissect-file-name1 (structure name)
2638 "Returns a `tramp-file-name' structure matching STRUCTURE.
2639 The structure consists of remote method, remote user,
2640 remote host and localname (filename on remote host)."
2642 (save-match-data
2643 (when (string-match (nth 0 structure) name)
2644 (make-tramp-file-name
2645 :method (and (nth 1 structure)
2646 (match-string (nth 1 structure) name))
2647 :user (and (nth 2 structure)
2648 (match-string (nth 2 structure) name))
2649 :host (and (nth 3 structure)
2650 (match-string (nth 3 structure) name))))))
2652 ;; This function returns all possible method completions, adding the
2653 ;; trailing method delimiter.
2654 (defun tramp-get-completion-methods (partial-method)
2655 "Returns all method completions for PARTIAL-METHOD."
2656 (mapcar
2657 (lambda (method)
2658 (and method
2659 (string-match (concat "^" (regexp-quote partial-method)) method)
2660 (tramp-completion-make-tramp-file-name method nil nil nil)))
2661 (mapcar 'car tramp-methods)))
2663 ;; Compares partial user and host names with possible completions.
2664 (defun tramp-get-completion-user-host
2665 (method partial-user partial-host user host)
2666 "Returns the most expanded string for user and host name completion.
2667 PARTIAL-USER must match USER, PARTIAL-HOST must match HOST."
2668 (cond
2670 ((and partial-user partial-host)
2671 (if (and host
2672 (string-match (concat "^" (regexp-quote partial-host)) host)
2673 (string-equal partial-user (or user partial-user)))
2674 (setq user partial-user)
2675 (setq user nil
2676 host nil)))
2678 (partial-user
2679 (setq host nil)
2680 (unless
2681 (and user (string-match (concat "^" (regexp-quote partial-user)) user))
2682 (setq user nil)))
2684 (partial-host
2685 (setq user nil)
2686 (unless
2687 (and host (string-match (concat "^" (regexp-quote partial-host)) host))
2688 (setq host nil)))
2690 (t (setq user nil
2691 host nil)))
2693 (unless (zerop (+ (length user) (length host)))
2694 (tramp-completion-make-tramp-file-name method user host nil)))
2696 (defun tramp-parse-default-user-host (method)
2697 "Return a list of (user host) tuples allowed to access for METHOD.
2698 This function is added always in `tramp-get-completion-function'
2699 for all methods. Resulting data are derived from default settings."
2700 `((,(tramp-find-user method nil nil) ,(tramp-find-host method nil nil))))
2702 ;; Generic function.
2703 (defun tramp-parse-group (regexp match-level skip-regexp)
2704 "Return a (user host) tuple allowed to access.
2705 User is always nil."
2706 (let (result)
2707 (when (re-search-forward regexp (point-at-eol) t)
2708 (setq result (list nil (match-string match-level))))
2710 (> (skip-chars-forward skip-regexp) 0)
2711 (forward-line 1))
2712 result))
2714 ;; Generic function.
2715 (defun tramp-parse-file (filename function)
2716 "Return a list of (user host) tuples allowed to access.
2717 User is always nil."
2718 ;; On Windows, there are problems in completion when
2719 ;; `default-directory' is remote.
2720 (let ((default-directory (tramp-compat-temporary-file-directory)))
2721 (when (file-readable-p filename)
2722 (with-temp-buffer
2723 (insert-file-contents filename)
2724 (goto-char (point-min))
2725 (cl-loop while (not (eobp)) collect (funcall function))))))
2727 ;;;###tramp-autoload
2728 (defun tramp-parse-rhosts (filename)
2729 "Return a list of (user host) tuples allowed to access.
2730 Either user or host may be nil."
2731 (tramp-parse-file filename 'tramp-parse-rhosts-group))
2733 (defun tramp-parse-rhosts-group ()
2734 "Return a (user host) tuple allowed to access.
2735 Either user or host may be nil."
2736 (let ((result)
2737 (regexp
2738 (concat
2739 "^\\(" tramp-host-regexp "\\)"
2740 "\\([ \t]+" "\\(" tramp-user-regexp "\\)" "\\)?")))
2741 (when (re-search-forward regexp (point-at-eol) t)
2742 (setq result (append (list (match-string 3) (match-string 1)))))
2743 (forward-line 1)
2744 result))
2746 ;;;###tramp-autoload
2747 (defun tramp-parse-shosts (filename)
2748 "Return a list of (user host) tuples allowed to access.
2749 User is always nil."
2750 (tramp-parse-file filename 'tramp-parse-shosts-group))
2752 (defun tramp-parse-shosts-group ()
2753 "Return a (user host) tuple allowed to access.
2754 User is always nil."
2755 (tramp-parse-group (concat "^\\(" tramp-host-regexp "\\)") 1 ","))
2757 ;;;###tramp-autoload
2758 (defun tramp-parse-sconfig (filename)
2759 "Return a list of (user host) tuples allowed to access.
2760 User is always nil."
2761 (tramp-parse-file filename 'tramp-parse-sconfig-group))
2763 (defun tramp-parse-sconfig-group ()
2764 "Return a (user host) tuple allowed to access.
2765 User is always nil."
2766 (tramp-parse-group
2767 (concat "^[ \t]*Host[ \t]+" "\\(" tramp-host-regexp "\\)") 1 ","))
2769 ;; Generic function.
2770 (defun tramp-parse-shostkeys-sknownhosts (dirname regexp)
2771 "Return a list of (user host) tuples allowed to access.
2772 User is always nil."
2773 ;; On Windows, there are problems in completion when
2774 ;; `default-directory' is remote.
2775 (let* ((default-directory (tramp-compat-temporary-file-directory))
2776 (files (and (file-directory-p dirname) (directory-files dirname))))
2777 (cl-loop
2778 for f in files
2779 when (and (not (string-match "^\\.\\.?$" f)) (string-match regexp f))
2780 collect (list nil (match-string 1 f)))))
2782 ;;;###tramp-autoload
2783 (defun tramp-parse-shostkeys (dirname)
2784 "Return a list of (user host) tuples allowed to access.
2785 User is always nil."
2786 (tramp-parse-shostkeys-sknownhosts
2787 dirname (concat "^key_[0-9]+_\\(" tramp-host-regexp "\\)\\.pub$")))
2789 ;;;###tramp-autoload
2790 (defun tramp-parse-sknownhosts (dirname)
2791 "Return a list of (user host) tuples allowed to access.
2792 User is always nil."
2793 (tramp-parse-shostkeys-sknownhosts
2794 dirname
2795 (concat "^\\(" tramp-host-regexp "\\)\\.ssh-\\(dss\\|rsa\\)\\.pub$")))
2797 ;;;###tramp-autoload
2798 (defun tramp-parse-hosts (filename)
2799 "Return a list of (user host) tuples allowed to access.
2800 User is always nil."
2801 (tramp-parse-file filename 'tramp-parse-hosts-group))
2803 (defun tramp-parse-hosts-group ()
2804 "Return a (user host) tuple allowed to access.
2805 User is always nil."
2806 (tramp-parse-group
2807 (concat "^\\(" tramp-ipv6-regexp "\\|" tramp-host-regexp "\\)") 1 " \t"))
2809 ;;;###tramp-autoload
2810 (defun tramp-parse-passwd (filename)
2811 "Return a list of (user host) tuples allowed to access.
2812 Host is always \"localhost\"."
2813 (with-tramp-connection-property nil "parse-passwd"
2814 (if (executable-find "getent")
2815 (with-temp-buffer
2816 (when (zerop (tramp-call-process nil "getent" nil t nil "passwd"))
2817 (goto-char (point-min))
2818 (cl-loop while (not (eobp)) collect
2819 (tramp-parse-etc-group-group))))
2820 (tramp-parse-file filename 'tramp-parse-passwd-group))))
2822 (defun tramp-parse-passwd-group ()
2823 "Return a (user host) tuple allowed to access.
2824 Host is always \"localhost\"."
2825 (let ((result)
2826 (regexp (concat "^\\(" tramp-user-regexp "\\):")))
2827 (when (re-search-forward regexp (point-at-eol) t)
2828 (setq result (list (match-string 1) "localhost")))
2829 (forward-line 1)
2830 result))
2832 ;;;###tramp-autoload
2833 (defun tramp-parse-etc-group (filename)
2834 "Return a list of (group host) tuples allowed to access.
2835 Host is always \"localhost\"."
2836 (with-tramp-connection-property nil "parse-group"
2837 (if (executable-find "getent")
2838 (with-temp-buffer
2839 (when (zerop (tramp-call-process nil "getent" nil t nil "group"))
2840 (goto-char (point-min))
2841 (cl-loop while (not (eobp)) collect
2842 (tramp-parse-etc-group-group))))
2843 (tramp-parse-file filename 'tramp-parse-etc-group-group))))
2845 (defun tramp-parse-etc-group-group ()
2846 "Return a (group host) tuple allowed to access.
2847 Host is always \"localhost\"."
2848 (let ((result)
2849 (split (split-string (buffer-substring (point) (point-at-eol)) ":")))
2850 (when (member (user-login-name) (split-string (nth 3 split) "," 'omit))
2851 (setq result (list (nth 0 split) "localhost")))
2852 (forward-line 1)
2853 result))
2855 ;;;###tramp-autoload
2856 (defun tramp-parse-netrc (filename)
2857 "Return a list of (user host) tuples allowed to access.
2858 User may be nil."
2859 (tramp-parse-file filename 'tramp-parse-netrc-group))
2861 (defun tramp-parse-netrc-group ()
2862 "Return a (user host) tuple allowed to access.
2863 User may be nil."
2864 (let ((result)
2865 (regexp
2866 (concat
2867 "^[ \t]*machine[ \t]+" "\\(" tramp-host-regexp "\\)"
2868 "\\([ \t]+login[ \t]+" "\\(" tramp-user-regexp "\\)" "\\)?")))
2869 (when (re-search-forward regexp (point-at-eol) t)
2870 (setq result (list (match-string 3) (match-string 1))))
2871 (forward-line 1)
2872 result))
2874 ;;;###tramp-autoload
2875 (defun tramp-parse-putty (registry-or-dirname)
2876 "Return a list of (user host) tuples allowed to access.
2877 User is always nil."
2878 (if (memq system-type '(windows-nt))
2879 (with-tramp-connection-property nil "parse-putty"
2880 (with-temp-buffer
2881 (when (zerop (tramp-call-process
2882 nil "reg" nil t nil "query" registry-or-dirname))
2883 (goto-char (point-min))
2884 (cl-loop while (not (eobp)) collect
2885 (tramp-parse-putty-group registry-or-dirname)))))
2886 ;; UNIX case.
2887 (tramp-parse-shostkeys-sknownhosts
2888 registry-or-dirname (concat "^\\(" tramp-host-regexp "\\)$"))))
2890 (defun tramp-parse-putty-group (registry)
2891 "Return a (user host) tuple allowed to access.
2892 User is always nil."
2893 (let ((result)
2894 (regexp (concat (regexp-quote registry) "\\\\\\(.+\\)")))
2895 (when (re-search-forward regexp (point-at-eol) t)
2896 (setq result (list nil (match-string 1))))
2897 (forward-line 1)
2898 result))
2900 ;;; Common file name handler functions for different backends:
2902 (defvar tramp-handle-file-local-copy-hook nil
2903 "Normal hook to be run at the end of `tramp-*-handle-file-local-copy'.")
2905 (defvar tramp-handle-write-region-hook nil
2906 "Normal hook to be run at the end of `tramp-*-handle-write-region'.")
2908 (defun tramp-handle-add-name-to-file
2909 (filename newname &optional ok-if-already-exists)
2910 "Like `add-name-to-file' for Tramp files."
2911 (with-parsed-tramp-file-name
2912 (if (tramp-tramp-file-p newname) newname filename) nil
2913 (unless (tramp-equal-remote filename newname)
2914 (tramp-error
2915 v 'file-error
2916 "add-name-to-file: %s"
2917 "only implemented for same method, same user, same host"))
2918 ;; Do the 'confirm if exists' thing.
2919 (when (file-exists-p newname)
2920 ;; What to do?
2921 (if (or (null ok-if-already-exists) ; not allowed to exist
2922 (and (numberp ok-if-already-exists)
2923 (not (yes-or-no-p
2924 (format
2925 "File %s already exists; make it a link anyway? "
2926 localname)))))
2927 (tramp-error v 'file-already-exists newname)
2928 (delete-file newname)))
2929 (tramp-flush-file-property v (file-name-directory localname))
2930 (tramp-flush-file-property v localname)
2931 (copy-file
2932 filename newname 'ok-if-already-exists 'keep-time
2933 'preserve-uid-gid 'preserve-permissions)))
2935 (defun tramp-handle-directory-file-name (directory)
2936 "Like `directory-file-name' for Tramp files."
2937 ;; If localname component of filename is "/", leave it unchanged.
2938 ;; Otherwise, remove any trailing slash from localname component.
2939 ;; Method, host, etc, are unchanged.
2940 (while (with-parsed-tramp-file-name directory nil
2941 (and (not (zerop (length localname)))
2942 (eq (aref localname (1- (length localname))) ?/)
2943 (not (string= localname "/"))))
2944 (setq directory (substring directory 0 -1)))
2945 directory)
2947 (defun tramp-handle-directory-files (directory &optional full match nosort)
2948 "Like `directory-files' for Tramp files."
2949 (when (file-directory-p directory)
2950 (setq directory (file-name-as-directory (expand-file-name directory)))
2951 (let ((temp (nreverse (file-name-all-completions "" directory)))
2952 result item)
2954 (while temp
2955 (setq item (directory-file-name (pop temp)))
2956 (when (or (null match) (string-match match item))
2957 (push (if full (concat directory item) item)
2958 result)))
2959 (if nosort result (sort result 'string<)))))
2961 (defun tramp-handle-directory-files-and-attributes
2962 (directory &optional full match nosort id-format)
2963 "Like `directory-files-and-attributes' for Tramp files."
2964 (mapcar
2965 (lambda (x)
2966 (cons x (file-attributes
2967 (if full x (expand-file-name x directory)) id-format)))
2968 (directory-files directory full match nosort)))
2970 (defun tramp-handle-dired-uncache (dir)
2971 "Like `dired-uncache' for Tramp files."
2972 (with-parsed-tramp-file-name
2973 (if (file-directory-p dir) dir (file-name-directory dir)) nil
2974 (tramp-flush-directory-property v localname)))
2976 (defun tramp-handle-file-accessible-directory-p (filename)
2977 "Like `file-accessible-directory-p' for Tramp files."
2978 (and (file-directory-p filename)
2979 (file-readable-p filename)))
2981 (defun tramp-handle-file-equal-p (filename1 filename2)
2982 "Like `file-equalp-p' for Tramp files."
2983 ;; Native `file-equalp-p' calls `file-truename', which requires a
2984 ;; remote connection. This can be avoided, if FILENAME1 and
2985 ;; FILENAME2 are not located on the same remote host.
2986 (when (string-equal
2987 (file-remote-p (expand-file-name filename1))
2988 (file-remote-p (expand-file-name filename2)))
2989 (tramp-run-real-handler 'file-equal-p (list filename1 filename2))))
2991 (defun tramp-handle-file-exists-p (filename)
2992 "Like `file-exists-p' for Tramp files."
2993 (not (null (file-attributes filename))))
2995 (defun tramp-handle-file-in-directory-p (filename directory)
2996 "Like `file-in-directory-p' for Tramp files."
2997 ;; Native `file-in-directory-p' calls `file-truename', which
2998 ;; requires a remote connection. This can be avoided, if FILENAME
2999 ;; and DIRECTORY are not located on the same remote host.
3000 (when (string-equal
3001 (file-remote-p (expand-file-name filename))
3002 (file-remote-p (expand-file-name directory)))
3003 (tramp-run-real-handler 'file-in-directory-p (list filename directory))))
3005 (defun tramp-handle-file-modes (filename)
3006 "Like `file-modes' for Tramp files."
3007 (let ((truename (or (file-truename filename) filename)))
3008 (when (file-exists-p truename)
3009 (tramp-mode-string-to-int
3010 (tramp-compat-file-attribute-modes (file-attributes truename))))))
3012 ;; Localname manipulation functions that grok Tramp localnames...
3013 (defun tramp-handle-file-name-as-directory (file)
3014 "Like `file-name-as-directory' but aware of Tramp files."
3015 ;; `file-name-as-directory' would be sufficient except localname is
3016 ;; the empty string.
3017 (let ((v (tramp-dissect-file-name file t)))
3018 ;; Run the command on the localname portion only unless we are in
3019 ;; completion mode.
3020 (tramp-make-tramp-file-name
3021 (tramp-file-name-method v)
3022 (tramp-file-name-user v)
3023 (tramp-file-name-domain v)
3024 (tramp-file-name-host v)
3025 (tramp-file-name-port v)
3026 (if (and (zerop (length (tramp-file-name-localname v)))
3027 (not (tramp-connectable-p file)))
3029 (tramp-run-real-handler
3030 'file-name-as-directory (list (or (tramp-file-name-localname v) ""))))
3031 (tramp-file-name-hop v))))
3033 (defun tramp-handle-file-name-case-insensitive-p (filename)
3034 "Like `file-name-case-insensitive-p' for Tramp files."
3035 ;; We make it a connection property, assuming that all file systems
3036 ;; on the remote host behave similar. This might be wrong for
3037 ;; mounted NFS directories or SMB/AFP shares; such more granular
3038 ;; tests will be added in case they are needed.
3039 (setq filename (expand-file-name filename))
3040 (with-parsed-tramp-file-name filename nil
3041 (or ;; Maybe there is a default value.
3042 (tramp-get-method-parameter v 'tramp-case-insensitive)
3044 ;; There isn't. So we must check, in case there's a connection already.
3045 (and (file-remote-p filename nil 'connected)
3046 (with-tramp-connection-property v "case-insensitive"
3047 (ignore-errors
3048 (with-tramp-progress-reporter v 5 "Checking case-insensitive"
3049 ;; The idea is to compare a file with lower case
3050 ;; letters with the same file with upper case letters.
3051 (let ((candidate
3052 (tramp-compat-file-name-unquote
3053 (directory-file-name filename)))
3054 tmpfile)
3055 ;; Check, whether we find an existing file with
3056 ;; lower case letters. This avoids us to create a
3057 ;; temporary file.
3058 (while (and (string-match
3059 "[a-z]" (file-remote-p candidate 'localname))
3060 (not (file-exists-p candidate)))
3061 (setq candidate
3062 (directory-file-name
3063 (file-name-directory candidate))))
3064 ;; Nothing found, so we must use a temporary file
3065 ;; for comparison. `make-nearby-temp-file' is added
3066 ;; to Emacs 26+ like `file-name-case-insensitive-p',
3067 ;; so there is no compatibility problem calling it.
3068 (unless
3069 (string-match
3070 "[a-z]" (file-remote-p candidate 'localname))
3071 (setq tmpfile
3072 (let ((default-directory
3073 (file-name-directory filename)))
3074 (tramp-compat-funcall
3075 'make-nearby-temp-file "tramp."))
3076 candidate tmpfile))
3077 ;; Check for the existence of the same file with
3078 ;; upper case letters.
3079 (unwind-protect
3080 (file-exists-p
3081 (concat
3082 (file-remote-p candidate)
3083 (upcase (file-remote-p candidate 'localname))))
3084 ;; Cleanup.
3085 (when tmpfile (delete-file tmpfile)))))))))))
3087 (defun tramp-handle-file-name-completion
3088 (filename directory &optional predicate)
3089 "Like `file-name-completion' for Tramp files."
3090 (unless (tramp-tramp-file-p directory)
3091 (error
3092 "tramp-handle-file-name-completion invoked on non-tramp directory `%s'"
3093 directory))
3094 (let (hits-ignored-extensions)
3096 (try-completion
3097 filename (file-name-all-completions filename directory)
3098 (lambda (x)
3099 (when (funcall (or predicate 'identity) (expand-file-name x directory))
3100 (not
3101 (and
3102 completion-ignored-extensions
3103 (string-match
3104 (concat (regexp-opt completion-ignored-extensions 'paren) "$") x)
3105 ;; We remember the hit.
3106 (push x hits-ignored-extensions))))))
3107 ;; No match. So we try again for ignored files.
3108 (try-completion filename hits-ignored-extensions))))
3110 (defun tramp-handle-file-name-directory (file)
3111 "Like `file-name-directory' but aware of Tramp files."
3112 ;; Everything except the last filename thing is the directory. We
3113 ;; cannot apply `with-parsed-tramp-file-name', because this expands
3114 ;; the remote file name parts. This is a problem when we are in
3115 ;; file name completion.
3116 (let ((v (tramp-dissect-file-name file t)))
3117 ;; Run the command on the localname portion only.
3118 (tramp-make-tramp-file-name
3119 (tramp-file-name-method v)
3120 (tramp-file-name-user v)
3121 (tramp-file-name-domain v)
3122 (tramp-file-name-host v)
3123 (tramp-file-name-port v)
3124 (tramp-run-real-handler
3125 'file-name-directory (list (or (tramp-file-name-localname v) "")))
3126 (tramp-file-name-hop v))))
3128 (defun tramp-handle-file-name-nondirectory (file)
3129 "Like `file-name-nondirectory' but aware of Tramp files."
3130 (with-parsed-tramp-file-name file nil
3131 (tramp-run-real-handler 'file-name-nondirectory (list localname))))
3133 (defun tramp-handle-file-newer-than-file-p (file1 file2)
3134 "Like `file-newer-than-file-p' for Tramp files."
3135 (cond
3136 ((not (file-exists-p file1)) nil)
3137 ((not (file-exists-p file2)) t)
3138 (t (time-less-p (tramp-compat-file-attribute-modification-time
3139 (file-attributes file2))
3140 (tramp-compat-file-attribute-modification-time
3141 (file-attributes file1))))))
3143 (defun tramp-handle-file-regular-p (filename)
3144 "Like `file-regular-p' for Tramp files."
3145 (and (file-exists-p filename)
3146 (eq ?-
3147 (aref (tramp-compat-file-attribute-modes (file-attributes filename))
3148 0))))
3150 (defun tramp-handle-file-remote-p (filename &optional identification connected)
3151 "Like `file-remote-p' for Tramp files."
3152 ;; We do not want traces in the debug buffer.
3153 (let ((tramp-verbose (min tramp-verbose 3)))
3154 (when (tramp-tramp-file-p filename)
3155 (let* ((v (tramp-dissect-file-name filename))
3156 (p (tramp-get-connection-process v))
3157 (c (and (process-live-p p)
3158 (tramp-get-connection-property p "connected" nil))))
3159 ;; We expand the file name only, if there is already a connection.
3160 (with-parsed-tramp-file-name
3161 (if c (expand-file-name filename) filename) nil
3162 (and (or (not connected) c)
3163 (cond
3164 ((eq identification 'method) method)
3165 ;; Domain and port are appended.
3166 ((eq identification 'user) (tramp-file-name-user-domain v))
3167 ((eq identification 'host) (tramp-file-name-host-port v))
3168 ((eq identification 'localname) localname)
3169 ((eq identification 'hop) hop)
3170 (t (tramp-make-tramp-file-name
3171 method user domain host port "" hop)))))))))
3173 (defun tramp-handle-file-selinux-context (_filename)
3174 "Like `file-selinux-context' for Tramp files."
3175 ;; Return nil context.
3176 '(nil nil nil nil))
3178 (defun tramp-handle-file-symlink-p (filename)
3179 "Like `file-symlink-p' for Tramp files."
3180 (let ((x (tramp-compat-file-attribute-type (file-attributes filename))))
3181 (and (stringp x) x)))
3183 (defun tramp-handle-file-truename (filename)
3184 "Like `file-truename' for Tramp files."
3185 (let ((result (expand-file-name filename))
3186 (numchase 0)
3187 ;; Don't make the following value larger than
3188 ;; necessary. People expect an error message in a
3189 ;; timely fashion when something is wrong;
3190 ;; otherwise they might think that Emacs is hung.
3191 ;; Of course, correctness has to come first.
3192 (numchase-limit 20)
3193 symlink-target)
3194 (format
3195 "%s%s"
3196 (with-parsed-tramp-file-name result v1
3197 (with-tramp-file-property v1 v1-localname "file-truename"
3198 (while (and (setq symlink-target (file-symlink-p result))
3199 (< numchase numchase-limit))
3200 (setq numchase (1+ numchase)
3201 result
3202 (with-parsed-tramp-file-name (expand-file-name result) v2
3203 (tramp-make-tramp-file-name
3204 v2-method v2-user v2-domain v2-host v2-port
3205 (funcall
3206 (if (tramp-compat-file-name-quoted-p v2-localname)
3207 'tramp-compat-file-name-quote 'identity)
3209 (if (stringp symlink-target)
3210 (if (file-remote-p symlink-target)
3211 (let (file-name-handler-alist)
3212 (tramp-compat-file-name-quote symlink-target))
3213 (expand-file-name
3214 symlink-target (file-name-directory v2-localname)))
3215 v2-localname)))))
3216 (when (>= numchase numchase-limit)
3217 (tramp-error
3218 v1 'file-error
3219 "Maximum number (%d) of symlinks exceeded" numchase-limit)))
3220 (directory-file-name result)))
3222 ;; Preserve trailing "/".
3223 (if (string-equal (file-name-nondirectory filename) "") "/" ""))))
3225 (defun tramp-handle-find-backup-file-name (filename)
3226 "Like `find-backup-file-name' for Tramp files."
3227 (with-parsed-tramp-file-name filename nil
3228 (let ((backup-directory-alist
3229 (if tramp-backup-directory-alist
3230 (mapcar
3231 (lambda (x)
3232 (cons
3233 (car x)
3234 (if (and (stringp (cdr x))
3235 (file-name-absolute-p (cdr x))
3236 (not (tramp-tramp-file-p (cdr x))))
3237 (tramp-make-tramp-file-name
3238 method user domain host port (cdr x) hop)
3239 (cdr x))))
3240 tramp-backup-directory-alist)
3241 backup-directory-alist)))
3242 (tramp-run-real-handler 'find-backup-file-name (list filename)))))
3244 (defun tramp-handle-insert-directory
3245 (filename switches &optional wildcard full-directory-p)
3246 "Like `insert-directory' for Tramp files."
3247 (unless switches (setq switches ""))
3248 ;; Mark trailing "/".
3249 (when (and (zerop (length (file-name-nondirectory filename)))
3250 (not full-directory-p))
3251 (setq switches (concat switches "F")))
3252 (with-parsed-tramp-file-name (expand-file-name filename) nil
3253 (with-tramp-progress-reporter v 0 (format "Opening directory %s" filename)
3254 (require 'ls-lisp)
3255 (let (ls-lisp-use-insert-directory-program start)
3256 (tramp-run-real-handler
3257 'insert-directory
3258 (list filename switches wildcard full-directory-p))
3259 ;; `ls-lisp' always returns full listings. We must remove
3260 ;; superfluous parts.
3261 (unless (string-match "l" switches)
3262 (save-excursion
3263 (goto-char (point-min))
3264 (while (setq start
3265 (text-property-not-all
3266 (point) (point-at-eol) 'dired-filename t))
3267 (delete-region
3268 start
3269 (or (text-property-any start (point-at-eol) 'dired-filename t)
3270 (point-at-eol)))
3271 (if (= (point-at-bol) (point-at-eol))
3272 ;; Empty line.
3273 (delete-region (point) (progn (forward-line) (point)))
3274 (forward-line)))))))))
3276 (defun tramp-handle-insert-file-contents
3277 (filename &optional visit beg end replace)
3278 "Like `insert-file-contents' for Tramp files."
3279 (barf-if-buffer-read-only)
3280 (setq filename (expand-file-name filename))
3281 (let (result local-copy remote-copy)
3282 (with-parsed-tramp-file-name filename nil
3283 (unwind-protect
3284 (if (not (file-exists-p filename))
3285 (tramp-error
3286 v tramp-file-missing
3287 "File `%s' not found on remote host" filename)
3289 (with-tramp-progress-reporter
3290 v 3 (format-message "Inserting `%s'" filename)
3291 (condition-case err
3292 (if (and (tramp-local-host-p v)
3293 (let (file-name-handler-alist)
3294 (file-readable-p localname)))
3295 ;; Short track: if we are on the local host, we can
3296 ;; run directly.
3297 (setq result
3298 (tramp-run-real-handler
3299 'insert-file-contents
3300 (list localname visit beg end replace)))
3302 ;; When we shall insert only a part of the file, we
3303 ;; copy this part. This works only for the shell file
3304 ;; name handlers.
3305 (when (and (or beg end)
3306 (tramp-get-method-parameter
3307 v 'tramp-login-program))
3308 (setq remote-copy (tramp-make-tramp-temp-file v))
3309 ;; This is defined in tramp-sh.el. Let's assume
3310 ;; this is loaded already.
3311 (tramp-compat-funcall
3312 'tramp-send-command
3314 (cond
3315 ((and beg end)
3316 (format "dd bs=1 skip=%d if=%s count=%d of=%s"
3317 beg (tramp-shell-quote-argument localname)
3318 (- end beg) remote-copy))
3319 (beg
3320 (format "dd bs=1 skip=%d if=%s of=%s"
3321 beg (tramp-shell-quote-argument localname)
3322 remote-copy))
3323 (end
3324 (format "dd bs=1 count=%d if=%s of=%s"
3325 end (tramp-shell-quote-argument localname)
3326 remote-copy))))
3327 (setq tramp-temp-buffer-file-name nil beg nil end nil))
3329 ;; `insert-file-contents-literally' takes care to
3330 ;; avoid calling jka-compr.el and epa.el. By
3331 ;; let-binding `inhibit-file-name-operation', we
3332 ;; propagate that care to the `file-local-copy'
3333 ;; operation.
3334 (setq local-copy
3335 (let ((inhibit-file-name-operation
3336 (when (eq inhibit-file-name-operation
3337 'insert-file-contents)
3338 'file-local-copy)))
3339 (cond
3340 ((stringp remote-copy)
3341 (file-local-copy
3342 (tramp-make-tramp-file-name
3343 method user domain host port remote-copy)))
3344 ((stringp tramp-temp-buffer-file-name)
3345 (copy-file
3346 filename tramp-temp-buffer-file-name 'ok)
3347 tramp-temp-buffer-file-name)
3348 (t (file-local-copy filename)))))
3350 ;; When the file is not readable for the owner, it
3351 ;; cannot be inserted, even if it is readable for the
3352 ;; group or for everybody.
3353 (set-file-modes local-copy (string-to-number "0600" 8))
3355 (when (and (null remote-copy)
3356 (tramp-get-method-parameter
3357 v 'tramp-copy-keep-tmpfile))
3358 ;; We keep the local file for performance reasons,
3359 ;; useful for "rsync".
3360 (setq tramp-temp-buffer-file-name local-copy))
3362 ;; We must ensure that `file-coding-system-alist'
3363 ;; matches `local-copy'.
3364 (let ((file-coding-system-alist
3365 (tramp-find-file-name-coding-system-alist
3366 filename local-copy)))
3367 (setq result
3368 (insert-file-contents
3369 local-copy visit beg end replace))))
3370 (error
3371 (add-hook 'find-file-not-found-functions
3372 `(lambda () (signal ',(car err) ',(cdr err)))
3373 nil t)
3374 (signal (car err) (cdr err))))))
3376 ;; Save exit.
3377 (progn
3378 (when visit
3379 (setq buffer-file-name filename)
3380 (setq buffer-read-only (not (file-writable-p filename)))
3381 (set-visited-file-modtime)
3382 (set-buffer-modified-p nil))
3383 (when (and (stringp local-copy)
3384 (or remote-copy (null tramp-temp-buffer-file-name)))
3385 (delete-file local-copy))
3386 (when (stringp remote-copy)
3387 (delete-file
3388 (tramp-make-tramp-file-name
3389 method user domain host port remote-copy)))))
3391 ;; Result.
3392 (list (expand-file-name filename)
3393 (cadr result)))))
3395 (defun tramp-handle-load (file &optional noerror nomessage nosuffix must-suffix)
3396 "Like `load' for Tramp files."
3397 (with-parsed-tramp-file-name (expand-file-name file) nil
3398 (unless nosuffix
3399 (cond ((file-exists-p (concat file ".elc"))
3400 (setq file (concat file ".elc")))
3401 ((file-exists-p (concat file ".el"))
3402 (setq file (concat file ".el")))))
3403 (when must-suffix
3404 ;; The first condition is always true for absolute file names.
3405 ;; Included for safety's sake.
3406 (unless (or (file-name-directory file)
3407 (string-match "\\.elc?\\'" file))
3408 (tramp-error
3409 v 'file-error
3410 "File `%s' does not include a `.el' or `.elc' suffix" file)))
3411 (unless noerror
3412 (when (not (file-exists-p file))
3413 (tramp-error
3414 v tramp-file-missing "Cannot load nonexistent file `%s'" file)))
3415 (if (not (file-exists-p file))
3417 (let ((tramp-message-show-message (not nomessage)))
3418 (with-tramp-progress-reporter v 0 (format "Loading %s" file)
3419 (let ((local-copy (file-local-copy file)))
3420 (unwind-protect
3421 (load local-copy noerror t nosuffix must-suffix)
3422 (delete-file local-copy)))))
3423 t)))
3425 (defun tramp-handle-make-symbolic-link
3426 (target linkname &optional ok-if-already-exists)
3427 "Like `make-symbolic-link' for Tramp files.
3428 This is the fallback implementation for backends which do not
3429 support symbolic links."
3430 (if (tramp-tramp-file-p (expand-file-name linkname))
3431 (tramp-error
3432 (tramp-dissect-file-name (expand-file-name linkname)) 'file-error
3433 "make-symbolic-link not supported")
3434 ;; This is needed prior Emacs 26.1, where TARGET has also be
3435 ;; checked for a file name handler.
3436 (tramp-run-real-handler
3437 'make-symbolic-link (list target linkname ok-if-already-exists))))
3439 (defun tramp-handle-shell-command
3440 (command &optional output-buffer error-buffer)
3441 "Like `shell-command' for Tramp files."
3442 (let* ((asynchronous (string-match "[ \t]*&[ \t]*\\'" command))
3443 ;; We cannot use `shell-file-name' and `shell-command-switch',
3444 ;; they are variables of the local host.
3445 (args (append
3446 (cons
3447 (tramp-get-method-parameter
3448 (tramp-dissect-file-name default-directory)
3449 'tramp-remote-shell)
3450 (tramp-get-method-parameter
3451 (tramp-dissect-file-name default-directory)
3452 'tramp-remote-shell-args))
3453 (list (substring command 0 asynchronous))))
3454 current-buffer-p
3455 (output-buffer
3456 (cond
3457 ((bufferp output-buffer) output-buffer)
3458 ((stringp output-buffer) (get-buffer-create output-buffer))
3459 (output-buffer
3460 (setq current-buffer-p t)
3461 (current-buffer))
3462 (t (get-buffer-create
3463 (if asynchronous
3464 "*Async Shell Command*"
3465 "*Shell Command Output*")))))
3466 (error-buffer
3467 (cond
3468 ((bufferp error-buffer) error-buffer)
3469 ((stringp error-buffer) (get-buffer-create error-buffer))))
3470 (buffer
3471 (if (and (not asynchronous) error-buffer)
3472 (with-parsed-tramp-file-name default-directory nil
3473 (list output-buffer (tramp-make-tramp-temp-file v)))
3474 output-buffer))
3475 (p (get-buffer-process output-buffer)))
3477 ;; Check whether there is another process running. Tramp does not
3478 ;; support 2 (asynchronous) processes in parallel.
3479 (when p
3480 (if (yes-or-no-p "A command is running. Kill it? ")
3481 (ignore-errors (kill-process p))
3482 (tramp-compat-user-error p "Shell command in progress")))
3484 (if current-buffer-p
3485 (progn
3486 (barf-if-buffer-read-only)
3487 (push-mark nil t))
3488 (with-current-buffer output-buffer
3489 (setq buffer-read-only nil)
3490 (erase-buffer)))
3492 (if (and (not current-buffer-p) (integerp asynchronous))
3493 (prog1
3494 ;; Run the process.
3495 (setq p (apply 'start-file-process "*Async Shell*" buffer args))
3496 ;; Display output.
3497 (with-current-buffer output-buffer
3498 (display-buffer output-buffer '(nil (allow-no-window . t)))
3499 (setq mode-line-process '(":%s"))
3500 (shell-mode)
3501 (set-process-sentinel p 'shell-command-sentinel)
3502 (set-process-filter p 'comint-output-filter)))
3504 (prog1
3505 ;; Run the process.
3506 (apply 'process-file (car args) nil buffer nil (cdr args))
3507 ;; Insert error messages if they were separated.
3508 (when (listp buffer)
3509 (with-current-buffer error-buffer
3510 (insert-file-contents (cadr buffer)))
3511 (delete-file (cadr buffer)))
3512 (if current-buffer-p
3513 ;; This is like exchange-point-and-mark, but doesn't
3514 ;; activate the mark. It is cleaner to avoid activation,
3515 ;; even though the command loop would deactivate the mark
3516 ;; because we inserted text.
3517 (goto-char (prog1 (mark t)
3518 (set-marker (mark-marker) (point)
3519 (current-buffer))))
3520 ;; There's some output, display it.
3521 (when (with-current-buffer output-buffer (> (point-max) (point-min)))
3522 (display-message-or-buffer output-buffer)))))))
3524 (defun tramp-handle-substitute-in-file-name (filename)
3525 "Like `substitute-in-file-name' for Tramp files.
3526 \"//\" and \"/~\" substitute only in the local filename part."
3527 ;; Check, whether the local part is a quoted file name.
3528 (if (tramp-compat-file-name-quoted-p filename)
3529 filename
3530 ;; First, we must replace environment variables.
3531 (setq filename (tramp-replace-environment-variables filename))
3532 (with-parsed-tramp-file-name filename nil
3533 ;; Ignore in LOCALNAME everything before "//" or "/~".
3534 (when (and (stringp localname) (string-match ".+?/\\(/\\|~\\)" localname))
3535 (setq filename
3536 (concat (file-remote-p filename)
3537 (replace-match "\\1" nil nil localname)))
3538 ;; "/m:h:~" does not work for completion. We use "/m:h:~/".
3539 (when (string-match "~$" filename)
3540 (setq filename (concat filename "/"))))
3541 ;; We do not want to replace environment variables, again.
3542 (let (process-environment)
3543 (tramp-run-real-handler 'substitute-in-file-name (list filename))))))
3545 (defun tramp-handle-set-visited-file-modtime (&optional time-list)
3546 "Like `set-visited-file-modtime' for Tramp files."
3547 (unless (buffer-file-name)
3548 (error "Can't set-visited-file-modtime: buffer `%s' not visiting a file"
3549 (buffer-name)))
3550 (unless time-list
3551 (let ((remote-file-name-inhibit-cache t))
3552 ;; '(-1 65535) means file doesn't exists yet.
3553 (setq time-list
3554 (or (tramp-compat-file-attribute-modification-time
3555 (file-attributes (buffer-file-name)))
3556 '(-1 65535)))))
3557 ;; We use '(0 0) as a don't-know value.
3558 (unless (equal time-list '(0 0))
3559 (tramp-run-real-handler 'set-visited-file-modtime (list time-list))))
3561 (defun tramp-handle-verify-visited-file-modtime (&optional buf)
3562 "Like `verify-visited-file-modtime' for Tramp files.
3563 At the time `verify-visited-file-modtime' calls this function, we
3564 already know that the buffer is visiting a file and that
3565 `visited-file-modtime' does not return 0. Do not call this
3566 function directly, unless those two cases are already taken care
3567 of."
3568 (with-current-buffer (or buf (current-buffer))
3569 (let ((f (buffer-file-name)))
3570 ;; There is no file visiting the buffer, or the buffer has no
3571 ;; recorded last modification time, or there is no established
3572 ;; connection.
3573 (if (or (not f)
3574 (eq (visited-file-modtime) 0)
3575 (not (file-remote-p f nil 'connected)))
3577 (with-parsed-tramp-file-name f nil
3578 (let* ((remote-file-name-inhibit-cache t)
3579 (attr (file-attributes f))
3580 (modtime (tramp-compat-file-attribute-modification-time attr))
3581 (mt (visited-file-modtime)))
3583 (cond
3584 ;; File exists, and has a known modtime.
3585 ((and attr (not (equal modtime '(0 0))))
3586 (< (abs (tramp-time-diff
3587 modtime
3588 ;; For compatibility, deal with both the old
3589 ;; (HIGH . LOW) and the new (HIGH LOW) return
3590 ;; values of `visited-file-modtime'.
3591 (if (atom (cdr mt))
3592 (list (car mt) (cdr mt))
3593 mt)))
3595 ;; Modtime has the don't know value.
3596 (attr t)
3597 ;; If file does not exist, say it is not modified if and
3598 ;; only if that agrees with the buffer's record.
3599 (t (equal mt '(-1 65535))))))))))
3601 (defun tramp-handle-file-notify-add-watch (filename _flags _callback)
3602 "Like `file-notify-add-watch' for Tramp files."
3603 ;; This is the default handler. tramp-gvfs.el and tramp-sh.el have
3604 ;; their own one.
3605 (setq filename (expand-file-name filename))
3606 (with-parsed-tramp-file-name filename nil
3607 (tramp-error
3608 v 'file-notify-error "File notification not supported for `%s'" filename)))
3610 (defun tramp-handle-file-notify-rm-watch (proc)
3611 "Like `file-notify-rm-watch' for Tramp files."
3612 ;; The descriptor must be a process object.
3613 (unless (processp proc)
3614 (tramp-error proc 'file-notify-error "Not a valid descriptor %S" proc))
3615 (tramp-message proc 6 "Kill %S" proc)
3616 (delete-process proc))
3618 (defun tramp-handle-file-notify-valid-p (proc)
3619 "Like `file-notify-valid-p' for Tramp files."
3620 (and (process-live-p proc)
3621 ;; Sometimes, the process is still in status `run' when the
3622 ;; file or directory to be watched is deleted already.
3623 (with-current-buffer (process-buffer proc)
3624 (file-exists-p
3625 (concat (file-remote-p default-directory)
3626 (process-get proc 'watch-name))))))
3628 ;;; Functions for establishing connection:
3630 ;; The following functions are actions to be taken when seeing certain
3631 ;; prompts from the remote host. See the variable
3632 ;; `tramp-actions-before-shell' for usage of these functions.
3634 (defun tramp-action-login (_proc vec)
3635 "Send the login name."
3636 (when (not (stringp tramp-current-user))
3637 (setq tramp-current-user
3638 (with-tramp-connection-property vec "login-as"
3639 (save-window-excursion
3640 (let ((enable-recursive-minibuffers t))
3641 (pop-to-buffer (tramp-get-connection-buffer vec))
3642 (read-string (match-string 0)))))))
3643 (with-current-buffer (tramp-get-connection-buffer vec)
3644 (tramp-message vec 6 "\n%s" (buffer-string)))
3645 (tramp-message vec 3 "Sending login name `%s'" tramp-current-user)
3646 (tramp-send-string vec (concat tramp-current-user tramp-local-end-of-line)))
3648 (defun tramp-action-password (proc vec)
3649 "Query the user for a password."
3650 (with-current-buffer (process-buffer proc)
3651 (let ((enable-recursive-minibuffers t)
3652 (case-fold-search t))
3653 ;; Let's check whether a wrong password has been sent already.
3654 ;; Sometimes, the process returns a new password request
3655 ;; immediately after rejecting the previous (wrong) one.
3656 (unless (tramp-get-connection-property vec "first-password-request" nil)
3657 (tramp-clear-passwd vec))
3658 (goto-char (point-min))
3659 (tramp-check-for-regexp proc tramp-password-prompt-regexp)
3660 (tramp-message vec 3 "Sending %s" (match-string 1))
3661 ;; We don't call `tramp-send-string' in order to hide the
3662 ;; password from the debug buffer.
3663 (process-send-string
3664 proc (concat (tramp-read-passwd proc) tramp-local-end-of-line))
3665 ;; Hide password prompt.
3666 (narrow-to-region (point-max) (point-max)))))
3668 (defun tramp-action-succeed (_proc _vec)
3669 "Signal success in finding shell prompt."
3670 (throw 'tramp-action 'ok))
3672 (defun tramp-action-permission-denied (proc _vec)
3673 "Signal permission denied."
3674 (kill-process proc)
3675 (throw 'tramp-action 'permission-denied))
3677 (defun tramp-action-yesno (proc vec)
3678 "Ask the user for confirmation using `yes-or-no-p'.
3679 Send \"yes\" to remote process on confirmation, abort otherwise.
3680 See also `tramp-action-yn'."
3681 (save-window-excursion
3682 (let ((enable-recursive-minibuffers t))
3683 (save-match-data (pop-to-buffer (tramp-get-connection-buffer vec)))
3684 (unless (yes-or-no-p (match-string 0))
3685 (kill-process proc)
3686 (throw 'tramp-action 'permission-denied))
3687 (with-current-buffer (tramp-get-connection-buffer vec)
3688 (tramp-message vec 6 "\n%s" (buffer-string)))
3689 (tramp-send-string vec (concat "yes" tramp-local-end-of-line)))))
3691 (defun tramp-action-yn (proc vec)
3692 "Ask the user for confirmation using `y-or-n-p'.
3693 Send \"y\" to remote process on confirmation, abort otherwise.
3694 See also `tramp-action-yesno'."
3695 (save-window-excursion
3696 (let ((enable-recursive-minibuffers t))
3697 (save-match-data (pop-to-buffer (tramp-get-connection-buffer vec)))
3698 (unless (y-or-n-p (match-string 0))
3699 (kill-process proc)
3700 (throw 'tramp-action 'permission-denied))
3701 (with-current-buffer (tramp-get-connection-buffer vec)
3702 (tramp-message vec 6 "\n%s" (buffer-string)))
3703 (tramp-send-string vec (concat "y" tramp-local-end-of-line)))))
3705 (defun tramp-action-terminal (_proc vec)
3706 "Tell the remote host which terminal type to use.
3707 The terminal type can be configured with `tramp-terminal-type'."
3708 (tramp-message vec 5 "Setting `%s' as terminal type." tramp-terminal-type)
3709 (with-current-buffer (tramp-get-connection-buffer vec)
3710 (tramp-message vec 6 "\n%s" (buffer-string)))
3711 (tramp-send-string vec (concat tramp-terminal-type tramp-local-end-of-line)))
3713 (defun tramp-action-process-alive (proc _vec)
3714 "Check, whether a process has finished."
3715 (unless (process-live-p proc)
3716 (throw 'tramp-action 'process-died)))
3718 (defun tramp-action-out-of-band (proc vec)
3719 "Check, whether an out-of-band copy has finished."
3720 ;; There might be pending output for the exit status.
3721 (tramp-accept-process-output proc 0.1)
3722 (cond ((and (not (process-live-p proc))
3723 (zerop (process-exit-status proc)))
3724 (tramp-message vec 3 "Process has finished.")
3725 (throw 'tramp-action 'ok))
3726 ((or (and (memq (process-status proc) '(stop exit))
3727 (not (zerop (process-exit-status proc))))
3728 (memq (process-status proc) '(signal)))
3729 ;; `scp' could have copied correctly, but set modes could have failed.
3730 ;; This can be ignored.
3731 (with-current-buffer (process-buffer proc)
3732 (goto-char (point-min))
3733 (if (re-search-forward tramp-operation-not-permitted-regexp nil t)
3734 (progn
3735 (tramp-message vec 5 "'set mode' error ignored.")
3736 (tramp-message vec 3 "Process has finished.")
3737 (throw 'tramp-action 'ok))
3738 (tramp-message vec 3 "Process has died.")
3739 (throw 'tramp-action 'out-of-band-failed))))
3740 (t nil)))
3742 ;;; Functions for processing the actions:
3744 (defun tramp-process-one-action (proc vec actions)
3745 "Wait for output from the shell and perform one action."
3746 (let ((case-fold-search t)
3747 found todo item pattern action)
3748 (while (not found)
3749 ;; Reread output once all actions have been performed.
3750 ;; Obviously, the output was not complete.
3751 (tramp-accept-process-output proc 1)
3752 (setq todo actions)
3753 (while todo
3754 (setq item (pop todo))
3755 (setq pattern (format "\\(%s\\)\\'" (symbol-value (nth 0 item))))
3756 (setq action (nth 1 item))
3757 (tramp-message
3758 vec 5 "Looking for regexp \"%s\" from remote shell" pattern)
3759 (when (tramp-check-for-regexp proc pattern)
3760 (tramp-message vec 5 "Call `%s'" (symbol-name action))
3761 (setq found (funcall action proc vec)))))
3762 found))
3764 (defun tramp-process-actions (proc vec pos actions &optional timeout)
3765 "Perform ACTIONS until success or TIMEOUT.
3766 PROC and VEC indicate the remote connection to be used. POS, if
3767 set, is the starting point of the region to be deleted in the
3768 connection buffer."
3769 ;; Enable `auth-source', unless "emacs -Q" has been called. We must
3770 ;; use `tramp-current-*' variables in case we have several hops.
3771 (tramp-set-connection-property
3772 (make-tramp-file-name
3773 :method tramp-current-method :user tramp-current-user
3774 :domain tramp-current-domain :host tramp-current-host
3775 :port tramp-current-port)
3776 "first-password-request" tramp-cache-read-persistent-data)
3777 (save-restriction
3778 (with-tramp-progress-reporter
3779 proc 3 "Waiting for prompts from remote shell"
3780 (let (exit)
3781 (if timeout
3782 (with-timeout (timeout (setq exit 'timeout))
3783 (while (not exit)
3784 (setq exit
3785 (catch 'tramp-action
3786 (tramp-process-one-action proc vec actions)))))
3787 (while (not exit)
3788 (setq exit
3789 (catch 'tramp-action
3790 (tramp-process-one-action proc vec actions)))))
3791 (with-current-buffer (tramp-get-connection-buffer vec)
3792 (widen)
3793 (tramp-message vec 6 "\n%s" (buffer-string)))
3794 (unless (eq exit 'ok)
3795 (tramp-clear-passwd vec)
3796 (delete-process proc)
3797 (tramp-error-with-buffer
3798 (tramp-get-connection-buffer vec) vec 'file-error
3799 (cond
3800 ((eq exit 'permission-denied) "Permission denied")
3801 ((eq exit 'out-of-band-failed)
3802 (format-message
3803 "Copy failed, see buffer `%s' for details"
3804 (tramp-get-connection-buffer vec)))
3805 ((eq exit 'process-died)
3806 (substitute-command-keys
3807 (concat
3808 "Tramp failed to connect. If this happens repeatedly, try\n"
3809 " `\\[tramp-cleanup-this-connection]'")))
3810 ((eq exit 'timeout)
3811 (format-message
3812 "Timeout reached, see buffer `%s' for details"
3813 (tramp-get-connection-buffer vec)))
3814 (t "Login failed")))))
3815 (when (numberp pos)
3816 (with-current-buffer (tramp-get-connection-buffer vec)
3817 (let (buffer-read-only) (delete-region pos (point))))))))
3819 ;;; Utility functions:
3821 (defun tramp-accept-process-output (proc timeout)
3822 "Like `accept-process-output' for Tramp processes.
3823 This is needed in order to hide `last-coding-system-used', which is set
3824 for process communication also."
3825 (with-current-buffer (process-buffer proc)
3826 (let (buffer-read-only last-coding-system-used)
3827 ;; Under Windows XP, `accept-process-output' doesn't return
3828 ;; sometimes. So we add an additional timeout. JUST-THIS-ONE
3829 ;; is set due to Bug#12145. It is an integer, in order to avoid
3830 ;; running timers as well.
3831 (tramp-message
3832 proc 10 "%s %s %s\n%s"
3833 proc (process-status proc)
3834 (with-timeout (timeout)
3835 (accept-process-output proc timeout nil 0))
3836 (buffer-string)))))
3838 (defun tramp-check-for-regexp (proc regexp)
3839 "Check, whether REGEXP is contained in process buffer of PROC.
3840 Erase echoed commands if exists."
3841 (with-current-buffer (process-buffer proc)
3842 (goto-char (point-min))
3844 ;; Check whether we need to remove echo output.
3845 (when (and (tramp-get-connection-property proc "check-remote-echo" nil)
3846 (re-search-forward tramp-echoed-echo-mark-regexp nil t))
3847 (let ((begin (match-beginning 0)))
3848 (when (re-search-forward tramp-echoed-echo-mark-regexp nil t)
3849 ;; Discard echo from remote output.
3850 (tramp-set-connection-property proc "check-remote-echo" nil)
3851 (tramp-message proc 5 "echo-mark found")
3852 (forward-line 1)
3853 (delete-region begin (point))
3854 (goto-char (point-min)))))
3856 (when (or (not (tramp-get-connection-property proc "check-remote-echo" nil))
3857 ;; Sometimes, the echo string is suppressed on the remote side.
3858 (not (string-equal
3859 (substring-no-properties
3860 tramp-echo-mark-marker
3861 0 (min tramp-echo-mark-marker-length (1- (point-max))))
3862 (buffer-substring-no-properties
3863 (point-min)
3864 (min (+ (point-min) tramp-echo-mark-marker-length)
3865 (point-max))))))
3866 ;; No echo to be handled, now we can look for the regexp.
3867 ;; Sometimes, lines are much too long, and we run into a "Stack
3868 ;; overflow in regexp matcher". For example, //DIRED// lines of
3869 ;; directory listings with some thousand files. Therefore, we
3870 ;; look from the end.
3871 (goto-char (point-max))
3872 (ignore-errors (re-search-backward regexp nil t)))))
3874 (defun tramp-wait-for-regexp (proc timeout regexp)
3875 "Wait for a REGEXP to appear from process PROC within TIMEOUT seconds.
3876 Expects the output of PROC to be sent to the current buffer. Returns
3877 the string that matched, or nil. Waits indefinitely if TIMEOUT is
3878 nil."
3879 (with-current-buffer (process-buffer proc)
3880 (let ((found (tramp-check-for-regexp proc regexp)))
3881 (cond (timeout
3882 (with-timeout (timeout)
3883 (while (not found)
3884 (tramp-accept-process-output proc 1)
3885 (unless (process-live-p proc)
3886 (tramp-error-with-buffer
3887 nil proc 'file-error "Process has died"))
3888 (setq found (tramp-check-for-regexp proc regexp)))))
3890 (while (not found)
3891 (tramp-accept-process-output proc 1)
3892 (unless (process-live-p proc)
3893 (tramp-error-with-buffer
3894 nil proc 'file-error "Process has died"))
3895 (setq found (tramp-check-for-regexp proc regexp)))))
3896 (tramp-message proc 6 "\n%s" (buffer-string))
3897 (when (not found)
3898 (if timeout
3899 (tramp-error
3900 proc 'file-error "[[Regexp `%s' not found in %d secs]]"
3901 regexp timeout)
3902 (tramp-error proc 'file-error "[[Regexp `%s' not found]]" regexp)))
3903 found)))
3905 ;; It seems that Tru64 Unix does not like it if long strings are sent
3906 ;; to it in one go. (This happens when sending the Perl
3907 ;; `file-attributes' implementation, for instance.) Therefore, we
3908 ;; have this function which sends the string in chunks.
3909 (defun tramp-send-string (vec string)
3910 "Send the STRING via connection VEC.
3912 The STRING is expected to use Unix line-endings, but the lines sent to
3913 the remote host use line-endings as defined in the variable
3914 `tramp-rsh-end-of-line'. The communication buffer is erased before sending."
3915 (let* ((p (tramp-get-connection-process vec))
3916 (chunksize (tramp-get-connection-property p "chunksize" nil)))
3917 (unless p
3918 (tramp-error
3919 vec 'file-error "Can't send string to remote host -- not logged in"))
3920 (tramp-set-connection-property p "last-cmd-time" (current-time))
3921 (tramp-message vec 10 "%s" string)
3922 (with-current-buffer (tramp-get-connection-buffer vec)
3923 ;; Clean up the buffer. We cannot call `erase-buffer' because
3924 ;; narrowing might be in effect.
3925 (let (buffer-read-only) (delete-region (point-min) (point-max)))
3926 ;; Replace "\n" by `tramp-rsh-end-of-line'.
3927 (setq string
3928 (mapconcat
3929 'identity (split-string string "\n") tramp-rsh-end-of-line))
3930 (unless (or (string= string "")
3931 (string-equal (substring string -1) tramp-rsh-end-of-line))
3932 (setq string (concat string tramp-rsh-end-of-line)))
3933 ;; Send the string.
3934 (if (and chunksize (not (zerop chunksize)))
3935 (let ((pos 0)
3936 (end (length string)))
3937 (while (< pos end)
3938 (tramp-message
3939 vec 10 "Sending chunk from %s to %s"
3940 pos (min (+ pos chunksize) end))
3941 (process-send-string
3942 p (substring string pos (min (+ pos chunksize) end)))
3943 (setq pos (+ pos chunksize))))
3944 (process-send-string p string)))))
3946 (defun tramp-get-inode (vec)
3947 "Returns the virtual inode number.
3948 If it doesn't exist, generate a new one."
3949 (with-tramp-file-property vec (tramp-file-name-localname vec) "inode"
3950 (setq tramp-inodes (1+ tramp-inodes))))
3952 (defun tramp-get-device (vec)
3953 "Returns the virtual device number.
3954 If it doesn't exist, generate a new one."
3955 (with-tramp-connection-property (tramp-get-connection-process vec) "device"
3956 (cons -1 (setq tramp-devices (1+ tramp-devices)))))
3958 (defun tramp-equal-remote (file1 file2)
3959 "Check, whether the remote parts of FILE1 and FILE2 are identical.
3960 The check depends on method, user and host name of the files. If
3961 one of the components is missing, the default values are used.
3962 The local file name parts of FILE1 and FILE2 are not taken into
3963 account.
3965 Example:
3967 (tramp-equal-remote \"/ssh::/etc\" \"/<your host name>:/home\")
3969 would yield t. On the other hand, the following check results in nil:
3971 (tramp-equal-remote \"/sudo::/etc\" \"/su::/etc\")"
3972 (and (tramp-tramp-file-p file1)
3973 (tramp-tramp-file-p file2)
3974 (string-equal (file-remote-p file1) (file-remote-p file2))))
3976 ;;;###tramp-autoload
3977 (defun tramp-mode-string-to-int (mode-string)
3978 "Converts a ten-letter `drwxrwxrwx'-style mode string into mode bits."
3979 (let* (case-fold-search
3980 (mode-chars (string-to-vector mode-string))
3981 (owner-read (aref mode-chars 1))
3982 (owner-write (aref mode-chars 2))
3983 (owner-execute-or-setid (aref mode-chars 3))
3984 (group-read (aref mode-chars 4))
3985 (group-write (aref mode-chars 5))
3986 (group-execute-or-setid (aref mode-chars 6))
3987 (other-read (aref mode-chars 7))
3988 (other-write (aref mode-chars 8))
3989 (other-execute-or-sticky (aref mode-chars 9)))
3990 (save-match-data
3991 (logior
3992 (cond
3993 ((char-equal owner-read ?r) (string-to-number "00400" 8))
3994 ((char-equal owner-read ?-) 0)
3995 (t (error "Second char `%c' must be one of `r-'" owner-read)))
3996 (cond
3997 ((char-equal owner-write ?w) (string-to-number "00200" 8))
3998 ((char-equal owner-write ?-) 0)
3999 (t (error "Third char `%c' must be one of `w-'" owner-write)))
4000 (cond
4001 ((char-equal owner-execute-or-setid ?x) (string-to-number "00100" 8))
4002 ((char-equal owner-execute-or-setid ?S) (string-to-number "04000" 8))
4003 ((char-equal owner-execute-or-setid ?s) (string-to-number "04100" 8))
4004 ((char-equal owner-execute-or-setid ?-) 0)
4005 (t (error "Fourth char `%c' must be one of `xsS-'"
4006 owner-execute-or-setid)))
4007 (cond
4008 ((char-equal group-read ?r) (string-to-number "00040" 8))
4009 ((char-equal group-read ?-) 0)
4010 (t (error "Fifth char `%c' must be one of `r-'" group-read)))
4011 (cond
4012 ((char-equal group-write ?w) (string-to-number "00020" 8))
4013 ((char-equal group-write ?-) 0)
4014 (t (error "Sixth char `%c' must be one of `w-'" group-write)))
4015 (cond
4016 ((char-equal group-execute-or-setid ?x) (string-to-number "00010" 8))
4017 ((char-equal group-execute-or-setid ?S) (string-to-number "02000" 8))
4018 ((char-equal group-execute-or-setid ?s) (string-to-number "02010" 8))
4019 ((char-equal group-execute-or-setid ?-) 0)
4020 (t (error "Seventh char `%c' must be one of `xsS-'"
4021 group-execute-or-setid)))
4022 (cond
4023 ((char-equal other-read ?r) (string-to-number "00004" 8))
4024 ((char-equal other-read ?-) 0)
4025 (t (error "Eighth char `%c' must be one of `r-'" other-read)))
4026 (cond
4027 ((char-equal other-write ?w) (string-to-number "00002" 8))
4028 ((char-equal other-write ?-) 0)
4029 (t (error "Ninth char `%c' must be one of `w-'" other-write)))
4030 (cond
4031 ((char-equal other-execute-or-sticky ?x) (string-to-number "00001" 8))
4032 ((char-equal other-execute-or-sticky ?T) (string-to-number "01000" 8))
4033 ((char-equal other-execute-or-sticky ?t) (string-to-number "01001" 8))
4034 ((char-equal other-execute-or-sticky ?-) 0)
4035 (t (error "Tenth char `%c' must be one of `xtT-'"
4036 other-execute-or-sticky)))))))
4038 (defconst tramp-file-mode-type-map
4039 '((0 . "-") ; Normal file (SVID-v2 and XPG2)
4040 (1 . "p") ; fifo
4041 (2 . "c") ; character device
4042 (3 . "m") ; multiplexed character device (v7)
4043 (4 . "d") ; directory
4044 (5 . "?") ; Named special file (XENIX)
4045 (6 . "b") ; block device
4046 (7 . "?") ; multiplexed block device (v7)
4047 (8 . "-") ; regular file
4048 (9 . "n") ; network special file (HP-UX)
4049 (10 . "l") ; symlink
4050 (11 . "?") ; ACL shadow inode (Solaris, not userspace)
4051 (12 . "s") ; socket
4052 (13 . "D") ; door special (Solaris)
4053 (14 . "w")) ; whiteout (BSD)
4054 "A list of file types returned from the `stat' system call.
4055 This is used to map a mode number to a permission string.")
4057 ;;;###tramp-autoload
4058 (defun tramp-file-mode-from-int (mode)
4059 "Turn an integer representing a file mode into an ls(1)-like string."
4060 (let ((type (cdr
4061 (assoc (logand (lsh mode -12) 15) tramp-file-mode-type-map)))
4062 (user (logand (lsh mode -6) 7))
4063 (group (logand (lsh mode -3) 7))
4064 (other (logand (lsh mode -0) 7))
4065 (suid (> (logand (lsh mode -9) 4) 0))
4066 (sgid (> (logand (lsh mode -9) 2) 0))
4067 (sticky (> (logand (lsh mode -9) 1) 0)))
4068 (setq user (tramp-file-mode-permissions user suid "s"))
4069 (setq group (tramp-file-mode-permissions group sgid "s"))
4070 (setq other (tramp-file-mode-permissions other sticky "t"))
4071 (concat type user group other)))
4073 (defun tramp-file-mode-permissions (perm suid suid-text)
4074 "Convert a permission bitset into a string.
4075 This is used internally by `tramp-file-mode-from-int'."
4076 (let ((r (> (logand perm 4) 0))
4077 (w (> (logand perm 2) 0))
4078 (x (> (logand perm 1) 0)))
4079 (concat (or (and r "r") "-")
4080 (or (and w "w") "-")
4081 (or (and suid x suid-text) ; suid, execute
4082 (and suid (upcase suid-text)) ; suid, !execute
4083 (and x "x") "-")))) ; !suid
4085 ;;;###tramp-autoload
4086 (defun tramp-get-local-uid (id-format)
4087 "The uid of the local user, in ID-FORMAT.
4088 ID-FORMAT valid values are `string' and `integer'."
4089 (if (equal id-format 'integer) (user-uid) (user-login-name)))
4091 ;;;###tramp-autoload
4092 (defun tramp-get-local-gid (id-format)
4093 "The gid of the local user, in ID-FORMAT.
4094 ID-FORMAT valid values are `string' and `integer'."
4095 ;; `group-gid' has been introduced with Emacs 24.4.
4096 (if (and (fboundp 'group-gid) (equal id-format 'integer))
4097 (tramp-compat-funcall 'group-gid)
4098 (tramp-compat-file-attribute-group-id (file-attributes "~/" id-format))))
4100 (defun tramp-get-local-locale (&optional vec)
4101 "Determine locale, supporting UTF8 if possible.
4102 VEC is used for tracing."
4103 ;; We use key nil for local connection properties.
4104 (with-tramp-connection-property nil "locale"
4105 (let ((candidates '("en_US.utf8" "C.utf8" "en_US.UTF-8"))
4106 locale)
4107 (with-temp-buffer
4108 (unless (or (memq system-type '(windows-nt))
4109 (not (zerop (tramp-call-process
4110 nil "locale" nil t nil "-a"))))
4111 (while candidates
4112 (goto-char (point-min))
4113 (if (string-match (format "^%s\r?$" (regexp-quote (car candidates)))
4114 (buffer-string))
4115 (setq locale (car candidates)
4116 candidates nil)
4117 (setq candidates (cdr candidates))))))
4118 ;; Return value.
4119 (when vec (tramp-message vec 7 "locale %s" (or locale "C")))
4120 (or locale "C"))))
4122 ;;;###tramp-autoload
4123 (defun tramp-check-cached-permissions (vec access)
4124 "Check `file-attributes' caches for VEC.
4125 Return t if according to the cache access type ACCESS is known to
4126 be granted."
4127 (let ((result nil)
4128 (offset (cond
4129 ((eq ?r access) 1)
4130 ((eq ?w access) 2)
4131 ((eq ?x access) 3))))
4132 (dolist (suffix '("string" "integer") result)
4133 (setq
4134 result
4136 result
4137 (let ((file-attr
4139 (tramp-get-file-property
4140 vec (tramp-file-name-localname vec)
4141 (concat "file-attributes-" suffix) nil)
4142 (file-attributes
4143 (tramp-make-tramp-file-name
4144 (tramp-file-name-method vec)
4145 (tramp-file-name-user vec)
4146 (tramp-file-name-domain vec)
4147 (tramp-file-name-host vec)
4148 (tramp-file-name-port vec)
4149 (tramp-file-name-localname vec)
4150 (tramp-file-name-hop vec))
4151 (intern suffix))))
4152 (remote-uid
4153 (tramp-get-connection-property
4154 vec (concat "uid-" suffix) nil))
4155 (remote-gid
4156 (tramp-get-connection-property
4157 vec (concat "gid-" suffix) nil))
4158 (unknown-id
4159 (if (string-equal suffix "string")
4160 tramp-unknown-id-string tramp-unknown-id-integer)))
4161 (and
4162 file-attr
4164 ;; Not a symlink.
4165 (eq t (tramp-compat-file-attribute-type file-attr))
4166 (null (tramp-compat-file-attribute-type file-attr)))
4168 ;; World accessible.
4169 (eq access
4170 (aref (tramp-compat-file-attribute-modes file-attr)
4171 (+ offset 6)))
4172 ;; User accessible and owned by user.
4173 (and
4174 (eq access
4175 (aref (tramp-compat-file-attribute-modes file-attr) offset))
4176 (or (equal remote-uid
4177 (tramp-compat-file-attribute-user-id file-attr))
4178 (equal unknown-id
4179 (tramp-compat-file-attribute-user-id file-attr))))
4180 ;; Group accessible and owned by user's principal group.
4181 (and
4182 (eq access
4183 (aref (tramp-compat-file-attribute-modes file-attr)
4184 (+ offset 3)))
4185 (or (equal remote-gid
4186 (tramp-compat-file-attribute-group-id file-attr))
4187 (equal unknown-id
4188 (tramp-compat-file-attribute-group-id
4189 file-attr))))))))))))
4191 ;;;###tramp-autoload
4192 (defun tramp-local-host-p (vec)
4193 "Return t if this points to the local host, nil otherwise."
4194 (let ((host (tramp-file-name-host vec))
4195 (port (tramp-file-name-port vec)))
4196 (and
4197 (stringp host)
4198 (string-match tramp-local-host-regexp host)
4199 ;; A port is an indication for an ssh tunnel or alike.
4200 (null port)
4201 ;; The method shall be applied to one of the shell file name
4202 ;; handlers. `tramp-local-host-p' is also called for "smb" and
4203 ;; alike, where it must fail.
4204 (tramp-get-method-parameter vec 'tramp-login-program)
4205 ;; The local temp directory must be writable for the other user.
4206 (file-writable-p
4207 (tramp-make-tramp-file-name
4208 (tramp-file-name-method vec)
4209 (tramp-file-name-user vec)
4210 (tramp-file-name-domain vec)
4211 host port
4212 (tramp-compat-temporary-file-directory)))
4213 ;; On some systems, chown runs only for root.
4214 (or (zerop (user-uid))
4215 ;; This is defined in tramp-sh.el. Let's assume this is
4216 ;; loaded already.
4217 (zerop (tramp-compat-funcall 'tramp-get-remote-uid vec 'integer))))))
4219 (defun tramp-get-remote-tmpdir (vec)
4220 "Return directory for temporary files on the remote host identified by VEC."
4221 (with-tramp-connection-property vec "tmpdir"
4222 (let ((dir (tramp-make-tramp-file-name
4223 (tramp-file-name-method vec)
4224 (tramp-file-name-user vec)
4225 (tramp-file-name-domain vec)
4226 (tramp-file-name-host vec)
4227 (tramp-file-name-port vec)
4228 (or (tramp-get-method-parameter vec 'tramp-tmpdir) "/tmp")
4229 (tramp-file-name-hop vec))))
4230 (or (and (file-directory-p dir) (file-writable-p dir)
4231 (file-remote-p dir 'localname))
4232 (tramp-error vec 'file-error "Directory %s not accessible" dir))
4233 dir)))
4235 ;;;###tramp-autoload
4236 (defun tramp-make-tramp-temp-file (vec)
4237 "Create a temporary file on the remote host identified by VEC.
4238 Return the local name of the temporary file."
4239 (let ((prefix (expand-file-name
4240 tramp-temp-name-prefix (tramp-get-remote-tmpdir vec)))
4241 result)
4242 (while (not result)
4243 ;; `make-temp-file' would be the natural choice for
4244 ;; implementation. But it calls `write-region' internally,
4245 ;; which also needs a temporary file - we would end in an
4246 ;; infinite loop.
4247 (setq result (make-temp-name prefix))
4248 (if (file-exists-p result)
4249 (setq result nil)
4250 ;; This creates the file by side effect.
4251 (set-file-times result)
4252 (set-file-modes result (string-to-number "0700" 8))))
4254 ;; Return the local part.
4255 (with-parsed-tramp-file-name result nil localname)))
4257 (defun tramp-delete-temp-file-function ()
4258 "Remove temporary files related to current buffer."
4259 (when (stringp tramp-temp-buffer-file-name)
4260 (ignore-errors (delete-file tramp-temp-buffer-file-name))))
4262 (add-hook 'kill-buffer-hook 'tramp-delete-temp-file-function)
4263 (add-hook 'tramp-unload-hook
4264 (lambda ()
4265 (remove-hook 'kill-buffer-hook
4266 'tramp-delete-temp-file-function)))
4268 (defun tramp-handle-make-auto-save-file-name ()
4269 "Like `make-auto-save-file-name' for Tramp files.
4270 Returns a file name in `tramp-auto-save-directory' for autosaving
4271 this file, if that variable is non-nil."
4272 (when (stringp tramp-auto-save-directory)
4273 (setq tramp-auto-save-directory
4274 (expand-file-name tramp-auto-save-directory)))
4275 ;; Create directory.
4276 (unless (or (null tramp-auto-save-directory)
4277 (file-exists-p tramp-auto-save-directory))
4278 (make-directory tramp-auto-save-directory t))
4280 (let ((system-type
4281 (if (and (stringp tramp-auto-save-directory)
4282 (file-remote-p tramp-auto-save-directory))
4283 'not-windows
4284 system-type))
4285 (auto-save-file-name-transforms
4286 (if (null tramp-auto-save-directory)
4287 auto-save-file-name-transforms))
4288 (buffer-file-name
4289 (if (null tramp-auto-save-directory)
4290 buffer-file-name
4291 (expand-file-name
4292 (tramp-subst-strs-in-string
4293 '(("_" . "|")
4294 ("/" . "_a")
4295 (":" . "_b")
4296 ("|" . "__")
4297 ("[" . "_l")
4298 ("]" . "_r"))
4299 (tramp-compat-file-name-unquote (buffer-file-name)))
4300 tramp-auto-save-directory))))
4301 ;; Run plain `make-auto-save-file-name'.
4302 (tramp-run-real-handler 'make-auto-save-file-name nil)))
4304 (defun tramp-subst-strs-in-string (alist string)
4305 "Replace all occurrences of the string FROM with TO in STRING.
4306 ALIST is of the form ((FROM . TO) ...)."
4307 (save-match-data
4308 (while alist
4309 (let* ((pr (car alist))
4310 (from (car pr))
4311 (to (cdr pr)))
4312 (while (string-match (regexp-quote from) string)
4313 (setq string (replace-match to t t string)))
4314 (setq alist (cdr alist))))
4315 string))
4317 (defun tramp-handle-temporary-file-directory ()
4318 "Like `temporary-file-directory' for Tramp files."
4319 (catch 'result
4320 (dolist (dir `(,(ignore-errors
4321 (tramp-get-remote-tmpdir
4322 (tramp-dissect-file-name default-directory)))
4323 ,default-directory))
4324 (when (and (stringp dir) (file-directory-p dir) (file-writable-p dir))
4325 (throw 'result (expand-file-name dir))))))
4327 (defun tramp-handle-make-nearby-temp-file (prefix &optional dir-flag suffix)
4328 "Like `make-nearby-temp-file' for Tramp files."
4329 (let ((temporary-file-directory
4330 (tramp-compat-temporary-file-directory-function)))
4331 (make-temp-file prefix dir-flag suffix)))
4333 ;;; Compatibility functions section:
4335 (defun tramp-call-process
4336 (vec program &optional infile destination display &rest args)
4337 "Calls `call-process' on the local host.
4338 It always returns a return code. The Lisp error raised when
4339 PROGRAM is nil is trapped also, returning 1. Furthermore, traces
4340 are written with verbosity of 6."
4341 (let ((default-directory (tramp-compat-temporary-file-directory))
4342 (v (or vec
4343 (make-tramp-file-name
4344 :method tramp-current-method :user tramp-current-user
4345 :domain tramp-current-domain :host tramp-current-host
4346 :port tramp-current-port)))
4347 (destination (if (eq destination t) (current-buffer) destination))
4348 output error result)
4349 (tramp-message
4350 v 6 "`%s %s' %s %s"
4351 program (mapconcat 'identity args " ") infile destination)
4352 (condition-case err
4353 (with-temp-buffer
4354 (setq result
4355 (apply
4356 'call-process program infile (or destination t) display args))
4357 ;; `result' could also be an error string.
4358 (when (stringp result)
4359 (setq error result
4360 result 1))
4361 (with-current-buffer
4362 (if (bufferp destination) destination (current-buffer))
4363 (setq output (buffer-string))))
4364 (error
4365 (setq error (error-message-string err)
4366 result 1)))
4367 (if (zerop (length error))
4368 (tramp-message v 6 "%d\n%s" result output)
4369 (tramp-message v 6 "%d\n%s\n%s" result output error))
4370 result))
4372 (defun tramp-call-process-region
4373 (vec start end program &optional delete buffer display &rest args)
4374 "Calls `call-process-region' on the local host.
4375 It always returns a return code. The Lisp error raised when
4376 PROGRAM is nil is trapped also, returning 1. Furthermore, traces
4377 are written with verbosity of 6."
4378 (let ((default-directory (tramp-compat-temporary-file-directory))
4379 (v (or vec
4380 (make-tramp-file-name
4381 :method tramp-current-method :user tramp-current-user
4382 :domain tramp-current-domain :host tramp-current-host
4383 :port tramp-current-port)))
4384 (buffer (if (eq buffer t) (current-buffer) buffer))
4385 result)
4386 (tramp-message
4387 v 6 "`%s %s' %s %s %s %s"
4388 program (mapconcat 'identity args " ") start end delete buffer)
4389 (condition-case err
4390 (progn
4391 (setq result
4392 (apply
4393 'call-process-region
4394 start end program delete buffer display args))
4395 ;; `result' could also be an error string.
4396 (when (stringp result)
4397 (signal 'file-error (list result)))
4398 (with-current-buffer (if (bufferp buffer) buffer (current-buffer))
4399 (if (zerop result)
4400 (tramp-message v 6 "%d" result)
4401 (tramp-message v 6 "%d\n%s" result (buffer-string)))))
4402 (error
4403 (setq result 1)
4404 (tramp-message v 6 "%d\n%s" result (error-message-string err))))
4405 result))
4407 ;;;###tramp-autoload
4408 (defun tramp-read-passwd (proc &optional prompt)
4409 "Read a password from user (compat function).
4410 Consults the auth-source package.
4411 Invokes `password-read' if available, `read-passwd' else."
4412 (let* ((case-fold-search t)
4413 (key (tramp-make-tramp-file-name
4414 tramp-current-method tramp-current-user tramp-current-domain
4415 tramp-current-host tramp-current-port ""))
4416 (pw-prompt
4417 (or prompt
4418 (with-current-buffer (process-buffer proc)
4419 (tramp-check-for-regexp proc tramp-password-prompt-regexp)
4420 (format "%s for %s " (capitalize (match-string 1)) key))))
4421 ;; We suspend the timers while reading the password.
4422 (stimers (with-timeout-suspend))
4423 auth-info auth-passwd)
4425 (unwind-protect
4426 (with-parsed-tramp-file-name key nil
4427 (prog1
4429 ;; See if auth-sources contains something useful.
4430 (ignore-errors
4431 (and (tramp-get-connection-property
4432 v "first-password-request" nil)
4433 ;; Try with Tramp's current method.
4434 (setq auth-info
4435 (auth-source-search
4436 :max 1
4437 (and tramp-current-user :user)
4438 (if tramp-current-domain
4439 (format
4440 "%s%s%s"
4441 tramp-current-user tramp-prefix-domain-format
4442 tramp-current-domain)
4443 tramp-current-user)
4444 :host
4445 (if tramp-current-port
4446 (format
4447 "%s%s%s"
4448 tramp-current-host tramp-prefix-port-format
4449 tramp-current-port)
4450 tramp-current-host)
4451 :port tramp-current-method
4452 :require
4453 (cons
4454 :secret (and tramp-current-user '(:user))))
4455 auth-passwd (plist-get
4456 (nth 0 auth-info) :secret)
4457 auth-passwd (if (functionp auth-passwd)
4458 (funcall auth-passwd)
4459 auth-passwd))))
4460 ;; Try the password cache.
4461 (let ((password (password-read pw-prompt key)))
4462 (password-cache-add key password)
4463 password)
4464 ;; Else, get the password interactively.
4465 (read-passwd pw-prompt))
4466 (tramp-set-connection-property v "first-password-request" nil)))
4467 ;; Reenable the timers.
4468 (with-timeout-unsuspend stimers))))
4470 ;;;###tramp-autoload
4471 (defun tramp-clear-passwd (vec)
4472 "Clear password cache for connection related to VEC."
4473 (let ((method (tramp-file-name-method vec))
4474 (user (tramp-file-name-user vec))
4475 (domain (tramp-file-name-domain vec))
4476 (user-domain (tramp-file-name-user-domain vec))
4477 (host (tramp-file-name-host vec))
4478 (port (tramp-file-name-port vec))
4479 (host-port (tramp-file-name-host-port vec))
4480 (hop (tramp-file-name-hop vec)))
4481 (when hop
4482 ;; Clear also the passwords of the hops.
4483 (tramp-clear-passwd
4484 (tramp-dissect-file-name
4485 (concat
4486 tramp-prefix-format
4487 (replace-regexp-in-string
4488 (concat tramp-postfix-hop-regexp "$")
4489 tramp-postfix-host-format hop)))))
4490 (auth-source-forget
4491 `(:max 1 ,(and user-domain :user) ,user-domain
4492 :host ,host-port :port ,method))
4493 (password-cache-remove
4494 (tramp-make-tramp-file-name method user domain host port ""))))
4496 ;; Snarfed code from time-date.el.
4498 (defconst tramp-half-a-year '(241 17024)
4499 "Evaluated by \"(days-to-time 183)\".")
4501 ;;;###tramp-autoload
4502 (defun tramp-time-diff (t1 t2)
4503 "Return the difference between the two times, in seconds.
4504 T1 and T2 are time values (as returned by `current-time' for example)."
4505 ;; Starting with Emacs 25.1, we could change this to use `time-subtract'.
4506 (float-time (tramp-compat-funcall 'subtract-time t1 t2)))
4508 (defun tramp-unquote-shell-quote-argument (s)
4509 "Remove quotation prefix \"/:\" from string S, and quote it then for shell."
4510 (shell-quote-argument (tramp-compat-file-name-unquote s)))
4512 ;; Currently (as of Emacs 20.5), the function `shell-quote-argument'
4513 ;; does not deal well with newline characters. Newline is replaced by
4514 ;; backslash newline. But if, say, the string `a backslash newline b'
4515 ;; is passed to a shell, the shell will expand this into "ab",
4516 ;; completely omitting the newline. This is not what was intended.
4517 ;; It does not appear to be possible to make the function
4518 ;; `shell-quote-argument' work with newlines without making it
4519 ;; dependent on the shell used. But within this package, we know that
4520 ;; we will always use a Bourne-like shell, so we use an approach which
4521 ;; groks newlines.
4523 ;; The approach is simple: we call `shell-quote-argument', then
4524 ;; massage the newline part of the result.
4526 ;; This function should produce a string which is grokked by a Unix
4527 ;; shell, even if the Emacs is running on Windows. Since this is the
4528 ;; kludges section, we bind `system-type' in such a way that
4529 ;; `shell-quote-argument' behaves as if on Unix.
4531 ;; Thanks to Mario DeWeerd for the hint that it is sufficient for this
4532 ;; function to work with Bourne-like shells.
4533 ;;;###tramp-autoload
4534 (defun tramp-shell-quote-argument (s)
4535 "Similar to `shell-quote-argument', but groks newlines.
4536 Only works for Bourne-like shells."
4537 (let ((system-type 'not-windows))
4538 (save-match-data
4539 (let ((result (tramp-unquote-shell-quote-argument s))
4540 (nl (regexp-quote (format "\\%s" tramp-rsh-end-of-line))))
4541 (when (and (>= (length result) 2)
4542 (string= (substring result 0 2) "\\~"))
4543 (setq result (substring result 1)))
4544 (while (string-match nl result)
4545 (setq result (replace-match (format "'%s'" tramp-rsh-end-of-line)
4546 t t result)))
4547 result))))
4549 ;;; Signal handling. This works for remote processes, which have set
4550 ;;; the process property `remote-pid'.
4552 (defun tramp-interrupt-process (&optional process _current-group)
4553 "Interrupt remote process PROC."
4554 ;; CURRENT-GROUP is not implemented yet.
4555 (let ((proc (cond
4556 ((processp process) process)
4557 ((bufferp process) (get-buffer-process process))
4558 ((stringp process) (or (get-process process)
4559 (get-buffer-process process)))
4560 ((null process) (get-buffer-process (current-buffer)))
4561 (t process)))
4562 pid)
4563 ;; If it's a Tramp process, send the INT signal remotely.
4564 (when (and (processp proc) (setq pid (process-get proc 'remote-pid)))
4565 (if (not (process-live-p proc))
4566 (tramp-error proc 'error "Process %s is not active" proc)
4567 (tramp-message proc 5 "Interrupt process %s with pid %s" proc pid)
4568 ;; This is for tramp-sh.el. Other backends do not support this (yet).
4569 (tramp-compat-funcall
4570 'tramp-send-command
4571 (tramp-get-connection-property proc "vector" nil)
4572 (format "kill -2 %d" pid))
4573 ;; Wait, until the process has disappeared. If it doesn't,
4574 ;; fall back to the default implementation.
4575 (with-timeout (1 (ignore))
4576 (while (process-live-p proc)
4577 ;; We cannot run `tramp-accept-process-output', it blocks timers.
4578 (accept-process-output proc 0.1))
4579 ;; Report success.
4580 proc)))))
4582 ;; `interrupt-process-functions' exists since Emacs 26.1.
4583 (when (boundp 'interrupt-process-functions)
4584 (add-hook 'interrupt-process-functions 'tramp-interrupt-process)
4585 (add-hook
4586 'tramp-unload-hook
4587 (lambda ()
4588 (remove-hook 'interrupt-process-functions 'tramp-interrupt-process))))
4590 ;;; Integration of eshell.el:
4592 ;; eshell.el keeps the path in `eshell-path-env'. We must change it
4593 ;; when `default-directory' points to another host.
4594 (defun tramp-eshell-directory-change ()
4595 "Set `eshell-path-env' to $PATH of the host related to `default-directory'."
4596 (setq eshell-path-env
4597 (if (tramp-tramp-file-p default-directory)
4598 (with-parsed-tramp-file-name default-directory nil
4599 (mapconcat
4600 'identity
4602 ;; When `tramp-own-remote-path' is in `tramp-remote-path',
4603 ;; the remote path is only set in the session cache.
4604 (tramp-get-connection-property
4605 (tramp-get-connection-process v) "remote-path" nil)
4606 (tramp-get-connection-property v "remote-path" nil))
4607 ":"))
4608 (getenv "PATH"))))
4610 (eval-after-load "esh-util"
4611 '(progn
4612 (add-hook 'eshell-mode-hook
4613 'tramp-eshell-directory-change)
4614 (add-hook 'eshell-directory-change-hook
4615 'tramp-eshell-directory-change)
4616 (add-hook 'tramp-unload-hook
4617 (lambda ()
4618 (remove-hook 'eshell-mode-hook
4619 'tramp-eshell-directory-change)
4620 (remove-hook 'eshell-directory-change-hook
4621 'tramp-eshell-directory-change)))))
4623 ;; Checklist for `tramp-unload-hook'
4624 ;; - Unload all `tramp-*' packages
4625 ;; - Reset `file-name-handler-alist'
4626 ;; - Cleanup hooks where Tramp functions are in
4627 ;; - Cleanup advised functions
4628 ;; - Cleanup autoloads
4629 ;;;###autoload
4630 (defun tramp-unload-tramp ()
4631 "Discard Tramp from loading remote files."
4632 (interactive)
4633 ;; ange-ftp settings must be enabled.
4634 (tramp-compat-funcall 'tramp-ftp-enable-ange-ftp)
4635 ;; Maybe it's not loaded yet.
4636 (ignore-errors (unload-feature 'tramp 'force)))
4638 (provide 'tramp)
4640 ;;; TODO:
4642 ;; * Avoid screen blanking when hitting `g' in dired. (Eli Tziperman)
4644 ;; * Better error checking. At least whenever we see something
4645 ;; strange when doing zerop, we should kill the process and start
4646 ;; again. (Greg Stark)
4648 ;; * Make shadowfile.el grok Tramp filenames. (Bug#4526, Bug#4846)
4650 ;; * I was wondering if it would be possible to use tramp even if I'm
4651 ;; actually using sshfs. But when I launch a command I would like
4652 ;; to get it executed on the remote machine where the files really
4653 ;; are. (Andrea Crotti)
4655 ;; * Run emerge on two remote files. Bug is described here:
4656 ;; <https://www.mail-archive.com/tramp-devel@nongnu.org/msg01041.html>.
4657 ;; (Bug#6850)
4659 ;; * Refactor code from different handlers. Start with
4660 ;; *-process-file. One idea is to generalize `tramp-send-command'
4661 ;; and friends, for most of the handlers this is the major
4662 ;; difference between the different backends. Other handlers but
4663 ;; *-process-file would profit from this as well.
4665 ;;; tramp.el ends here
4667 ;; Local Variables:
4668 ;; mode: Emacs-Lisp
4669 ;; coding: utf-8
4670 ;; End: