ps/Modules/Cole.PowerShell.Developer/Public/Format-TextWrapToDisplay.ps1

72 lines
2.3 KiB
PowerShell
Raw Permalink Normal View History

2023-05-30 22:51:22 -07:00
function Format-TextWrapToDisplay {
<#
.SYNOPSIS
Formats an input array of strings to no wider than the display of the screen
Keeps whole words together where possible
.PARAMETER InputText
Input text
.PARAMETER MaxWidth
Specify a specific fixed with. Defaults to the current console width.
.EXAMPLE
Format-TextWrapToDisplay -InputText <lorem ipsum text>
#>
[CmdletBinding()]
[OutputType([string[]])]
Param(
[Parameter(Mandatory = $false)]
[Alias('Width')]
[int]$MaxWidth,
[parameter(Mandatory = $false, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
[Alias('Text')]
[string[]]$InputText
)
$lines = @()
if ($MaxWidth -eq 0) {
$MaxWidth = (Get-ConsoleDisplayWidth)
}
$currentLineWords = @()
$currentLineCharCount = 0
$wordArray = $InputText.Split((' ',"`r","`n"),[System.StringSplitOptions]::RemoveEmptyEntries)
# Write-Output $linesArray
#foreach($line in $linesArray) {
# $lineSplits = $line.Split((' ',"`r","`n"),[System.StringSplitOptions]::RemoveEmptyEntries)
foreach($word in $wordArray) {
$currentWordLength = $word.Length
# We have a word that is longer than the current display width, so we need to account for that
if (($currentLineCharCount -eq 0) -and (($MaxWidth - $currentWordLength) -lt 2)) {
# add the word to the lines and continue
$lines += $word
Write-Host "triggered on too long of a word"
continue
}
# The current line buffer is larger than the offset allowance if we add another word
# Stop and stuff it on the output buffer, then continue
if (($MaxWidth - ($currentLineCharCount + $currentWordLength)) -lt 2) {
$lines += ($currentLineWords -join ' ').Trim()
$currentLineCharCount = 0
$currentLineWords = @()
}
$currentLineWords += $word
# add one to account for spaces
$currentLineCharCount += ($currentWordLength + 1)
}
$lines += ($currentLineWords -join ' ').Trim()
$currentLineWords = @()
$currentLineCharCount = 0
#}
return $lines
}