mirror of
https://github.com/MindWorkAI/AI-Studio.git
synced 2026-12-06 04:51:36 +00:00
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:
1 parent
f7666861f1
commit
918572c158
150 files changed
+12850
-302
No files matched your search
@@ -0,0 +1,46 @@
|
||||
using System.Globalization;
|
||||
|
||||
using DocumentFormat.OpenXml;
|
||||
|
||||
namespace AIStudio.Tools.DocumentSegments.Word;
|
||||
|
||||
/// <summary>
|
||||
/// Hands out numbers for the changes of the change tracking which the writer adds to a Word document, e.g., the
|
||||
/// second part of an insertion, which no change, comment, or bookmark of the document uses yet.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// Word tells these apart by their numbers and offers to repair a document in which two of them share one.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The numbers of the document are searched once, at the first need, so that a long document is not searched again
|
||||
/// for each paragraph; from then on, only the writer adds numbers, each one higher than the last. While the writer
|
||||
/// puts a paragraph together, the elements it moves back are out of the document, so the writer names them.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
/// <param name="roots">The parts of the document whose paragraphs are segments, e.g., the body and the headers.</param>
|
||||
internal sealed class WordAnnotationIds(IReadOnlyList<OpenXmlElement> roots)
|
||||
{
|
||||
private const string WORDPROCESSING_NAMESPACE = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
|
||||
|
||||
private int? next;
|
||||
|
||||
/// <summary>
|
||||
/// Hands out the next free number.
|
||||
/// </summary>
|
||||
/// <param name="detached">The elements which are out of the document right now and go back into it, e.g., those of the paragraph the writer puts together.</param>
|
||||
public string Next(IEnumerable<OpenXmlElement> detached)
|
||||
{
|
||||
var id = this.next ?? HighestId(roots.Concat(detached)) + 1;
|
||||
this.next = id + 1;
|
||||
return id.ToString(CultureInfo.InvariantCulture);
|
||||
}
|
||||
|
||||
private static int HighestId(IEnumerable<OpenXmlElement> elements) => elements
|
||||
.SelectMany(element => element.Descendants().Prepend(element))
|
||||
.SelectMany(element => element.GetAttributes())
|
||||
.Where(attribute => attribute is { LocalName: "id", NamespaceUri: WORDPROCESSING_NAMESPACE })
|
||||
.Select(attribute => int.TryParse(attribute.Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var id) ? id : 0)
|
||||
.DefaultIfEmpty(0)
|
||||
.Max();
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace AIStudio.Tools.DocumentSegments.Word;
|
||||
|
||||
/// <summary>
|
||||
/// The elements one tag stands for, which go back into the paragraph together and in their order.
|
||||
/// </summary>
|
||||
/// <param name="Pieces">The elements.</param>
|
||||
/// <param name="Order">Where the elements stood in the paragraph, so that those the model dropped follow its words in their order.</param>
|
||||
internal sealed record WordAtom(IReadOnlyList<WordPiece> Pieces, int Order);
|
||||
@@ -0,0 +1,24 @@
|
||||
using W = DocumentFormat.OpenXml.Wordprocessing;
|
||||
|
||||
namespace AIStudio.Tools.DocumentSegments.Word;
|
||||
|
||||
/// <summary>
|
||||
/// Words between a start and an end which are elements of their own and stay as they are, and in their order:
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <list type="bullet">
|
||||
/// <item>A field whose result shows words, e.g., an entry of a table of contents or a cross reference. The words
|
||||
/// are its result, while the start of the field with its instruction and the end of the field stay.</item>
|
||||
/// <item>A bookmark around words, e.g., the one a cross reference to a caption points to. It encloses the same
|
||||
/// words afterward, so that the cross reference shows the new label and number, not the whole caption.</item>
|
||||
/// </list>
|
||||
/// </remarks>
|
||||
/// <param name="Opening">The start: of a field, with its instruction and the mark which separates the result, or of a bookmark.</param>
|
||||
/// <param name="Closing">The end of the field or of the bookmark.</param>
|
||||
internal sealed record WordBoundaryPair(WordAtom Opening, WordAtom Closing) : WordPair
|
||||
{
|
||||
/// <summary>
|
||||
/// Whether the pair encloses the result of a field, which Word replaces whenever it updates the field.
|
||||
/// </summary>
|
||||
public bool IsField => this.Opening.Pieces is [{ Element: W.FieldChar }, ..];
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
using DocumentFormat.OpenXml;
|
||||
|
||||
namespace AIStudio.Tools.DocumentSegments.Word;
|
||||
|
||||
/// <summary>
|
||||
/// An element which encloses runs, e.g., a link, a content control, or an insertion of the change tracking.
|
||||
/// The writer creates it anew around the new words, with the attributes and properties of the original.
|
||||
/// </summary>
|
||||
/// <param name="Container">The original element.</param>
|
||||
internal sealed record WordContainerPair(OpenXmlElement Container) : WordPair;
|
||||
@@ -0,0 +1,10 @@
|
||||
using W = DocumentFormat.OpenXml.Wordprocessing;
|
||||
|
||||
namespace AIStudio.Tools.DocumentSegments.Word;
|
||||
|
||||
/// <summary>
|
||||
/// Words in a formatting other than the most common one of their surroundings, e.g., a word in bold. The
|
||||
/// writer gives the new words within the pair this formatting.
|
||||
/// </summary>
|
||||
/// <param name="Format">The properties of the runs of these words.</param>
|
||||
internal sealed record WordFormatPair(W.RunProperties? Format) : WordPair;
|
||||
@@ -0,0 +1,36 @@
|
||||
using W = DocumentFormat.OpenXml.Wordprocessing;
|
||||
|
||||
namespace AIStudio.Tools.DocumentSegments.Word;
|
||||
|
||||
/// <summary>
|
||||
/// Notes the language of new words in a Word document, so that its spell checking and hyphenation follow it.
|
||||
/// </summary>
|
||||
internal static class WordLanguage
|
||||
{
|
||||
/// <summary>
|
||||
/// The languages Word records apart from the others: those with East Asian characters, and those with complex scripts.
|
||||
/// </summary>
|
||||
private static readonly string[] EAST_ASIAN_LANGUAGES = ["zh", "ja", "ko"];
|
||||
private static readonly string[] COMPLEX_SCRIPT_LANGUAGES = ["ar", "fa", "he", "hi", "ur"];
|
||||
|
||||
/// <summary>
|
||||
/// Notes the language of a run.
|
||||
/// </summary>
|
||||
/// <param name="run">The run with new words.</param>
|
||||
/// <param name="languageTag">The IETF tag of the language, e.g., "de-DE"; empty to leave the run as it is.</param>
|
||||
public static void Set(W.Run run, string languageTag)
|
||||
{
|
||||
if (languageTag.Length == 0)
|
||||
return;
|
||||
|
||||
var properties = run.RunProperties ?? run.PrependChild(new W.RunProperties());
|
||||
var languages = properties.Languages ??= new W.Languages();
|
||||
var primaryLanguage = languageTag.Split('-')[0];
|
||||
if (EAST_ASIAN_LANGUAGES.Contains(primaryLanguage, StringComparer.OrdinalIgnoreCase))
|
||||
languages.EastAsia = languageTag;
|
||||
else if (COMPLEX_SCRIPT_LANGUAGES.Contains(primaryLanguage, StringComparer.OrdinalIgnoreCase))
|
||||
languages.Bidi = languageTag;
|
||||
else
|
||||
languages.Val = languageTag;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
namespace AIStudio.Tools.DocumentSegments.Word;
|
||||
|
||||
/// <summary>
|
||||
/// What a pair of tags in a paragraph stands for.
|
||||
/// </summary>
|
||||
internal abstract record WordPair;
|
||||
@@ -0,0 +1,66 @@
|
||||
using DocumentFormat.OpenXml;
|
||||
|
||||
using W = DocumentFormat.OpenXml.Wordprocessing;
|
||||
|
||||
namespace AIStudio.Tools.DocumentSegments.Word;
|
||||
|
||||
/// <summary>
|
||||
/// A paragraph of a Word document as a segment, with all the writer needs to put it together again.
|
||||
/// </summary>
|
||||
/// <param name="Paragraph">The paragraph.</param>
|
||||
/// <param name="Segment">Its words with tags.</param>
|
||||
/// <param name="Pairs">What each pair of tags stands for.</param>
|
||||
/// <param name="Placeholders">What each tag of its own stands for.</param>
|
||||
/// <param name="TextFormats">The properties of the runs with words within each pair, and with 0 outside of any pair: the most common formatting there, or the formatting of a pair of formatting.</param>
|
||||
/// <param name="PiecesBefore">What goes before the words: the starts of bookmarks, comments, and the like, and the parts of fields which go on in another paragraph, see WordSegmentReader.</param>
|
||||
/// <param name="PiecesAfter">What goes after the words: the ends of bookmarks, comments, and the like, and the parts of fields which go on in another paragraph.</param>
|
||||
/// <param name="HasMixedFormatting">Whether runs with words within the same pair differ in their formatting, which the new words do not keep; only when the formatting changes too often for pairs of formatting.</param>
|
||||
/// <param name="AnnotationIds">The numbers for new changes of the change tracking, which all paragraphs of the document share.</param>
|
||||
internal sealed record WordParagraph(
|
||||
W.Paragraph Paragraph,
|
||||
DocumentSegment Segment,
|
||||
IReadOnlyDictionary<int, WordPair> Pairs,
|
||||
IReadOnlyDictionary<int, WordAtom> Placeholders,
|
||||
IReadOnlyDictionary<int, W.RunProperties?> TextFormats,
|
||||
IReadOnlyList<WordPiece> PiecesBefore,
|
||||
IReadOnlyList<WordPiece> PiecesAfter,
|
||||
bool HasMixedFormatting,
|
||||
WordAnnotationIds AnnotationIds)
|
||||
{
|
||||
/// <summary>
|
||||
/// All elements the tags stand for, in the order they stood in the paragraph.
|
||||
/// </summary>
|
||||
public IEnumerable<WordAtom> AtomsInOrder => this.Placeholders.Values
|
||||
.Concat(this.Pairs.Values.OfType<WordBoundaryPair>().SelectMany(pair => new[] { pair.Opening, pair.Closing }))
|
||||
.OrderBy(atom => atom.Order);
|
||||
|
||||
/// <summary>
|
||||
/// The elements the writer moves into the new paragraph, or copies, which are out of the document while it writes.
|
||||
/// </summary>
|
||||
public IEnumerable<OpenXmlElement> MovedElements => this.PiecesBefore
|
||||
.Concat(this.PiecesAfter)
|
||||
.Concat(this.AtomsInOrder.SelectMany(atom => atom.Pieces))
|
||||
.Select(piece => piece.Element)
|
||||
.Concat(this.Pairs.Values.OfType<WordContainerPair>().Select(pair => pair.Container));
|
||||
|
||||
/// <summary>
|
||||
/// Hands out a number for a new change of the change tracking, see WordAnnotationIds.
|
||||
/// </summary>
|
||||
public string NextAnnotationId() => this.AnnotationIds.Next(this.MovedElements);
|
||||
|
||||
/// <summary>
|
||||
/// The properties for new words within a pair, or outside of any pair for 0.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Words within a pair without words of its own, e.g., when the model moved them there, get the
|
||||
/// properties of the words outside of any pair, or else of the first words of the paragraph.
|
||||
/// </remarks>
|
||||
/// <param name="pairId">The number of the innermost pair; 0 for none.</param>
|
||||
public W.RunProperties? TextFormatOf(int pairId)
|
||||
{
|
||||
if (this.TextFormats.TryGetValue(pairId, out var format) || this.TextFormats.TryGetValue(0, out format))
|
||||
return format;
|
||||
|
||||
return this.TextFormats.Values.FirstOrDefault();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,434 @@
|
||||
using System.Text;
|
||||
|
||||
using AIStudio.Tools.OpenXml;
|
||||
|
||||
using DocumentFormat.OpenXml;
|
||||
|
||||
using W = DocumentFormat.OpenXml.Wordprocessing;
|
||||
|
||||
namespace AIStudio.Tools.DocumentSegments.Word;
|
||||
|
||||
/// <summary>
|
||||
/// Puts a paragraph of a Word document together again around its new words.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The properties of the paragraph stay, and so do all elements its tags stand for: the writer moves them into
|
||||
/// the new paragraph rather than copying them, so that a text box keeps the new words of its own paragraphs,
|
||||
/// whichever paragraph is written first. New words get the formatting of their innermost pair.
|
||||
/// </remarks>
|
||||
internal static class WordParagraphWriter
|
||||
{
|
||||
/// <summary>
|
||||
/// Replaces the content of a paragraph with its new words.
|
||||
/// </summary>
|
||||
/// <param name="paragraph">The paragraph, as the reader read it from this document.</param>
|
||||
/// <param name="newText">The new words with tags, as the model wrote them.</param>
|
||||
/// <param name="languageTag">The IETF tag of the language of the new words; empty to leave the languages as they are.</param>
|
||||
/// <returns>Whether the paragraph kept all of its inline structure and formatting.</returns>
|
||||
public static bool Write(WordParagraph paragraph, string newText, string languageTag)
|
||||
{
|
||||
var element = paragraph.Paragraph;
|
||||
foreach (var child in element.ChildElements.Where(child => child is not W.ParagraphProperties).ToList())
|
||||
child.Remove();
|
||||
|
||||
foreach (var piece in paragraph.PiecesBefore)
|
||||
AppendPiece(element, piece, paragraph);
|
||||
|
||||
var writtenAtoms = new HashSet<WordAtom>();
|
||||
bool keepsTags;
|
||||
if (TaggedText.TryRead(newText, out var taggedText, out _))
|
||||
{
|
||||
var tokenWriter = new TokenWriter(paragraph, languageTag, writtenAtoms);
|
||||
tokenWriter.Write(taggedText);
|
||||
keepsTags = taggedText.HasSameTagsAs(paragraph.Segment.Source, out _) && tokenWriter.KeptAllContainers;
|
||||
}
|
||||
else
|
||||
{
|
||||
keepsTags = false;
|
||||
AppendWords(element, TaggedText.RemoveTags(newText), paragraph.TextFormatOf(0), languageTag, paragraph);
|
||||
}
|
||||
|
||||
// What the model dropped follows its words, so that no picture or reference gets lost:
|
||||
foreach (var atom in paragraph.AtomsInOrder.Where(atom => !writtenAtoms.Contains(atom)))
|
||||
{
|
||||
foreach (var piece in atom.Pieces)
|
||||
AppendPiece(element, piece, paragraph);
|
||||
}
|
||||
|
||||
foreach (var piece in paragraph.PiecesAfter)
|
||||
AppendPiece(element, piece, paragraph);
|
||||
|
||||
return keepsTags && !paragraph.HasMixedFormatting;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether Word allows an element within another one.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The writer builds the pairs as the model nested them and puts the tags of their own where the model put them,
|
||||
/// which may be a place the source never had. Within an insertion or a move of the change tracking, Word allows
|
||||
/// runs and what lies between runs, but no link, simple field, custom XML, or subdocument; it would offer to
|
||||
/// repair the file. Everything else the writer creates may stand where the model put it.
|
||||
/// </remarks>
|
||||
/// <param name="parent">Where the element would go.</param>
|
||||
/// <param name="child">The element.</param>
|
||||
private static bool Allows(OpenXmlElement parent, OpenXmlElement child) =>
|
||||
parent is not (W.InsertedRun or W.MoveToRun) || child is not (W.Hyperlink or W.SimpleField or W.CustomXmlRun or W.SubDocumentReference);
|
||||
|
||||
/// <summary>
|
||||
/// Writes the tokens of the new words into the paragraph, one after the other.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// Only pairs whose both tags arrived go back; TaggedText.TryRead made sure that they nest. When the tags do not
|
||||
/// fit the source, the pairs follow the nesting of the model, so that a link keeps its words although the model
|
||||
/// dropped a tab. The writer keeps that valid for Word, see Allows:
|
||||
/// </para>
|
||||
/// <list type="bullet">
|
||||
/// <item>A tag of its own, e.g., a linked logo which the model moved into an insertion, goes right after the
|
||||
/// insertion, and the insertion goes on behind it. Nothing gets lost, so this counts as kept.</item>
|
||||
/// <item>A pair whose container may not stand within its outer pair, e.g., a link which the model put into an
|
||||
/// insertion, loses its container and keeps its words. This happens only when the tags do not fit anyway.</item>
|
||||
/// <item>A tag of its own which the model moved into the result of a field goes right behind the field, see
|
||||
/// FieldAround. Nothing gets lost, so this counts as kept.</item>
|
||||
/// </list>
|
||||
/// </remarks>
|
||||
private sealed class TokenWriter(WordParagraph paragraph, string languageTag, HashSet<WordAtom> writtenAtoms)
|
||||
{
|
||||
/// <summary>
|
||||
/// A pair whose opening tag was written and whose closing tag is still to come.
|
||||
/// </summary>
|
||||
/// <param name="id">The number of the pair.</param>
|
||||
/// <param name="outer">Where the content goes again once the pair closes, i.e., where its container stands.</param>
|
||||
/// <param name="container">The container the pair stands for; null when it has none, or when it lost it.</param>
|
||||
/// <param name="isField">Whether the pair encloses the result of a field, which Word replaces whenever it updates the field.</param>
|
||||
private sealed class OpenPair(int id, OpenXmlElement outer, OpenXmlElement? container, bool isField = false)
|
||||
{
|
||||
public int Id => id;
|
||||
|
||||
public bool IsField => isField;
|
||||
|
||||
/// <summary>
|
||||
/// The tags of their own which the model moved into the result of this field, which go right behind it, see FieldAround.
|
||||
/// </summary>
|
||||
public List<WordAtom> MovedBehind { get; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Where the container stands; it moves when the container is opened again behind an element, see AppendWhereAllowed.
|
||||
/// </summary>
|
||||
public OpenXmlElement Outer { get; set; } = outer;
|
||||
|
||||
public OpenXmlElement? Container => container;
|
||||
|
||||
/// <summary>
|
||||
/// The copy of the container which was opened again behind an element which may not stand within it, and the
|
||||
/// element within the copy which holds the words; null as long as the first copy takes the words.
|
||||
/// </summary>
|
||||
public ContainerShell? Reopened { get; set; }
|
||||
}
|
||||
|
||||
private readonly List<OpenPair> openPairs = [];
|
||||
private readonly Dictionary<int, HashSet<int>> sourcePairsAround = PairsAroundPlaceholders(paragraph.Segment.Source);
|
||||
private OpenXmlElement target = paragraph.Paragraph;
|
||||
|
||||
/// <summary>
|
||||
/// Whether every pair whose both tags arrived kept its container.
|
||||
/// </summary>
|
||||
public bool KeptAllContainers { get; private set; } = true;
|
||||
|
||||
public void Write(TaggedText taggedText)
|
||||
{
|
||||
var openIds = taggedText.Tokens.Where(token => token.Kind is TaggedTokenKind.OPEN).Select(token => token.Id).ToHashSet();
|
||||
var closeIds = taggedText.Tokens.Where(token => token.Kind is TaggedTokenKind.CLOSE).Select(token => token.Id).ToHashSet();
|
||||
foreach (var token in taggedText.Tokens)
|
||||
{
|
||||
switch (token.Kind)
|
||||
{
|
||||
case TaggedTokenKind.TEXT:
|
||||
AppendWords(this.target, token.Text, paragraph.TextFormatOf(this.openPairs.Count == 0 ? 0 : this.openPairs[^1].Id), languageTag, paragraph);
|
||||
break;
|
||||
|
||||
case TaggedTokenKind.OPEN when closeIds.Contains(token.Id) && paragraph.Pairs.TryGetValue(token.Id, out var openedPair):
|
||||
this.Open(token.Id, openedPair);
|
||||
break;
|
||||
|
||||
case TaggedTokenKind.CLOSE when openIds.Contains(token.Id) && paragraph.Pairs.TryGetValue(token.Id, out var closedPair):
|
||||
this.Close(closedPair);
|
||||
break;
|
||||
|
||||
case TaggedTokenKind.PLACEHOLDER when paragraph.Placeholders.TryGetValue(token.Id, out var atom) && !writtenAtoms.Contains(atom):
|
||||
if (this.FieldAround(token.Id) is { } field)
|
||||
field.MovedBehind.Add(atom);
|
||||
else
|
||||
this.AppendAtom(atom);
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void Open(int pairId, WordPair pair)
|
||||
{
|
||||
switch (pair)
|
||||
{
|
||||
case WordContainerPair { Container: var container } when Allows(this.target, container):
|
||||
var (shell, content) = ShellOf(container);
|
||||
this.target.AppendChild(shell);
|
||||
this.openPairs.Add(new(pairId, this.target, container, container is W.SimpleField));
|
||||
this.target = content;
|
||||
break;
|
||||
|
||||
// The words stay where they are, without the container:
|
||||
case WordContainerPair:
|
||||
this.KeptAllContainers = false;
|
||||
this.openPairs.Add(new(pairId, this.target, null));
|
||||
break;
|
||||
|
||||
// The start of a field or of a bookmark goes before the words, its end follows them:
|
||||
case WordBoundaryPair boundary:
|
||||
this.openPairs.Add(new(pairId, this.target, null, boundary.IsField));
|
||||
this.AppendAtom(boundary.Opening);
|
||||
break;
|
||||
|
||||
// The words within the pair take its formatting, see WordParagraph.TextFormatOf:
|
||||
default:
|
||||
this.openPairs.Add(new(pairId, this.target, null));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private void Close(WordPair pair)
|
||||
{
|
||||
var openPair = this.openPairs[^1];
|
||||
this.openPairs.RemoveAt(this.openPairs.Count - 1);
|
||||
this.target = openPair.Outer;
|
||||
|
||||
// The rest of an insertion behind a tag which moved out of it would be empty ballast, when nothing follows the tag:
|
||||
if (openPair.Reopened is (var shell, var content) && !content.HasChildren)
|
||||
shell.Remove();
|
||||
|
||||
if (pair is WordBoundaryPair { Closing: var closing })
|
||||
this.AppendAtom(closing);
|
||||
|
||||
foreach (var atom in openPair.MovedBehind)
|
||||
this.AppendAtom(atom);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Finds the outermost field into whose result the model moved a tag of its own, although the tag lay outside
|
||||
/// of it in the source.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Word replaces the result of a field whenever it updates the field, e.g., before printing, which would delete
|
||||
/// a reference to a footnote or a picture there. A tag which lay in the result in the source stays there.
|
||||
/// </remarks>
|
||||
/// <param name="placeholderId">The number of the tag.</param>
|
||||
/// <returns>The field, behind which the tag goes; null when the tag stays where the model put it.</returns>
|
||||
private OpenPair? FieldAround(int placeholderId)
|
||||
{
|
||||
var sourcePairs = this.sourcePairsAround.GetValueOrDefault(placeholderId);
|
||||
return this.openPairs.FirstOrDefault(openPair => openPair.IsField && sourcePairs?.Contains(openPair.Id) is not true);
|
||||
}
|
||||
|
||||
private void AppendAtom(WordAtom atom)
|
||||
{
|
||||
writtenAtoms.Add(atom);
|
||||
foreach (var piece in atom.Pieces)
|
||||
{
|
||||
var element = piece.Element.Detached();
|
||||
if (piece.InRun)
|
||||
this.target.AppendChild(RunOf(piece, element, paragraph));
|
||||
else
|
||||
this.AppendWhereAllowed(element);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Appends an element to the innermost container which allows it, and opens the containers it left again behind it.
|
||||
/// </summary>
|
||||
private void AppendWhereAllowed(OpenXmlElement element)
|
||||
{
|
||||
var level = this.openPairs.Count;
|
||||
var place = this.target;
|
||||
while (!Allows(place, element) && level > 0)
|
||||
{
|
||||
level--;
|
||||
place = this.openPairs[level].Outer;
|
||||
}
|
||||
|
||||
place.AppendChild(element);
|
||||
for (; level < this.openPairs.Count; level++)
|
||||
{
|
||||
var openPair = this.openPairs[level];
|
||||
openPair.Outer = place;
|
||||
if (openPair.Container is null)
|
||||
continue;
|
||||
|
||||
var (shell, content) = ShellOf(openPair.Container);
|
||||
place.AppendChild(shell);
|
||||
|
||||
// Word tells the changes of its change tracking apart by their numbers, so the second part of an insertion needs a number of its own:
|
||||
if (shell is W.RunTrackChangeType change)
|
||||
change.Id = paragraph.NextAnnotationId();
|
||||
|
||||
openPair.Reopened = new ContainerShell(shell, content);
|
||||
place = content;
|
||||
}
|
||||
|
||||
this.target = place;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an empty copy of an element which encloses runs, with its attributes and properties.
|
||||
/// </summary>
|
||||
/// <returns>The copy, and the element within it which takes the runs.</returns>
|
||||
private static ContainerShell ShellOf(OpenXmlElement container)
|
||||
{
|
||||
var shell = container.CloneNode(false);
|
||||
switch (container)
|
||||
{
|
||||
case W.SdtRun contentControl:
|
||||
if (contentControl.SdtProperties is { } contentControlProperties)
|
||||
shell.AppendChild(contentControlProperties.CloneNode(true));
|
||||
|
||||
if (contentControl.SdtEndCharProperties is { } endProperties)
|
||||
shell.AppendChild(endProperties.CloneNode(true));
|
||||
|
||||
return new(shell, shell.AppendChild(new W.SdtContentRun()));
|
||||
|
||||
case W.CustomXmlRun { CustomXmlProperties: { } customXmlProperties }:
|
||||
shell.AppendChild(customXmlProperties.CloneNode(true));
|
||||
break;
|
||||
|
||||
case W.SimpleField { FieldData: { } fieldData }:
|
||||
shell.AppendChild(fieldData.CloneNode(true));
|
||||
break;
|
||||
}
|
||||
|
||||
return new(shell, shell);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Moves an element of the paragraph into the new paragraph, with a run of its own when it sat in a run.
|
||||
/// </summary>
|
||||
private static void AppendPiece(OpenXmlElement target, WordPiece piece, WordParagraph paragraph)
|
||||
{
|
||||
var element = piece.Element.Detached();
|
||||
target.AppendChild(piece.InRun ? RunOf(piece, element, paragraph) : element);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Finds for every tag of its own the pairs it lies in.
|
||||
/// </summary>
|
||||
private static Dictionary<int, HashSet<int>> PairsAroundPlaceholders(TaggedText taggedText)
|
||||
{
|
||||
var pairsAround = new Dictionary<int, HashSet<int>>();
|
||||
var openPairs = new Stack<int>();
|
||||
foreach (var token in taggedText.Tokens)
|
||||
{
|
||||
switch (token.Kind)
|
||||
{
|
||||
case TaggedTokenKind.OPEN:
|
||||
openPairs.Push(token.Id);
|
||||
break;
|
||||
|
||||
case TaggedTokenKind.CLOSE when openPairs.Count > 0:
|
||||
openPairs.Pop();
|
||||
break;
|
||||
|
||||
case TaggedTokenKind.PLACEHOLDER:
|
||||
pairsAround[token.Id] = [..openPairs];
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return pairsAround;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Puts an element which belongs into a run, e.g., a tab or a picture, into a run of its own with its formatting.
|
||||
/// </summary>
|
||||
private static W.Run RunOf(WordPiece piece, OpenXmlElement element, WordParagraph paragraph)
|
||||
{
|
||||
var run = new W.Run();
|
||||
if (piece.RunProperties is { } format)
|
||||
run.AppendChild(CopyOf(format, paragraph));
|
||||
|
||||
run.AppendChild(element);
|
||||
return run;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Copies the properties of a run for a new run.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A change of formatting which the change tracking recorded gets a number of its own in each copy, since Word
|
||||
/// tells these changes apart by their numbers, see WordAnnotationIds.
|
||||
/// </remarks>
|
||||
private static W.RunProperties CopyOf(W.RunProperties format, WordParagraph paragraph)
|
||||
{
|
||||
var copy = (W.RunProperties)format.CloneNode(true);
|
||||
if (copy.RunPropertiesChange is { } change)
|
||||
change.Id = paragraph.NextAnnotationId();
|
||||
|
||||
return copy;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Appends words as a run, with tabs and line breaks as Word writes them.
|
||||
/// </summary>
|
||||
private static void AppendWords(OpenXmlElement target, string words, W.RunProperties? format, string languageTag, WordParagraph paragraph)
|
||||
{
|
||||
if (words.Length == 0)
|
||||
return;
|
||||
|
||||
var run = new W.Run();
|
||||
if (format is not null)
|
||||
run.AppendChild(CopyOf(format, paragraph));
|
||||
|
||||
var text = new StringBuilder();
|
||||
foreach (var character in words)
|
||||
{
|
||||
switch (character)
|
||||
{
|
||||
case '\t':
|
||||
AppendText(run, text);
|
||||
run.AppendChild(new W.TabChar());
|
||||
break;
|
||||
|
||||
case '\n':
|
||||
AppendText(run, text);
|
||||
run.AppendChild(new W.Break());
|
||||
break;
|
||||
|
||||
case '\r':
|
||||
break;
|
||||
|
||||
default:
|
||||
text.Append(character);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
AppendText(run, text);
|
||||
WordLanguage.Set(run, languageTag);
|
||||
target.AppendChild(run);
|
||||
}
|
||||
|
||||
private static void AppendText(W.Run run, StringBuilder text)
|
||||
{
|
||||
if (text.Length == 0)
|
||||
return;
|
||||
|
||||
run.AppendChild(new W.Text(OpenXmlText.XmlSafe(text.ToString())) { Space = SpaceProcessingModeValues.Preserve });
|
||||
text.Clear();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// An empty copy of an element which encloses runs, see ShellOf.
|
||||
/// </summary>
|
||||
/// <param name="Shell">The copy, which goes into the paragraph.</param>
|
||||
/// <param name="Content">The element within the copy which takes the runs; the copy itself for most elements.</param>
|
||||
private readonly record struct ContainerShell(OpenXmlElement Shell, OpenXmlElement Content);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
using DocumentFormat.OpenXml;
|
||||
|
||||
using W = DocumentFormat.OpenXml.Wordprocessing;
|
||||
|
||||
namespace AIStudio.Tools.DocumentSegments.Word;
|
||||
|
||||
/// <summary>
|
||||
/// One element of a paragraph which goes back into it as it is, e.g., a tab, a picture, or a whole field instruction.
|
||||
/// </summary>
|
||||
/// <param name="Element">The original element, which the writer moves rather than copies, so that changes to paragraphs inside it, e.g., in a text box, stay.</param>
|
||||
/// <param name="RunProperties">The properties of the run the element sat in; null for an element outside of a run.</param>
|
||||
/// <param name="InRun">Whether the element sat in a run, so that the writer puts it into a run of its own.</param>
|
||||
internal readonly record struct WordPiece(OpenXmlElement Element, W.RunProperties? RunProperties, bool InRun);
|
||||
@@ -0,0 +1,44 @@
|
||||
using AIStudio.Tools.PluginSystem;
|
||||
using AIStudio.Tools.Rust;
|
||||
|
||||
using DocumentFormat.OpenXml;
|
||||
using DocumentFormat.OpenXml.Packaging;
|
||||
|
||||
namespace AIStudio.Tools.DocumentSegments.Word;
|
||||
|
||||
/// <summary>
|
||||
/// Word documents (.docx), whose paragraphs a model works on, while layout, styles, pictures, tables, headers,
|
||||
/// footers, and notes stay as they are.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// How the new document comes about is the same for every Office document, see OpenXmlSegmentFormat. See
|
||||
/// WordSegmentReader for what becomes a segment.
|
||||
/// </remarks>
|
||||
internal sealed class WordSegmentFormat : OpenXmlSegmentFormat<WordprocessingDocument, WordParagraph>
|
||||
{
|
||||
private static string TA(string fallbackEN) => I18N.I.TA(fallbackEN, typeof(WordSegmentFormat).Namespace, nameof(WordSegmentFormat));
|
||||
|
||||
/// <inheritdoc />
|
||||
public override FileTypeFilter FileType => FileTypes.MS_WORD;
|
||||
|
||||
/// <inheritdoc />
|
||||
public override string LimitsNotice => TA("Charts, SmartArt, comments, the alternative texts of pictures, and the properties of the document, such as its title, stay as they are. Paragraphs keep their direction, so new text in a language written from right to left, such as Arabic or Hebrew, may need adjustments. New text often needs more room than the original, so please check text boxes and table cells of a fixed size.");
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override string FileExtension => ".docx";
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override WordprocessingDocument Open(Stream stream, bool isEditable) => WordprocessingDocument.Open(stream, isEditable);
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override IReadOnlyList<WordParagraph> ReadParagraphs(WordprocessingDocument document) => WordSegmentReader.Read(document);
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override OpenXmlElement ElementOf(WordParagraph paragraph) => paragraph.Paragraph;
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override DocumentSegment SegmentOf(WordParagraph paragraph) => paragraph.Segment;
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override bool Write(WordParagraph paragraph, string newText, string languageTag) => WordParagraphWriter.Write(paragraph, newText, languageTag);
|
||||
}
|
||||
@@ -0,0 +1,623 @@
|
||||
using DocumentFormat.OpenXml;
|
||||
using DocumentFormat.OpenXml.Packaging;
|
||||
|
||||
using W = DocumentFormat.OpenXml.Wordprocessing;
|
||||
using W14 = DocumentFormat.OpenXml.Office2010.Word;
|
||||
|
||||
namespace AIStudio.Tools.DocumentSegments.Word;
|
||||
|
||||
/// <summary>
|
||||
/// Reads the paragraphs of a Word document as segments: of the body, the tables, and the text boxes, of the
|
||||
/// headers and footers, and of the footnotes and endnotes.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// Words become text, and elements which enclose runs, e.g., links or content controls, become pairs of tags.
|
||||
/// A field whose result lies in the same paragraph becomes a pair as well, around its result; the parts of a field
|
||||
/// which goes on in another paragraph, e.g., a table of contents, go to the edge of their paragraph instead, see
|
||||
/// ParagraphReader.AddFieldEdge. Everything else
|
||||
/// within the paragraph, e.g., tabs, pictures, references to notes, or formulas, becomes a tag of its own.
|
||||
/// A bookmark around words of the paragraph is a pair as well, see BookmarkPairsOf. Other bookmarks and the ranges
|
||||
/// of comments are no tags: their starts go before the new words, their ends after them.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// A paragraph inside another one, e.g., in a text box, is a segment of its own; for the paragraph around it,
|
||||
/// its text box is a tag of its own. Text boxes also have a copy for older versions of Word, which holds the same
|
||||
/// words and therefore costs nothing more. Content controls bound to data stay as they are, since Word fills them
|
||||
/// from their data anyway, and so do those which offer a choice, a date, or a check box.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
internal static class WordSegmentReader
|
||||
{
|
||||
/// <summary>
|
||||
/// Reads the paragraphs which can be segments, in the order of the document.
|
||||
/// </summary>
|
||||
/// <param name="document">The document.</param>
|
||||
public static IReadOnlyList<WordParagraph> Read(WordprocessingDocument document)
|
||||
{
|
||||
var paragraphs = new List<WordParagraph>();
|
||||
var roots = RootsOf(document).ToList();
|
||||
var annotationIds = new WordAnnotationIds(roots);
|
||||
foreach (var root in roots)
|
||||
{
|
||||
foreach (var paragraph in root.Descendants<W.Paragraph>())
|
||||
{
|
||||
if (IsInBoundContentControl(paragraph))
|
||||
continue;
|
||||
|
||||
if (ReadParagraph(paragraph, annotationIds) is { } read)
|
||||
paragraphs.Add(read);
|
||||
}
|
||||
}
|
||||
|
||||
return paragraphs;
|
||||
}
|
||||
|
||||
private static IEnumerable<OpenXmlElement> RootsOf(WordprocessingDocument document)
|
||||
{
|
||||
if (document.MainDocumentPart is not { } mainPart)
|
||||
yield break;
|
||||
|
||||
if (mainPart.Document?.Body is { } body)
|
||||
yield return body;
|
||||
|
||||
foreach (var headerPart in mainPart.HeaderParts)
|
||||
{
|
||||
if (headerPart.Header is { } header)
|
||||
yield return header;
|
||||
}
|
||||
|
||||
foreach (var footerPart in mainPart.FooterParts)
|
||||
{
|
||||
if (footerPart.Footer is { } footer)
|
||||
yield return footer;
|
||||
}
|
||||
|
||||
// The separators of the notes hold no words of their own:
|
||||
if (mainPart.FootnotesPart?.Footnotes is { } footnotes)
|
||||
{
|
||||
foreach (var footnote in footnotes.Elements<W.Footnote>().Where(note => note.Type is null || note.Type.Value == W.FootnoteEndnoteValues.Normal))
|
||||
yield return footnote;
|
||||
}
|
||||
|
||||
if (mainPart.EndnotesPart?.Endnotes is { } endnotes)
|
||||
{
|
||||
foreach (var endnote in endnotes.Elements<W.Endnote>().Where(note => note.Type is null || note.Type.Value == W.FootnoteEndnoteValues.Normal))
|
||||
yield return endnote;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads a paragraph, with its changes of formatting as pairs as long as they are few, see FormatSpans.MAX_PAIRS.
|
||||
/// </summary>
|
||||
private static WordParagraph? ReadParagraph(W.Paragraph paragraph, WordAnnotationIds annotationIds)
|
||||
{
|
||||
var reader = new ParagraphReader(usesFormatPairs: true, annotationIds);
|
||||
var read = reader.TryRead(paragraph);
|
||||
return reader.FormatPairCount <= FormatSpans.MAX_PAIRS ? read : new ParagraphReader(usesFormatPairs: false, annotationIds).TryRead(paragraph);
|
||||
}
|
||||
|
||||
private static bool IsInBoundContentControl(W.Paragraph paragraph) => paragraph.Ancestors<W.SdtElement>().Any(contentControl => !IsEditable(contentControl));
|
||||
|
||||
/// <summary>
|
||||
/// Whether the words of a content control are words of the user rather than data or a choice.
|
||||
/// </summary>
|
||||
private static bool IsEditable(W.SdtElement contentControl) => contentControl.SdtProperties?.ChildElements.Any(property => property
|
||||
is W.DataBinding
|
||||
or W.ShowingPlaceholder
|
||||
or W.SdtContentDropDownList
|
||||
or W.SdtContentComboBox
|
||||
or W.SdtContentDate
|
||||
or W14.SdtContentCheckBox) is not true;
|
||||
|
||||
/// <summary>
|
||||
/// What one element of a paragraph is, before the tags are numbered.
|
||||
/// </summary>
|
||||
private abstract record Item;
|
||||
|
||||
/// <summary>
|
||||
/// Words of a run.
|
||||
/// </summary>
|
||||
private sealed record TextItem(OpenXmlElement Element, W.RunProperties? Format, string Text) : Item;
|
||||
|
||||
/// <summary>
|
||||
/// An element which goes back as it is.
|
||||
/// </summary>
|
||||
private sealed record PieceItem(WordPiece Piece, PieceKind Kind) : Item;
|
||||
|
||||
/// <summary>
|
||||
/// An element which encloses runs, with what it encloses.
|
||||
/// </summary>
|
||||
private sealed record ContainerItem(OpenXmlElement Container, List<Item> Children) : Item;
|
||||
|
||||
/// <summary>
|
||||
/// Where the parts of a field lie among the items of its level, see PartsOfField.
|
||||
/// </summary>
|
||||
/// <param name="Separate">The mark which separates the instruction from the result; null for a field without a result here.</param>
|
||||
/// <param name="End">The end of the field; null when the field goes on in the next paragraph.</param>
|
||||
private readonly record struct FieldParts(int? Separate, int? End);
|
||||
|
||||
/// <summary>
|
||||
/// A part of a field which goes on in another paragraph, see ParagraphReader.AddFieldEdge.
|
||||
/// </summary>
|
||||
/// <param name="Pieces">The elements of the part.</param>
|
||||
/// <param name="OpensField">Whether the field goes on after the part, e.g., after its start; false for its end.</param>
|
||||
/// <param name="WordsBefore">How many runs of words came before the part.</param>
|
||||
private readonly record struct FieldEdge(IReadOnlyList<WordPiece> Pieces, bool OpensField, int WordsBefore);
|
||||
|
||||
private enum PieceKind
|
||||
{
|
||||
PLAIN,
|
||||
FIELD_BEGIN,
|
||||
FIELD_SEPARATE,
|
||||
FIELD_END,
|
||||
MARKER_START,
|
||||
MARKER_END,
|
||||
DROPPED,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads one paragraph.
|
||||
/// </summary>
|
||||
private sealed class ParagraphReader
|
||||
{
|
||||
private readonly TaggedTextBuilder builder = new();
|
||||
private readonly FormatSpanReader<W.RunProperties> spans;
|
||||
private readonly Dictionary<int, WordPair> pairs = [];
|
||||
private readonly Dictionary<int, WordAtom> placeholders = [];
|
||||
private readonly Dictionary<int, W.RunProperties?> textFormats = [];
|
||||
private readonly List<WordPiece> piecesBefore = [];
|
||||
private readonly List<WordPiece> piecesAfter = [];
|
||||
private readonly List<FieldEdge> fieldEdges = [];
|
||||
private readonly WordAnnotationIds annotationIds;
|
||||
private int nextOrder;
|
||||
private int wordCount;
|
||||
|
||||
public ParagraphReader(bool usesFormatPairs, WordAnnotationIds annotationIds)
|
||||
{
|
||||
this.spans = new(this.builder, usesFormatPairs, FormatKeyOf);
|
||||
this.annotationIds = annotationIds;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// How many changes of formatting became pairs.
|
||||
/// </summary>
|
||||
public int FormatPairCount => this.spans.FormatPairCount;
|
||||
|
||||
public WordParagraph? TryRead(W.Paragraph paragraph)
|
||||
{
|
||||
this.Build(ItemsOf(paragraph), 0);
|
||||
|
||||
// Words which read as a tag could not be told apart from the tags of the paragraph:
|
||||
var text = this.builder.Build();
|
||||
if (text.HasTagLikeWords)
|
||||
return null;
|
||||
|
||||
// The pairs of formatting have their formatting already, the other pairs and the words outside of any pair get the most common one:
|
||||
foreach (var (pairId, format) in this.spans.BaseFormats)
|
||||
this.textFormats[pairId] = format;
|
||||
|
||||
// Now that all words are known, the parts of fields which go on in another paragraph find their edge, see AddFieldEdge:
|
||||
foreach (var edge in this.fieldEdges)
|
||||
{
|
||||
var goesBefore = edge.OpensField ? edge.WordsBefore == 0 : edge.WordsBefore < this.wordCount;
|
||||
(goesBefore ? this.piecesBefore : this.piecesAfter).AddRange(edge.Pieces);
|
||||
}
|
||||
|
||||
return new(paragraph, new DocumentSegment(text), this.pairs, this.placeholders, this.textFormats, this.piecesBefore, this.piecesAfter, this.spans.HasMixedFormatting, this.annotationIds);
|
||||
}
|
||||
|
||||
private void Build(List<Item> items, int pairId)
|
||||
{
|
||||
var baseFormatKey = this.BaseFormatKeyOf(items);
|
||||
var bookmarkEnds = BookmarkPairsOf(items);
|
||||
var index = 0;
|
||||
while (index < items.Count)
|
||||
{
|
||||
switch (items[index])
|
||||
{
|
||||
case TextItem:
|
||||
index = this.BuildWords(items, index, pairId, baseFormatKey, bookmarkEnds);
|
||||
break;
|
||||
|
||||
case PieceItem { Kind: PieceKind.MARKER_START } when bookmarkEnds.TryGetValue(index, out var bookmarkEnd):
|
||||
index = this.BuildBoundaryPair(items, index, bookmarkEnd);
|
||||
break;
|
||||
|
||||
case PieceItem { Kind: PieceKind.DROPPED }:
|
||||
index++;
|
||||
break;
|
||||
|
||||
case PieceItem { Kind: PieceKind.MARKER_START } startMarker:
|
||||
this.piecesBefore.Add(startMarker.Piece);
|
||||
index++;
|
||||
break;
|
||||
|
||||
case PieceItem { Kind: PieceKind.MARKER_END } endMarker:
|
||||
this.piecesAfter.Add(endMarker.Piece);
|
||||
index++;
|
||||
break;
|
||||
|
||||
case PieceItem { Kind: PieceKind.FIELD_BEGIN }:
|
||||
index = this.BuildField(items, index);
|
||||
break;
|
||||
|
||||
// The parts of a field which began in an earlier paragraph:
|
||||
case PieceItem { Kind: PieceKind.FIELD_SEPARATE }:
|
||||
this.AddFieldEdge(items, index, index, opensField: true);
|
||||
index++;
|
||||
break;
|
||||
|
||||
case PieceItem { Kind: PieceKind.FIELD_END }:
|
||||
this.AddFieldEdge(items, index, index, opensField: false);
|
||||
index++;
|
||||
break;
|
||||
|
||||
case ContainerItem container when HasWords(container.Children):
|
||||
var containerPair = this.builder.Open();
|
||||
this.pairs[containerPair] = new WordContainerPair(container.Container);
|
||||
this.Build(container.Children, containerPair);
|
||||
this.builder.Close(containerPair);
|
||||
index++;
|
||||
break;
|
||||
|
||||
default:
|
||||
this.AddPlaceholder(items, index, index);
|
||||
index++;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads a field which starts at the given item.
|
||||
/// </summary>
|
||||
/// <returns>The index of the first item after the field.</returns>
|
||||
private int BuildField(List<Item> items, int begin)
|
||||
{
|
||||
var (separate, end) = PartsOfField(items, begin);
|
||||
switch (separate, end)
|
||||
{
|
||||
// A field with its result in this paragraph: the result is words within a pair.
|
||||
case ({ } separateIndex, { } endIndex):
|
||||
return this.BuildBoundaryPair(items, begin, endIndex, separateIndex);
|
||||
|
||||
// A field without a result, which shows nothing:
|
||||
case (null, { } endWithoutResult):
|
||||
this.AddPlaceholder(items, begin, endWithoutResult);
|
||||
return endWithoutResult + 1;
|
||||
|
||||
// A field whose result goes on in the next paragraphs, e.g., a table of contents:
|
||||
case ({ } separateWithoutEnd, null):
|
||||
this.AddFieldEdge(items, begin, separateWithoutEnd, opensField: true);
|
||||
return separateWithoutEnd + 1;
|
||||
|
||||
// A field whose instruction goes on in the next paragraph:
|
||||
default:
|
||||
this.AddFieldEdge(items, begin, items.Count - 1, opensField: true);
|
||||
return items.Count;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Notes a part of a field which goes on in another paragraph, e.g., the start or the end of a table of contents.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// Such a part is no tag, since the model could move it among the words: the words after the start of a field
|
||||
/// and before its end are its result, which Word replaces whenever it updates the field. Instead, the part goes
|
||||
/// to the edge of its paragraph, before or after the new words, see TryRead.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The edge follows the source: a start without words before it goes before the new words, an end without
|
||||
/// words after it goes after them. A part with words on that side, too, goes to the other edge, so that these
|
||||
/// words leave the field rather than join it: an update shows them twice then, instead of deleting them.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
/// <param name="items">The items of this level.</param>
|
||||
/// <param name="first">The first item of the part.</param>
|
||||
/// <param name="last">The last item of the part.</param>
|
||||
/// <param name="opensField">Whether the field goes on after the part, e.g., after its start; false for its end.</param>
|
||||
private void AddFieldEdge(List<Item> items, int first, int last, bool opensField) => this.fieldEdges.Add(new FieldEdge(PiecesOf(items, first, last), opensField, this.wordCount));
|
||||
|
||||
/// <summary>
|
||||
/// Reads words between a start and an end which stay as they are, see WordBoundaryPair.
|
||||
/// </summary>
|
||||
/// <param name="items">The items of this level.</param>
|
||||
/// <param name="start">The first item of the start.</param>
|
||||
/// <param name="end">The item of the end.</param>
|
||||
/// <param name="startEnd">The last item of the start, e.g., the mark which separates the result of a field; the start itself when it is one item.</param>
|
||||
/// <returns>The index of the first item after the end.</returns>
|
||||
private int BuildBoundaryPair(List<Item> items, int start, int end, int? startEnd = null)
|
||||
{
|
||||
var wordsStart = (startEnd ?? start) + 1;
|
||||
var opening = this.AtomOf(items, start, wordsStart - 1);
|
||||
var pair = this.builder.Open();
|
||||
this.Build(items.GetRange(wordsStart, end - wordsStart), pair);
|
||||
this.builder.Close(pair);
|
||||
this.pairs[pair] = new WordBoundaryPair(opening, this.AtomOf(items, end, end));
|
||||
return end + 1;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Finds the bookmarks of a level which become pairs around their words.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// A cross reference shows the words its bookmark encloses, e.g., the label and the number of a caption. As a
|
||||
/// pair, the bookmark encloses the new words of the model alike; as a mark before and after the words, it would
|
||||
/// widen to the whole paragraph, and the cross reference would show the whole caption once Word updates it.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// That takes a bookmark whose start and end lie in the same level, with words in between, and which crosses
|
||||
/// neither another such bookmark nor a field: pairs have to nest. Every other bookmark, an empty one such as
|
||||
/// the one Word keeps for the last place of editing included, stays a mark, as do the ranges of comments.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
/// <returns>The index of the end of each such bookmark, by the index of its start.</returns>
|
||||
private static Dictionary<int, int> BookmarkPairsOf(List<Item> items)
|
||||
{
|
||||
var openStarts = new Dictionary<string, int>(StringComparer.Ordinal);
|
||||
var candidates = new List<(int Start, int End)>();
|
||||
for (var index = 0; index < items.Count; index++)
|
||||
{
|
||||
switch (items[index])
|
||||
{
|
||||
case PieceItem { Kind: PieceKind.MARKER_START, Piece.Element: W.BookmarkStart { Id.Value: { } startId } }:
|
||||
openStarts[startId] = index;
|
||||
break;
|
||||
|
||||
case PieceItem { Kind: PieceKind.MARKER_END, Piece.Element: W.BookmarkEnd { Id.Value: { } endId } } when openStarts.Remove(endId, out var start):
|
||||
var enclosed = items.GetRange(start + 1, index - start - 1);
|
||||
if (HasWords(enclosed) && FieldsAreWhole(enclosed))
|
||||
candidates.Add((start, index));
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Of two bookmarks which cross, the one which starts first becomes a pair:
|
||||
var pairs = new Dictionary<int, int>();
|
||||
foreach (var (start, end) in candidates.OrderBy(candidate => candidate.Start))
|
||||
{
|
||||
if (pairs.All(pair => !Cross(pair.Key, pair.Value, start, end)))
|
||||
pairs[start] = end;
|
||||
}
|
||||
|
||||
return pairs;
|
||||
}
|
||||
|
||||
private static bool Cross(int firstStart, int firstEnd, int secondStart, int secondEnd) =>
|
||||
(firstStart < secondStart && secondStart < firstEnd && firstEnd < secondEnd) ||
|
||||
(secondStart < firstStart && firstStart < secondEnd && secondEnd < firstEnd);
|
||||
|
||||
/// <summary>
|
||||
/// Whether every field which starts among the items also ends among them, and the other way round.
|
||||
/// </summary>
|
||||
private static bool FieldsAreWhole(List<Item> items)
|
||||
{
|
||||
var depth = 0;
|
||||
foreach (var item in items)
|
||||
{
|
||||
if (item is PieceItem { Kind: PieceKind.FIELD_BEGIN })
|
||||
depth++;
|
||||
else if (item is PieceItem { Kind: PieceKind.FIELD_END } && --depth < 0)
|
||||
return false;
|
||||
}
|
||||
|
||||
return depth == 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Finds the separator and the end of a field among the items which follow its start, skipping the fields within it.
|
||||
/// </summary>
|
||||
private static FieldParts PartsOfField(List<Item> items, int begin)
|
||||
{
|
||||
int? separate = null;
|
||||
var depth = 0;
|
||||
for (var index = begin + 1; index < items.Count; index++)
|
||||
{
|
||||
switch (items[index])
|
||||
{
|
||||
case PieceItem { Kind: PieceKind.FIELD_BEGIN }:
|
||||
depth++;
|
||||
break;
|
||||
|
||||
case PieceItem { Kind: PieceKind.FIELD_SEPARATE } when depth == 0:
|
||||
separate ??= index;
|
||||
break;
|
||||
|
||||
case PieceItem { Kind: PieceKind.FIELD_END } when depth == 0:
|
||||
return new(separate, index);
|
||||
|
||||
case PieceItem { Kind: PieceKind.FIELD_END }:
|
||||
depth--;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return new(separate, null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the words which follow each other from the given item on, up to the next tag.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Bookmarks and hints for the layout between the runs do not end the words. Where their formatting
|
||||
/// changes, the words in the most common formatting of this pair stay words, and those in any other
|
||||
/// formatting go into a pair of their own.
|
||||
/// </remarks>
|
||||
/// <returns>The index of the first item after the words.</returns>
|
||||
private int BuildWords(List<Item> items, int start, int pairId, string baseFormatKey, Dictionary<int, int> bookmarkEnds)
|
||||
{
|
||||
var words = new List<TextItem>();
|
||||
var index = start;
|
||||
for (; index < items.Count; index++)
|
||||
{
|
||||
if (items[index] is TextItem text)
|
||||
words.Add(text);
|
||||
else if (items[index] is PieceItem { Kind: PieceKind.MARKER_START } startMarker && !bookmarkEnds.ContainsKey(index))
|
||||
this.piecesBefore.Add(startMarker.Piece);
|
||||
else if (items[index] is PieceItem { Kind: PieceKind.MARKER_END } endMarker)
|
||||
this.piecesAfter.Add(endMarker.Piece);
|
||||
else if (items[index] is not PieceItem { Kind: PieceKind.DROPPED })
|
||||
break;
|
||||
}
|
||||
|
||||
this.wordCount += words.Count(word => !string.IsNullOrWhiteSpace(word.Text));
|
||||
this.spans.AddWords(words.Select(WordsOf), pairId, baseFormatKey, (formatPair, format) =>
|
||||
{
|
||||
this.pairs[formatPair] = new WordFormatPair(format);
|
||||
this.textFormats[formatPair] = format;
|
||||
});
|
||||
|
||||
return index;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Finds the formatting most words of a pair have, or of the paragraph outside of any pair.
|
||||
/// </summary>
|
||||
private string BaseFormatKeyOf(List<Item> items) => this.spans.BaseKeyOf(items.OfType<TextItem>().Select(WordsOf));
|
||||
|
||||
private static FormattedWords<W.RunProperties?> WordsOf(TextItem item) => new(item.Text, item.Format);
|
||||
|
||||
private void AddPlaceholder(List<Item> items, int first, int last)
|
||||
{
|
||||
var placeholder = this.builder.Placeholder();
|
||||
this.placeholders[placeholder] = this.AtomOf(items, first, last);
|
||||
}
|
||||
|
||||
private WordAtom AtomOf(List<Item> items, int first, int last) => new(PiecesOf(items, first, last), this.nextOrder++);
|
||||
|
||||
private static List<WordPiece> PiecesOf(List<Item> items, int first, int last)
|
||||
{
|
||||
var pieces = new List<WordPiece>();
|
||||
for (var index = first; index <= last; index++)
|
||||
{
|
||||
pieces.Add(items[index] switch
|
||||
{
|
||||
TextItem text => new WordPiece(text.Element, text.Format, true),
|
||||
PieceItem piece => piece.Piece,
|
||||
ContainerItem container => new WordPiece(container.Container, null, false),
|
||||
|
||||
_ => throw new InvalidOperationException("A paragraph holds an item of an unknown kind."),
|
||||
});
|
||||
}
|
||||
|
||||
return pieces;
|
||||
}
|
||||
|
||||
private static bool HasWords(List<Item> items) => items.Any(item => item switch
|
||||
{
|
||||
TextItem => true,
|
||||
ContainerItem container => HasWords(container.Children),
|
||||
|
||||
_ => false,
|
||||
});
|
||||
|
||||
/// <summary>
|
||||
/// Tells the formatting of runs apart, leaving out what changes nothing about how words look.
|
||||
/// </summary>
|
||||
private static string FormatKeyOf(W.RunProperties format)
|
||||
{
|
||||
var copy = (W.RunProperties)format.CloneNode(true);
|
||||
copy.Languages = null;
|
||||
copy.NoProof = null;
|
||||
|
||||
// A run without anything that changes its look counts as having no properties at all:
|
||||
return copy.HasAttributes || copy.HasChildren ? copy.OuterXml : string.Empty;
|
||||
}
|
||||
|
||||
private static List<Item> ItemsOf(OpenXmlElement parent)
|
||||
{
|
||||
var items = new List<Item>();
|
||||
foreach (var child in parent.ChildElements)
|
||||
{
|
||||
switch (child)
|
||||
{
|
||||
// The properties of a paragraph, of custom XML, or of a simple field go with their element, see WordParagraphWriter.ShellOf:
|
||||
case W.ParagraphProperties or W.CustomXmlProperties or W.FieldData:
|
||||
break;
|
||||
|
||||
case W.Run run:
|
||||
AddItemsOfRun(run, items);
|
||||
break;
|
||||
|
||||
case W.ProofError:
|
||||
items.Add(new PieceItem(new WordPiece(child, null, false), PieceKind.DROPPED));
|
||||
break;
|
||||
|
||||
case W.BookmarkStart or W.CommentRangeStart or W.PermStart or W.MoveFromRangeStart or W.MoveToRangeStart:
|
||||
items.Add(new PieceItem(new WordPiece(child, null, false), PieceKind.MARKER_START));
|
||||
break;
|
||||
|
||||
case W.BookmarkEnd or W.CommentRangeEnd or W.PermEnd or W.MoveFromRangeEnd or W.MoveToRangeEnd:
|
||||
items.Add(new PieceItem(new WordPiece(child, null, false), PieceKind.MARKER_END));
|
||||
break;
|
||||
|
||||
// A simple field encloses its result, like a field of its own whose result lies in the paragraph:
|
||||
case W.Hyperlink or W.InsertedRun or W.MoveToRun or W.CustomXmlRun or W.SimpleField or W.BidirectionalOverride or W.BidirectionalEmbedding:
|
||||
items.Add(new ContainerItem(child, ItemsOf(child)));
|
||||
break;
|
||||
|
||||
case W.SdtRun { SdtContentRun: { } content } contentControl when IsEditable(contentControl):
|
||||
items.Add(new ContainerItem(child, ItemsOf(content)));
|
||||
break;
|
||||
|
||||
// Formulas, deleted runs, and whatever else:
|
||||
default:
|
||||
items.Add(new PieceItem(new WordPiece(child, null, false), PieceKind.PLAIN));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return items;
|
||||
}
|
||||
|
||||
private static void AddItemsOfRun(W.Run run, List<Item> items)
|
||||
{
|
||||
var format = run.RunProperties;
|
||||
foreach (var child in run.ChildElements)
|
||||
{
|
||||
switch (child)
|
||||
{
|
||||
case W.RunProperties:
|
||||
break;
|
||||
|
||||
case W.Text text:
|
||||
items.Add(new TextItem(child, format, text.Text));
|
||||
break;
|
||||
|
||||
// Shown as a hyphen at which no line breaks, which the same character carries over:
|
||||
case W.NoBreakHyphen:
|
||||
items.Add(new TextItem(child, format, "‑"));
|
||||
break;
|
||||
|
||||
// Hints for the layout, which the new words do not need:
|
||||
case W.LastRenderedPageBreak or W.SoftHyphen:
|
||||
items.Add(new PieceItem(new WordPiece(child, format, true), PieceKind.DROPPED));
|
||||
break;
|
||||
|
||||
case W.FieldChar { FieldCharType: { } type }:
|
||||
items.Add(new PieceItem(new WordPiece(child, format, true), KindOfFieldChar(type.Value)));
|
||||
break;
|
||||
|
||||
default:
|
||||
items.Add(new PieceItem(new WordPiece(child, format, true), PieceKind.PLAIN));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static PieceKind KindOfFieldChar(W.FieldCharValues type)
|
||||
{
|
||||
if (type == W.FieldCharValues.Begin)
|
||||
return PieceKind.FIELD_BEGIN;
|
||||
|
||||
if (type == W.FieldCharValues.Separate)
|
||||
return PieceKind.FIELD_SEPARATE;
|
||||
|
||||
return type == W.FieldCharValues.End ? PieceKind.FIELD_END : PieceKind.PLAIN;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user