diff --git a/testdata/example-out-no-indent.ttml b/testdata/example-out-no-indent.ttml new file mode 100644 index 0000000..88d7947 --- /dev/null +++ b/testdata/example-out-no-indent.ttml @@ -0,0 +1 @@ +Copyright testTitle test

(deep rumbling)

MAN:

How did we end up here?

This place is horrible.

Smells like balls.

We don't belong

in this shithole.

(computer playing

electronic melody)

diff --git a/ttml.go b/ttml.go index 7f1ffd9..492caf7 100644 --- a/ttml.go +++ b/ttml.go @@ -596,8 +596,29 @@ func (t TTMLOutDuration) MarshalText() ([]byte, error) { return []byte(formatDuration(time.Duration(t), ".", 3)), nil } +// WriteToTTMLOptions represents TTML write options. +type WriteToTTMLOptions struct { + Indent string // Default is 4 spaces. +} + +// WriteToTTMLOption represents a WriteToTTML option. +type WriteToTTMLOption func(o *WriteToTTMLOptions) + +// WriteToTTMLWithIndentOption sets the indent option. +func WriteToTTMLWithIndentOption(indent string) WriteToTTMLOption { + return func(o *WriteToTTMLOptions) { + o.Indent = indent + } +} + // WriteToTTML writes subtitles in .ttml format -func (s Subtitles) WriteToTTML(o io.Writer) (err error) { +func (s Subtitles) WriteToTTML(o io.Writer, opts ...WriteToTTMLOption) (err error) { + // Create write options + wo := &WriteToTTMLOptions{Indent: " "} + for _, opt := range opts { + opt(wo) + } + // Do not write anything if no subtitles if len(s.Items) == 0 { return ErrNoSubtitlesToWrite @@ -714,7 +735,10 @@ func (s Subtitles) WriteToTTML(o io.Writer) (err error) { // Marshal XML var e = xml.NewEncoder(o) - e.Indent("", " ") + + // Set indent + e.Indent("", wo.Indent) + if err = e.Encode(ttml); err != nil { err = fmt.Errorf("astisub: xml encoding failed: %w", err) return diff --git a/ttml_test.go b/ttml_test.go index bba9e36..0f0ac77 100644 --- a/ttml_test.go +++ b/ttml_test.go @@ -68,3 +68,20 @@ func TestTTMLBreakLines(t *testing.T) { assert.Equal(t, strings.TrimSpace(string(c)), strings.TrimSpace(w.String())) } + +func TestWriteToTTMLWithIndentOption(t *testing.T) { + // Open + s, err := astisub.OpenFile("./testdata/example-in.ttml") + assert.NoError(t, err) + + // Write + w := &bytes.Buffer{} + + err = s.WriteToTTML(w, astisub.WriteToTTMLWithIndentOption("")) + assert.NoError(t, err) + + c, err := ioutil.ReadFile("./testdata/example-out-no-indent.ttml") + assert.NoError(t, err) + + assert.Equal(t, strings.TrimSpace(string(c)), strings.TrimSpace(w.String())) +}