26.07.21
This commit is contained in:
@@ -5,13 +5,15 @@
|
||||
/// Каждое значение из массива помещается в отдельный параграф, причём первое значение
|
||||
/// остаётся в текущем параграфе, а последующие создают новые.
|
||||
/// Текст между вхождениями и после последнего сохраняется в соответствующих параграфах.
|
||||
/// Поддерживает разрывы страниц и смену ориентации (альбомная/книжная) через <see cref="ReplaceItem.SplitValue"/>.
|
||||
/// </summary>
|
||||
internal static class MultiReplaceExt
|
||||
{
|
||||
// ---------- ПУБЛИЧНЫЕ МЕТОДЫ (СИГНАТУРЫ НЕИЗМЕННЫ) ----------
|
||||
// ---------- ПУБЛИЧНЫЕ МЕТОДЫ (для Body) ----------
|
||||
|
||||
#region Body.Replace с одним ключом
|
||||
|
||||
/// <summary>Заменяет все вхождения oldValue в теле документа на массив строк (каждая строка в отдельном параграфе).</summary>
|
||||
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;
|
||||
@@ -19,6 +21,7 @@ internal static class MultiReplaceExt
|
||||
body.Replace(dict, comparisonType);
|
||||
}
|
||||
|
||||
/// <summary>Заменяет все вхождения oldValue в теле документа на массив ReplaceItem (каждый элемент в отдельном параграфе с учётом разрывов).</summary>
|
||||
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;
|
||||
@@ -30,6 +33,7 @@ internal static class MultiReplaceExt
|
||||
|
||||
#region Body.Replace со словарём массивов
|
||||
|
||||
/// <summary>Заменяет все вхождения из словаря (ключ -> массив строк) в теле документа.</summary>
|
||||
internal static void Replace(this Body body, IEnumerable<KeyValuePair<string, IEnumerable<string>>> replacements, StringComparison comparisonType)
|
||||
{
|
||||
if (body is null || replacements is null) return;
|
||||
@@ -44,6 +48,7 @@ internal static class MultiReplaceExt
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Заменяет все вхождения из словаря (ключ -> массив ReplaceItem) в теле документа.</summary>
|
||||
internal static void Replace(this Body body, IEnumerable<KeyValuePair<string, IEnumerable<ReplaceItem>>> replacements, StringComparison comparisonType)
|
||||
{
|
||||
if (body is null || replacements is null) return;
|
||||
@@ -62,6 +67,7 @@ internal static class MultiReplaceExt
|
||||
|
||||
#region Paragraph.ReplaceWithMultiple (один ключ)
|
||||
|
||||
/// <summary>Заменяет все вхождения oldValue в параграфе на массив строк (каждая строка в новом параграфе).</summary>
|
||||
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)
|
||||
@@ -79,6 +85,7 @@ internal static class MultiReplaceExt
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>Заменяет все вхождения oldValue в параграфе на массив ReplaceItem (каждый элемент в новом параграфе с учётом разрывов).</summary>
|
||||
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)
|
||||
@@ -152,7 +159,7 @@ internal static class MultiReplaceExt
|
||||
public int End { get; } = end;
|
||||
}
|
||||
|
||||
private class ParagraphStructure(string fullText, List<MultiReplaceExt.RunSegment> segments)
|
||||
private class ParagraphStructure(string fullText, List<RunSegment> segments)
|
||||
{
|
||||
public string FullText { get; } = fullText;
|
||||
public List<RunSegment> Segments { get; } = segments;
|
||||
@@ -182,18 +189,24 @@ internal static class MultiReplaceExt
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
/// <summary>Клонирует свойства параграфа, но не копирует SectionProperties.</summary>
|
||||
private static Paragraph CloneParagraphProperties(Paragraph original)
|
||||
{
|
||||
var newPara = new Paragraph();
|
||||
if (original.ParagraphProperties is not null)
|
||||
newPara.ParagraphProperties = (ParagraphProperties)original.ParagraphProperties.CloneNode(true);
|
||||
{
|
||||
var props = new ParagraphProperties();
|
||||
foreach (var child in original.ParagraphProperties.ChildElements)
|
||||
{
|
||||
if (child is not SectionProperties)
|
||||
props.AppendChild(child.CloneNode(true));
|
||||
}
|
||||
newPara.ParagraphProperties = props;
|
||||
}
|
||||
return newPara;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Строит параграф, содержащий копии всех элементов исходного параграфа,
|
||||
/// попадающих в текстовый диапазон [start, end).
|
||||
/// </summary>
|
||||
/// <summary>Строит параграф из текстового диапазона [start, end) исходного параграфа.</summary>
|
||||
private static Paragraph? BuildRangeParagraph(Paragraph original, ParagraphStructure structure, int start, int end)
|
||||
{
|
||||
if (start >= end) return null;
|
||||
@@ -207,7 +220,6 @@ internal static class MultiReplaceExt
|
||||
var seg = structure.Segments.FirstOrDefault(s => s.Run == run);
|
||||
if (seg is null)
|
||||
{
|
||||
// Run без текста (разрыв, поле) – копируем целиком, т.к. не можем привязать к позиции
|
||||
newPara.AppendChild(run.CloneNode(true));
|
||||
continue;
|
||||
}
|
||||
@@ -217,31 +229,27 @@ internal static class MultiReplaceExt
|
||||
|
||||
if (seg.Start >= start && seg.End <= end)
|
||||
{
|
||||
// Полностью внутри диапазона
|
||||
newPara.AppendChild(run.CloneNode(true));
|
||||
}
|
||||
else
|
||||
{
|
||||
// Частичное пересечение – обрезаем текст
|
||||
var runClone = (Run)run.CloneNode(true);
|
||||
foreach (var t in runClone.Elements<Text>().ToList())
|
||||
t.Remove();
|
||||
|
||||
int cutStart = Math.Max(start, seg.Start) - seg.Start;
|
||||
int cutEnd = Math.Min(end, seg.End) - seg.Start;
|
||||
string newText = seg.Text.Substring(cutStart, cutEnd - cutStart);
|
||||
runClone.AppendChild(new Text(newText));
|
||||
newPara.AppendChild(runClone);
|
||||
}
|
||||
int cutStart = Math.Max(start, seg.Start) - seg.Start;
|
||||
int cutEnd = Math.Min(end, seg.End) - seg.Start;
|
||||
string newText = seg.Text.Substring(cutStart, cutEnd - cutStart);
|
||||
runClone.AppendChild(new Text(newText));
|
||||
newPara.AppendChild(runClone);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// Не Run – копируем всегда (закладки, поля и т.п.), т.к. не можем определить позицию
|
||||
newPara.AppendChild(child.CloneNode(true));
|
||||
}
|
||||
}
|
||||
|
||||
// Удаляем пустые Run
|
||||
foreach (var run in newPara.Descendants<Run>().Where(r => !r.HasChildren).ToList())
|
||||
run.Remove();
|
||||
|
||||
@@ -251,18 +259,13 @@ internal static class MultiReplaceExt
|
||||
return newPara;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Строит параграф, содержащий все элементы исходного параграфа,
|
||||
/// которые находятся строго после указанной текстовой позиции,
|
||||
/// пропуская нетекстовые элементы до первого текстового сегмента.
|
||||
/// </summary>
|
||||
/// <summary>Строит параграф из текста после позиции position, пропуская нетекстовые элементы до первого текстового сегмента.</summary>
|
||||
private static Paragraph? BuildAfterParagraph(Paragraph original, ParagraphStructure structure, int position)
|
||||
{
|
||||
if (position >= structure.FullText.Length) return null;
|
||||
|
||||
var newPara = CloneParagraphProperties(original);
|
||||
|
||||
// Находим первый текстовый сегмент, который начинается на или после position
|
||||
var firstTextSeg = structure.Segments.FirstOrDefault(s => s.Start >= position);
|
||||
bool passedFirstText = false;
|
||||
|
||||
@@ -273,7 +276,6 @@ internal static class MultiReplaceExt
|
||||
var seg = structure.Segments.FirstOrDefault(s => s.Run == run);
|
||||
if (seg is null)
|
||||
{
|
||||
// Run без текста – добавляем только если уже прошли первый текстовый сегмент
|
||||
if (passedFirstText)
|
||||
newPara.AppendChild(run.CloneNode(true));
|
||||
continue;
|
||||
@@ -281,14 +283,12 @@ internal static class MultiReplaceExt
|
||||
|
||||
if (seg.Start >= position)
|
||||
{
|
||||
// Полностью после позиции
|
||||
newPara.AppendChild(run.CloneNode(true));
|
||||
if (seg == firstTextSeg)
|
||||
passedFirstText = true;
|
||||
}
|
||||
else if (seg.End > position)
|
||||
{
|
||||
// Частично пересекает – обрезаем текст
|
||||
var runClone = (Run)run.CloneNode(true);
|
||||
foreach (var t in runClone.Elements<Text>().ToList())
|
||||
t.Remove();
|
||||
@@ -299,11 +299,9 @@ internal static class MultiReplaceExt
|
||||
newPara.AppendChild(runClone);
|
||||
passedFirstText = true;
|
||||
}
|
||||
// seg.End <= position – игнорируем
|
||||
}
|
||||
else
|
||||
{
|
||||
// Не Run – добавляем только если уже прошли первый текстовый сегмент
|
||||
if (passedFirstText)
|
||||
newPara.AppendChild(child.CloneNode(true));
|
||||
}
|
||||
@@ -318,11 +316,7 @@ internal static class MultiReplaceExt
|
||||
return newPara;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Вставляет в параграф новый Run с текстом из ReplaceItem,
|
||||
/// копируя форматирование из сегмента, содержащего указанную позицию.
|
||||
/// Если BreakPage == true, добавляет отдельный Run с разрывом страницы.
|
||||
/// </summary>
|
||||
/// <summary>Вставляет Run с текстом из ReplaceItem, копируя форматирование из сегмента по позиции.</summary>
|
||||
private static void InsertFormattedRun(Paragraph para, ReplaceItem item, ParagraphStructure structure, int position)
|
||||
{
|
||||
var seg = structure.Segments.FirstOrDefault(s => position >= s.Start && position < s.End);
|
||||
@@ -333,42 +327,65 @@ internal static class MultiReplaceExt
|
||||
textRun.RunProperties = (RunProperties)seg.Run.RunProperties.CloneNode(true);
|
||||
textRun.AppendChild(new Text(item.Text ?? string.Empty));
|
||||
para.AppendChild(textRun);
|
||||
|
||||
if (item.BreakPage)
|
||||
{
|
||||
var breakRun = new Run(new Break() { Type = BreakValues.Page });
|
||||
if (seg.Run.RunProperties is not null)
|
||||
breakRun.RunProperties = (RunProperties)seg.Run.RunProperties.CloneNode(true);
|
||||
para.AppendChild(breakRun);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Добавляет содержимое одного параграфа в другой (клонируя элементы).
|
||||
/// </summary>
|
||||
/// <summary>Добавляет SectionProperties для смены ориентации, включая явный разрыв раздела.</summary>
|
||||
private static void AddSectionProperties(Paragraph para, PageBreakType splitValue)
|
||||
{
|
||||
if (para is null) return;
|
||||
PageOrientationValues orientation = splitValue == PageBreakType.NewLandscapeSection
|
||||
? PageOrientationValues.Landscape
|
||||
: PageOrientationValues.Portrait;
|
||||
|
||||
uint width, height;
|
||||
if (orientation == PageOrientationValues.Landscape)
|
||||
{
|
||||
width = 16838; // A4 landscape
|
||||
height = 11906;
|
||||
}
|
||||
else
|
||||
{
|
||||
width = 11906; // A4 portrait
|
||||
height = 16838;
|
||||
}
|
||||
|
||||
var sectionProps = new SectionProperties(
|
||||
new PageSize
|
||||
{
|
||||
Width = width,
|
||||
Height = height,
|
||||
Orient = orientation
|
||||
},
|
||||
new SectionType { Val = SectionMarkValues.NextPage } // явный разрыв раздела
|
||||
);
|
||||
|
||||
para.ParagraphProperties ??= new ParagraphProperties();
|
||||
para.ParagraphProperties.AppendChild(sectionProps);
|
||||
}
|
||||
|
||||
/// <summary>Сливает содержимое исходного параграфа в целевой (клонирует дочерние элементы).</summary>
|
||||
private static void MergeParagraph(Paragraph target, Paragraph source)
|
||||
{
|
||||
foreach (var child in source.ChildElements)
|
||||
target.AppendChild(child.CloneNode(true));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Основной алгоритм: обрабатывает все вхождения всех ключей из предоставленных словарей.
|
||||
/// </summary>
|
||||
/// <summary>Основной алгоритм множественной замены с поддержкой разрывов и смены ориентации.</summary>
|
||||
private static List<Paragraph>? ProcessMultiReplacements(
|
||||
Paragraph original,
|
||||
IEnumerable<KeyValuePair<string, IEnumerable<string>>>? stringReplacements,
|
||||
IEnumerable<KeyValuePair<string, IEnumerable<ReplaceItem>>>? itemReplacements,
|
||||
StringComparison comparisonType)
|
||||
{
|
||||
// 1. Собираем определения замен
|
||||
// 1. Сбор определений
|
||||
var definitions = new List<MatchDefinition>();
|
||||
if (stringReplacements is not null)
|
||||
{
|
||||
foreach (var kvp in stringReplacements)
|
||||
{
|
||||
if (string.IsNullOrEmpty(kvp.Key) || kvp.Value is null || kvp.Value.Count() == 0) continue;
|
||||
definitions.Add(new MatchDefinition(kvp.Key, [.. kvp.Value.Select(v => new ReplaceItem(v, false))]));
|
||||
var items = kvp.Value.Select(v => new ReplaceItem(v, PageBreakType.None));
|
||||
definitions.Add(new MatchDefinition(kvp.Key, items));
|
||||
}
|
||||
}
|
||||
if (itemReplacements is not null)
|
||||
@@ -379,7 +396,6 @@ internal static class MultiReplaceExt
|
||||
definitions.Add(new MatchDefinition(kvp.Key, kvp.Value));
|
||||
}
|
||||
}
|
||||
|
||||
if (definitions.Count == 0) return null;
|
||||
|
||||
// 2. Анализ структуры параграфа
|
||||
@@ -389,7 +405,7 @@ internal static class MultiReplaceExt
|
||||
string fullText = structure.FullText;
|
||||
if (fullText.Length == 0) return null;
|
||||
|
||||
// 3. Находим все вхождения всех ключей
|
||||
// 3. Поиск всех вхождений
|
||||
var matches = new List<Match>();
|
||||
foreach (var def in definitions)
|
||||
{
|
||||
@@ -405,22 +421,21 @@ internal static class MultiReplaceExt
|
||||
pos += def.Key.Length;
|
||||
}
|
||||
}
|
||||
|
||||
if (matches.Count == 0) return null;
|
||||
|
||||
// 4. Сортируем по позиции
|
||||
matches.Sort((a, b) => a.Start.CompareTo(b.Start));
|
||||
|
||||
// 5. Построение результирующих параграфов
|
||||
// 4. Построение результата
|
||||
var resultParas = new List<Paragraph>();
|
||||
Paragraph? currentPara = null;
|
||||
int currentPos = 0;
|
||||
PageBreakType? pendingOrientation = null; // отложенная смена ориентации для следующего параграфа
|
||||
|
||||
for (int i = 0; i < matches.Count; i++)
|
||||
{
|
||||
var match = matches[i];
|
||||
|
||||
// Текст перед текущим совпадением (от currentPos до match.Start)
|
||||
// Текст перед совпадением
|
||||
if (currentPos < match.Start)
|
||||
{
|
||||
var textPart = BuildRangeParagraph(original, structure, currentPos, match.Start);
|
||||
@@ -438,51 +453,113 @@ internal static class MultiReplaceExt
|
||||
}
|
||||
}
|
||||
|
||||
// Обрабатываем значения замены для этого совпадения
|
||||
var values = match.Definition.Values;
|
||||
var values = match.Definition.Values.ToList();
|
||||
if (values.Count == 0) continue;
|
||||
|
||||
// Первое значение – в текущий параграф (или создаём новый)
|
||||
if (currentPara is null)
|
||||
for (int vIdx = 0; vIdx < values.Count; vIdx++)
|
||||
{
|
||||
currentPara = CloneParagraphProperties(original);
|
||||
resultParas.Add(currentPara);
|
||||
var item = values[vIdx];
|
||||
|
||||
bool createNew = false;
|
||||
if (vIdx == 0)
|
||||
{
|
||||
// Создаём новый параграф, если у первого элемента есть разрыв/смена ориентации
|
||||
if (currentPara is null || item.SplitValue != PageBreakType.None)
|
||||
createNew = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
createNew = true;
|
||||
}
|
||||
|
||||
if (createNew)
|
||||
{
|
||||
var newPara = CloneParagraphProperties(original);
|
||||
resultParas.Add(newPara);
|
||||
currentPara = newPara;
|
||||
|
||||
// Если есть отложенная ориентация, применяем её к этому новому параграфу и сбрасываем
|
||||
if (pendingOrientation.HasValue)
|
||||
{
|
||||
AddSectionProperties(currentPara, pendingOrientation.Value);
|
||||
pendingOrientation = null;
|
||||
}
|
||||
|
||||
// Если это первый созданный параграф и у него есть разрыв/смена ориентации,
|
||||
// явно задаём книжную ориентацию, чтобы избежать наследования альбомной.
|
||||
if (resultParas.Count == 1 && vIdx == 0 && item.SplitValue != PageBreakType.None)
|
||||
{
|
||||
if (currentPara.ParagraphProperties?.GetFirstChild<SectionProperties>() is null)
|
||||
{
|
||||
AddSectionProperties(currentPara, PageBreakType.NewPortraitSection);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Вставляем текст
|
||||
InsertFormattedRun(currentPara, item, structure, match.Start);
|
||||
|
||||
// Обработка разрывов страниц (обычный PageBreak)
|
||||
if (item.SplitValue == PageBreakType.PageBreak)
|
||||
{
|
||||
var seg = structure.Segments.FirstOrDefault(s => match.Start >= s.Start && match.Start < s.End);
|
||||
var breakRun = new Run(new Break { Type = BreakValues.Page });
|
||||
if (seg is not null && seg.Run.RunProperties is not null)
|
||||
breakRun.RunProperties = (RunProperties)seg.Run.RunProperties.CloneNode(true);
|
||||
currentPara.AppendChild(breakRun);
|
||||
}
|
||||
// Смена ориентации – откладываем для следующего параграфа
|
||||
else if (item.SplitValue == PageBreakType.NewLandscapeSection ||
|
||||
item.SplitValue == PageBreakType.NewPortraitSection)
|
||||
{
|
||||
pendingOrientation = item.SplitValue;
|
||||
}
|
||||
}
|
||||
|
||||
values.ForFirstNext(first =>
|
||||
{
|
||||
InsertFormattedRun(currentPara, first, structure, match.Start);
|
||||
},
|
||||
next =>
|
||||
{
|
||||
// Остальные значения – в новые параграфы
|
||||
var newPara = CloneParagraphProperties(original);
|
||||
InsertFormattedRun(newPara, next, structure, match.Start);
|
||||
resultParas.Add(newPara);
|
||||
currentPara = newPara; // теперь текущий параграф – последний созданный
|
||||
});
|
||||
|
||||
currentPos = match.End;
|
||||
}
|
||||
|
||||
// Текст после последнего совпадения – используем BuildAfterParagraph, чтобы пропустить лишние разрывы
|
||||
// Текст после последнего совпадения
|
||||
if (currentPos < fullText.Length)
|
||||
{
|
||||
var textPart = BuildAfterParagraph(original, structure, currentPos);
|
||||
if (textPart is not null)
|
||||
{
|
||||
if (currentPara is null)
|
||||
if (pendingOrientation.HasValue)
|
||||
{
|
||||
currentPara = textPart;
|
||||
resultParas.Add(currentPara);
|
||||
// Создаём новый параграф для остатка и применяем ориентацию
|
||||
var newPara = CloneParagraphProperties(original);
|
||||
MergeParagraph(newPara, textPart);
|
||||
AddSectionProperties(newPara, pendingOrientation.Value);
|
||||
resultParas.Add(newPara);
|
||||
pendingOrientation = null;
|
||||
}
|
||||
else
|
||||
{
|
||||
MergeParagraph(currentPara, textPart);
|
||||
if (currentPara is null)
|
||||
{
|
||||
currentPara = textPart;
|
||||
resultParas.Add(currentPara);
|
||||
}
|
||||
else
|
||||
{
|
||||
MergeParagraph(currentPara, textPart);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Удаляем пустые параграфы
|
||||
// Если осталась отложенная ориентация (например, замена в конце документа, и не было создано новых параграфов),
|
||||
// создаём новый параграф с этой ориентацией (пустой, чтобы начать новую секцию)
|
||||
if (pendingOrientation.HasValue)
|
||||
{
|
||||
var newPara = CloneParagraphProperties(original);
|
||||
AddSectionProperties(newPara, pendingOrientation.Value);
|
||||
resultParas.Add(newPara);
|
||||
pendingOrientation = null;
|
||||
}
|
||||
|
||||
// Очистка пустых параграфов
|
||||
for (int i = resultParas.Count - 1; i >= 0; i--)
|
||||
{
|
||||
if (!resultParas[i].ChildElements.OfType<Run>().Any() && resultParas[i].ParagraphProperties is null)
|
||||
|
||||
Reference in New Issue
Block a user