From 9b6d394e01d50db4395cfe402531bfd96c540462 Mon Sep 17 00:00:00 2001
From: Gilbert Sanchez <me@gilbertsanchez.com>
Date: Fri, 27 Dec 2024 02:11:45 -0800
Subject: [PATCH] fix(init/pwsh): preserve ViModeChangeHandler (#6225)

* Combine ViModeChangeHandler

If a user has defined a ViModeChangeHandler setting this would respect that as well as redraw the prompt (to allow rendering things like the character change).

* Add newline

* Use call operator to limit new closure scope

* Pass any args to original handler
---
 src/init/starship.ps1 | 16 ++++++++++++++--
 1 file changed, 14 insertions(+), 2 deletions(-)

diff --git a/src/init/starship.ps1 b/src/init/starship.ps1
index f31d223d..e87156a7 100755
--- a/src/init/starship.ps1
+++ b/src/init/starship.ps1
@@ -211,8 +211,20 @@ $null = New-Module starship {
     )
 
     try {
-        Set-PSReadLineOption -ViModeIndicator script -ViModeChangeHandler {
-            [Microsoft.PowerShell.PSConsoleReadLine]::InvokePrompt()
+        # Combine user defined ViModeChangeHandler if it exists
+        if((Get-PSReadLineOption).ViModeChangeHandler){
+            # &{...} to limit the scope of the GetNewClosure
+            & {
+                $originalHandler = (Get-PSReadLineOption).ViModeChangeHandler
+                Set-PSReadLineOption -ViModeChangeHandler {
+                    [Microsoft.PowerShell.PSConsoleReadLine]::InvokePrompt()
+                    & $originalHandler @args
+                }.GetNewClosure()
+            }
+        } else {
+            Set-PSReadLineOption -ViModeIndicator script -ViModeChangeHandler {
+                [Microsoft.PowerShell.PSConsoleReadLine]::InvokePrompt()
+            }
         }
     } catch {}