indent writer
diff --git a/indentwriter/indent.go b/indentwriter/indent.go
new file mode 100755
index 0000000..cb28159
--- /dev/null
+++ b/indentwriter/indent.go
@@ -0,0 +1,46 @@
+package indentwriter
+
+import (
+ "io"
+)
+
+// Writer indents each line of its input.
+type Writer struct {
+ w io.Writer
+ bol bool
+ pre [][]byte
+ sel int
+}
+
+// NewWriter makes a new write filter that indents the input lines.
+// Each line is prefixed with the corresponding element of pre. If
+// there are more lines than elements, the last element of pre is
+// repeated for each subsequent line.
+func NewWriter(w io.Writer, pre [][]byte) io.Writer {
+ return &Writer{
+ w: w,
+ pre: pre,
+ bol: true,
+ }
+}
+
+// The only errors returned are from the underlying writer.
+func (w *Writer) Write(p []byte) (n int, err error) {
+ for _, c := range p {
+ if w.bol {
+ if _, err = w.w.Write(w.pre[w.sel]); err != nil {
+ return n, err
+ }
+ }
+ _, err = w.w.Write([]byte{c})
+ if err != nil {
+ return n, err
+ }
+ n++
+ w.bol = c == '\n'
+ if w.bol && w.sel < len(w.pre)-1 {
+ w.sel++
+ }
+ }
+ return n, nil
+}
diff --git a/indentwriter/indent_test.go b/indentwriter/indent_test.go
new file mode 100644
index 0000000..57c10d5
--- /dev/null
+++ b/indentwriter/indent_test.go
@@ -0,0 +1,93 @@
+package indentwriter
+
+import (
+ "bytes"
+ "testing"
+)
+
+type T struct {
+ inp, exp string
+ pre []string
+}
+
+var ts = []T{
+ {
+ `
+The quick brown fox
+jumps over the lazy
+dog.
+But not quickly.
+`[1:],
+ `
+xxxThe quick brown fox
+xxxjumps over the lazy
+xxxdog.
+xxxBut not quickly.
+`[1:],
+ []string{"xxx"},
+ },
+ {
+ `
+The quick brown fox
+jumps over the lazy
+dog.
+But not quickly.
+`[1:],
+ `
+xxaThe quick brown fox
+xxxjumps over the lazy
+xxxdog.
+xxxBut not quickly.
+`[1:],
+ []string{"xxa", "xxx"},
+ },
+ {
+ `
+The quick brown fox
+jumps over the lazy
+dog.
+But not quickly.
+`[1:],
+ `
+xxaThe quick brown fox
+xxbjumps over the lazy
+xxcdog.
+xxxBut not quickly.
+`[1:],
+ []string{"xxa", "xxb", "xxc", "xxx"},
+ },
+ {
+ `
+The quick brown fox
+jumps over the lazy
+dog.
+
+But not quickly.`[1:],
+ `
+xxaThe quick brown fox
+xxxjumps over the lazy
+xxxdog.
+xxx
+xxxBut not quickly.`[1:],
+ []string{"xxa", "xxx"},
+ },
+}
+
+func TestIndent(t *testing.T) {
+ for _, test := range ts {
+ b := new(bytes.Buffer)
+ pre := make([][]byte, len(test.pre))
+ for i := range test.pre {
+ pre[i] = []byte(test.pre[i])
+ }
+ w := NewWriter(b, pre)
+ if _, err := w.Write([]byte(test.inp)); err != nil {
+ t.Error(err)
+ }
+ if got := b.String(); got != test.exp {
+ t.Errorf("mismatch %q != %q", got, test.exp)
+ t.Log(got)
+ t.Log(test.exp)
+ }
+ }
+}