Subject: bug#59804: shell-resync-dirs hangs in (t)csh

From: Eli Zaretskii <[email-masked]>
Date: Sun, 04 Dec 2022 10:17:10 +0200

> From: Nicolas Graner <[email-masked]>
> Date: Sat, 03 Dec 2022 12:37:11 +0100
> 
> In a shell buffer where the running shell is csh or tcsh, the command
> shell-resync-dirs never returns.
> 
> You can test this even without changing your normal shell by typing
> `csh' in any shell buffer, then M-<RET>
> Emacs hangs until you quit with C-g.
> 
> The reason is that the `dirs' command in (t)csh (unlike its equivalent
> in bash) adds a trailing space to its output. This triggers an infinite
> loop.
> 
> As evidence that the trailing space is the culprit, note that this
> kludge, whiche removes it, fixes the problem:
> 
> (setq shell-dirstack-query "dirs | sed 's/ $//'")

Thanks for the analysis.  Does the patch below fix this problem?  If not,
could you point out more precisely where the command infloops and why?

diff --git a/lisp/shell.el b/lisp/shell.el
index b396bc2..dadbdcb 100644
--- a/lisp/shell.el
+++ b/lisp/shell.el
@@ -1162,6 +1162,7 @@ shell-resync-dirs
          (dlsl nil)
          (pos 0)
          (ds nil))
+    (setq dls (string-trim-right dls "[ ]+"))
     ;; Split the dirlist into whitespace and non-whitespace chunks.
     ;; dlsl will be a reversed list of tokens.
     (while (string-match "\\(\\S-+\\|\\s-+\\)" dls pos)