This commit is contained in:
melekhin
2026-08-03 16:31:54 +07:00
parent 25207773f7
commit 265bfc7419
+111 -267
View File
@@ -1,12 +1,5 @@
namespace QWERTYkez.WordProcessor; namespace QWERTYkez.WordProcessor;
#if DEBUG
public static class Debugger
{
public static StringBuilder Builder { get; } = new();
}
#endif
/// <summary> /// <summary>
/// Выполняет замену всех вхождений ключей из словаря на соответствующие массивы значений. /// Выполняет замену всех вхождений ключей из словаря на соответствующие массивы значений.
/// Каждое значение из массива помещается в отдельный параграф, причём первое значение /// Каждое значение из массива помещается в отдельный параграф, причём первое значение
@@ -23,15 +16,13 @@ internal static class MultiReplaceExt
internal static void Replace(this Body body, string oldValue, IEnumerable<string> newValues, StringComparison comparisonType) internal static void Replace(this Body body, string oldValue, IEnumerable<string> newValues, StringComparison comparisonType)
{ {
if (body is null || string.IsNullOrEmpty(oldValue) || newValues is null) return; if (body is null || string.IsNullOrEmpty(oldValue) || newValues is null) return;
var dict = new Dictionary<string, IEnumerable<string>> { { oldValue, newValues } }; body.Replace(new Dictionary<string, IEnumerable<string>> { { oldValue, newValues } }, comparisonType);
body.Replace(dict, comparisonType);
} }
internal static void Replace(this Body body, string oldValue, IEnumerable<ReplaceItem> newValues, StringComparison comparisonType) internal static void Replace(this Body body, string oldValue, IEnumerable<ReplaceItem> newValues, StringComparison comparisonType)
{ {
if (body is null || string.IsNullOrEmpty(oldValue) || newValues is null) return; if (body is null || string.IsNullOrEmpty(oldValue) || newValues is null) return;
var dict = new Dictionary<string, IEnumerable<ReplaceItem>> { { oldValue, newValues } }; body.Replace(new Dictionary<string, IEnumerable<ReplaceItem>> { { oldValue, newValues } }, comparisonType);
body.Replace(dict, comparisonType);
} }
#endregion #endregion
@@ -41,27 +32,29 @@ internal static class MultiReplaceExt
internal static void Replace(this Body body, IEnumerable<KeyValuePair<string, IEnumerable<string>>> replacements, StringComparison comparisonType) internal static void Replace(this Body body, IEnumerable<KeyValuePair<string, IEnumerable<string>>> replacements, StringComparison comparisonType)
{ {
if (body is null || replacements is null) return; if (body is null || replacements is null) return;
var paragraphs = body.Elements<Paragraph>().ToList(); ReplaceInBody(body, replacements, null, comparisonType);
for (int i = paragraphs.Count - 1; i >= 0; i--)
{
var p = paragraphs[i];
if (p?.Parent is null) continue;
var newParas = ProcessMultiReplacements(p, replacements, null, comparisonType);
if (newParas is not null && newParas.Count > 0)
ParagraphReplacer.ReplaceParagraph(p, newParas);
}
} }
internal static void Replace(this Body body, IEnumerable<KeyValuePair<string, IEnumerable<ReplaceItem>>> replacements, StringComparison comparisonType) internal static void Replace(this Body body, IEnumerable<KeyValuePair<string, IEnumerable<ReplaceItem>>> replacements, StringComparison comparisonType)
{ {
if (body is null || replacements is null) return; if (body is null || replacements is null) return;
ReplaceInBody(body, null, replacements, comparisonType);
}
private static void ReplaceInBody(
Body body,
IEnumerable<KeyValuePair<string, IEnumerable<string>>>? stringReplacements,
IEnumerable<KeyValuePair<string, IEnumerable<ReplaceItem>>>? itemReplacements,
StringComparison comparisonType)
{
var paragraphs = body.Elements<Paragraph>().ToList(); var paragraphs = body.Elements<Paragraph>().ToList();
for (int i = paragraphs.Count - 1; i >= 0; i--) for (int i = paragraphs.Count - 1; i >= 0; i--)
{ {
var p = paragraphs[i]; var p = paragraphs[i];
if (p?.Parent is null) continue; if (p?.Parent is null) continue;
var newParas = ProcessMultiReplacements(p, null, replacements, comparisonType);
if (newParas is not null && newParas.Count > 0) var newParas = ProcessMultiReplacements(p, stringReplacements, itemReplacements, comparisonType);
if (newParas is { Count: > 0 })
ParagraphReplacer.ReplaceParagraph(p, newParas); ParagraphReplacer.ReplaceParagraph(p, newParas);
} }
} }
@@ -72,14 +65,13 @@ internal static class MultiReplaceExt
internal static bool ReplaceWithMultiple(this Paragraph? paragraph, string oldValue, IEnumerable<string> newValues, StringComparison comparisonType) internal static bool ReplaceWithMultiple(this Paragraph? paragraph, string oldValue, IEnumerable<string> newValues, StringComparison comparisonType)
{ {
if (paragraph is null || string.IsNullOrEmpty(oldValue) || newValues is null || newValues.Count() == 0) if (paragraph?.Parent is null || string.IsNullOrEmpty(oldValue) || newValues is null || !newValues.Any())
return false; return false;
var dict = new Dictionary<string, IEnumerable<string>> { { oldValue, newValues } }; var dict = new Dictionary<string, IEnumerable<string>> { { oldValue, newValues } };
var newParas = ProcessMultiReplacements(paragraph, dict, null, comparisonType); var newParas = ProcessMultiReplacements(paragraph, dict, null, comparisonType);
if (newParas is null || newParas.Count == 0) return false;
if (paragraph.Parent is not null) if (newParas is { Count: > 0 })
{ {
ParagraphReplacer.ReplaceParagraph(paragraph, newParas); ParagraphReplacer.ReplaceParagraph(paragraph, newParas);
return true; return true;
@@ -89,14 +81,13 @@ internal static class MultiReplaceExt
internal static bool ReplaceWithMultiple(this Paragraph? paragraph, string oldValue, IEnumerable<ReplaceItem> newValues, StringComparison comparisonType) internal static bool ReplaceWithMultiple(this Paragraph? paragraph, string oldValue, IEnumerable<ReplaceItem> newValues, StringComparison comparisonType)
{ {
if (paragraph is null || string.IsNullOrEmpty(oldValue) || newValues is null || newValues.Count() == 0) if (paragraph?.Parent is null || string.IsNullOrEmpty(oldValue) || newValues is null || !newValues.Any())
return false; return false;
var dict = new Dictionary<string, IEnumerable<ReplaceItem>> { { oldValue, newValues } }; var dict = new Dictionary<string, IEnumerable<ReplaceItem>> { { oldValue, newValues } };
var newParas = ProcessMultiReplacements(paragraph, null, dict, comparisonType); var newParas = ProcessMultiReplacements(paragraph, null, dict, comparisonType);
if (newParas is null || newParas.Count == 0) return false;
if (paragraph.Parent is not null) if (newParas is { Count: > 0 })
{ {
ParagraphReplacer.ReplaceParagraph(paragraph, newParas); ParagraphReplacer.ReplaceParagraph(paragraph, newParas);
return true; return true;
@@ -112,26 +103,23 @@ internal static class MultiReplaceExt
Paragraph paragraph, Paragraph paragraph,
IEnumerable<KeyValuePair<string, IEnumerable<string>>> replacements, IEnumerable<KeyValuePair<string, IEnumerable<string>>> replacements,
StringComparison comparisonType) StringComparison comparisonType)
{ => ProcessMultiReplacements(paragraph, replacements, null, comparisonType);
return ProcessMultiReplacements(paragraph, replacements, null, comparisonType);
}
internal static List<Paragraph>? ProcessParagraphWithAllReplacements( internal static List<Paragraph>? ProcessParagraphWithAllReplacements(
Paragraph paragraph, Paragraph paragraph,
IEnumerable<KeyValuePair<string, IEnumerable<ReplaceItem>>> replacements, IEnumerable<KeyValuePair<string, IEnumerable<ReplaceItem>>> replacements,
StringComparison comparisonType) StringComparison comparisonType)
{ => ProcessMultiReplacements(paragraph, null, replacements, comparisonType);
return ProcessMultiReplacements(paragraph, null, replacements, comparisonType);
}
internal static List<Paragraph>? ProcessParagraphWithAllReplacements( internal static List<Paragraph>? ProcessParagraphWithAllReplacements(
Paragraph paragraph, Paragraph paragraph,
IEnumerable<KeyValuePair<string, string>> replacements, IEnumerable<KeyValuePair<string, string>> replacements,
StringComparison comparisonType) StringComparison comparisonType)
{ {
Dictionary<string, IEnumerable<string>> dict = replacements var dict = replacements
.Where(kvp => !string.IsNullOrEmpty(kvp.Key)) .Where(kvp => !string.IsNullOrEmpty(kvp.Key))
.ToDictionary(kvp => kvp.Key, kvp => (IEnumerable<string>)[kvp.Value]); .ToDictionary(kvp => kvp.Key, kvp => (IEnumerable<string>)[kvp.Value]);
return ProcessMultiReplacements(paragraph, dict, null, comparisonType); return ProcessMultiReplacements(paragraph, dict, null, comparisonType);
} }
@@ -147,9 +135,9 @@ internal static class MultiReplaceExt
private class Match private class Match
{ {
public MatchDefinition Definition { get; set; } = null!; public MatchDefinition Definition { get; init; } = null!;
public int Start { get; set; } public int Start { get; init; }
public int End { get; set; } public int End { get; init; }
} }
private class RunSegment(Run run, string text, int start, int end) private class RunSegment(Run run, string text, int start, int end)
@@ -168,13 +156,15 @@ internal static class MultiReplaceExt
private static ParagraphStructure AnalyzeParagraphStructure(List<Run> runs) private static ParagraphStructure AnalyzeParagraphStructure(List<Run> runs)
{ {
var segments = new List<RunSegment>(); var segments = new List<RunSegment>(runs.Count);
var sb = new StringBuilder(); var sb = new StringBuilder();
int pos = 0; int pos = 0;
foreach (var run in runs) foreach (var run in runs)
{ {
string text = GetRunText(run); string text = GetRunText(run);
if (string.IsNullOrEmpty(text)) continue; if (string.IsNullOrEmpty(text)) continue;
segments.Add(new RunSegment(run, text, pos, pos + text.Length)); segments.Add(new RunSegment(run, text, pos, pos + text.Length));
sb.Append(text); sb.Append(text);
pos += text.Length; pos += text.Length;
@@ -194,16 +184,18 @@ internal static class MultiReplaceExt
private static Paragraph CloneParagraphWithoutSection(Paragraph original) private static Paragraph CloneParagraphWithoutSection(Paragraph original)
{ {
var newPara = new Paragraph(); var newPara = new Paragraph();
if (original.ParagraphProperties is not null) if (original.ParagraphProperties is null) return newPara;
{
var newProps = new ParagraphProperties(); var newProps = new ParagraphProperties();
foreach (var child in original.ParagraphProperties.ChildElements) foreach (var child in original.ParagraphProperties.ChildElements)
{ {
if (child is not SectionProperties && child is not PageBreakBefore) if (child is not SectionProperties and not PageBreakBefore)
newProps.AppendChild(child.CloneNode(true)); newProps.AppendChild(child.CloneNode(true));
} }
if (newProps.HasChildren)
newPara.ParagraphProperties = newProps; newPara.ParagraphProperties = newProps;
}
return newPara; return newPara;
} }
@@ -215,25 +207,26 @@ internal static class MultiReplaceExt
foreach (var seg in structure.Segments) foreach (var seg in structure.Segments)
{ {
if (seg.End <= position) continue; if (seg.End <= position) continue;
if (seg.Start >= position) if (seg.Start >= position)
{ {
newPara.AppendChild(seg.Run.CloneNode(true)); newPara.AppendChild(seg.Run.CloneNode(true));
} }
else if (seg.End > position) else
{ {
var runClone = (Run)seg.Run.CloneNode(true); var runClone = (Run)seg.Run.CloneNode(true);
foreach (var t in runClone.Elements<Text>().ToList()) t.Remove(); runClone.RemoveAllChildren<Text>(); // Упрощенная очистка
int offset = position - seg.Start; int offset = position - seg.Start;
string newText = seg.Text.Substring(offset); runClone.AppendChild(new Text(seg.Text.Substring(offset)));
runClone.AppendChild(new Text(newText));
newPara.AppendChild(runClone); newPara.AppendChild(runClone);
} }
} }
foreach (var run in newPara.Descendants<Run>().Where(r => !r.HasChildren).ToList())
run.Remove(); // Удаляем пустые Run-ы без вложений
if (!newPara.ChildElements.OfType<Run>().Any() && newPara.ParagraphProperties is null) newPara.Elements<Run>().Where(r => !r.HasChildren).ToList().ForEach(r => r.Remove());
return null;
return newPara; return !newPara.Elements<Run>().Any() && newPara.ParagraphProperties is null ? null : newPara;
} }
private static void InsertFormattedRun(Paragraph para, ReplaceItem item, ParagraphStructure structure, int position) private static void InsertFormattedRun(Paragraph para, ReplaceItem item, ParagraphStructure structure, int position)
@@ -244,45 +237,40 @@ internal static class MultiReplaceExt
var textRun = new Run(); var textRun = new Run();
if (seg.Run.RunProperties is not null) if (seg.Run.RunProperties is not null)
textRun.RunProperties = (RunProperties)seg.Run.RunProperties.CloneNode(true); textRun.RunProperties = (RunProperties)seg.Run.RunProperties.CloneNode(true);
textRun.AppendChild(new Text(item.Text ?? string.Empty)); textRun.AppendChild(new Text(item.Text ?? string.Empty));
para.AppendChild(textRun); para.AppendChild(textRun);
} }
/// <summary> /// <summary>
/// Добавляет SectionProperties к параграфу. Все значения (PageSize, PageMargin) берутся из документа. /// Добавляет SectionProperties к параграфу. Все значения (PageSize, PageMargin) берутся из документа.
/// Для книжных секций (addPageSize=false) Orient не устанавливается (not set).
/// </summary> /// </summary>
private static void AddSectionProperties(Paragraph para, PageBreakType splitValue, bool addPageSize, SectionProperties sourceSection, SectionProperties portraitSection) private static void AddSectionProperties(Paragraph para, PageBreakType splitValue, bool addPageSize, SectionProperties? sourceSection, SectionProperties? portraitSection)
{ {
if (para is null) return; if (para is null) return;
// Удаляем существующие секции // Удаляем существующие секции и разрывы
if (para.ParagraphProperties is not null) if (para.ParagraphProperties is not null)
{ {
var sections = para.ParagraphProperties.Elements<SectionProperties>().ToList(); para.ParagraphProperties.RemoveAllChildren<SectionProperties>();
foreach (var sec in sections) sec.Remove(); para.ParagraphProperties.RemoveAllChildren<PageBreakBefore>();
var pageBreaks = para.ParagraphProperties.Elements<PageBreakBefore>().ToList();
foreach (var pb in pageBreaks) pb.Remove();
} }
para.ParagraphProperties ??= new ParagraphProperties(); para.ParagraphProperties ??= new ParagraphProperties();
var sectionProps = new SectionProperties(); var sectionProps = new SectionProperties();
// Добавляем PageSize // Добавляем PageSize
SectionProperties? sizeSource = addPageSize ? sourceSection : portraitSection; var sizeSource = addPageSize ? sourceSection : portraitSection;
var sourcePageSize = sizeSource?.GetFirstChild<PageSize>(); var sourcePageSize = sizeSource?.GetFirstChild<PageSize>()
if (sourcePageSize is null && portraitSection is not null) ?? portraitSection?.GetFirstChild<PageSize>()
sourcePageSize = portraitSection.GetFirstChild<PageSize>(); ?? sourceSection?.GetFirstChild<PageSize>();
if (sourcePageSize is null && sourceSection is not null)
sourcePageSize = sourceSection.GetFirstChild<PageSize>();
if (sourcePageSize is not null) if (sourcePageSize is not null)
{ {
var pageSizeClone = (PageSize)sourcePageSize.CloneNode(true); var pageSizeClone = (PageSize)sourcePageSize.CloneNode(true);
bool sourceIsLandscape = pageSizeClone.Orient?.Value == PageOrientationValues.Landscape || bool sourceIsLandscape = pageSizeClone.Orient?.Value == PageOrientationValues.Landscape ||
(pageSizeClone.Width?.Value > pageSizeClone.Height?.Value); pageSizeClone.Width?.Value > pageSizeClone.Height?.Value;
bool targetIsLandscape = addPageSize && splitValue == PageBreakType.NewLandscapeSection;
bool targetIsLandscape = (addPageSize && splitValue == PageBreakType.NewLandscapeSection);
if (targetIsLandscape && !sourceIsLandscape) if (targetIsLandscape && !sourceIsLandscape)
{ {
@@ -292,19 +280,11 @@ internal static class MultiReplaceExt
else if (!targetIsLandscape && sourceIsLandscape) else if (!targetIsLandscape && sourceIsLandscape)
{ {
pageSizeClone.SwapValues(); pageSizeClone.SwapValues();
if (addPageSize) pageSizeClone.Orient = addPageSize ? PageOrientationValues.Portrait : null;
pageSizeClone.Orient = PageOrientationValues.Portrait;
else
pageSizeClone.Orient = null; // не задаём Orient (not set)
} }
else else
{ {
if (targetIsLandscape) pageSizeClone.Orient = targetIsLandscape ? PageOrientationValues.Landscape : (addPageSize ? PageOrientationValues.Portrait : null);
pageSizeClone.Orient = PageOrientationValues.Landscape;
else if (addPageSize)
pageSizeClone.Orient = PageOrientationValues.Portrait;
else
pageSizeClone.Orient = null; // not set
} }
sectionProps.AppendChild(pageSizeClone); sectionProps.AppendChild(pageSizeClone);
} }
@@ -313,26 +293,23 @@ internal static class MultiReplaceExt
PageMargin? marginToUse = null; PageMargin? marginToUse = null;
if (addPageSize) if (addPageSize)
{ {
var sourceMargin = sourceSection?.GetFirstChild<PageMargin>() var sourceMargin = sourceSection?.GetFirstChild<PageMargin>() ?? portraitSection?.GetFirstChild<PageMargin>();
?? portraitSection?.GetFirstChild<PageMargin>();
if (sourceMargin is not null) if (sourceMargin is not null)
{ {
var marginClone = (PageMargin)sourceMargin.CloneNode(true); var marginClone = (PageMargin)sourceMargin.CloneNode(true);
var sourceOrient = sourceSection?.GetFirstChild<PageSize>()?.Orient; var sourceIsLndscape = sourceSection?.GetFirstChild<PageSize>()?.Orient?.Value == PageOrientationValues.Landscape ||
bool sourceIsLandscape = sourceOrient?.Value == PageOrientationValues.Landscape || sourceSection?.GetFirstChild<PageSize>()?.Width?.Value > sourceSection?.GetFirstChild<PageSize>()?.Height?.Value;
(sourceSection?.GetFirstChild<PageSize>()?.Width?.Value > sourceSection?.GetFirstChild<PageSize>()?.Height?.Value);
if ((splitValue == PageBreakType.NewLandscapeSection && !sourceIsLandscape) || if ((splitValue == PageBreakType.NewLandscapeSection && !sourceIsLndscape) ||
(splitValue == PageBreakType.NewPortraitSection && sourceIsLandscape)) (splitValue == PageBreakType.NewPortraitSection && sourceIsLndscape))
{ {
marginClone.SwapBottomRight(); marginClone.SwapBottomRight();
} }
marginToUse = marginClone; marginToUse = marginClone;
} }
} }
else else if (portraitSection?.GetFirstChild<PageMargin>() is { } portraitMargin)
{ {
var portraitMargin = portraitSection?.GetFirstChild<PageMargin>();
if (portraitMargin is not null)
marginToUse = (PageMargin)portraitMargin.CloneNode(true); marginToUse = (PageMargin)portraitMargin.CloneNode(true);
} }
@@ -343,62 +320,6 @@ internal static class MultiReplaceExt
para.ParagraphProperties.AppendChild(sectionProps); para.ParagraphProperties.AppendChild(sectionProps);
} }
private static void MergeParagraph(Paragraph target, Paragraph source)
{
foreach (var child in source.ChildElements)
target.AppendChild(child.CloneNode(true));
}
/// <summary>Выводит структуру документа: для каждого параграфа показывает текст, наличие секции, ориентацию, размеры и поля.</summary>
private static void LogDocumentStructure(Body body, string title)
{
#if DEBUG
Debugger.Builder.AppendLine($"=== {title} ===");
var paragraphs = body.Descendants<Paragraph>().ToList();
int index = 0;
foreach (var para in paragraphs)
{
var text = para.InnerText.Replace("\n", "\\n").Replace("\r", "\\r");
var section = para.ParagraphProperties?.GetFirstChild<SectionProperties>();
string sectionInfo = "None";
if (section is not null)
{
var pageSize = section.GetFirstChild<PageSize>();
string orient = pageSize?.Orient?.ToString() ?? "not set";
string sizeInfo = "";
if (pageSize is not null)
{
sizeInfo = $" Size: W={pageSize.Width?.Value}, H={pageSize.Height?.Value}";
}
var margins = section.GetFirstChild<PageMargin>();
string marginInfo = "";
if (margins is not null)
{
marginInfo = $" Margins: Top={margins.Top?.Value}, Bottom={margins.Bottom?.Value}, Left={margins.Left?.Value}, Right={margins.Right?.Value}";
}
sectionInfo = $"Orient={orient}{sizeInfo}{marginInfo}";
}
Debugger.Builder.AppendLine($" Para {index}: Text='{text}', Section={sectionInfo}");
index++;
}
// Логируем секции из Body (если есть)
var bodySections = body.Elements<SectionProperties>().ToList();
if (bodySections.Any())
{
Debugger.Builder.AppendLine(" Body SectionProperties:");
foreach (var sec in bodySections)
{
var ps = sec.GetFirstChild<PageSize>();
var pm = sec.GetFirstChild<PageMargin>();
Debugger.Builder.AppendLine($" PageSize: Width={ps?.Width}, Height={ps?.Height}, Orient={ps?.Orient}");
Debugger.Builder.AppendLine($" PageMargin: Top={pm?.Top}, Bottom={pm?.Bottom}, Left={pm?.Left}, Right={pm?.Right}");
}
}
Debugger.Builder.AppendLine($"=== END {title} ===");
#endif
}
/// <summary>Основной алгоритм множественной замены с поддержкой разрывов и смены ориентации.</summary> /// <summary>Основной алгоритм множественной замены с поддержкой разрывов и смены ориентации.</summary>
private static List<Paragraph>? ProcessMultiReplacements( private static List<Paragraph>? ProcessMultiReplacements(
Paragraph original, Paragraph original,
@@ -406,83 +327,61 @@ internal static class MultiReplaceExt
IEnumerable<KeyValuePair<string, IEnumerable<ReplaceItem>>>? itemReplacements, IEnumerable<KeyValuePair<string, IEnumerable<ReplaceItem>>>? itemReplacements,
StringComparison comparisonType) StringComparison comparisonType)
{ {
var body = original.Ancestors<Body>().FirstOrDefault();
// 1. Сбор определений
var definitions = new List<MatchDefinition>(); var definitions = new List<MatchDefinition>();
if (stringReplacements is not null) if (stringReplacements is not null)
{ {
foreach (var kvp in stringReplacements) definitions.AddRange(stringReplacements
{ .Where(kvp => !string.IsNullOrEmpty(kvp.Key) && kvp.Value != null && kvp.Value.Any())
if (string.IsNullOrEmpty(kvp.Key) || kvp.Value is null || kvp.Value.Count() == 0) continue; .Select(kvp => new MatchDefinition(kvp.Key, kvp.Value.Select(v => new ReplaceItem(v, PageBreakType.None)))));
var items = kvp.Value.Select(v => new ReplaceItem(v, PageBreakType.None));
definitions.Add(new MatchDefinition(kvp.Key, items));
}
} }
if (itemReplacements is not null) if (itemReplacements is not null)
{ {
foreach (var kvp in itemReplacements) definitions.AddRange(itemReplacements
{ .Where(kvp => !string.IsNullOrEmpty(kvp.Key) && kvp.Value != null && kvp.Value.Any())
if (string.IsNullOrEmpty(kvp.Key) || kvp.Value is null || kvp.Value.Count() == 0) continue; .Select(kvp => new MatchDefinition(kvp.Key, kvp.Value)));
definitions.Add(new MatchDefinition(kvp.Key, kvp.Value));
}
} }
if (definitions.Count == 0) return null; if (definitions.Count == 0) return null;
// 2. Анализ структуры параграфа var runs = original.Elements<Run>().ToList();
var runs = original.Descendants<Run>().ToList();
if (runs.Count == 0) return null; if (runs.Count == 0) return null;
var structure = AnalyzeParagraphStructure(runs); var structure = AnalyzeParagraphStructure(runs);
string fullText = structure.FullText; string fullText = structure.FullText;
if (fullText.Length == 0) return null; if (fullText.Length == 0) return null;
// 3. Поиск всех вхождений
var matches = new List<Match>(); var matches = new List<Match>();
foreach (var def in definitions) foreach (var def in definitions)
{ {
int pos = 0; int pos = 0;
while ((pos = fullText.IndexOf(def.Key, pos, comparisonType)) != -1) while ((pos = fullText.IndexOf(def.Key, pos, comparisonType)) != -1)
{ {
matches.Add(new Match matches.Add(new Match { Definition = def, Start = pos, End = pos + def.Key.Length });
{
Definition = def,
Start = pos,
End = pos + def.Key.Length
});
pos += def.Key.Length; pos += def.Key.Length;
} }
} }
if (matches.Count == 0) return null; if (matches.Count == 0) return null;
matches.Sort((a, b) => a.Start.CompareTo(b.Start)); matches.Sort((a, b) => a.Start.CompareTo(b.Start));
// 4. Получаем исходную секцию для копирования (из original или из документа) var body = original.Ancestors<Body>().FirstOrDefault();
SectionProperties? sourceSection = original.ParagraphProperties?.GetFirstChild<SectionProperties>()?.CloneNode(true) as SectionProperties; var sourceSection = original.ParagraphProperties?.GetFirstChild<SectionProperties>()?.CloneNode(true) as SectionProperties
if (sourceSection is null && body is not null) ?? body?.Elements<SectionProperties>().LastOrDefault()?.CloneNode(true) as SectionProperties
{ ?? new SectionProperties();
sourceSection = body.Elements<SectionProperties>().LastOrDefault()?.CloneNode(true) as SectionProperties;
}
sourceSection ??= new SectionProperties();
// Получаем книжную секцию для копирования полей (из документа) var portraitSection = body?.Elements<SectionProperties>().FirstOrDefault()?.CloneNode(true) as SectionProperties
SectionProperties? portraitSection = null; ?? new SectionProperties();
if (body is not null)
{
portraitSection = body.Elements<SectionProperties>().FirstOrDefault()?.CloneNode(true) as SectionProperties;
}
portraitSection ??= new SectionProperties();
// 5. Построение результата
var resultParas = new List<Paragraph>(); var resultParas = new List<Paragraph>();
Paragraph? currentPara = null; Paragraph? currentPara = null;
int currentPos = 0; int currentPos = 0;
bool sectionChangeInsideGroup = false; bool sectionChangeInsideGroup = false;
PageBreakType? lastOrientation = null; PageBreakType? lastOrientation = null;
for (int i = 0; i < matches.Count; i++) foreach (var match in matches)
{ {
var match = matches[i];
// Текст перед совпадением (если есть)
if (currentPos < match.Start) if (currentPos < match.Start)
{ {
var beforePara = CloneParagraphWithoutSection(original); var beforePara = CloneParagraphWithoutSection(original);
@@ -490,6 +389,7 @@ internal static class MultiReplaceExt
{ {
if (seg.End <= currentPos) continue; if (seg.End <= currentPos) continue;
if (seg.Start >= match.Start) break; if (seg.Start >= match.Start) break;
if (seg.Start >= currentPos && seg.End <= match.Start) if (seg.Start >= currentPos && seg.End <= match.Start)
{ {
beforePara.AppendChild(seg.Run.CloneNode(true)); beforePara.AppendChild(seg.Run.CloneNode(true));
@@ -498,14 +398,14 @@ internal static class MultiReplaceExt
{ {
int startOffset = Math.Max(0, currentPos - seg.Start); int startOffset = Math.Max(0, currentPos - seg.Start);
int endOffset = Math.Min(seg.Text.Length, match.Start - seg.Start); int endOffset = Math.Min(seg.Text.Length, match.Start - seg.Start);
var runClone = (Run)seg.Run.CloneNode(true); var runClone = (Run)seg.Run.CloneNode(true);
foreach (var t in runClone.Elements<Text>().ToList()) t.Remove(); runClone.RemoveAllChildren<Text>();
string textPart = seg.Text.Substring(startOffset, endOffset - startOffset); runClone.AppendChild(new Text(seg.Text.Substring(startOffset, endOffset - startOffset)));
runClone.AppendChild(new Text(textPart));
beforePara.AppendChild(runClone); beforePara.AppendChild(runClone);
} }
} }
if (beforePara.ChildElements.OfType<Run>().Any()) if (beforePara.Elements<Run>().Any())
{ {
resultParas.Add(beforePara); resultParas.Add(beforePara);
currentPara = beforePara; currentPara = beforePara;
@@ -518,23 +418,16 @@ internal static class MultiReplaceExt
for (int vIdx = 0; vIdx < values.Count; vIdx++) for (int vIdx = 0; vIdx < values.Count; vIdx++)
{ {
var item = values[vIdx]; var item = values[vIdx];
currentPara = CloneParagraphWithoutSection(original);
// Создаём новый параграф для каждого элемента resultParas.Add(currentPara);
var newPara = CloneParagraphWithoutSection(original);
resultParas.Add(newPara);
currentPara = newPara;
InsertFormattedRun(currentPara, item, structure, match.Start); InsertFormattedRun(currentPara, item, structure, match.Start);
// Обработка смены ориентации if (item.SplitValue is PageBreakType.NewLandscapeSection or PageBreakType.NewPortraitSection)
if (item.SplitValue == PageBreakType.NewLandscapeSection || item.SplitValue == PageBreakType.NewPortraitSection)
{ {
bool addPageSize = (vIdx != 0); bool addPageSize = vIdx != 0;
PageBreakType orientation = item.SplitValue; var orientation = vIdx != 0 ? PageBreakType.NewLandscapeSection : item.SplitValue;
if (vIdx != 0)
{
orientation = PageBreakType.NewLandscapeSection;
}
AddSectionProperties(currentPara, orientation, addPageSize, sourceSection, portraitSection); AddSectionProperties(currentPara, orientation, addPageSize, sourceSection, portraitSection);
lastOrientation = item.SplitValue; lastOrientation = item.SplitValue;
sectionChangeInsideGroup = true; sectionChangeInsideGroup = true;
@@ -543,62 +436,37 @@ internal static class MultiReplaceExt
{ {
var seg = structure.Segments.FirstOrDefault(s => match.Start >= s.Start && match.Start < s.End); var seg = structure.Segments.FirstOrDefault(s => match.Start >= s.Start && match.Start < s.End);
var breakRun = new Run(new Break { Type = BreakValues.Page }); var breakRun = new Run(new Break { Type = BreakValues.Page });
if (seg is not null && seg.Run.RunProperties is not null) if (seg?.Run.RunProperties is not null)
breakRun.RunProperties = (RunProperties)seg.Run.RunProperties.CloneNode(true); breakRun.RunProperties = (RunProperties)seg.Run.RunProperties.CloneNode(true);
currentPara.AppendChild(breakRun); currentPara.AppendChild(breakRun);
} }
} }
// Закрываем секцию, если была смена и последний параграф не имеет секции if (sectionChangeInsideGroup && lastOrientation.HasValue && currentPara?.ParagraphProperties?.GetFirstChild<SectionProperties>() is null)
if (sectionChangeInsideGroup && lastOrientation.HasValue && currentPara is not null)
{ {
if (currentPara.ParagraphProperties?.GetFirstChild<SectionProperties>() is null) AddSectionProperties(currentPara!, lastOrientation.Value, lastOrientation.Value == PageBreakType.NewLandscapeSection, sourceSection, portraitSection);
{
bool addPageSize = (lastOrientation.Value == PageBreakType.NewLandscapeSection);
AddSectionProperties(currentPara, lastOrientation.Value, addPageSize, sourceSection, portraitSection);
}
} }
// Если исходная секция была landscape, внутри группы была смена, и последняя ориентация — книжная, if (body is not null && sourceSection.GetFirstChild<PageSize>() is { } sourcePageSize)
// добавляем landscape секцию в Body, чтобы остаток остался landscape.
if (body is not null)
{ {
var sourcePageSize = sourceSection.GetFirstChild<PageSize>(); bool sourceIsLandscape = sourcePageSize.Orient?.Value == PageOrientationValues.Landscape || sourcePageSize.Width?.Value > sourcePageSize.Height?.Value;
if (sourcePageSize is not null) bool lastIsPortrait = lastOrientation == PageBreakType.NewPortraitSection;
if (sourceIsLandscape && sectionChangeInsideGroup && lastIsPortrait && !body.Elements<SectionProperties>().Any(s => s.GetFirstChild<PageSize>()?.Orient?.Value == PageOrientationValues.Landscape))
{ {
bool sourceIsLandscape = sourcePageSize.Orient?.Value == PageOrientationValues.Landscape ||
(sourcePageSize.Width?.Value > sourcePageSize.Height?.Value);
bool lastIsPortrait = lastOrientation.HasValue && lastOrientation.Value == PageBreakType.NewPortraitSection;
if (sourceIsLandscape && sectionChangeInsideGroup && lastIsPortrait)
{
// Проверяем, есть ли уже секция landscape на Body
bool hasBodyLandscape = false;
foreach (var bodySec in body.Elements<SectionProperties>())
{
var ps = bodySec.GetFirstChild<PageSize>();
if (ps is not null && ps.Orient?.Value == PageOrientationValues.Landscape)
{
hasBodyLandscape = true;
break;
}
}
if (!hasBodyLandscape)
{
// Создаём секцию landscape для Body
var bodySection = new SectionProperties(); var bodySection = new SectionProperties();
var pageSizeClone = (PageSize)sourcePageSize.CloneNode(true); var pageSizeClone = (PageSize)sourcePageSize.CloneNode(true);
// Если ориентация не landscape, меняем
if (pageSizeClone.Orient?.Value != PageOrientationValues.Landscape) if (pageSizeClone.Orient?.Value != PageOrientationValues.Landscape)
{ {
pageSizeClone.SwapValues(); pageSizeClone.SwapValues();
pageSizeClone.Orient = PageOrientationValues.Landscape; pageSizeClone.Orient = PageOrientationValues.Landscape;
} }
bodySection.AppendChild(pageSizeClone); bodySection.AppendChild(pageSizeClone);
var sourceMargin = sourceSection.GetFirstChild<PageMargin>();
if (sourceMargin is not null) if (sourceSection.GetFirstChild<PageMargin>() is { } sourceMargin)
{ {
var marginClone = (PageMargin)sourceMargin.CloneNode(true); var marginClone = (PageMargin)sourceMargin.CloneNode(true);
// Если исходная секция не landscape, но мы делаем landscape, меняем поля
if (sourceSection.GetFirstChild<PageSize>()?.Orient?.Value != PageOrientationValues.Landscape) if (sourceSection.GetFirstChild<PageSize>()?.Orient?.Value != PageOrientationValues.Landscape)
{ {
marginClone.SwapBottomRight(); marginClone.SwapBottomRight();
@@ -609,44 +477,20 @@ internal static class MultiReplaceExt
body.AppendChild(bodySection); body.AppendChild(bodySection);
} }
} }
}
}
currentPos = match.End; currentPos = match.End;
} }
// 6. Обработка остатка текста (если есть) if (currentPos < fullText.Length && BuildRemainderParagraph(original, structure, currentPos) is { } remainderPara)
if (currentPos < fullText.Length)
{ {
var remainderPara = BuildRemainderParagraph(original, structure, currentPos);
if (remainderPara is not null)
{
// Если внутри группы была смена, применяем последнюю ориентацию к остатку
if (sectionChangeInsideGroup && lastOrientation.HasValue) if (sectionChangeInsideGroup && lastOrientation.HasValue)
{ {
var breakRun = new Run(new Break { Type = BreakValues.Page }); remainderPara.InsertAt(new Run(new Break { Type = BreakValues.Page }), 0);
remainderPara.InsertAt(breakRun, 0); AddSectionProperties(remainderPara, lastOrientation.Value, lastOrientation.Value == PageBreakType.NewLandscapeSection, sourceSection, portraitSection);
bool addPageSize = (lastOrientation.Value == PageBreakType.NewLandscapeSection);
AddSectionProperties(remainderPara, lastOrientation.Value, addPageSize, sourceSection, portraitSection);
} }
resultParas.Add(remainderPara); resultParas.Add(remainderPara);
} }
}
// 7. Очистка пустых параграфов
for (int i = resultParas.Count - 1; i >= 0; i--)
{
var p = resultParas[i];
if (!p.ChildElements.OfType<Run>().Any() && p.ParagraphProperties is null)
resultParas.RemoveAt(i);
}
// Логирование
#if DEBUG
if (body is not null)
LogDocumentStructure(body, "FINAL DOCUMENT STRUCTURE");
#endif
resultParas.RemoveAll(p => !p.Elements<Run>().Any() && p.ParagraphProperties is null);
return resultParas.Count > 0 ? resultParas : null; return resultParas.Count > 0 ? resultParas : null;
} }
} }