1
0
mirror of https://github.com/fumiama/go-docx.git synced 2026-06-04 23:30:25 +08:00

add MergeSamePropRunsOf

This commit is contained in:
源文雨
2023-03-07 17:48:10 +08:00
parent e12804cfab
commit 2a630f6342
2 changed files with 64 additions and 2 deletions

View File

@@ -122,6 +122,50 @@ func MergeSamePropRuns(r1, r2 *Run) bool {
return true
}
// MergeSamePropRunsOf merges runs with the same properties of names
func MergeSamePropRunsOf(name ...string) RunMergeRule {
return func(r1, r2 *Run) bool {
if r1 == nil || r2 == nil {
return false
}
if r1.RunProperties == r2.RunProperties {
return true
}
if r1.RunProperties == nil && r2.RunProperties != nil {
return false
}
if r1.RunProperties != nil && r2.RunProperties == nil {
return false
}
rr1 := reflect.ValueOf(r1.RunProperties).Elem()
rr2 := reflect.ValueOf(r2.RunProperties).Elem()
for _, n := range name {
x1 := rr1.FieldByName(n)
x2 := rr2.FieldByName(n)
if x1.IsZero() && x2.IsZero() {
continue
}
if x1.IsZero() && !x2.IsZero() {
return false
}
if !x1.IsZero() && x2.IsZero() {
return false
}
xx1 := x1.Elem()
if xx1.NumField() <= 1 {
continue
}
xx2 := x2.Elem()
for j := 1; j < xx1.NumField(); j++ {
if !xx1.Field(j).Equal(xx2.Field(j)) {
return false
}
}
}
return true
}
}
// MergeText will merge contiguous run texts in a paragraph into one run
//
// note: np is not a deep-copy

View File

@@ -187,8 +187,9 @@ const xml2merge = `<w:p w14:paraId="343EA723" w14:textId="17A5316C" w:rsidR="00B
</w:p>`
const (
allmergedtext = `某某某大学2016-2017学年第1学期期末考试A卷`
propmergedtext = `某某某大学201|6|-201|7|学年第|1|学期期|末|考试||A||卷|`
allmergedtext = `某某某大学2016-2017学年第1学期期末考试A卷`
propmergedtext = `某某某大学201|6|-201|7|学年第|1|学期期|末|考试||A||卷|`
namedpropmergdtext = `某某某大学2016-2017学年第|1|学期期|末|考试|A|卷|`
)
func TestMergeText(t *testing.T) {
@@ -224,4 +225,21 @@ func TestMergeText(t *testing.T) {
if sb.String() != propmergedtext {
t.Fatal("expected merged text [", propmergedtext, "] but has [", sb.String(), "]")
}
np = p.MergeText(MergeSamePropRunsOf("Bold", "Size", "Underline"))
if len(np.Children) != 7 {
t.Fatal("expected 7 runs but has", len(np.Children))
}
sb.Reset()
for _, r := range np.Children {
if len(r.(*Run).Children) > 1 {
t.Fatal("expected 0/1 run.child but has", len(r.(*Run).Children))
}
if len(r.(*Run).Children) == 1 {
sb.WriteString(r.(*Run).Children[0].(*Text).Text)
}
sb.WriteString("|")
}
if sb.String() != namedpropmergdtext {
t.Fatal("expected merged text [", namedpropmergdtext, "] but has [", sb.String(), "]")
}
}