diff --git a/Sources/SwiftlyCore/StringExtensions.swift b/Sources/SwiftlyCore/StringExtensions.swift index 3e01c67c..15156cdf 100644 --- a/Sources/SwiftlyCore/StringExtensions.swift +++ b/Sources/SwiftlyCore/StringExtensions.swift @@ -1,64 +1,103 @@ -/// A description +import Foundation + extension String { - /// Wraps text to fit within specified column width - /// - /// This method reformats the string to ensure each line fits within the specified column width, - /// attempting to break at spaces when possible to avoid splitting words. - /// - /// - Parameters: - /// - columns: Maximum width (in characters) for each line - /// - wrappingIndent: Number of spaces to add at the beginning of each wrapped line (not the first line) - /// - /// - Returns: A new string with appropriate line breaks to maintain the specified column width - func wrapText(to columns: Int, wrappingIndent: Int = 0) -> String { - let effectiveColumns = columns - wrappingIndent - guard effectiveColumns > 0 else { return self } + func wrapText(to columns: Int) -> String { + guard columns > 0 else { return self } var result: [Substring] = [] - var currentIndex = self.startIndex - - while currentIndex < self.endIndex { - let nextChunk = self[currentIndex...].prefix(effectiveColumns) - - // Handle line breaks in the current chunk - if let lastLineBreak = nextChunk.lastIndex(of: "\n") { - result.append( - contentsOf: self[currentIndex.. lineStart { + let prevIndex = index(before: searchIndex) + if self[prevIndex].isWhitespace && self[prevIndex] != "\n" { + lastWhitespace = prevIndex + break + } + searchIndex = prevIndex + } + + if let lastWS = lastWhitespace { + result.append(self[lineStart.. String.Index { + guard index < endIndex else { return index } + + let remainingRange = index..