From 6a522d9c682d7d49a572cf4908159d6218ec273c Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Wed, 8 Jun 2022 10:35:07 -0700 Subject: [PATCH] Make `AnsiRegex` able to capture Hyperlink ansi sequences (#17442) * Add the hyperlink ansi regex * Add test * Add comment --- .../FormatAndOutput/common/StringDecorated.cs | 5 ++++- test/powershell/engine/Formatting/PSStyle.Tests.ps1 | 9 +++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/src/System.Management.Automation/FormatAndOutput/common/StringDecorated.cs b/src/System.Management.Automation/FormatAndOutput/common/StringDecorated.cs index c2497bdff5..4e64738741 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/StringDecorated.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/StringDecorated.cs @@ -109,8 +109,11 @@ namespace System.Management.Automation.Internal // CSI escape sequences private const string CsiRegex = @"(\x1b\[\?\d+[hl])"; + // Hyperlink escape sequences. Note: '.*?' makes '.*' do non-greedy match. + private const string HyperlinkRegex = @"(\x1b\]8;;.*?\x1b\\)"; + // replace regex with .NET 6 API once available - internal static readonly Regex AnsiRegex = new Regex($"{GraphicsRegex}|{CsiRegex}", RegexOptions.Compiled); + internal static readonly Regex AnsiRegex = new Regex($"{GraphicsRegex}|{CsiRegex}|{HyperlinkRegex}", RegexOptions.Compiled); /// /// Get the ranges of all escape sequences in the text. diff --git a/test/powershell/engine/Formatting/PSStyle.Tests.ps1 b/test/powershell/engine/Formatting/PSStyle.Tests.ps1 index 6855ea713c..4fc8087a90 100644 --- a/test/powershell/engine/Formatting/PSStyle.Tests.ps1 +++ b/test/powershell/engine/Formatting/PSStyle.Tests.ps1 @@ -277,6 +277,15 @@ Describe 'Tests for $PSStyle automatic variable' { $result = & $pwsh -noprofile -Command { $PSStyle.Progress.UseOSCIndicator = $true; 'hello'} | Format-List $result | Out-String -Stream | Should -BeExactly 'hello' } + + It 'Able to handle Hyperlink ansi sequences' { + $word = "This is a link" + $hyperlink = $PSStyle.FormatHyperlink($word, "some random text as a link") + $strDec = [System.Management.Automation.Internal.StringDecorated]::new($hyperlink) + $strDec.IsDecorated | Should -BeTrue + $strDec.ContentLength | Should -Be $word.Length + $strDec.ToString("PlainText") | Should -Be $word + } } Describe 'Handle strings with escape sequences in formatting' {