forked from visualon/OpenXmlPowerTools-old
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TextReplacer.cs
445 lines (422 loc) · 21.7 KB
/
TextReplacer.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
/***************************************************************************
Copyright (c) Microsoft Corporation 2012-2013.
This code is licensed using the Microsoft Public License (Ms-PL). The text of the license can be found here:
http://www.microsoft.com/resources/sharedsource/licensingbasics/publiclicense.mspx
Published at http://OpenXmlDeveloper.org
Resource Center and Documentation: http://openxmldeveloper.org/wiki/w/wiki/powertools-for-open-xml.aspx
Developer: Eric White
Blog: http://www.ericwhite.com
Twitter: @EricWhiteDev
Email: [email protected]
Version: 2.6.00
***************************************************************************/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using DocumentFormat.OpenXml.Packaging;
namespace OpenXmlPowerTools
{
public partial class WmlDocument : OpenXmlPowerToolsDocument
{
public WmlDocument SearchAndReplace(string search, string replace, bool matchCase)
{
return TextReplacer.SearchAndReplace(this, search, replace, matchCase);
}
}
public partial class PmlDocument : OpenXmlPowerToolsDocument
{
public PmlDocument SearchAndReplace(string search, string replace, bool matchCase)
{
return TextReplacer.SearchAndReplace(this, search, replace, matchCase);
}
}
public class TextReplacer
{
private class MatchSemaphore
{
public int MatchId;
public MatchSemaphore(int matchId)
{
MatchId = matchId;
}
}
private static XObject CloneWithAnnotation(XNode node)
{
XElement element = node as XElement;
if (element != null)
{
XElement newElement = new XElement(element.Name,
element.Attributes(),
element.Nodes().Select(n => CloneWithAnnotation(n)));
if (element.Annotation<MatchSemaphore>() != null)
newElement.AddAnnotation(element.Annotation<MatchSemaphore>());
}
return node;
}
private static object WmlSearchAndReplaceTransform(XNode node,
string search, string replace, bool matchCase)
{
XElement element = node as XElement;
if (element != null)
{
if (element.Name == W.p)
{
string contents = element.Descendants(W.t).Select(t => (string)t).StringConcatenate();
if (contents.Contains(search) ||
(!matchCase && contents.ToUpper().Contains(search.ToUpper())))
{
XElement paragraphWithSplitRuns = new XElement(W.p,
element.Attributes(),
element.Nodes().Select(n => WmlSearchAndReplaceTransform(n, search,
replace, matchCase)));
XElement[] subRunArray = paragraphWithSplitRuns
.Elements(W.r)
.Where(e => {
XElement subRunElement = e.Elements().FirstOrDefault(el => el.Name != W.rPr);
if (subRunElement == null)
return false;
return W.SubRunLevelContent.Contains(subRunElement.Name);
})
.ToArray();
int paragraphChildrenCount = subRunArray.Length;
int matchId = 1;
foreach (var pc in subRunArray
.Take(paragraphChildrenCount - (search.Length - 1))
.Select((c, i) => new { Child = c, Index = i, }))
{
var subSequence = subRunArray.SequenceAt(pc.Index).Take(search.Length);
var zipped = subSequence.Zip(search, (pcp, c) => new
{
ParagraphChildProjection = pcp,
CharacterToCompare = c,
});
bool dontMatch = zipped.Any(z => {
if (z.ParagraphChildProjection.Annotation<MatchSemaphore>() != null)
return true;
bool b;
if (matchCase)
b = z.ParagraphChildProjection.Value != z.CharacterToCompare.ToString();
else
b = z.ParagraphChildProjection.Value.ToUpper() != z.CharacterToCompare.ToString().ToUpper();
return b;
});
bool match = !dontMatch;
if (match)
{
foreach (var item in subSequence)
item.AddAnnotation(new MatchSemaphore(matchId));
++matchId;
}
}
// The following code is locally impure, as this is the most expressive way to write it.
XElement paragraphWithReplacedRuns = (XElement)CloneWithAnnotation(paragraphWithSplitRuns);
for (int id = 1; id < matchId; ++id)
{
List<XElement> elementsToReplace = paragraphWithReplacedRuns
.Elements()
.Where(e => {
var sem = e.Annotation<MatchSemaphore>();
if (sem == null)
return false;
return sem.MatchId == id;
})
.ToList();
elementsToReplace.First().AddBeforeSelf(
new XElement(W.r,
elementsToReplace.First().Elements(W.rPr),
new XElement(W.t, replace)));
elementsToReplace.Remove();
}
var groupedAdjacentRunsWithIdenticalFormatting =
paragraphWithReplacedRuns
.Elements()
.GroupAdjacent(ce =>
{
if (ce.Name != W.r)
return "DontConsolidate";
if (ce.Elements().Where(e => e.Name != W.rPr).Count() != 1 ||
ce.Element(W.t) == null)
return "DontConsolidate";
if (ce.Element(W.rPr) == null)
return "";
return ce.Element(W.rPr).ToString(SaveOptions.None);
});
XElement paragraphWithConsolidatedRuns = new XElement(W.p,
groupedAdjacentRunsWithIdenticalFormatting.Select(g =>
{
if (g.Key == "DontConsolidate")
return (object)g;
string textValue = g.Select(r => r.Element(W.t).Value).StringConcatenate();
XAttribute xs = null;
if (textValue[0] == ' ' || textValue[textValue.Length - 1] == ' ')
xs = new XAttribute(XNamespace.Xml + "space", "preserve");
return new XElement(W.r,
g.First().Elements(W.rPr),
new XElement(W.t, xs, textValue));
}));
return paragraphWithConsolidatedRuns;
}
return element;
}
if (element.Name == W.r && element.Elements(W.t).Any())
{
var collectionOfRuns = element.Elements()
.Where(e => e.Name != W.rPr)
.Select(e =>
{
if (e.Name == W.t)
{
string s = (string)e;
IEnumerable<XElement> collectionOfSubRuns = s.Select(c =>
{
XElement newRun = new XElement(W.r,
element.Elements(W.rPr),
new XElement(W.t,
c == ' ' ?
new XAttribute(XNamespace.Xml + "space", "preserve") :
null, c));
return newRun;
});
return (object)collectionOfSubRuns;
}
else
{
XElement newRun = new XElement(W.r,
element.Elements(W.rPr),
e);
return newRun;
}
});
return collectionOfRuns;
}
return new XElement(element.Name,
element.Attributes(),
element.Nodes().Select(n => WmlSearchAndReplaceTransform(n,
search, replace, matchCase)));
}
return node;
}
private static void WmlSearchAndReplaceInXDocument(XDocument xDocument, string search,
string replace, bool matchCase)
{
XElement newRoot = (XElement)WmlSearchAndReplaceTransform(xDocument.Root,
search, replace, matchCase);
xDocument.Elements().First().ReplaceWith(newRoot);
}
public static WmlDocument SearchAndReplace(WmlDocument doc, string search, string replace, bool matchCase)
{
using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc))
{
using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument())
{
SearchAndReplace(document, search, replace, matchCase);
}
return streamDoc.GetModifiedWmlDocument();
}
}
public static void SearchAndReplace(WordprocessingDocument wordDoc, string search,
string replace, bool matchCase)
{
if (RevisionAccepter.HasTrackedRevisions(wordDoc))
throw new InvalidDataException(
"Search and replace will not work with documents " +
"that contain revision tracking.");
XDocument xDoc;
xDoc = wordDoc.MainDocumentPart.DocumentSettingsPart.GetXDocument();
if (xDoc.Descendants(W.trackRevisions).Any())
throw new InvalidDataException("Revision tracking is turned on for document.");
xDoc = wordDoc.MainDocumentPart.GetXDocument();
WmlSearchAndReplaceInXDocument(xDoc, search, replace, matchCase);
wordDoc.MainDocumentPart.PutXDocument();
foreach (var part in wordDoc.MainDocumentPart.HeaderParts)
{
xDoc = part.GetXDocument();
WmlSearchAndReplaceInXDocument(xDoc, search, replace, matchCase);
part.PutXDocument();
}
foreach (var part in wordDoc.MainDocumentPart.FooterParts)
{
xDoc = part.GetXDocument();
WmlSearchAndReplaceInXDocument(xDoc, search, replace, matchCase);
part.PutXDocument();
}
if (wordDoc.MainDocumentPart.EndnotesPart != null)
{
xDoc = wordDoc.MainDocumentPart.EndnotesPart.GetXDocument();
WmlSearchAndReplaceInXDocument(xDoc, search, replace, matchCase);
wordDoc.MainDocumentPart.EndnotesPart.PutXDocument();
}
if (wordDoc.MainDocumentPart.FootnotesPart != null)
{
xDoc = wordDoc.MainDocumentPart.FootnotesPart.GetXDocument();
WmlSearchAndReplaceInXDocument(xDoc, search, replace, matchCase);
wordDoc.MainDocumentPart.FootnotesPart.PutXDocument();
}
}
private static object PmlReplaceTextTransform(XNode node, string search, string replace,
bool matchCase)
{
XElement element = node as XElement;
if (element != null)
{
if (element.Name == A.p)
{
string contents = element.Descendants(A.t).Select(t => (string)t).StringConcatenate();
if (contents.Contains(search) ||
(!matchCase && contents.ToUpper().Contains(search.ToUpper())))
{
XElement paragraphWithSplitRuns = new XElement(A.p,
element.Attributes(),
element.Nodes().Select(n => PmlReplaceTextTransform(n, search,
replace, matchCase)));
XElement[] subRunArray = paragraphWithSplitRuns
.Elements(A.r)
.Where(e =>
{
XElement subRunElement = e.Elements().FirstOrDefault(el => el.Name != A.rPr);
if (subRunElement == null)
return false;
return subRunElement.Name == A.t;
})
.ToArray();
int paragraphChildrenCount = subRunArray.Length;
int matchId = 1;
foreach (var pc in subRunArray
.Take(paragraphChildrenCount - (search.Length - 1))
.Select((c, i) => new { Child = c, Index = i, }))
{
var subSequence = subRunArray.SequenceAt(pc.Index).Take(search.Length);
var zipped = subSequence.Zip(search, (pcp, c) => new
{
ParagraphChildProjection = pcp,
CharacterToCompare = c,
});
bool dontMatch = zipped.Any(z =>
{
if (z.ParagraphChildProjection.Annotation<MatchSemaphore>() != null)
return true;
bool b;
if (matchCase)
b = z.ParagraphChildProjection.Value != z.CharacterToCompare.ToString();
else
b = z.ParagraphChildProjection.Value.ToUpper() != z.CharacterToCompare.ToString().ToUpper();
return b;
});
bool match = !dontMatch;
if (match)
{
foreach (var item in subSequence)
item.AddAnnotation(new MatchSemaphore(matchId));
++matchId;
}
}
// The following code is locally impure, as this is the most expressive way to write it.
XElement paragraphWithReplacedRuns = (XElement)CloneWithAnnotation(paragraphWithSplitRuns);
for (int id = 1; id < matchId; ++id)
{
List<XElement> elementsToReplace = paragraphWithReplacedRuns
.Elements()
.Where(e =>
{
var sem = e.Annotation<MatchSemaphore>();
if (sem == null)
return false;
return sem.MatchId == id;
})
.ToList();
elementsToReplace.First().AddBeforeSelf(
new XElement(A.r,
elementsToReplace.First().Elements(A.rPr),
new XElement(A.t, replace)));
elementsToReplace.Remove();
}
var groupedAdjacentRunsWithIdenticalFormatting =
paragraphWithReplacedRuns
.Elements()
.GroupAdjacent(ce =>
{
if (ce.Name != A.r)
return "DontConsolidate";
if (ce.Elements().Where(e => e.Name != A.rPr).Count() != 1 ||
ce.Element(A.t) == null)
return "DontConsolidate";
if (ce.Element(A.rPr) == null)
return "";
return ce.Element(A.rPr).ToString(SaveOptions.None);
});
XElement paragraphWithConsolidatedRuns = new XElement(A.p,
groupedAdjacentRunsWithIdenticalFormatting.Select(g =>
{
if (g.Key == "DontConsolidate")
return (object)g;
string textValue = g.Select(r => r.Element(A.t).Value).StringConcatenate();
return new XElement(A.r,
g.First().Elements(A.rPr),
new XElement(A.t, textValue));
}));
return paragraphWithConsolidatedRuns;
}
}
if (element.Name == A.r && element.Elements(A.t).Any())
{
var collectionOfRuns = element.Elements()
.Where(e => e.Name != A.rPr)
.Select(e =>
{
if (e.Name == A.t)
{
string s = (string)e;
IEnumerable<XElement> collectionOfSubRuns = s.Select(c =>
{
XElement newRun = new XElement(A.r,
element.Elements(A.rPr),
new XElement(A.t, c));
return newRun;
});
return (object)collectionOfSubRuns;
}
else
{
XElement newRun = new XElement(A.r,
element.Elements(A.rPr),
e);
return newRun;
}
});
return collectionOfRuns;
}
return new XElement(element.Name,
element.Attributes(),
element.Nodes().Select(n => PmlReplaceTextTransform(n, search, replace, matchCase)));
}
return node;
}
public static PmlDocument SearchAndReplace(PmlDocument doc, string search, string replace, bool matchCase)
{
using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc))
{
using (PresentationDocument document = streamDoc.GetPresentationDocument())
{
SearchAndReplace(document, search, replace, matchCase);
}
return streamDoc.GetModifiedPmlDocument();
}
}
public static void SearchAndReplace(PresentationDocument pDoc, string search,
string replace, bool matchCase)
{
PresentationPart presentationPart = pDoc.PresentationPart;
foreach (var slidePart in presentationPart.SlideParts)
{
XDocument slideXDoc = slidePart.GetXDocument();
XElement root = slideXDoc.Root;
XElement newRoot = (XElement)PmlReplaceTextTransform(root, search, replace, matchCase);
slidePart.PutXDocument(new XDocument(newRoot));
}
}
}
}