From 4b4ec86114bb317184f80e540e1582672a1a2d6f Mon Sep 17 00:00:00 2001 From: Vincent Ambo Date: Wed, 23 Aug 2023 22:20:37 +0300 Subject: fix(emacs-pkgs/term-switcher): switch buffers by object, not name The terminal switcher uses ivy to select buffers from a list of buffer *names*, however this can cause weird situations if, for example, two `vterm` sessions are in the same folder and buffer name uniquification is active. This commit implements a corrected solution, which constructs an association list of buffer names to their actual buffer object, and retrieves the buffer object from that list after the user has made their selection. This way, changes in buffer names during terminal selection do not lead to confusing results. Change-Id: I3ab3d6b715b32606cf771dabc31d9d4507c8b856 Reviewed-on: https://cl.tvl.fyi/c/depot/+/9145 Tested-by: BuildkiteCI Reviewed-by: tazjin --- tools/emacs-pkgs/term-switcher/term-switcher.el | 28 ++++++++++++------------- 1 file changed, 13 insertions(+), 15 deletions(-) diff --git a/tools/emacs-pkgs/term-switcher/term-switcher.el b/tools/emacs-pkgs/term-switcher/term-switcher.el index b7e4b049468e..9effac051ecc 100644 --- a/tools/emacs-pkgs/term-switcher/term-switcher.el +++ b/tools/emacs-pkgs/term-switcher/term-switcher.el @@ -27,18 +27,15 @@ :type '(string) :group 'term-switcher) -(defun ts/open-or-create-vterm (buffer-name) - "Switch to the buffer with BUFFER-NAME or create a new vterm - buffer." - (if (equal "New vterm" buffer-name) - ;; Don't open semi-broken vterms over tramp. - (if (file-remote-p default-directory) - (let ((default-directory "~")) - (vterm)) - (vterm)) - (if-let ((buffer (get-buffer buffer-name))) - (switch-to-buffer buffer) - (error "Could not find vterm buffer: %s" buffer-name)))) +(defun ts/open-or-create-vterm (buffer) + "Switch to the terminal in BUFFER, or create a new one if buffer is nil." + (if buffer + (switch-to-buffer buffer) + ;; Don't open semi-broken vterms over tramp. + (if (file-remote-p default-directory) + (let ((default-directory "~")) + (vterm)) + (vterm)))) (defun ts/is-vterm-buffer (buffer) "Determine whether BUFFER runs a vterm." @@ -48,15 +45,16 @@ "Switch to an existing vterm buffer or create a new one." (interactive) - (let ((terms (-map #'buffer-name + (let ((terms (-map (lambda (b) (cons (buffer-name b) b)) (-filter #'ts/is-vterm-buffer (buffer-list))))) (if terms (ivy-read "Switch to vterm: " - (cons "New vterm" terms) + (cons "New vterm" (-map #'car terms)) :caller 'ts/switch-to-terminal :preselect (s-concat "^" term-switcher-buffer-prefix) :require-match t - :action #'ts/open-or-create-vterm) + :action (lambda (match) + (ts/open-or-create-vterm (cdr (assoc match terms))))) (vterm)))) (provide 'term-switcher) -- cgit 1.4.1