Added whole documents to the Translation, Grammar & Spelling, and Rewrite & Improve assistants (#1179)

Co-authored-by: Thorsten Sommer <SommerEngineering@users.noreply.github.com>
This commit is contained in:
Sabrina-devopsandThorsten Sommer authored and GitHub committed 2026-11-28 20:27:23 +01:00
1 parent f7666861f1
commit 918572c158
150 files changed
+12850 -302

No files matched your search

@@ -0,0 +1,103 @@
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Validation;
using W = DocumentFormat.OpenXml.Wordprocessing;
namespace AIStudio.Tests.Tools.DocumentSegments.Word;
/// <summary>
/// Builds the Word documents of the tests in code, so that no binary document is checked in.
/// </summary>
internal static class TestWordDocument
{
/// <summary>
/// The relationship of the link which every document of the tests has, for a W.Hyperlink to point to.
/// </summary>
public const string LINK_ID = "rIdManual";
private const string HEADER_ID = "rIdHeader";
private const string FOOTER_ID = "rIdFooter";
/// <summary>
/// A document with nothing but the given paragraphs.
/// </summary>
/// <param name="path">Where to create the document.</param>
/// <param name="paragraphs">The paragraphs of its body.</param>
public static void Create(string path, params W.Paragraph[] paragraphs)
{
using var document = WordprocessingDocument.Create(path, WordprocessingDocumentType.Document);
var mainPart = document.AddMainDocumentPart();
mainPart.AddHyperlinkRelationship(new Uri("https://example.org/manual"), true, LINK_ID);
mainPart.Document = new W.Document(new W.Body(paragraphs));
}
/// <summary>
/// A document with what Word documents commonly hold: a link, a tab, a reference to a footnote, a field
/// with its result, a bookmark, words with mixed formatting, a header, a footer, a footnote, and an endnote.
/// </summary>
/// <param name="path">Where to create the document.</param>
public static void CreateSample(string path)
{
using var document = WordprocessingDocument.Create(path, WordprocessingDocumentType.Document);
var mainPart = document.AddMainDocumentPart();
mainPart.AddHyperlinkRelationship(new Uri("https://example.org/manual"), true, LINK_ID);
var headerPart = mainPart.AddNewPart<HeaderPart>(HEADER_ID);
headerPart.Header = new W.Header(Paragraph(Run("Confidential")));
var footerPart = mainPart.AddNewPart<FooterPart>(FOOTER_ID);
footerPart.Footer = new W.Footer(Paragraph(Run("Page footer")));
var endnotesPart = mainPart.AddNewPart<EndnotesPart>();
endnotesPart.Endnotes = new W.Endnotes(
new W.Endnote(Paragraph(new W.Run(new W.SeparatorMark()))) { Type = W.FootnoteEndnoteValues.Separator, Id = -1 },
new W.Endnote(Paragraph(new W.Run(new W.ContinuationSeparatorMark()))) { Type = W.FootnoteEndnoteValues.ContinuationSeparator, Id = 0 },
new W.Endnote(Paragraph(new W.Run(new W.EndnoteReferenceMark()), Run(" An endnote."))) { Id = 1 });
var footnotesPart = mainPart.AddNewPart<FootnotesPart>();
footnotesPart.Footnotes = new W.Footnotes(
new W.Footnote(Paragraph(new W.Run(new W.SeparatorMark()))) { Type = W.FootnoteEndnoteValues.Separator, Id = -1 },
new W.Footnote(Paragraph(new W.Run(new W.ContinuationSeparatorMark()))) { Type = W.FootnoteEndnoteValues.ContinuationSeparator, Id = 0 },
new W.Footnote(Paragraph(new W.Run(new W.FootnoteReferenceMark()), Run(" A note."))) { Id = 1 });
mainPart.Document = new W.Document(new W.Body(
Paragraph(Run("Getting started")),
Paragraph(Run("Read the "), new W.Hyperlink(Run("manual")) { Id = LINK_ID }, Run(" first."), new W.Run(new W.TabChar()), Run("Done")),
Paragraph(Run("See the note"), new W.Run(new W.FootnoteReference { Id = 1 })),
Paragraph(
new W.Run(new W.FieldChar { FieldCharType = W.FieldCharValues.Begin }),
new W.Run(new W.FieldCode(" REF _Ref1 \\h ") { Space = SpaceProcessingModeValues.Preserve }),
new W.Run(new W.FieldChar { FieldCharType = W.FieldCharValues.Separate }),
Run("Introduction"),
new W.Run(new W.FieldChar { FieldCharType = W.FieldCharValues.End })),
Paragraph(new W.BookmarkStart { Id = "1", Name = "_Ref1" }, Run("Chapter"), new W.BookmarkEnd { Id = "1" }),
Paragraph(Run("Mixed "), Bold("bold"), Run(" words")),
Paragraph(Run("2026")),
new W.SectionProperties(
new W.HeaderReference { Type = W.HeaderFooterValues.Default, Id = HEADER_ID },
new W.FooterReference { Type = W.HeaderFooterValues.Default, Id = FOOTER_ID })));
}
public static W.Paragraph Paragraph(params OpenXmlElement[] content) => new(content);
public static W.Run Run(string text, W.RunProperties? properties = null) => properties is null
? new W.Run(new W.Text(text) { Space = SpaceProcessingModeValues.Preserve })
: new W.Run(properties, new W.Text(text) { Space = SpaceProcessingModeValues.Preserve });
public static W.Run Bold(string text) => Run(text, new W.RunProperties(new W.Bold()));
public static W.Run Italic(string text) => Run(text, new W.RunProperties(new W.Italic()));
public static W.Hyperlink Link(string text) => new(Run(text)) { Id = LINK_ID };
/// <summary>
/// What the validator finds, without where it finds it: new runs move the places of what the source already had.
/// </summary>
public static List<string> ValidationErrorsOf(WordprocessingDocument document) => new OpenXmlValidator(FileFormatVersions.Office2019)
.Validate(document)
.Select(error => $"{error.Part?.Uri}: {error.Description}")
.Order(StringComparer.Ordinal)
.ToList();
}
@@ -0,0 +1,416 @@
using AIStudio.Tools.DocumentSegments;
using AIStudio.Tools.DocumentSegments.Word;
using DocumentFormat.OpenXml.Packaging;
using Microsoft.Extensions.Logging.Abstractions;
using W = DocumentFormat.OpenXml.Wordprocessing;
using static AIStudio.Tests.Tools.DocumentSegments.Word.TestWordDocument;
namespace AIStudio.Tests.Tools.DocumentSegments.Word;
/// <summary>
/// Checks that words in bold, in italics, or in a link in the middle of a sentence keep their formatting when the
/// model moves them.
/// </summary>
[TestFixture]
public sealed class WordInlineFormattingTests
{
private const string SENTENCE = "This is <1>very</1> <2>important</2> and <3>linked</3> text.";
private readonly WordSegmentFormat format = new();
private string testFolder = string.Empty;
private string source = string.Empty;
private string target = string.Empty;
[SetUp]
public void CreateFolder()
{
this.testFolder = Directory.CreateDirectory(Path.Join(Path.GetTempPath(), "mindwork-ai-studio-tests", Guid.NewGuid().ToString("N"))).FullName;
this.source = Path.Join(this.testFolder, "source.docx");
this.target = Path.Join(this.testFolder, "target.docx");
}
[TearDown]
public void RemoveFolder() => Directory.Delete(this.testFolder, true);
[Test]
public async Task ChangesOfFormattingBecomePairs()
{
this.CreateSentence();
var keys = await this.KeysAsync();
Assert.That(keys, Is.EqualTo(new[] { SENTENCE }), "Words in another formatting than most words of the paragraph go into pairs, like the link.");
}
[Test]
public async Task TheFormattingFollowsItsWords()
{
this.CreateSentence();
var result = await this.WriteAsync(SENTENCE, "<2>Wichtig</2> ist es <1>sehr</1>, und <3>verlinkt</3> auch.");
using var document = WordprocessingDocument.Open(this.target, false);
var paragraph = document.MainDocumentPart!.Document!.Body!.Elements<W.Paragraph>().Single();
using (Assert.EnterMultipleScope())
{
Assert.That(result.SimplifiedCount, Is.Zero);
Assert.That(paragraph.InnerText, Is.EqualTo("Wichtig ist es sehr, und verlinkt auch."));
Assert.That(TextsWhere(paragraph, run => run.RunProperties?.Bold is not null), Is.EqualTo(new[] { "sehr" }));
Assert.That(TextsWhere(paragraph, run => run.RunProperties?.Italic is not null), Is.EqualTo(new[] { "Wichtig" }));
Assert.That(paragraph.Elements<W.Hyperlink>().Select(link => link.InnerText), Is.EqualTo(new[] { "verlinkt" }));
Assert.That(TextsWhere(paragraph, run => run.RunProperties?.Bold is null && run.RunProperties?.Italic is null), Is.EqualTo(new[] { " ist es ", ", und ", " auch." }), "The words around keep the most common formatting.");
}
}
[Test]
public async Task AMissingPairLosesItsFormattingButNotItsWords()
{
this.CreateSentence();
var result = await this.WriteAsync(SENTENCE, "Das ist sehr <2>wichtig</2> und <3>verlinkter</3> Text.");
using var document = WordprocessingDocument.Open(this.target, false);
var paragraph = document.MainDocumentPart!.Document!.Body!.Elements<W.Paragraph>().Single();
using (Assert.EnterMultipleScope())
{
Assert.That(result.SimplifiedCount, Is.EqualTo(1));
Assert.That(paragraph.InnerText, Is.EqualTo("Das ist sehr wichtig und verlinkter Text."));
Assert.That(TextsWhere(paragraph, run => run.RunProperties?.Bold is not null), Is.Empty);
Assert.That(TextsWhere(paragraph, run => run.RunProperties?.Italic is not null), Is.EqualTo(new[] { "wichtig" }));
}
}
[Test]
public async Task ASpaceGetsNoPairOfItsOwn()
{
Create(this.source, Paragraph(Run("Spaces"), Bold(" "), Run("between")));
Assert.That(await this.KeysAsync(), Is.EqualTo(new[] { "Spaces between" }));
}
[Test]
public async Task TheMostCommonFormattingNeedsNoPair()
{
Create(this.source, Paragraph(Bold("Mostly bold words "), Run("and"), Bold(" more bold words")));
Assert.That(await this.KeysAsync(), Is.EqualTo(new[] { "Mostly bold words <1>and</1> more bold words" }));
}
[Test]
public async Task TooManyChangesOfFormattingKeepOneFormatting()
{
var runs = Enumerable.Range(0, 13).SelectMany(_ => new[] { Run("plain "), Bold("bold ") }).ToArray<DocumentFormat.OpenXml.OpenXmlElement>();
Create(this.source, Paragraph(runs));
var key = string.Concat(Enumerable.Repeat("plain bold ", 13));
var keys = await this.KeysAsync();
var result = await this.WriteAsync(key, key.ToUpperInvariant());
using (Assert.EnterMultipleScope())
{
Assert.That(keys, Is.EqualTo(new[] { key }), "Thirteen words in bold are more pairs than a model keeps in place reliably.");
Assert.That(result.SimplifiedCount, Is.EqualTo(1), "The paragraph keeps one formatting and counts as simplified.");
}
}
[Test]
public async Task TooManyChangesOfFormattingKeepTheMostCommonFormatting()
{
// A glossary: each term in bold comes first, but most letters are those of the plain explanations:
var runs = Enumerable.Range(0, 13).SelectMany(_ => new[] { Bold("Term "), Run("explained in plain words. ") }).ToArray<DocumentFormat.OpenXml.OpenXmlElement>();
Create(this.source, Paragraph(runs));
var key = string.Concat(Enumerable.Repeat("Term explained in plain words. ", 13));
var result = await this.WriteAsync(key, key.ToUpperInvariant());
using var document = WordprocessingDocument.Open(this.target, false);
var paragraph = document.MainDocumentPart!.Document!.Body!.Elements<W.Paragraph>().Single();
using (Assert.EnterMultipleScope())
{
Assert.That(result.SimplifiedCount, Is.EqualTo(1));
Assert.That(paragraph.InnerText, Is.EqualTo(key.ToUpperInvariant()));
Assert.That(TextsWhere(paragraph, run => run.RunProperties?.Bold is not null), Is.Empty, "The new words get the formatting of most letters, not the one of the first word.");
}
}
[Test]
public async Task ATagMovedIntoAnInsertionGoesRightBehindIt()
{
// A linked tab has no words, so it is a tag of its own, which the model may move; Word allows no link within an insertion:
var linkedTab = new W.Hyperlink(new W.Run(new W.TabChar())) { Id = LINK_ID };
Create(this.source, Paragraph(linkedTab, Run(" text "), new W.InsertedRun(Run("inserted")) { Id = "1", Author = "Tester" }));
var key = (await this.KeysAsync()).Single();
var result = await this.WriteAsync(key, "Text <2>eingefügt <1/>und mehr</2>");
using var document = WordprocessingDocument.Open(this.target, false);
var paragraph = document.MainDocumentPart!.Document!.Body!.Elements<W.Paragraph>().Single();
using (Assert.EnterMultipleScope())
{
Assert.That(key, Is.EqualTo("<1/> text <2>inserted</2>"));
Assert.That(ValidationErrorsOf(document), Is.EqualTo(this.SourceValidationErrors()), "The new document is as valid as the source.");
Assert.That(result.SimplifiedCount, Is.Zero, "Nothing got lost, the link only moved next to the insertion.");
Assert.That(paragraph.ChildElements.Select(child => child.LocalName), Is.EqualTo(new[] { "r", "ins", "hyperlink", "ins" }), "The insertion goes on behind the link.");
Assert.That(paragraph.Elements<W.InsertedRun>().Select(insertion => insertion.InnerText), Is.EqualTo(new[] { "eingefügt ", "und mehr" }));
}
}
[Test]
public async Task ANestingWhichWordForbidsKeepsTheWords()
{
Create(this.source, Paragraph(Run("See "), new W.Hyperlink(new W.InsertedRun(Run("link")) { Id = "1", Author = "Tester" }) { Id = LINK_ID }));
var key = (await this.KeysAsync()).Single();
// The model swapped the pairs, so that the link would lie within the insertion:
var result = await this.WriteAsync(key, "Siehe <2><1>Link</1></2>");
using var document = WordprocessingDocument.Open(this.target, false);
var paragraph = document.MainDocumentPart!.Document!.Body!.Elements<W.Paragraph>().Single();
using (Assert.EnterMultipleScope())
{
Assert.That(key, Is.EqualTo("See <1><2>link</2></1>"));
Assert.That(ValidationErrorsOf(document), Is.EqualTo(this.SourceValidationErrors()), "The new document is as valid as the source.");
Assert.That(result.SimplifiedCount, Is.EqualTo(1));
Assert.That(paragraph.InnerText, Is.EqualTo("Siehe Link"), "Words beat structure.");
Assert.That(paragraph.Descendants<W.InsertedRun>().Single().InnerText, Is.EqualTo("Link"));
}
}
[Test]
public async Task ASimpleFieldIsAPairAroundItsResult()
{
Create(this.source, Paragraph(Run("See "), new W.SimpleField(Run("Figure 1")) { Instruction = " REF _Ref1 \\h " }, Run(".")));
var key = (await this.KeysAsync()).Single();
var result = await this.WriteAsync(key, "Siehe <1>Abbildung 1</1>.");
using var document = WordprocessingDocument.Open(this.target, false);
var field = document.MainDocumentPart!.Document!.Body!.Descendants<W.SimpleField>().Single();
using (Assert.EnterMultipleScope())
{
Assert.That(key, Is.EqualTo("See <1>Figure 1</1>."));
Assert.That(ValidationErrorsOf(document), Is.EqualTo(this.SourceValidationErrors()), "The new document is as valid as the source.");
Assert.That(result.SimplifiedCount, Is.Zero);
Assert.That(field.InnerText, Is.EqualTo("Abbildung 1"));
Assert.That(field.Instruction?.Value, Is.EqualTo(" REF _Ref1 \\h "), "The field keeps its instruction.");
}
}
[Test]
public async Task ATagMovedIntoTheResultOfAFieldGoesRightBehindIt()
{
// Word replaces the result of a field whenever it updates the field, which would delete the reference to the footnote there:
Create(this.source, Paragraph(
Run("See "),
new W.Run(new W.FieldChar { FieldCharType = W.FieldCharValues.Begin }),
new W.Run(new W.FieldCode(" REF _Ref1 \\h ") { Space = DocumentFormat.OpenXml.SpaceProcessingModeValues.Preserve }),
new W.Run(new W.FieldChar { FieldCharType = W.FieldCharValues.Separate }),
Run("Figure"),
new W.Run(new W.TabChar()),
Run("1"),
new W.Run(new W.FieldChar { FieldCharType = W.FieldCharValues.End }),
Run(" for details."),
new W.Run(new W.FootnoteReference { Id = 1 })));
var key = (await this.KeysAsync()).Single();
var result = await this.WriteAsync(key, "Siehe <1>Abbildung<2/>1<3/></1> für Details.");
using var document = WordprocessingDocument.Open(this.target, false);
var paragraph = document.MainDocumentPart!.Document!.Body!.Elements<W.Paragraph>().Single();
using (Assert.EnterMultipleScope())
{
Assert.That(key, Is.EqualTo("See <1>Figure<2/>1</1> for details.<3/>"));
Assert.That(result.SimplifiedCount, Is.Zero, "Nothing got lost, the reference only moved behind the field.");
Assert.That(OutlineOf(paragraph), Is.EqualTo(new[] { "Siehe ", "begin", "separate", "Abbildung", "tab", "1", "end", "footnote", " für Details." }), "The tab lay in the result in the source, so it stays there.");
}
}
[Test]
public async Task ATagMovedIntoASimpleFieldGoesRightBehindIt()
{
Create(this.source, Paragraph(Run("See "), new W.SimpleField(Run("Figure 1")) { Instruction = " REF _Ref1 \\h " }, Run(" for details."), new W.Run(new W.FootnoteReference { Id = 1 })));
var key = (await this.KeysAsync()).Single();
await this.WriteAsync(key, "Siehe <1>Abbildung 1<2/></1> für Details.");
using var document = WordprocessingDocument.Open(this.target, false);
var field = document.MainDocumentPart!.Document!.Body!.Descendants<W.SimpleField>().Single();
using (Assert.EnterMultipleScope())
{
Assert.That(key, Is.EqualTo("See <1>Figure 1</1> for details.<2/>"));
Assert.That(field.InnerText, Is.EqualTo("Abbildung 1"));
Assert.That(field.Descendants<W.FootnoteReference>(), Is.Empty, "An update of the field would delete the reference.");
Assert.That(field.NextSibling()?.Descendants<W.FootnoteReference>().Count(), Is.EqualTo(1), "The reference follows the field right away.");
}
}
[Test]
public async Task NewChangesOfTheChangeTrackingGetNumbersOfTheirOwn()
{
// A change of formatting, which the new words split in two, an insertion which goes on behind a linked tab, and a deletion with the highest number:
var changedFormat = new W.RunProperties(new W.Bold(), new W.RunPropertiesChange(new W.PreviousRunProperties()) { Id = "1", Author = "Tester" });
var linkedTab = new W.Hyperlink(new W.Run(new W.TabChar())) { Id = LINK_ID };
Create(this.source, Paragraph(
Run("Bold words", changedFormat),
linkedTab,
new W.InsertedRun(Run("inserted")) { Id = "2", Author = "Tester" },
new W.DeletedRun(new W.Run(new W.DeletedText("gone"))) { Id = "3", Author = "Tester" }));
var key = (await this.KeysAsync()).Single();
await this.WriteAsync(key, "Fette <2>eingefügt <1/>und mehr</2> Wörter<3/>");
using var document = WordprocessingDocument.Open(this.target, false);
var paragraph = document.MainDocumentPart!.Document!.Body!.Elements<W.Paragraph>().Single();
var ids = paragraph.Descendants<W.RunPropertiesChange>().Select(change => change.Id?.Value)
.Concat(paragraph.Descendants<W.InsertedRun>().Select(insertion => insertion.Id?.Value))
.Concat(paragraph.Descendants<W.DeletedRun>().Select(deletion => deletion.Id?.Value))
.ToList();
using (Assert.EnterMultipleScope())
{
Assert.That(key, Is.EqualTo("Bold words<1/><2>inserted</2><3/>"));
Assert.That(ValidationErrorsOf(document), Is.EqualTo(this.SourceValidationErrors()), "The new document is as valid as the source.");
Assert.That(ids, Has.Count.EqualTo(5), "Two runs with the change of formatting, two parts of the insertion, and the deletion.");
Assert.That(ids, Is.Unique, "Word tells the changes apart by their numbers, also from the deletion which was out of the document while the paragraph was written.");
}
}
[Test]
public async Task CustomXmlKeepsItsPropertiesOnce()
{
var customXml = new W.CustomXmlRun(new W.CustomXmlProperties(new W.CustomXmlAttribute { Name = "role", Val = "author" }), Run("Alice")) { Element = "name" };
Create(this.source, Paragraph(customXml, Run(" wrote this.")));
var key = (await this.KeysAsync()).Single();
await this.WriteAsync(key, "<1>Alicia</1> schrieb das.");
using var document = WordprocessingDocument.Open(this.target, false);
var written = document.MainDocumentPart!.Document!.Body!.Descendants<W.CustomXmlRun>().Single();
using (Assert.EnterMultipleScope())
{
Assert.That(key, Is.EqualTo("<1>Alice</1> wrote this."), "The properties of custom XML are no tag of their own.");
Assert.That(ValidationErrorsOf(document), Is.EqualTo(this.SourceValidationErrors()), "The new document is as valid as the source.");
Assert.That(written.Elements<W.CustomXmlProperties>().Count(), Is.EqualTo(1));
Assert.That(written.FirstChild, Is.InstanceOf<W.CustomXmlProperties>(), "The properties come first, as the schema demands.");
}
}
[Test]
public async Task ACaptionBookmarkEnclosesTheNewLabelAndNumber()
{
// A caption as Word writes it: a cross reference points to the bookmark around its label and number:
Create(this.source, Paragraph(
new W.BookmarkStart { Id = "0", Name = "_Ref1" },
Run("Figure "),
new W.Run(new W.FieldChar { FieldCharType = W.FieldCharValues.Begin }),
new W.Run(new W.FieldCode(" SEQ Figure \\* ARABIC ") { Space = DocumentFormat.OpenXml.SpaceProcessingModeValues.Preserve }),
new W.Run(new W.FieldChar { FieldCharType = W.FieldCharValues.Separate }),
Run("1"),
new W.Run(new W.FieldChar { FieldCharType = W.FieldCharValues.End }),
new W.BookmarkEnd { Id = "0" },
Run(": Overview of the system")));
var key = (await this.KeysAsync()).Single();
var result = await this.WriteAsync(key, "<1>Abbildung <2>1</2></1>: Übersicht über das System");
using var document = WordprocessingDocument.Open(this.target, false);
var paragraph = document.MainDocumentPart!.Document!.Body!.Elements<W.Paragraph>().Single();
var enclosed = paragraph.ChildElements.SkipWhile(child => child is not W.BookmarkStart).Skip(1).TakeWhile(child => child is not W.BookmarkEnd);
using (Assert.EnterMultipleScope())
{
Assert.That(key, Is.EqualTo("<1>Figure <2>1</2></1>: Overview of the system"));
Assert.That(ValidationErrorsOf(document), Is.EqualTo(this.SourceValidationErrors()), "The new document is as valid as the source.");
Assert.That(result.SimplifiedCount, Is.Zero);
Assert.That(string.Concat(enclosed.SelectMany(child => child.Descendants<W.Text>()).Select(text => text.Text)), Is.EqualTo("Abbildung 1"), "A cross reference shows the new label and number, not the whole caption.");
}
}
[Test]
public async Task WordsWhichReadAsATagOnlyTogetherKeepTheParagraphAsItIs()
{
// Thirteen words in bold leave the paragraph one formatting for its words, so "<1" in bold and ">" in plain type meet:
var runs = Enumerable.Range(0, 13)
.SelectMany(_ => new[] { Run("plain "), Bold("bold ") })
.Append(Bold("Press <1"))
.Append(Run("> to continue."))
.ToArray<DocumentFormat.OpenXml.OpenXmlElement>();
Create(this.source, Paragraph(runs));
Assert.That(await this.KeysAsync(), Is.Empty, "A model could not tell such words apart from the tags of the paragraph.");
}
[Test]
public async Task ABookmarkWithoutWordsIsNoTag()
{
Create(this.source, Paragraph(new W.BookmarkStart { Id = "1", Name = "_GoBack" }, new W.BookmarkEnd { Id = "1" }, Run("Some text.")));
Assert.That(await this.KeysAsync(), Is.EqualTo(new[] { "Some text." }));
}
[Test]
public async Task OfTwoCrossingBookmarksTheFirstIsAPair()
{
Create(this.source, Paragraph(
new W.BookmarkStart { Id = "0", Name = "First" },
Run("one "),
new W.BookmarkStart { Id = "1", Name = "Second" },
Run("two"),
new W.BookmarkEnd { Id = "0" },
Run(" three"),
new W.BookmarkEnd { Id = "1" }));
var key = (await this.KeysAsync()).Single();
await this.WriteAsync(key, key.ToUpperInvariant());
using var document = WordprocessingDocument.Open(this.target, false);
using (Assert.EnterMultipleScope())
{
Assert.That(key, Is.EqualTo("<1>one two</1> three"), "Pairs have to nest, so the second bookmark widens to the paragraph.");
Assert.That(ValidationErrorsOf(document), Is.EqualTo(this.SourceValidationErrors()), "The new document is as valid as the source.");
Assert.That(document.MainDocumentPart!.Document!.Body!.InnerText, Is.EqualTo("ONE TWO THREE"));
}
}
private List<string> SourceValidationErrors()
{
using var document = WordprocessingDocument.Open(this.source, false);
return ValidationErrorsOf(document);
}
private void CreateSentence() => Create(this.source, Paragraph(Run("This is "), Bold("very"), Run(" "), Italic("important"), Run(" and "), Link("linked"), Run(" text.")));
private async Task<List<string>> KeysAsync() => (await this.format.ReadAsync(this.source, CancellationToken.None)).Select(segment => segment.Key).ToList();
private Task<SegmentWriteResult> WriteAsync(string key, string newText)
{
var results = new SegmentResults(new Dictionary<string, SegmentOutcome> { [key] = SegmentOutcome.Transformed(newText) });
return this.format.WriteAsync(this.source, this.target, results, string.Empty, NullLogger.Instance, CancellationToken.None);
}
/// <summary>
/// What a paragraph holds, in its order: words, the parts of fields without their instruction, tabs, and references to footnotes.
/// </summary>
private static List<string> OutlineOf(W.Paragraph paragraph) => paragraph
.Descendants()
.Select(element => element switch
{
W.Text text => text.Text,
W.FieldChar fieldChar => fieldChar.FieldCharType?.InnerText,
W.TabChar => "tab",
W.FootnoteReference => "footnote",
_ => null,
})
.OfType<string>()
.ToList();
private static List<string> TextsWhere(W.Paragraph paragraph, Func<W.Run, bool> condition) => paragraph
.Elements<W.Run>()
.Where(condition)
.Select(run => run.InnerText)
.ToList();
}
@@ -0,0 +1,414 @@
using AIStudio.Tools.DocumentSegments;
using AIStudio.Tools.DocumentSegments.Word;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using Microsoft.Extensions.Logging.Abstractions;
using A = DocumentFormat.OpenXml.Drawing;
using DW = DocumentFormat.OpenXml.Drawing.Wordprocessing;
using V = DocumentFormat.OpenXml.Vml;
using W = DocumentFormat.OpenXml.Wordprocessing;
using Wps = DocumentFormat.OpenXml.Office2010.Word.DrawingShape;
using static AIStudio.Tests.Tools.DocumentSegments.Word.TestWordDocument;
namespace AIStudio.Tests.Tools.DocumentSegments.Word;
/// <summary>
/// Checks which parts of a Word document a model works on, and that everything else stays as it is.
/// </summary>
[TestFixture]
public sealed class WordSegmentFormatTests
{
private const string LINK_PARAGRAPH = "Read the <1>manual</1> first.<2/>Done";
private readonly WordSegmentFormat format = new();
private string testFolder = string.Empty;
private string source = string.Empty;
private string target = string.Empty;
[SetUp]
public void CreateDocument()
{
this.testFolder = Directory.CreateDirectory(Path.Join(Path.GetTempPath(), "mindwork-ai-studio-tests", Guid.NewGuid().ToString("N"))).FullName;
this.source = Path.Join(this.testFolder, "source.docx");
this.target = Path.Join(this.testFolder, "target.docx");
TestWordDocument.CreateSample(this.source);
}
[TearDown]
public void RemoveFolder() => Directory.Delete(this.testFolder, true);
[Test]
public async Task TheParagraphsBecomeSegmentsWithTags()
{
var keys = (await this.format.ReadAsync(this.source, CancellationToken.None)).Select(segment => segment.Key).ToList();
using (Assert.EnterMultipleScope())
{
Assert.That(keys, Does.Contain("Getting started"));
Assert.That(keys, Does.Contain(LINK_PARAGRAPH), "A link is a pair, a tab a tag of its own.");
Assert.That(keys, Does.Contain("See the note<1/>"), "The reference to a footnote is a tag of its own.");
Assert.That(keys, Does.Contain("<1>Introduction</1>"), "The result of a field is words within a pair.");
Assert.That(keys, Does.Contain("<1>Chapter</1>"), "A bookmark around words is a pair, so that a cross reference to it shows the new words alone.");
Assert.That(keys, Does.Contain("Mixed <1>bold</1> words"), "A word in bold is a pair.");
Assert.That(keys, Does.Contain("Confidential"), "Headers are read.");
Assert.That(keys, Does.Contain("Page footer"), "Footers are read.");
Assert.That(keys, Does.Contain("<1/> A note."), "Footnotes are read, without their separators.");
Assert.That(keys, Does.Contain("<1/> An endnote."), "Endnotes are read, without their separators.");
}
}
[Test]
public async Task WritingTheSourceBackChangesNothing()
{
var result = await this.format.WriteAsync(this.source, this.target, await this.ResultsAsync(key => key), "de-DE", NullLogger.Instance, CancellationToken.None);
using var sourceDocument = WordprocessingDocument.Open(this.source, false);
using var targetDocument = WordprocessingDocument.Open(this.target, false);
using (Assert.EnterMultipleScope())
{
Assert.That(result.Outcome, Is.EqualTo(SegmentWriteOutcome.WRITTEN));
Assert.That(BodyOf(targetDocument).OuterXml, Is.EqualTo(BodyOf(sourceDocument).OuterXml));
}
}
[Test]
public async Task NewWordsKeepTheStructure()
{
var result = await this.format.WriteAsync(this.source, this.target, await this.ResultsAsync(key => key.ToUpperInvariant()), "de-DE", NullLogger.Instance, CancellationToken.None);
using var sourceDocument = WordprocessingDocument.Open(this.source, false);
using var document = WordprocessingDocument.Open(this.target, false);
var paragraphs = BodyOf(document).Elements<W.Paragraph>().ToList();
var link = paragraphs[1].Descendants<W.Hyperlink>().SingleOrDefault();
using (Assert.EnterMultipleScope())
{
Assert.That(TestWordDocument.ValidationErrorsOf(document), Is.EqualTo(TestWordDocument.ValidationErrorsOf(sourceDocument)), "The new document is as valid as the source.");
Assert.That(result.SimplifiedCount, Is.Zero, "Every paragraph keeps its inline structure and formatting.");
Assert.That(paragraphs[0].InnerText, Is.EqualTo("GETTING STARTED"));
Assert.That(link?.InnerText, Is.EqualTo("MANUAL"), "The link encloses its new words.");
Assert.That(link?.Id?.Value, Is.EqualTo("rIdManual"), "The link keeps its address.");
Assert.That(paragraphs[1].Descendants<W.TabChar>().Count(), Is.EqualTo(1), "The tab stays.");
Assert.That(paragraphs[1].InnerText, Is.EqualTo("READ THE MANUAL FIRST.DONE"));
Assert.That(paragraphs[2].Descendants<W.FootnoteReference>().Select(reference => reference.Id?.Value), Is.EqualTo(new long?[] { 1 }), "The reference to the footnote stays.");
Assert.That(paragraphs[3].Descendants<W.FieldChar>().Select(fieldChar => fieldChar.FieldCharType?.Value), Is.EqualTo(new[] { W.FieldCharValues.Begin, W.FieldCharValues.Separate, W.FieldCharValues.End }), "The field keeps its parts in their order.");
Assert.That(paragraphs[3].Descendants<W.Text>().Select(text => text.Text), Is.EqualTo(new[] { "INTRODUCTION" }), "The new words are the result of the field.");
Assert.That(paragraphs[3].Descendants<W.FieldCode>().Single().Text, Is.EqualTo(" REF _Ref1 \\h "), "The instruction of the field stays.");
Assert.That(paragraphs[4].ChildElements.First(), Is.TypeOf<W.BookmarkStart>(), "The bookmark starts before the new words.");
Assert.That(paragraphs[4].ChildElements.Last(), Is.TypeOf<W.BookmarkEnd>(), "The bookmark ends after the new words.");
Assert.That(paragraphs[4].InnerText, Is.EqualTo("CHAPTER"));
Assert.That(paragraphs[5].InnerText, Is.EqualTo("MIXED BOLD WORDS"));
Assert.That(paragraphs[5].Elements<W.Run>().Where(run => run.RunProperties?.Bold is not null).Select(run => run.InnerText), Is.EqualTo(new[] { "BOLD" }), "The word in bold stays bold.");
Assert.That(paragraphs[6].InnerText, Is.EqualTo("2026"));
Assert.That(document.MainDocumentPart!.HeaderParts.Single().Header!.InnerText, Is.EqualTo("CONFIDENTIAL"));
Assert.That(document.MainDocumentPart.FooterParts.Single().Footer!.InnerText, Is.EqualTo("PAGE FOOTER"));
Assert.That(document.MainDocumentPart.FootnotesPart!.Footnotes!.Elements<W.Footnote>().Last().InnerText, Is.EqualTo(" A NOTE."));
Assert.That(document.MainDocumentPart.EndnotesPart!.Endnotes!.Elements<W.Endnote>().Last().InnerText, Is.EqualTo(" AN ENDNOTE."));
Assert.That(link?.Descendants<W.Languages>().SingleOrDefault()?.Val?.Value, Is.EqualTo("de-DE"), "New words carry their language.");
}
}
[Test]
public async Task WhatTheModelDroppedFollowsItsWords()
{
var results = await this.ResultsAsync(key => key == LINK_PARAGRAPH ? "Lies zuerst das Handbuch. Fertig" : key);
var result = await this.format.WriteAsync(this.source, this.target, results, "de-DE", NullLogger.Instance, CancellationToken.None);
using var document = WordprocessingDocument.Open(this.target, false);
var paragraph = BodyOf(document).Elements<W.Paragraph>().ElementAt(1);
using (Assert.EnterMultipleScope())
{
Assert.That(result.SimplifiedCount, Is.EqualTo(1));
Assert.That(paragraph.InnerText, Is.EqualTo("Lies zuerst das Handbuch. Fertig"));
Assert.That(paragraph.Descendants<W.Hyperlink>(), Is.Empty, "A link whose tags the model dropped goes.");
Assert.That(paragraph.Elements<W.Run>().Last().GetFirstChild<W.TabChar>(), Is.Not.Null, "The tab follows the words rather than getting lost.");
}
}
/// <remarks>
/// The format skips a paragraph whose text stays as it was, so this test hands every key to the writer itself:
/// a writer which puts a paragraph together again from its own tags has to yield the same document.
/// </remarks>
[Test]
public void WritingEveryKeyThroughTheWriterKeepsTheDocument()
{
File.Copy(this.source, this.target);
using (var document = WordprocessingDocument.Open(this.target, true))
{
foreach (var paragraph in WordSegmentReader.Read(document))
Assert.That(WordParagraphWriter.Write(paragraph, paragraph.Segment.Key, string.Empty), Is.True, $"'{paragraph.Segment.Key}' keeps its inline structure and formatting.");
}
using var sourceDocument = WordprocessingDocument.Open(this.source, false);
using var targetDocument = WordprocessingDocument.Open(this.target, false);
using (Assert.EnterMultipleScope())
{
Assert.That(ValidationErrorsOf(targetDocument), Is.EqualTo(ValidationErrorsOf(sourceDocument)), "The new document is as valid as the source.");
foreach (var (sourceRoot, targetRoot) in RootsOf(sourceDocument).Zip(RootsOf(targetDocument)))
{
Assert.That(StructureOf(targetRoot), Is.EqualTo(StructureOf(sourceRoot)), $"Every element of {sourceRoot.LocalName} besides the runs stays, in its order.");
Assert.That(FormattedTextOf(targetRoot), Is.EqualTo(FormattedTextOf(sourceRoot)), $"Every word of {sourceRoot.LocalName} keeps its formatting.");
}
}
}
[Test]
public async Task ATextBoxKeepsTheNewWordsOfItsParagraphs()
{
this.CreateWithTextBox();
var result = await this.format.WriteAsync(this.source, this.target, await this.ResultsAsync(key => key.ToUpperInvariant()), string.Empty, NullLogger.Instance, CancellationToken.None);
Assert.That(result.SimplifiedCount, Is.Zero);
this.AssertTextBoxIsWritten();
}
[Test]
public void ATextBoxKeepsTheNewWordsOfItsParagraphsInEitherOrder()
{
this.CreateWithTextBox();
File.Copy(this.source, this.target);
// The format writes the paragraph around the text box first; here, the paragraphs within the text box come first:
using (var document = WordprocessingDocument.Open(this.target, true))
{
foreach (var paragraph in WordSegmentReader.Read(document).Reverse())
WordParagraphWriter.Write(paragraph, paragraph.Segment.Key.ToUpperInvariant(), string.Empty);
}
this.AssertTextBoxIsWritten();
}
[Test]
public async Task OnlyContentControlsWithWordsOfTheUserAreRead()
{
var editable = new W.SdtRun(new W.SdtProperties(new W.SdtAlias { Val = "Name" }), new W.SdtContentRun(Run("Alice")));
var choice = new W.SdtRun(new W.SdtProperties(new W.SdtContentDropDownList(new W.ListItem { DisplayText = "Yes", Value = "Yes" })), new W.SdtContentRun(Run("Yes")));
var bound = new W.SdtBlock(
new W.SdtProperties(new W.DataBinding { XPath = "/data/name", StoreItemId = "{6A55B0DB-1A2F-4D0E-9B3A-1F0C3D3B2E11}" }),
new W.SdtContentBlock(Paragraph(Run("Bound text"))));
Create(this.source, Paragraph(Run("Name: "), editable, Run(" Choice: "), choice));
using (var sourceToExtend = WordprocessingDocument.Open(this.source, true))
BodyOf(sourceToExtend).AppendChild(bound);
var keys = (await this.format.ReadAsync(this.source, CancellationToken.None)).Select(segment => segment.Key).ToList();
await this.format.WriteAsync(this.source, this.target, await this.ResultsAsync(key => key.ToUpperInvariant()), string.Empty, NullLogger.Instance, CancellationToken.None);
using var sourceDocument = WordprocessingDocument.Open(this.source, false);
using var document = WordprocessingDocument.Open(this.target, false);
var contentControls = BodyOf(document).Descendants<W.SdtRun>().ToList();
using (Assert.EnterMultipleScope())
{
Assert.That(keys, Is.EqualTo(new[] { "Name: <1>Alice</1> Choice: <2/>" }), "Words of the user are a pair, a choice is a tag of its own, and bound words stay out.");
Assert.That(ValidationErrorsOf(document), Is.EqualTo(ValidationErrorsOf(sourceDocument)), "The new document is as valid as the source.");
Assert.That(contentControls.Select(contentControl => contentControl.InnerText), Is.EqualTo(new[] { "ALICE", "Yes" }));
Assert.That(BodyOf(document).Descendants<W.SdtBlock>().Single().InnerText, Is.EqualTo("Bound text"));
}
}
[Test]
public async Task ADeletionOfTheChangeTrackingStaysAsItIs()
{
Create(this.source, Paragraph(
Run("Keep "),
new W.DeletedRun(new W.Run(new W.DeletedText("gone"))) { Id = "1", Author = "Tester" },
new W.InsertedRun(Run("new")) { Id = "2", Author = "Tester" }));
var keys = (await this.format.ReadAsync(this.source, CancellationToken.None)).Select(segment => segment.Key).ToList();
await this.format.WriteAsync(this.source, this.target, await this.ResultsAsync(key => key.ToUpperInvariant()), string.Empty, NullLogger.Instance, CancellationToken.None);
using var sourceDocument = WordprocessingDocument.Open(this.source, false);
using var document = WordprocessingDocument.Open(this.target, false);
using (Assert.EnterMultipleScope())
{
Assert.That(keys, Is.EqualTo(new[] { "Keep <1/><2>new</2>" }), "Deleted words are no words of the paragraph any more.");
Assert.That(ValidationErrorsOf(document), Is.EqualTo(ValidationErrorsOf(sourceDocument)), "The new document is as valid as the source.");
Assert.That(BodyOf(document).Descendants<W.DeletedRun>().Single().InnerText, Is.EqualTo("gone"));
Assert.That(BodyOf(document).Descendants<W.InsertedRun>().Single().InnerText, Is.EqualTo("NEW"));
}
}
[Test]
public async Task AFieldAcrossParagraphsKeepsItsParts()
{
// A table of contents starts in one paragraph and ends in another one:
Create(this.source,
Paragraph(
new W.Run(new W.FieldChar { FieldCharType = W.FieldCharValues.Begin }),
new W.Run(new W.FieldCode(" TOC \\o \"1-3\" ") { Space = SpaceProcessingModeValues.Preserve }),
new W.Run(new W.FieldChar { FieldCharType = W.FieldCharValues.Separate }),
Run("Introduction")),
Paragraph(Run("Methods"), new W.Run(new W.FieldChar { FieldCharType = W.FieldCharValues.End })));
var keys = (await this.format.ReadAsync(this.source, CancellationToken.None)).Select(segment => segment.Key).ToList();
await this.format.WriteAsync(this.source, this.target, await this.ResultsAsync(key => key.ToUpperInvariant()), string.Empty, NullLogger.Instance, CancellationToken.None);
using var sourceDocument = WordprocessingDocument.Open(this.source, false);
using var document = WordprocessingDocument.Open(this.target, false);
var paragraphs = BodyOf(document).Elements<W.Paragraph>().ToList();
using (Assert.EnterMultipleScope())
{
Assert.That(keys, Is.EqualTo(new[] { "Introduction", "Methods" }), "The parts of a field which goes on in another paragraph are no tags, so the model cannot move them among the words.");
Assert.That(ValidationErrorsOf(document), Is.EqualTo(ValidationErrorsOf(sourceDocument)), "The new document is as valid as the source.");
Assert.That(BodyOf(document).Descendants<W.FieldChar>().Select(fieldChar => fieldChar.FieldCharType?.Value), Is.EqualTo(new[] { W.FieldCharValues.Begin, W.FieldCharValues.Separate, W.FieldCharValues.End }));
Assert.That(BodyOf(document).InnerText, Is.EqualTo(" TOC \\o \"1-3\" INTRODUCTIONMETHODS"));
Assert.That(paragraphs[0].Elements<W.Run>().First().GetFirstChild<W.FieldChar>()?.FieldCharType?.Value, Is.EqualTo(W.FieldCharValues.Begin), "The start stays at the start of its paragraph.");
Assert.That(paragraphs[1].Elements<W.Run>().Last().GetFirstChild<W.FieldChar>()?.FieldCharType?.Value, Is.EqualTo(W.FieldCharValues.End), "The end stays at the end of its paragraph.");
}
}
[Test]
public async Task WordsBesideAFieldAcrossParagraphsLeaveTheFieldRatherThanJoinIt()
{
// A field which starts after words and ends before words; an update of the field replaces its result:
Create(this.source,
Paragraph(
Run("Contents: "),
new W.Run(new W.FieldChar { FieldCharType = W.FieldCharValues.Begin }),
new W.Run(new W.FieldCode(" TOC \\o \"1-3\" ") { Space = SpaceProcessingModeValues.Preserve }),
new W.Run(new W.FieldChar { FieldCharType = W.FieldCharValues.Separate }),
Run("Introduction")),
Paragraph(Run("Methods"), new W.Run(new W.FieldChar { FieldCharType = W.FieldCharValues.End }), Run(" Chapter 1")));
await this.format.WriteAsync(this.source, this.target, await this.ResultsAsync(key => key.ToUpperInvariant()), string.Empty, NullLogger.Instance, CancellationToken.None);
using var document = WordprocessingDocument.Open(this.target, false);
var paragraphs = BodyOf(document).Elements<W.Paragraph>().ToList();
using (Assert.EnterMultipleScope())
{
Assert.That(paragraphs[0].Elements<W.Run>().First().InnerText, Is.EqualTo("CONTENTS: INTRODUCTION"), "The words come first, so an update never deletes them.");
Assert.That(paragraphs[0].Elements<W.Run>().Last().GetFirstChild<W.FieldChar>()?.FieldCharType?.Value, Is.EqualTo(W.FieldCharValues.Separate));
Assert.That(paragraphs[1].Elements<W.Run>().First().GetFirstChild<W.FieldChar>()?.FieldCharType?.Value, Is.EqualTo(W.FieldCharValues.End), "The words follow the end, so an update never deletes them.");
Assert.That(paragraphs[1].InnerText, Is.EqualTo("METHODS CHAPTER 1"));
}
}
[Test]
public async Task WordsWhoseTagsCannotBeReadKeepEverythingTheTagsStoodFor()
{
var results = await this.ResultsAsync(key => key == LINK_PARAGRAPH ? "Lies zuerst das <1>Handbuch. Fertig" : key);
var result = await this.format.WriteAsync(this.source, this.target, results, "de-DE", NullLogger.Instance, CancellationToken.None);
using var document = WordprocessingDocument.Open(this.target, false);
var paragraph = BodyOf(document).Elements<W.Paragraph>().ElementAt(1);
using (Assert.EnterMultipleScope())
{
Assert.That(result.SimplifiedCount, Is.EqualTo(1));
Assert.That(paragraph.InnerText, Is.EqualTo("Lies zuerst das Handbuch. Fertig"), "The words stay, without tags.");
Assert.That(paragraph.Elements<W.Run>().Last().GetFirstChild<W.TabChar>(), Is.Not.Null, "The tab follows the words rather than getting lost.");
}
}
[Test]
public async Task AChangedSourceWritesNothing()
{
var result = await this.format.WriteAsync(this.source, this.target, new SegmentResults(new Dictionary<string, SegmentOutcome>()), "de-DE", NullLogger.Instance, CancellationToken.None);
using (Assert.EnterMultipleScope())
{
Assert.That(result.Outcome, Is.EqualTo(SegmentWriteOutcome.SOURCE_CHANGED));
Assert.That(File.Exists(this.target), Is.False);
}
}
private async Task<SegmentResults> ResultsAsync(Func<string, string> transform)
{
var segments = await this.format.ReadAsync(this.source, CancellationToken.None);
return new SegmentResults(segments
.Where(segment => segment.HasWords)
.DistinctBy(segment => segment.Key)
.ToDictionary(segment => segment.Key, segment => SegmentOutcome.Transformed(transform(segment.Key))));
}
private static W.Body BodyOf(WordprocessingDocument document) => document.MainDocumentPart!.Document!.Body!;
private void AssertTextBoxIsWritten()
{
using var sourceDocument = WordprocessingDocument.Open(this.source, false);
using var document = WordprocessingDocument.Open(this.target, false);
var paragraph = BodyOf(document).Elements<W.Paragraph>().Single();
using (Assert.EnterMultipleScope())
{
Assert.That(ValidationErrorsOf(document), Is.EqualTo(ValidationErrorsOf(sourceDocument)), "The new document is as valid as the source.");
Assert.That(string.Concat(paragraph.Elements<W.Run>().SelectMany(run => run.Elements<W.Text>()).Select(text => text.Text)), Is.EqualTo("BEFORE AFTER"));
Assert.That(paragraph.Descendants<W.TextBoxContent>().Select(content => content.InnerText), Is.EqualTo(new[] { "INSIDE THE BOX", "INSIDE THE BOX" }), "Both copies of the text box keep their new words, which only moving the text box keeps.");
}
}
/// <summary>
/// A document with a text box, which declares the prefix of the shapes of current versions of Word at its root, as Word does.
/// </summary>
private void CreateWithTextBox()
{
Create(this.source, ParagraphWithTextBox());
using var document = WordprocessingDocument.Open(this.source, true);
document.MainDocumentPart!.Document!.AddNamespaceDeclaration("wps", "http://schemas.microsoft.com/office/word/2010/wordprocessingShape");
}
/// <summary>
/// A paragraph with a text box, as Word writes it: one copy for current versions of Word, one for older ones.
/// </summary>
private static W.Paragraph ParagraphWithTextBox()
{
var textBox = new AlternateContent(
new AlternateContentChoice(new W.Drawing(new DW.Inline(
new DW.Extent { Cx = 914_400, Cy = 457_200 },
new DW.DocProperties { Id = 1U, Name = "Text Box 1" },
new A.Graphic(new A.GraphicData(new Wps.WordprocessingShape(
new Wps.NonVisualDrawingShapeProperties { TextBox = true },
new Wps.ShapeProperties(),
new Wps.TextBoxInfo2(new W.TextBoxContent(Paragraph(Run("Inside the box")))),
new Wps.TextBodyProperties())) { Uri = "http://schemas.microsoft.com/office/word/2010/wordprocessingShape" })))) { Requires = "wps" },
new AlternateContentFallback(new W.Picture(new V.Shape(new V.TextBox(new W.TextBoxContent(Paragraph(Run("Inside the box"))))) { Id = "Text Box 1" })));
return Paragraph(Run("Before "), new W.Run(textBox), Run(" after"));
}
private static IEnumerable<OpenXmlElement> RootsOf(WordprocessingDocument document)
{
var mainPart = document.MainDocumentPart!;
yield return mainPart.Document!.Body!;
yield return mainPart.HeaderParts.Single().Header!;
yield return mainPart.FooterParts.Single().Footer!;
yield return mainPart.FootnotesPart!.Footnotes!;
yield return mainPart.EndnotesPart!.Endnotes!;
}
/// <summary>
/// The elements of a part in their order, apart from runs and their properties, which a writer may split or join.
/// </summary>
private static List<string> StructureOf(OpenXmlElement root) => root
.Descendants()
.Where(element => element is not (W.Run or W.Text or W.RunProperties) && !element.Ancestors<W.RunProperties>().Any())
.Select(element => element.LocalName)
.ToList();
/// <summary>
/// The words of a part with their formatting, joined where the formatting stays the same.
/// </summary>
private static List<string> FormattedTextOf(OpenXmlElement root)
{
var spans = new List<(string Format, string Text)>();
foreach (var text in root.Descendants<W.Text>())
{
var format = text.Ancestors<W.Run>().FirstOrDefault()?.RunProperties?.OuterXml ?? string.Empty;
if (spans.Count > 0 && spans[^1].Format == format)
spans[^1] = (format, spans[^1].Text + text.Text);
else
spans.Add((format, text.Text));
}
return spans.Select(span => $"{span.Format}: {span.Text}").ToList();
}
}