Add template functions trim and wrap
authorMikael Berthe <mikael@lilotux.net>
Sun, 07 May 2017 21:53:13 +0200
changeset 93 1cef5da83488
parent 92 aa7d918e727d
child 94 4c0206d283e5
Add template functions trim and wrap
printer/templateprinter.go
--- a/printer/templateprinter.go	Sun May 07 19:52:58 2017 +0200
+++ b/printer/templateprinter.go	Sun May 07 21:53:13 2017 +0200
@@ -6,11 +6,14 @@
 package printer
 
 import (
+	"bytes"
 	"encoding/json"
 	"fmt"
+	"go/doc"
 	"io"
 	"os"
 	"reflect"
+	"strings"
 	"text/template"
 
 	"github.com/m0t0k1ch1/gomif"
@@ -42,6 +45,8 @@
 		"fromhtml": html2string,
 		"fromunix": unix2string,
 		"color":    ansiColor,
+		"trim":     strings.TrimSpace,
+		"wrap":     wrap,
 	}).Parse(tmpl)
 	if err != nil {
 		return nil, err
@@ -150,3 +155,17 @@
 	}
 	return colors.ANSICodeString(desc)
 }
+
+// Wrap text with indent prefix
+// Currently paragraph-based (cf. doc.ToText), which is not very good for
+// our use case since CRs are ignored.
+func wrap(indent string, lineLength int, text string) string {
+	var buf bytes.Buffer
+
+	width := lineLength - len(indent)
+	if width < 10 {
+		width = 10
+	}
+	doc.ToText(&buf, text, indent, indent+"  ", width)
+	return buf.String()
+}