2024-06-02 07:53:13 +01:00
|
|
|
// SPDX-FileCopyrightText: 2024 Dan Anglin <d.n.i.anglin@gmail.com>
|
|
|
|
//
|
|
|
|
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
|
|
|
2024-07-07 18:09:46 +01:00
|
|
|
package printer
|
2024-05-29 18:33:16 +01:00
|
|
|
|
|
|
|
import (
|
2024-07-08 18:31:39 +01:00
|
|
|
"regexp"
|
2024-05-29 18:33:16 +01:00
|
|
|
"strings"
|
|
|
|
"unicode"
|
|
|
|
)
|
|
|
|
|
2024-07-07 18:09:46 +01:00
|
|
|
func (p Printer) wrapLines(text string, nIndent int) string {
|
|
|
|
if nIndent >= p.lineWrapCharacterLimit {
|
|
|
|
nIndent = 0
|
|
|
|
}
|
|
|
|
|
|
|
|
separator := "\n" + strings.Repeat(" ", nIndent)
|
|
|
|
|
2024-05-29 18:33:16 +01:00
|
|
|
lines := strings.Split(text, "\n")
|
|
|
|
|
|
|
|
if len(lines) == 1 {
|
2024-07-07 22:46:40 +01:00
|
|
|
return wrapLine(lines[0], separator, p.lineWrapCharacterLimit-nIndent)
|
2024-05-29 18:33:16 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
var builder strings.Builder
|
|
|
|
|
2024-07-08 18:31:39 +01:00
|
|
|
singleDigitListItemRegex := regexp.MustCompile(`^[0-9]{1}\.\s.*$`)
|
|
|
|
doubleDigitListItemRegex := regexp.MustCompile(`^[0-9]{2}\.\s.*$`)
|
2024-07-07 22:46:40 +01:00
|
|
|
|
2024-07-08 18:31:39 +01:00
|
|
|
for ind, line := range lines {
|
|
|
|
builder.WriteString(wrapLine(line, separator+extraIndent(line, singleDigitListItemRegex, doubleDigitListItemRegex), p.lineWrapCharacterLimit-nIndent))
|
2024-05-29 18:33:16 +01:00
|
|
|
|
2024-07-08 18:31:39 +01:00
|
|
|
if ind < len(lines)-1 {
|
2024-05-29 18:33:16 +01:00
|
|
|
builder.WriteString(separator)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return builder.String()
|
|
|
|
}
|
|
|
|
|
|
|
|
func wrapLine(line, separator string, charLimit int) string {
|
|
|
|
if len(line) <= charLimit {
|
|
|
|
return line
|
|
|
|
}
|
|
|
|
|
|
|
|
leftcursor, rightcursor := 0, 0
|
|
|
|
|
|
|
|
var builder strings.Builder
|
|
|
|
|
|
|
|
for rightcursor < (len(line) - charLimit) {
|
2024-06-02 14:06:49 +01:00
|
|
|
rightcursor += (charLimit - 1)
|
2024-05-29 18:33:16 +01:00
|
|
|
|
2024-06-02 14:06:49 +01:00
|
|
|
for (rightcursor > leftcursor) && !unicode.IsSpace(rune(line[rightcursor-1])) {
|
2024-05-29 18:33:16 +01:00
|
|
|
rightcursor--
|
|
|
|
}
|
|
|
|
|
|
|
|
if rightcursor == leftcursor {
|
|
|
|
rightcursor = leftcursor + charLimit
|
|
|
|
}
|
|
|
|
|
|
|
|
builder.WriteString(line[leftcursor:rightcursor] + separator)
|
|
|
|
leftcursor = rightcursor
|
|
|
|
}
|
|
|
|
|
|
|
|
builder.WriteString(line[rightcursor:])
|
|
|
|
|
|
|
|
return builder.String()
|
|
|
|
}
|
2024-07-08 18:31:39 +01:00
|
|
|
|
|
|
|
func extraIndent(line string, singleDigitListItemRegex, doubleDigitListItemRegex *regexp.Regexp) string {
|
|
|
|
if strings.HasPrefix(line, symbolBullet) {
|
|
|
|
return " "
|
|
|
|
}
|
|
|
|
|
|
|
|
if singleDigitListItemRegex.MatchString(line) {
|
|
|
|
return " "
|
|
|
|
}
|
|
|
|
|
|
|
|
if doubleDigitListItemRegex.MatchString(line) {
|
|
|
|
return " "
|
|
|
|
}
|
|
|
|
|
|
|
|
return ""
|
|
|
|
}
|