Table of Contents

Edit text at a position

Change text where a person or a program points: after the third character of a run, across two paragraphs, at the end of a heading. DocumentPosition names the point, and five methods change text there the way Word does when someone types, presses Enter, Backspace or Delete, or types over a selection. Each returns a DocumentEdit that takes the edit back exactly.

Type, Enter, Backspace, type over

using DocWright.Dom;
using DocWright.Dom.Editing;

using var document = new WordDocument();
Paragraph paragraph = document.AppendParagraph("Hello world");
var run = (TextRun)paragraph.Inlines[0];
DomNodeId runId = run.NodeId;

// Type ",", press Enter, type, press Backspace: each call returns a record.
DocumentEdit typed = document.InsertText(DocumentPosition.InRun(run, 5), ",");
DocumentEdit enter = document.SplitParagraph(typed.After);
DocumentEdit more = document.InsertText(enter.After, "brave new");
Console.WriteLine(Texts(document));

DocumentEdit back = document.MergeWithPrevious(enter.After.Paragraph);
Console.WriteLine(Texts(document));

// A selection typed over: delete and insert as one record.
var selection = new DocumentSpan(DocumentPosition.InParagraph(paragraph, 6), DocumentPosition.InParagraph(paragraph, 16));
DocumentEdit over = document.ReplaceRange(selection, " ");
Console.WriteLine($"{Texts(document)}   caret at {over.After.Offset}");

// What a layout cache must redo after Enter:
Console.WriteLine($"Enter changed paragraphs {string.Join(", ", enter.ChangedParagraphKeys)}");

// Undo in reverse order: the same run instance, under the same id.
foreach (DocumentEdit edit in new[] { over, back, more, enter, typed })
{
    edit.Undo();
}

Console.WriteLine($"{Texts(document)}   same run: {document.FindNode(runId) == run}");

Output

Hello, | brave new world
Hello,brave new world
Hello, world   caret at 7
Enter changed paragraphs 2, 3
Hello world   same run: True
Call Is Rule (measured in Word)
InsertText(at, text, format?) typing, or pasting plain text The text goes after every marker at the position, so it joins a bookmark, hyperlink or field result that starts there and not one that ends there. It takes the formatting of the character before, or the character after at a paragraph's start, or the paragraph mark in an empty paragraph. \t is a tab, \v a line break, and a line ending splits the paragraph.
SplitParagraph(at) Enter Both halves keep the paragraph's properties; the original paragraph mark goes with the second half. At the end of a paragraph whose style has a different next style (Heading 1 to Normal), the new paragraph takes that style and no direct formatting.
MergeWithPrevious(paragraph) Backspace at a paragraph's start The previous paragraph keeps its properties and mark, unless it is empty, when it is the one that goes.
DeleteRange(span) Delete over a selection Across paragraphs, the paragraphs between go and the two ends are not joined. A span that is only a paragraph mark joins the two paragraphs. Deleting a footnote reference deletes the footnote.
ReplaceRange(span, text, format?) typing over a selection Across paragraphs the two ends are joined, keeping the first paragraph's properties. The text takes the formatting of the first character covered.

Delete and type over are different in Word

using DocWright.Dom;
using DocWright.Dom.Editing;

using var four = new WordDocument();
foreach (string text in new[] { "aaaa", "bbbb", "cccc", "dddd" })
{
    four.AppendParagraph(text);
}

Paragraph[] p = four.Sections[0].Blocks.OfType<Paragraph>().ToArray();
var span = new DocumentSpan(DocumentPosition.InParagraph(p[0], 2), DocumentPosition.InParagraph(p[2], 2));

DocumentEdit deleted = four.DeleteRange(span);          // Word's Delete key: the ends stay apart
Console.WriteLine($"Delete:    {Texts(four)}");
deleted.Undo();

four.ReplaceRange(span, "Z");                            // typing over: the ends join
Console.WriteLine($"Type over: {Texts(four)}");

Output

Delete:    aa | cc | dddd
Type over: aaZcc | dddd

Word's Delete key over a selection from the middle of one paragraph to the middle of another leaves the two ends as separate paragraphs, each with its own properties. Typing over the same selection joins them. DeleteRange and ReplaceRange follow Word, so pick the one that matches what the user did.

Word's corrections as you type

TypingCorrections makes the corrections Word's AutoFormat As You Type makes (WQ-0108). Call AfterCharacter after each character with the caret just after it, and AfterParagraph after Enter. Each returns the correction as an edit of its own (empty when there is none), so one undo takes back the correction and leaves what was typed, as in Word:

