~dricottone/textwrap

ref: b4b5e0f115cd621eb226f0de660f7b641b61f724 textwrap/common/textwrap.go -rw-r--r-- 1.3 KiB
b4b5e0f1Dominic Ricottone Updating go version and module name 2 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package common

import (
	"strings"
	"regexp"
)

func MakeBreakline(length int) string {
	return strings.Repeat("-", length)
}

func MakeWrappedLine(line string, length int, re_quote *regexp.Regexp) []string {
	offset := 0
	prefix := ""

	quote := re_quote.FindString(line)
	len_quote := len(quote)
	if len_quote != 0 && len_quote < length {
		offset = len_quote
		prefix = quote
	}

	buffer := []string{prefix}
	line_number := 0
	for index, rune := range line[offset:] {
		buffer[line_number] += string(rune)
		if (index + 1) % (length - offset) == 0 {
			buffer = append(buffer, prefix)
			line_number += 1
		}
	}

	return buffer
}

func WrapArray(lines []string, length int) ([]string, error) {
	// Compile regular expressions
	re_quote, err := regexp.Compile("^([> ]*)")
	if err != nil {
		return nil, err
	}
	re_break, err := regexp.Compile("^(?:-{5,}|={5,})$")
	if err != nil {
		return nil, err
	}

	wrapped := []string{}

	for i := 0; i < len(lines); i++ {
		line := strings.TrimSpace(lines[i])

		if len(line) > length {
			if re_break.MatchString(line) {
				wrapped = append(wrapped, MakeBreakline(length))
			} else {
				wrapped = append(wrapped, MakeWrappedLine(line, length, re_quote)...)
			}
		} else {
			wrapped = append(wrapped, line)
		}
	}

	return wrapped, nil
}