PSColor icon indicating copy to clipboard operation
PSColor copied to clipboard

pscolor eats the context when using select-string with context

Open kchan345 opened this issue 7 years ago • 2 comments

Hi,

Example of the issue:

test.txt content: 1 2 3 4 5 6 7 8

command: select-string .\test.txt -pattern "5" -context 3

output when only pscolor module is loaded: test.txt:5:5

output when no modules are loaded:

  test.txt:2:2
  test.txt:3:3
  test.txt:4:4
> test.txt:5:5
  test.txt:6:6
  test.txt:7:7
  test.txt:8:8

Thank you for your color module :)

kchan345 avatar Jul 07 '17 22:07 kchan345

I took a look and modified matchinfo.ps1 as follow.

function MatchInfo {
    param (
        [Parameter(Mandatory=$True,Position=1)]
        $match
    )

    $contextStartLineNumber = $match.LineNumber - $match.Context.DisplayPreContext.Length

    $relPath = $match.RelativePath($pwd)

    foreach ($contextLine in $match.Context.DisplayPreContext) {
        matchInfoFormatLine $relPath ($contextStartLineNumber++) $contextLine $false
    }

    matchInfoFormatLine $relPath $match.LineNumber $match.Line $true

    foreach ($contextLine in $match.Context.DisplayPostContext) {
        matchInfoFormatLine $relPath (++$contextStartLineNumber) $contextLine $false
    }
}

function matchInfoFormatLine {
    param (
        $relPath,
        $lineNum,
        $line,
        $isMatch
    )

    if ($true -eq $isMatch) {
        Write-host ">" -noNewLine
    }
    else {
        Write-host " " -noNewLine
    }

    Write-host $relPath -foregroundcolor $global:PSColor.Match.Path.Color -noNewLine
    Write-host ':' -foregroundcolor $global:PSColor.Match.Default.Color -noNewLine
    Write-host $lineNum -foregroundcolor $global:PSColor.Match.LineNumber.Color -noNewLine
    Write-host ':' -foregroundcolor $global:PSColor.Match.Default.Color -noNewLine
    Write-host $line -foregroundcolor $global:PSColor.Match.Line.Color
}

kchan345 avatar Jul 08 '17 01:07 kchan345

that solution seems to work. Can this be added to the original code ?

moyue83 avatar Oct 27 '20 08:10 moyue83