Repository navigation
Source Lines and Two Panes
English | Русский
Every element of the document knows the source lines it came from, and the viewer converts source lines to positions on the screen and back. That is enough to keep the viewer in step with an editor, to mark lines, or to show two versions of a document side by side.

Lines are counted from 0, unlike the line numbers on the screen. A fractional part
is a part of a line: 12.5 is the middle of line 12.
| Task | Member |
|---|---|
| where a line is |
GetSourceLineOffset(line) — a position in the viewer's coordinates |
| what line is at a position | GetSourceLineAt(offset) |
| what line is visible |
GetVisibleSourceLine(fraction) — the line at a fraction of the height of the scrolling; the ViewportChanged event tells when to ask again |
| scroll to a line |
ScrollToSourceLine(line, fraction) — the line stands at a fraction of the height of the scrolling |
| a range of lines in the text map |
TextMap.RangeOfSourceLines(start, end) — for marks or selecting |
| the line of a text map position | TextMap.SourceLineOf(position) |
The scrolling around the viewer must scroll by pixels: a ScrollViewer does; a list needs
VirtualizingPanel.ScrollUnit="Pixel".
A viewer and a TextBox editor scroll together: MdTextBoxLines finds the source lines of the editor by
the positions of characters, so wrapped lines do not get in the way, and MdScrollSync keeps the same
source line at the anchor of both. The one the user works with leads.
MainWindow.xaml, the window handles Loaded and Unloaded:
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<TextBox x:Name="Editor"
AcceptsReturn="True"
TextWrapping="Wrap"
FontFamily="Consolas"
VerticalScrollBarVisibility="Auto"
TextChanged="OnEditorChanged" />
<ScrollViewer Grid.Column="1">
<md:MarkdownViewer x:Name="Viewer" Margin="24,16" />
</ScrollViewer>
</Grid>MainWindow.xaml.cs, in the window class (using Beresta.Markdown.Wpf.Scrolling;):
private MdScrollSync? _sync;
private void OnLoaded(object sender, RoutedEventArgs e)
=> _sync = new MdScrollSync(new MdTextBoxLines(Editor), Viewer, MdLineMap.Identity);
private void OnUnloaded(object sender, RoutedEventArgs e)
{
_sync?.Dispose();
_sync = null;
}
private void OnEditorChanged(object sender, TextChangedEventArgs e) => Viewer.Markdown = Editor.Text;MdTextBoxLines also tells where the visible source lines of the editor stand: VisibleRows(element)
gives each line with the top and the height of the screen line it starts at, in the coordinates of your
element — enough for line numbers in a column next to the editor. Anything else with source lines in its
own scrolling scrolls together with a viewer once it implements IMdScrollSide; the viewer is a side too.
Which lines of two versions match is told by MdLineMap: pairs of anchor lines — for example, the
unchanged lines of a diff — with lines between anchors mapped linearly; two copies of one text need no
anchors, MdLineMap.Identity. The diff itself is computed by your application. With the map, a diff
side by side can be shown three ways:
| Way | What the user sees |
|---|---|
MdScrollSync |
each pane keeps its height and its scrolling; the pane the user works with leads, and the other one follows so that matching lines stand at the same height at a fixed point |
MdPaneAligner |
matching lines stand at the same height along the whole document, and opposite a change the other pane gets an empty place |
| by hand | your own logic on GetVisibleSourceLine, ScrollToSourceLine and Gaps
|
Both helpers take two viewers and a map, detach on Dispose() and take a new map in Map — after a new
diff you do not create them again. They are two different things: do not put MdScrollSync on aligned
panes.
MainWindow.xaml, two viewers in two scrolling panes; the window handles Loaded and Unloaded:
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<ScrollViewer>
<md:MarkdownViewer x:Name="LeftViewer" Markdown="{Binding Old}" Margin="24,16" />
</ScrollViewer>
<ScrollViewer Grid.Column="1">
<md:MarkdownViewer x:Name="RightViewer" Markdown="{Binding New}" Margin="24,16" />
</ScrollViewer>
</Grid>MainWindow.xaml.cs, in the window class (using Beresta.Markdown.Wpf.Scrolling; using Beresta.Markdown.Wpf.Selection;):
private MdScrollSync? _sync;
private void OnLoaded(object sender, RoutedEventArgs e)
{
var left = (LeftViewer.Markdown ?? string.Empty).Split('\n');
var right = (RightViewer.Markdown ?? string.Empty).Split('\n');
var matches = MatchLines(left, right);
var anchors = matches.SelectMany(match => new[]
{
((double)match.Left, (double)match.Right),
(match.Left + 1.0, match.Right + 1.0)
});
_sync = new MdScrollSync(LeftViewer, RightViewer, new MdLineMap(anchors));
MarkChanges(LeftViewer, left.Length, matches.Select(match => match.Left), "Removed");
MarkChanges(RightViewer, right.Length, matches.Select(match => match.Right), "Added");
}
private void OnUnloaded(object sender, RoutedEventArgs e)
{
_sync?.Dispose();
_sync = null;
}
private static List<(int Left, int Right)> MatchLines(string[] left, string[] right)
{
var matches = new List<(int Left, int Right)>();
var next = 0;
for (var i = 0; i < left.Length; i++)
{
var j = Array.IndexOf(right, left[i], next);
if (j >= 0)
{
matches.Add((i, j));
next = j + 1;
}
}
return matches;
}
private static void MarkChanges(MarkdownViewer viewer, int lineCount, IEnumerable<int> matched, string style)
=> viewer.MarkLayers.Add(new MdMarkLayer("Diff")
{
Marks = Enumerable.Range(0, lineCount)
.Except(matched)
.Select(line => new MdMark(line, line) { Style = style })
.ToList()
});Each matched line is anchored at its start and at its end, so it stays aligned along its whole height.
MatchLines is a naive stand-in that finds equal lines in order; a real application takes the matches
from its diff. The changed lines are marks across the whole
width; lines between the panes are drawn by your application — see
Coordinates.
MdPaneAligner puts empty places so that every pair of the map stands at the same height
in both panes. The panes usually stand in one shared scrolling — then nothing has to be synchronized; if
each has its own, the aligner keeps their offsets equal. The places are computed again when heights of
blocks become known and when a new text comes; blocks out of view have estimated heights, and their places
are corrected while scrolling without the visible part jumping.
MainWindow.xaml, one scrolling for both panes:
<ScrollViewer>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<md:MarkdownViewer x:Name="LeftViewer" Markdown="{Binding Old}" Margin="24,16" />
<md:MarkdownViewer x:Name="RightViewer" Grid.Column="1" Markdown="{Binding New}" Margin="24,16" />
</Grid>
</ScrollViewer>MainWindow.xaml.cs, the same as above, with the aligner instead of the synchronization:
private MdPaneAligner? _aligner;
private void OnLoaded(object sender, RoutedEventArgs e)
{
// the map and the marks — as in the example above
_aligner = new MdPaneAligner(LeftViewer, RightViewer, new MdLineMap(anchors));
}
private void OnUnloaded(object sender, RoutedEventArgs e)
{
_aligner?.Dispose();
_aligner = null;
}Gaps of a viewer is a list of MdGap(line, height): an empty place of that height before a source
line. It stands before the outermost element that starts at the line: between blocks, before a list
item, before a block in a quote or a callout, before a table row, between lines of a paragraph or code —
in code also in the column of line numbers. At the closing fence of code the place stands inside the
code, under its last line. Elements are not cut. If nothing starts at the line — the
underline === of a heading, a delimiter of a table — the place stands at the nearest boundary of the
block. A place is not text: it is not selected or copied and has no number in the margin. Its look is the
theme key Md.Gap.Brush, a hatching by default. A place inside a block that is not created yet counts in
the estimate of its height. With JoinSoftLineBreaks
a place at a line inside a paragraph stands at the boundary of the paragraph.
MainWindow.xaml.cs (using Beresta.Markdown.Wpf.Scrolling;):
Viewer.Gaps = [new MdGap(12, 40), new MdGap(30, 18.5)];Beresta.Markdown.Wpf · Issues · MIT License
Basics
- Getting Started
- How It Renders
- Supported Markdown
- Settings and Hooks
- Scrolling and Virtualization
- Comparison
Working with Text
Appearance
Integration
- Application Links
- Images
- Untrusted Text
- Task Lists
- Source Lines and Two Panes
- Coordinates
- Live Preview
Editing
Your Own Syntax
Ready-made Extensions
Основы
- Начало работы
- Как рисует вьюер
- Что поддерживается
- Настройки и перехват
- Прокрутка и виртуализация
- Сравнение
Работа с текстом
Оформление
Встраивание в приложение
- Ссылки приложения
- Картинки
- Чужой текст
- Списки задач
- Строки исходника и две панели
- Координаты
- Живой предпросмотр
Правка
Свой синтаксис
Готовые расширения