Subject: Re: bug#28591: 27.0.50; xterm-set-window-title

From: Mark Oteiza <[email-masked]>
Date: Mon, 25 Sep 2017 13:24:24 -0400

Mark Oteiza <[email-masked]> writes:

> Katsumi Yamaoka <[email-masked]> writes:
>
>> The feature looks nice but I want the original title to come back
>> when Emacs exits or suspends (even if it launches with -Q).
>
> I posted a patch here
> https://lists.gnu.org/archive/html/emacs-devel/2017-09/msg00728.html
>
> but at the moment it's not clear to me how to handle other terminals
> that use an xterm- family terminfo.

The following lightly tested patch appears to do the right thing here.

diff --git a/lisp/term/xterm.el b/lisp/term/xterm.el
index 6a17d382b0..d7214fc849 100644
--- a/lisp/term/xterm.el
+++ b/lisp/term/xterm.el
@@ -708,6 +708,16 @@ xterm--version-handler
           ;;(xterm--init-activate-get-selection)
           (xterm--init-activate-set-selection))))))
 
+(defvar xterm-window-title-stack nil)
+
+(defun xterm--title-handler ()
+  (let ((str "")
+        chr)
+    (while (and (setq chr (read-event nil nil 2))
+                (not (equal chr ?\\)))
+      (setq str (concat str (string chr))))
+    (push str xterm-window-title-stack)))
+
 (defvar xterm-query-timeout 2
   "Seconds to wait for an answer from the terminal.
 Can be nil to mean \"no timeout\".")
@@ -837,12 +847,28 @@ xterm--init-activate-set-selection
 
 (defun xterm--init-frame-title ()
   "Terminal initialization for XTerm frame titles."
+  (xterm-push-title-stack)
   (xterm-set-window-title)
+  (add-hook 'delete-frame-functions 'xterm-pop-title-stack)
   (add-hook 'after-make-frame-functions 'xterm-set-window-title-flag)
   (add-hook 'window-configuration-change-hook 'xterm-unset-window-title-flag)
-  (add-hook 'post-command-hook 'xterm-set-window-title)
+  (add-hook 'pre-redisplay-functions 'xterm-set-window-title)
   (add-hook 'minibuffer-exit-hook 'xterm-set-window-title))
 
+(defun xterm-push-title-stack ()
+  "Store terminal window title in XTerm's internal stack."
+  ;; (send-string-to-terminal "\e[22;0t")
+  (xterm--query "\e[21;0t"
+                '(("\e]l" . xterm--title-handler))))
+
+(defun xterm-pop-title-stack (&optional terminal)
+  "Pop terminal window title from XTerm's internal stack."
+  ;; (send-string-to-terminal "\e[23;0t" terminal)
+  (when xterm-window-title-stack
+    (send-string-to-terminal
+     (format "\e]2;%s\a" (pop xterm-window-title-stack))
+     terminal)))
+
 (defvar xterm-window-title-flag nil
   "Whether a new frame has been created, calling for a title update.")
 
@@ -861,7 +887,7 @@ xterm-set-window-title
 The title is constructed from `frame-title-format'."
   (send-string-to-terminal
    (format "\e]2;%s\a" (format-mode-line frame-title-format))
-   terminal))
+   (if (windowp terminal) (window-frame terminal) terminal)))
 
 (defun xterm--selection-char (type)
   (pcase type