namespace QWERTYkez.WordProcessor;
///
/// Выполняет замену всех вхождений ключей из словаря на соответствующие массивы значений.
/// Поддерживает разрывы страниц и смену ориентации (альбомная/книжная) через .
///
internal static class MultiReplaceExt
{
// ---------- ПУБЛИЧНЫЕ МЕТОДЫ (для Body) ----------
#region Body.Replace с одним ключом
internal static void Replace(this Body body, string oldValue, IEnumerable newValues, StringComparison comparisonType)
{
if (body is null || string.IsNullOrEmpty(oldValue) || newValues is null) return;
var dict = new Dictionary> { { oldValue, newValues } };
body.Replace(dict, comparisonType);
}
internal static void Replace(this Body body, string oldValue, IEnumerable newValues, StringComparison comparisonType)
{
if (body is null || string.IsNullOrEmpty(oldValue) || newValues is null) return;
var dict = new Dictionary> { { oldValue, newValues } };
body.Replace(dict, comparisonType);
}
#endregion
#region Body.Replace со словарём массивов
internal static void Replace(this Body body, IEnumerable>> replacements, StringComparison comparisonType)
{
if (body is null || replacements is null) return;
var paragraphs = body.Elements().ToList();
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>> replacements, StringComparison comparisonType)
{
if (body is null || replacements is null) return;
var paragraphs = body.Elements().ToList();
for (int i = paragraphs.Count - 1; i >= 0; i--)
{
var p = paragraphs[i];
if (p?.Parent is null) continue;
var newParas = ProcessMultiReplacements(p, null, replacements, comparisonType);
if (newParas is not null && newParas.Count > 0)
ParagraphReplacer.ReplaceParagraph(p, newParas);
}
}
#endregion
#region Paragraph.ReplaceWithMultiple (один ключ)
internal static bool ReplaceWithMultiple(this Paragraph? paragraph, string oldValue, IEnumerable newValues, StringComparison comparisonType)
{
if (paragraph is null || string.IsNullOrEmpty(oldValue) || newValues is null || newValues.Count() == 0)
return false;
var dict = new Dictionary> { { oldValue, newValues } };
var newParas = ProcessMultiReplacements(paragraph, dict, null, comparisonType);
if (newParas is null || newParas.Count == 0) return false;
if (paragraph.Parent is not null)
{
ParagraphReplacer.ReplaceParagraph(paragraph, newParas);
return true;
}
return false;
}
internal static bool ReplaceWithMultiple(this Paragraph? paragraph, string oldValue, IEnumerable newValues, StringComparison comparisonType)
{
if (paragraph is null || string.IsNullOrEmpty(oldValue) || newValues is null || newValues.Count() == 0)
return false;
var dict = new Dictionary> { { oldValue, newValues } };
var newParas = ProcessMultiReplacements(paragraph, null, dict, comparisonType);
if (newParas is null || newParas.Count == 0) return false;
if (paragraph.Parent is not null)
{
ParagraphReplacer.ReplaceParagraph(paragraph, newParas);
return true;
}
return false;
}
#endregion
#region ProcessParagraphWithAllReplacements (для обратной совместимости)
internal static List? ProcessParagraphWithAllReplacements(
Paragraph paragraph,
IEnumerable>> replacements,
StringComparison comparisonType)
{
return ProcessMultiReplacements(paragraph, replacements, null, comparisonType);
}
internal static List? ProcessParagraphWithAllReplacements(
Paragraph paragraph,
IEnumerable>> replacements,
StringComparison comparisonType)
{
return ProcessMultiReplacements(paragraph, null, replacements, comparisonType);
}
internal static List? ProcessParagraphWithAllReplacements(
Paragraph paragraph,
IEnumerable> replacements,
StringComparison comparisonType)
{
Dictionary> dict = replacements
.Where(kvp => !string.IsNullOrEmpty(kvp.Key))
.ToDictionary(kvp => kvp.Key, kvp => (IEnumerable)[kvp.Value]);
return ProcessMultiReplacements(paragraph, dict, null, comparisonType);
}
#endregion
// ---------- ВНУТРЕННЯЯ РЕАЛИЗАЦИЯ ----------
private class MatchDefinition(string key, IEnumerable values)
{
public string Key { get; } = key;
public IEnumerable Values { get; } = values;
}
private class Match
{
public MatchDefinition Definition { get; set; } = null!;
public int Start { get; set; }
public int End { get; set; }
}
private class RunSegment(Run run, string text, int start, int end)
{
public Run Run { get; } = run;
public string Text { get; } = text;
public int Start { get; } = start;
public int End { get; } = end;
}
private class ParagraphStructure(string fullText, List segments)
{
public string FullText { get; } = fullText;
public List Segments { get; } = segments;
}
private static ParagraphStructure AnalyzeParagraphStructure(List runs)
{
var segments = new List();
var sb = new StringBuilder();
int pos = 0;
foreach (var run in runs)
{
string text = GetRunText(run);
if (string.IsNullOrEmpty(text)) continue;
segments.Add(new RunSegment(run, text, pos, pos + text.Length));
sb.Append(text);
pos += text.Length;
}
return new ParagraphStructure(sb.ToString(), segments);
}
private static string GetRunText(Run run)
{
var sb = new StringBuilder();
foreach (var text in run.Elements())
sb.Append(text.Text);
return sb.ToString();
}
/// Клонирует параграф, удаляя все SectionProperties и PageBreakBefore.
private static Paragraph CloneParagraphWithoutSection(Paragraph original)
{
var newPara = new Paragraph();
if (original.ParagraphProperties is not null)
{
var newProps = new ParagraphProperties();
foreach (var child in original.ParagraphProperties.ChildElements)
{
if (child is not SectionProperties && child is not PageBreakBefore)
newProps.AppendChild(child.CloneNode(true));
}
newPara.ParagraphProperties = newProps;
}
return newPara;
}
private static Paragraph? BuildRemainderParagraph(Paragraph original, ParagraphStructure structure, int position)
{
if (position >= structure.FullText.Length) return null;
var newPara = CloneParagraphWithoutSection(original);
foreach (var seg in structure.Segments)
{
if (seg.End <= position) continue;
if (seg.Start >= position)
{
newPara.AppendChild(seg.Run.CloneNode(true));
}
else if (seg.End > position)
{
var runClone = (Run)seg.Run.CloneNode(true);
foreach (var t in runClone.Elements().ToList()) t.Remove();
int offset = position - seg.Start;
string newText = seg.Text.Substring(offset);
runClone.AppendChild(new Text(newText));
newPara.AppendChild(runClone);
}
}
foreach (var run in newPara.Descendants().Where(r => !r.HasChildren).ToList())
run.Remove();
if (!newPara.ChildElements.OfType().Any() && newPara.ParagraphProperties is null)
return null;
return newPara;
}
private static void InsertFormattedRun(Paragraph para, string text, ParagraphStructure structure, int position)
{
var seg = structure.Segments.FirstOrDefault(s => position >= s.Start && position < s.End);
if (seg is null) return;
var textRun = new Run();
if (seg.Run.RunProperties is not null)
textRun.RunProperties = (RunProperties)seg.Run.RunProperties.CloneNode(true);
textRun.AppendChild(new Text(text));
para.AppendChild(textRun);
}
///
/// Добавляет SectionProperties к параграфу. Все значения (PageSize, PageMargin) берутся из документа.
/// Для книжных секций (addPageSize=false) Orient не устанавливается (not set).
///
private static void AddSectionProperties(
Paragraph para,
BreakType splitValue,
bool addPageSize,
SectionProperties sourceSection,
SectionProperties portraitSection)
{
if (para is null) return;
if (para.ParagraphProperties is not null)
{
var sections = para.ParagraphProperties.Elements().ToList();
foreach (var sec in sections) sec.Remove();
var pageBreaks = para.ParagraphProperties.Elements().ToList();
foreach (var pb in pageBreaks) pb.Remove();
}
para.ParagraphProperties ??= new ParagraphProperties();
var sectionProps = new SectionProperties();
var pageSizeClone = CreatePageSizeClone(addPageSize, splitValue, sourceSection, portraitSection);
if (pageSizeClone is not null)
sectionProps.AppendChild(pageSizeClone);
var marginClone = CreateMarginClone(addPageSize, splitValue, sourceSection, portraitSection);
if (marginClone is not null)
sectionProps.AppendChild(marginClone);
sectionProps.AppendChild(new SectionType { Val = SectionMarkValues.NextPage });
para.ParagraphProperties.AppendChild(sectionProps);
}
private static PageSize? CreatePageSizeClone(
bool addPageSize,
BreakType splitValue,
SectionProperties sourceSection,
SectionProperties portraitSection)
{
if (!addPageSize && splitValue != BreakType.NewLandscapeSection)
return null;
SectionProperties? sizeSource = addPageSize ? sourceSection : portraitSection;
var sourcePageSize = sizeSource?.GetFirstChild()
?? portraitSection.GetFirstChild()
?? sourceSection.GetFirstChild();
if (sourcePageSize is null)
return null;
var clone = (PageSize)sourcePageSize.CloneNode(true);
bool sourceIsLandscape = clone.Orient?.Value == PageOrientationValues.Landscape ||
(clone.Width?.Value > clone.Height?.Value);
bool targetIsLandscape = addPageSize && splitValue == BreakType.NewLandscapeSection;
if (targetIsLandscape && !sourceIsLandscape)
{
clone.SwapValues();
clone.Orient = PageOrientationValues.Landscape;
}
else if (!targetIsLandscape && sourceIsLandscape)
{
clone.SwapValues();
clone.Orient = addPageSize ? PageOrientationValues.Portrait : null;
}
else
{
clone.Orient = targetIsLandscape ? PageOrientationValues.Landscape :
addPageSize ? PageOrientationValues.Portrait : null;
}
return clone;
}
private static PageMargin? CreateMarginClone(
bool addPageSize,
BreakType splitValue,
SectionProperties sourceSection,
SectionProperties portraitSection)
{
PageMargin? marginToUse = null;
if (addPageSize)
{
var sourceMargin = sourceSection?.GetFirstChild()
?? portraitSection?.GetFirstChild();
if (sourceMargin is not null)
{
var clone = (PageMargin)sourceMargin.CloneNode(true);
var sourceOrient = sourceSection?.GetFirstChild()?.Orient;
bool sourceIsLandscape = sourceOrient?.Value == PageOrientationValues.Landscape ||
(sourceSection?.GetFirstChild()?.Width?.Value > sourceSection?.GetFirstChild()?.Height?.Value);
if ((splitValue == BreakType.NewLandscapeSection && !sourceIsLandscape) ||
(splitValue == BreakType.NewPortraitSection && sourceIsLandscape))
{
clone.SwapBottomRight();
}
marginToUse = clone;
}
}
else
{
var portraitMargin = portraitSection?.GetFirstChild();
if (portraitMargin is not null)
marginToUse = (PageMargin)portraitMargin.CloneNode(true);
}
return marginToUse;
}
private static void EnsureBodyLandscapeSection(
Body body,
SectionProperties sourceSection,
bool sectionChangeInsideGroup,
BreakType? lastOrientation)
{
if (body is null || sourceSection is null) return;
var sourcePageSize = sourceSection.GetFirstChild();
if (sourcePageSize is null) return;
bool sourceIsLandscape = sourcePageSize.Orient?.Value == PageOrientationValues.Landscape ||
(sourcePageSize.Width?.Value > sourcePageSize.Height?.Value);
bool lastIsPortrait = lastOrientation.HasValue && lastOrientation.Value == BreakType.NewPortraitSection;
if (!(sourceIsLandscape && sectionChangeInsideGroup && lastIsPortrait))
return;
foreach (var bodySec in body.Elements())
{
var ps = bodySec.GetFirstChild();
if (ps is not null && ps.Orient?.Value == PageOrientationValues.Landscape)
return;
}
var bodySection = new SectionProperties();
var pageSizeClone = (PageSize)sourcePageSize.CloneNode(true);
if (pageSizeClone.Orient?.Value != PageOrientationValues.Landscape)
{
pageSizeClone.SwapValues();
pageSizeClone.Orient = PageOrientationValues.Landscape;
}
bodySection.AppendChild(pageSizeClone);
var sourceMargin = sourceSection.GetFirstChild();
if (sourceMargin is not null)
{
var marginClone = (PageMargin)sourceMargin.CloneNode(true);
if (sourceSection.GetFirstChild()?.Orient?.Value != PageOrientationValues.Landscape)
marginClone.SwapBottomRight();
bodySection.AppendChild(marginClone);
}
bodySection.AppendChild(new SectionType { Val = SectionMarkValues.NextPage });
body.AppendChild(bodySection);
}
private static void MergeParagraph(Paragraph target, Paragraph source)
{
foreach (var child in source.ChildElements)
target.AppendChild(child.CloneNode(true));
}
/// Основной алгоритм множественной замены с поддержкой разрывов и смены ориентации.
private static List? ProcessMultiReplacements(
Paragraph original,
IEnumerable>>? stringReplacements,
IEnumerable>>? itemReplacements,
StringComparison comparisonType)
{
var body = original.Ancestors().FirstOrDefault();
// 1. Сбор определений
var definitions = new List();
if (stringReplacements is not null)
{
foreach (var kvp in stringReplacements)
{
if (string.IsNullOrEmpty(kvp.Key) || kvp.Value is null || kvp.Value.Count() == 0) continue;
var items = kvp.Value.Select(v => new ReplaceItem(v));
definitions.Add(new MatchDefinition(kvp.Key, items));
}
}
if (itemReplacements is not null)
{
foreach (var kvp in itemReplacements)
{
if (string.IsNullOrEmpty(kvp.Key) || kvp.Value is null || kvp.Value.Count() == 0) continue;
definitions.Add(new MatchDefinition(kvp.Key, kvp.Value));
}
}
if (definitions.Count == 0) return null;
// 2. Анализ структуры параграфа
var runs = original.Descendants().ToList();
if (runs.Count == 0) return null;
var structure = AnalyzeParagraphStructure(runs);
string fullText = structure.FullText;
if (fullText.Length == 0) return null;
// 3. Поиск всех вхождений
var matches = new List();
foreach (var def in definitions)
{
int pos = 0;
while ((pos = fullText.IndexOf(def.Key, pos, comparisonType)) != -1)
{
matches.Add(new Match
{
Definition = def,
Start = pos,
End = pos + def.Key.Length
});
pos += def.Key.Length;
}
}
if (matches.Count == 0) return null;
matches.Sort((a, b) => a.Start.CompareTo(b.Start));
// 4. Получаем исходную секцию для копирования (из original или из документа)
SectionProperties? sourceSection = original.ParagraphProperties?.GetFirstChild()?.CloneNode(true) as SectionProperties;
if (sourceSection is null && body is not null)
{
sourceSection = body.Elements().LastOrDefault()?.CloneNode(true) as SectionProperties;
}
sourceSection ??= new SectionProperties();
SectionProperties? portraitSection = null;
if (body is not null)
{
portraitSection = body.Elements().FirstOrDefault()?.CloneNode(true) as SectionProperties;
}
portraitSection ??= new SectionProperties();
// 5. Построение результата
var resultParas = new List();
Paragraph? currentPara = null;
int currentPos = 0;
bool sectionChangeInsideGroup = false;
BreakType? lastOrientation = null;
// Состояние обработки группы
bool pageBreakBeforeNext = false;
BreakType? pendingOrientation = null;
bool firstSplitMarkerHandled = false;
int textCount = 0;
Paragraph? lastTextPara = null;
for (int i = 0; i < matches.Count; i++)
{
var match = matches[i];
// Текст перед совпадением
if (currentPos < match.Start)
{
var beforePara = CloneParagraphWithoutSection(original);
foreach (var seg in structure.Segments)
{
if (seg.End <= currentPos) continue;
if (seg.Start >= match.Start) break;
if (seg.Start >= currentPos && seg.End <= match.Start)
{
beforePara.AppendChild(seg.Run.CloneNode(true));
}
else if (seg.Start < match.Start && seg.End > currentPos)
{
int startOffset = Math.Max(0, currentPos - seg.Start);
int endOffset = Math.Min(seg.Text.Length, match.Start - seg.Start);
var runClone = (Run)seg.Run.CloneNode(true);
foreach (var t in runClone.Elements().ToList()) t.Remove();
string textPart = seg.Text.Substring(startOffset, endOffset - startOffset);
runClone.AppendChild(new Text(textPart));
beforePara.AppendChild(runClone);
}
}
if (beforePara.ChildElements.OfType().Any())
{
resultParas.Add(beforePara);
currentPara = beforePara;
lastTextPara = beforePara;
}
}
var values = match.Definition.Values.ToList();
if (values.Count == 0) continue;
// Сбрасываем флаги для новой группы
pageBreakBeforeNext = false;
pendingOrientation = null;
firstSplitMarkerHandled = false;
textCount = 0;
lastTextPara = null;
foreach (var item in values)
{
if (!string.IsNullOrEmpty(item.Text))
{
// Если есть отложенная ориентация — применяем её
if (pendingOrientation.HasValue)
{
var newPara = CloneParagraphWithoutSection(original);
resultParas.Add(newPara);
currentPara = newPara;
bool addPageSize = (pendingOrientation.Value == BreakType.NewLandscapeSection);
AddSectionProperties(currentPara, pendingOrientation.Value, addPageSize, sourceSection, portraitSection);
lastOrientation = pendingOrientation;
sectionChangeInsideGroup = true;
pendingOrientation = null;
textCount++;
lastTextPara = currentPara;
if (pageBreakBeforeNext)
{
var breakRun = new Run(new Break { Type = BreakValues.Page });
currentPara.InsertAt(breakRun, 0);
pageBreakBeforeNext = false;
}
InsertFormattedRun(currentPara, item.Text, structure, match.Start);
}
else
{
var newPara = CloneParagraphWithoutSection(original);
resultParas.Add(newPara);
currentPara = newPara;
textCount++;
lastTextPara = currentPara;
if (pageBreakBeforeNext)
{
var breakRun = new Run(new Break { Type = BreakValues.Page });
currentPara.InsertAt(breakRun, 0);
pageBreakBeforeNext = false;
}
InsertFormattedRun(currentPara, item.Text, structure, match.Start);
}
}
else if (item.BreakValue.HasValue)
{
var breakType = item.BreakValue.Value;
if (breakType == BreakType.PageBreak)
{
if (currentPara is not null)
{
var breakRun = new Run(new Break { Type = BreakValues.Page });
var lastRun = currentPara.Descendants().LastOrDefault();
if (lastRun?.RunProperties is not null)
breakRun.RunProperties = (RunProperties)lastRun.RunProperties.CloneNode(true);
currentPara.AppendChild(breakRun);
}
else
{
pageBreakBeforeNext = true;
}
}
else if (breakType == BreakType.NewLandscapeSection || breakType == BreakType.NewPortraitSection)
{
if (currentPara is null)
{
var newPara = CloneParagraphWithoutSection(original);
resultParas.Add(newPara);
currentPara = newPara;
AddSectionProperties(currentPara, breakType, false, sourceSection, portraitSection);
lastOrientation = breakType;
sectionChangeInsideGroup = true;
firstSplitMarkerHandled = true;
pendingOrientation = null;
textCount = 0;
lastTextPara = null;
}
else
{
if (!firstSplitMarkerHandled)
{
if (lastTextPara is not null)
{
if (lastTextPara.ParagraphProperties?.GetFirstChild() is null)
{
lastTextPara.ParagraphProperties ??= new ParagraphProperties();
var sourcePageSize = sourceSection.GetFirstChild();
if (sourcePageSize is not null)
{
lastTextPara.ParagraphProperties.AppendChild(sourceSection.CloneNode(true));
}
else
{
AddSectionProperties(lastTextPara, breakType, false, sourceSection, portraitSection);
}
lastOrientation = breakType;
sectionChangeInsideGroup = true;
}
firstSplitMarkerHandled = true;
pendingOrientation = null;
}
else
{
AddSectionProperties(currentPara, breakType, false, sourceSection, portraitSection);
lastOrientation = breakType;
sectionChangeInsideGroup = true;
firstSplitMarkerHandled = true;
pendingOrientation = null;
}
}
else
{
pendingOrientation = breakType;
}
}
}
}
}
// Закрываем секцию, если была смена
if (sectionChangeInsideGroup && lastOrientation.HasValue && currentPara is not null)
{
if (currentPara.ParagraphProperties?.GetFirstChild() is null)
{
bool addPageSize = (lastOrientation.Value == BreakType.NewLandscapeSection);
AddSectionProperties(currentPara, lastOrientation.Value, addPageSize, sourceSection, portraitSection);
}
}
EnsureBodyLandscapeSection(body!, sourceSection, sectionChangeInsideGroup, lastOrientation);
currentPos = match.End;
}
// 6. Обработка остатка текста
if (currentPos < fullText.Length)
{
var remainderPara = BuildRemainderParagraph(original, structure, currentPos);
if (remainderPara is not null)
{
if (pendingOrientation.HasValue)
{
var breakRun = new Run(new Break { Type = BreakValues.Page });
remainderPara.InsertAt(breakRun, 0);
bool addPageSize = (pendingOrientation.Value == BreakType.NewLandscapeSection);
AddSectionProperties(remainderPara, pendingOrientation.Value, addPageSize, sourceSection, portraitSection);
pendingOrientation = null;
}
else if (sectionChangeInsideGroup && lastOrientation.HasValue)
{
var breakRun = new Run(new Break { Type = BreakValues.Page });
remainderPara.InsertAt(breakRun, 0);
bool addPageSize = (lastOrientation.Value == BreakType.NewLandscapeSection);
AddSectionProperties(remainderPara, lastOrientation.Value, addPageSize, sourceSection, portraitSection);
}
resultParas.Add(remainderPara);
}
}
// 7. Очистка пустых параграфов
for (int i = resultParas.Count - 1; i >= 0; i--)
{
var p = resultParas[i];
if (!p.ChildElements.OfType().Any() && p.ParagraphProperties is null)
resultParas.RemoveAt(i);
}
return resultParas.Count > 0 ? resultParas : null;
}
}