Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

- add ReplaceRawByCallback #34

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions docx.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,10 @@ func (d *Docx) ReplaceRaw(oldString string, newString string, num int) {
d.content = strings.Replace(d.content, oldString, newString, num)
}

func (d *Docx) ReplaceRawByCallback(callback func(content string) string) {
d.content = callback(d.content)
}

func (d *Docx) Replace(oldString string, newString string, num int) (err error) {
oldString, err = encode(oldString)
if err != nil {
Expand Down
19 changes: 19 additions & 0 deletions docx_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"embed"
"fmt"
"io/ioutil"
"regexp"
"strings"
"testing"
)
Expand Down Expand Up @@ -104,6 +105,24 @@ func TestReplace(t *testing.T) {
}
}

func TestReplaceRawByCallback(t *testing.T) {
d := loadFile(testFile)

d.ReplaceRawByCallback(func(oldContent string) string {
return regexp.
MustCompile(`document\.`).
ReplaceAllStringFunc(oldContent, func(src string) string {
return "line1\r\nline2"
})
})

d.WriteToFile(testFileResult)
d = loadFile(testFileResult)
if strings.Contains(d.content, "word document.") {
t.Error("Should not contain 'word document.' after replacement, got ", d.content)
}
}

// To make test failure messages easier to read, trim off the beginning and end of the document to focus on the part expected
// to have changed
func extractMiddle(start, end int, content string) string {
Expand Down