using DocWright.Dom;
using DocWright.Dom.Editing;

using WordDocument document = BlankDocument.Create();
DocumentPosition caret = DocumentPosition.StartOf((Paragraph)document.Sections[0].Blocks[0]);

// Each keystroke, then the correction Word would make at it ("~" is Enter).
foreach (char key in "he said \"hello\" -- twice (c) 2026~1. first point~")
{
    if (key == '~')
    {
        Paragraph ended = caret.Paragraph;
        caret = document.SplitParagraph(caret).After;
        caret = document.AfterParagraph(ended, caret).After;
        continue;
    }

    caret = document.InsertText(caret, key.ToString()).After;
    caret = document.AfterCharacter(caret).After;
}

foreach (Paragraph paragraph in document.Sections[0].Blocks.OfType<Paragraph>())
{
    string list = paragraph.Format.NumberingId is null ? "" : "  (numbered list)";
    Console.WriteLine($"[{paragraph.GetText().TrimEnd()}]{list}");
}

Output

[He said “hello” – twice © 2026]
[First point]  (numbered list)
[]  (numbered list)
Typed Becomes When
" ' “ ” ‘ ’ by context as typed
a -- b, a - b, a--b en dash, en dash, em dash the space after the next word
(c) (r) (tm) ... © ® ™ … the space after it
1st, 1/2 superscript st, ½ (also ¼ ¾) the space after it
www.example.com, me@example.com a hyperlink (http://www.example.com/, mailto:) the space after it
1. 1) a. * - > at a paragraph's start a numbered or bulleted list the space after the marker
--- === alone a bottom border Enter
a sentence's first word, THe a capital, The the space after it

TypingCorrectionOptions turns each one off. Misspellings (teh, adn) are replaced from a list of your own or DocWright's (below).

Replace text as you type, and what a correction did

TypingCorrectionOptions.ReplaceText (on by default) replaces a finished word found in Replacements, keeping the case it was typed in as Word does (WQ-0120): teh becomes the, Teh becomes The, TEH becomes THE, and punctuation around the word stays. The default list is TypingCorrections.CommonMisspellings, DocWright's own list of common English misspellings; pass your own dictionary (keys in lower case) to change it, or leave a word out to stop correcting it. The overloads that take an IList<TypingCorrection> say what each correction did, its kind, where its result is and the text it replaced, which is what Word's AutoCorrect Options button offers to undo or stop:

var made = new List<TypingCorrection>();
DocumentEdit fix = document.AfterCharacter(caret, new TypingCorrectionOptions(), made);
foreach (TypingCorrection c in made)
{
    Console.WriteLine($"{c.Kind}: '{c.Original}' at {c.Start.Offset}, {c.Length} characters");
}

Positions

A position is a paragraph and an offset into its content:

  • A text run counts one per character. A tab, a break, an image, a shape and a note reference count one each.
  • Bookmark and hyperlink markers, field characters and a field's code count nothing. A field's result is ordinary text, and inline content controls are looked through.
  • DocumentPosition.InRun(run, offset) converts a run offset, which is what a laid-out line or glyph run reports. InParagraph(paragraph, offset), StartOf and EndOf give paragraph positions, and FindRun(out offset) goes back to a run.

A position is a value, not a cursor. Every edit returns the position a caret goes to next in After.

Undo and redo

Undo puts back the very nodes the edit removed and detaches the ones it created. Every node that existed before has its place, its content and its NodeId again, and the document saves byte for byte as it did. Redo re-applies the edit with the same created nodes, so a later edit that refers to a run the first one created stays valid.

  • Undo records in the reverse of the order they were made, as an undo stack does. Grouping a burst of typing into one step is up to you.
  • A record checks the nodes it touches before it changes anything. If the document has changed since in a way that contradicts it, Undo and Redo throw InvalidOperationException and leave the document as it was.
  • ChangedParagraphKeys lists the NodeId value of every paragraph the edit changed, created or removed: what a layout cache keyed by paragraph has to redo.

What is refused

These throw InvalidOperationException or ArgumentException, and the document is unchanged:

  • a span that crosses a table cell, a section or another container, or covers a table
  • Backspace at the first paragraph of a later section, which in Word removes the section break
  • a split inside an inline content control
  • text inside a check box, list, date, picture, group, equation or citation content control, or one whose content is locked: set its value with ContentControl.SetValue (a plain-text control takes typed text as Word's does: see Forms)
  • any edit in a shape's text box. A DOCX save writes the shape from its preserved drawing, so the edit would be lost.
  • a position between the two halves of a surrogate pair, or text holding a control character other than tab, vertical tab and line endings