Skip to content

Instantly share code, notes, and snippets.

@lzybkr
Created June 23, 2016 16:10
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save lzybkr/dcb973dccd54900b67783c48083c28f7 to your computer and use it in GitHub Desktop.
Save lzybkr/dcb973dccd54900b67783c48083c28f7 to your computer and use it in GitHub Desktop.
<Configuration>
<ViewDefinitions>
<View>
<Name>MatchInfo</Name>
<ViewSelectedBy>
<TypeName>Microsoft.PowerShell.Commands.MatchInfo</TypeName>
</ViewSelectedBy>
<CustomControl>
<CustomEntries>
<CustomEntry>
<CustomItem>
<ExpressionBinding>
<ScriptBlock>
[string]$curDir = $pwd.Path
if (!$host.UI.SupportsVirtualTerminal)
{
$_.ToString($curDir)
return
}
function FormatLine($matchInfo, [string]$line, [int]$lineNumber, [string]$displayPath, [string]$prefix, [switch]$isMatchLine)
{
if ($isMatchLine)
{
$esc = [char]0x1b
$matchStart = $matchInfo.Matches[0].Index
$matchLength = $matchInfo.Matches[0].Length
$matchEnd = $matchStart + $matchLength
$line = $line.Substring(0, $matchStart) + "${esc}[93m" + $line.Substring($matchStart, $matchLength) + "${esc}[0m" + $line.Substring($matchEnd)
}
if ($matchInfo.Path -ne 'InputStream')
{
"{0}{1}:{2}:{3}" -f $prefix, $displayPath, $lineNumber, $line
}
else
{
"{0}{1}" -f $prefix, $line
}
}
$displayPath = if ('' -eq $curDir) { $_.Path } else { $_.RelativePath($curDir) }
if ($null -eq $_.Context)
{
FormatLine -MatchInfo $_ -Line $_.Line -LineNumber $_.LineNumber -DisplayPath $displayPath -Prefix "" -IsMatchLine
}
else
{
$lines = . {
$displayLineNumber = $_.LineNumber - $_.Context.DisplayPreContext.Length;
foreach ($contextLine in $_.Context.DisplayPreContext)
{
FormatLine -MatchInfo $_ -Line $contextLine -LineNumber $displayLineNumber -DisplayPath $displayPath -Prefix " "
$displayLineNumber += 1
}
FormatLine -MatchInfo $_ -Line $_.Line -LineNumber $displayLineNumber -DisplayPath $displayPath -Prefix "> " -IsMatchLine
$displayLineNumber += 1
foreach ($contextLine in $_.Context.DisplayPostContext)
{
FormatLine -MatchInfo $_ -Line $contextLine -LineNumber $displayLineNumber -DisplayPath $displayPath -Prefix " "
$displayLineNumber += 1
}
}
$lines -join ([Environment]::Newline)
}
</ScriptBlock>
</ExpressionBinding>
</CustomItem>
</CustomEntry>
</CustomEntries>
</CustomControl>
</View>
</ViewDefinitions>
</Configuration>
@Jaykul
Copy link

Jaykul commented Aug 18, 2018

Need a foreach on matches to handle the -AllMatches instead of just highlighting the first one

    if ($isMatchLine)
    {
        $esc = [char]0x1b
        for($i = $matchInfo.Matches.Count -1; $i -ge 0; $i--){
            $match = $matchInfo.Matches[$i]
            $Line = $Line.Insert($match.Index + $match.Length, "$esc[0m").Insert($match.Index, (Get-PSReadLineOption).EmphasisColor)
        }
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment