Skip to content

Instantly share code, notes, and snippets.

@Szeraax
Last active November 20, 2021 05:29
Show Gist options
  • Save Szeraax/13088e212f78caa5c46f2521bf3e2623 to your computer and use it in GitHub Desktop.
Save Szeraax/13088e212f78caa5c46f2521bf3e2623 to your computer and use it in GitHub Desktop.
Colorize-Strings
function Colorize-Strings {
param(
[Alias("FullName", "Name")]
[parameter(
ValueFromPipeline,
ValueFromPipelineByPropertyName)]
$InputObject,
$Delimeter,
$Colors,
[switch]$DisableSort
)
begin {
if (-not $PSBoundParameters.Colors) {
$colors = 31..36 | ForEach-Object {
"`e[", $_, 'm' -join ''
}
}
if ($delim = $PSBoundParameters.Delimeter) {
$delim = [regex]::Escape($delim)
$re = [regex]"(?=$delim)"
}
else {
$re = [regex]"(?<=[a-z])(?=[A-Z\W])"
}
[System.Collections.Generic.List[string]]$list = @()
}
process {
foreach ($item in $InputObject) {
$list.Add($item)
}
}
end {
if (-not $PSBoundParameters.DisableSort) {
$list = $list | Sort-Object Name, { $_ }
}
$same_withNext = ''
$same_withPrev = ''
$color = ''
$count = 0
for ($i = 0; $i -lt $list.Count; $i++) {
$prefixText = ''
$default = (Get-PSReadLineOption).DefaultTokenColor
$pre = $default
$priorColor = $default
$words = $list[$i] -csplit $re
$nextWords = $list[$i + 1] -csplit $re
$res = Compare-Object -ReferenceObject $words -DifferenceObject $nextWords -SyncWindow 0 -IncludeEqual
$same_withNext = foreach ($item in $res) {
if ($item.SideIndicator -ne '==') { break }
$item
}
if ($i) {
$prevWords = $list[$i - 1] -csplit $re
$res = Compare-Object -ReferenceObject $words -DifferenceObject $prevWords -SyncWindow 0 -IncludeEqual
$same_withPrev = foreach ($item in $res) {
if ($item.SideIndicator -ne '==') { break }
$item
}
}
if ($same_withPrev.count -ge $same_withNext.count -and $same_withPrev.count -eq $count) {
$same = $same_withPrev
}
elseif ($same_withNext.count) {
$same = $same_withNext
$color = $colors | Where-Object { -not $_.Equals($priorColor) } | Get-Random
$priorColor = $color
$pre = $PSStyle.Foreground.$color
}
else {
$same = @()
$color = $default
}
$count = $same.count
$prefixText = $same.InputObject -join ''
# write-host $prefixText
$prefixText_re = [regex]::Escape($prefixText)
$text = $list[$i] -replace "^$prefixText_re"
"${color}${prefixText}${default}$text"
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment