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
| public class ReplaceHelper { public ReplaceHelper(Document doc) { mDoc = doc; }
public void Replace(string oldText, string newText) { mDoc.Range.Replace(new Regex(Regex.Escape(oldText)), new ReplaceEvaluatorFindAndInsertText(newText), false); }
public class ReplaceEvaluatorFindAndInsertText : IReplacingCallback { public ReplaceEvaluatorFindAndInsertText(string text)
{ mText = text; }
ReplaceAction IReplacingCallback.Replacing(ReplacingArgs e) { Node currentNode = e.MatchNode;
if (e.MatchOffset > 0) currentNode = SplitRun((Run)currentNode, e.MatchOffset);
ArrayList runs = new ArrayList();
int remainingLength = e.Match.Value.Length;
while ((remainingLength > 0) && (currentNode != null) && (currentNode.GetText().Length <= remainingLength)) { runs.Add(currentNode);
remainingLength = remainingLength - currentNode.GetText().Length;
do { currentNode = currentNode.NextSibling; } while ((currentNode != null) && (currentNode.NodeType != NodeType.Run)); }
if ((currentNode != null) && (remainingLength > 0)) { SplitRun((Run)currentNode, remainingLength);
runs.Add(currentNode); }
DocumentBuilder builder = new DocumentBuilder(e.MatchNode.Document as Document);
builder.MoveTo((Run)runs[runs.Count - 1]);
builder.Write(mText);
foreach (Run run in runs)
run.Remove();
return ReplaceAction.Skip; }
private static Run SplitRun(Run run, int position) { Run afterRun = (Run)run.Clone(true);
afterRun.Text = run.Text.Substring(position);
run.Text = run.Text.Substring(0, position);
run.ParentNode.InsertAfter(afterRun, run);
return afterRun; }
private string mText; }
private Document mDoc; }
|