From 8b2de76eff43e2a0861bcde9296e84c7173c0f98 Mon Sep 17 00:00:00 2001 From: MartinGC94 <42123497+MartinGC94@users.noreply.github.com> Date: Mon, 19 Jun 2023 19:20:13 +0200 Subject: [PATCH] Fix completion of the foreach-statement variable (#19814) --- .../engine/CommandCompletion/CompletionCompleters.cs | 11 +++++++++++ .../Host/TabCompletion/TabCompletion.Tests.ps1 | 5 +++++ 2 files changed, 16 insertions(+) diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs index 8dae46f339..1d69925f4e 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs @@ -5592,6 +5592,17 @@ namespace System.Management.Automation return AstVisitAction.Continue; } + public override AstVisitAction VisitForEachStatement(ForEachStatementAst forEachStatementAst) + { + if (forEachStatementAst.Extent.StartOffset > StopSearchOffset || forEachStatementAst.Variable == CompletionVariableAst) + { + return AstVisitAction.StopVisit; + } + + SaveVariableInfo(forEachStatementAst.Variable.VariablePath.UserPath, variableType: null, isConstraint: false); + return AstVisitAction.Continue; + } + public override AstVisitAction VisitAttribute(AttributeAst attributeAst) { // Attributes can't assign values to variables so they aren't interesting. diff --git a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 index a9cc9801d0..2981f583eb 100644 --- a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 +++ b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 @@ -74,6 +74,11 @@ Describe "TabCompletion" -Tags CI { $res.CompletionMatches[0].CompletionText | Should -BeExactly 'pscustomobject' } + It 'Should complete foreach variable' { + $res = TabExpansion2 -inputScript 'foreach ($CurrentItem in 1..10){$CurrentIt' + $res.CompletionMatches[0].CompletionText | Should -BeExactly '$CurrentItem' + } + foreach ($Operator in [System.Management.Automation.CompletionCompleters]::CompleteOperator("")) { It "Should complete $($Operator.CompletionText)" {