wrapText wraps text to fit within a given width.
(text string, width int)
| 709 | |
| 710 | // wrapText wraps text to fit within a given width. |
| 711 | func wrapText(text string, width int) string { |
| 712 | if width <= 0 { |
| 713 | return text |
| 714 | } |
| 715 | |
| 716 | var result strings.Builder |
| 717 | words := strings.Fields(text) |
| 718 | lineLen := 0 |
| 719 | |
| 720 | for i, word := range words { |
| 721 | wordLen := len(word) |
| 722 | |
| 723 | if lineLen+wordLen+1 > width && lineLen > 0 { |
| 724 | result.WriteString("\n") |
| 725 | lineLen = 0 |
| 726 | } |
| 727 | |
| 728 | if lineLen > 0 { |
| 729 | result.WriteString(" ") |
| 730 | lineLen++ |
| 731 | } |
| 732 | |
| 733 | result.WriteString(word) |
| 734 | lineLen += wordLen |
| 735 | |
| 736 | // Handle very long words |
| 737 | if wordLen > width && i < len(words)-1 { |
| 738 | result.WriteString("\n") |
| 739 | lineLen = 0 |
| 740 | } |
| 741 | } |
| 742 | |
| 743 | return result.String() |
| 744 | } |
| 745 | |
| 746 | // max returns the maximum of two integers. |
| 747 | func max(a, b int) int { |
no test coverage detected