Repository navigation
Selection
English | Русский
Text in the viewer is selected like in one document, not like in separate text boxes: one selection runs across paragraphs, lists, tables and code, including the blocks that are scrolled out of view.

| Action | Result |
|---|---|
| drag | selects from the press point to the pointer; past the edge of the scrolling the page scrolls along |
| Shift + click | moves the end of the selection to the click |
| double click | selects a word |
| triple click | selects a paragraph, a heading, a table cell or a code block |
| Ctrl+A | selects the whole document |
| Ctrl+C, Ctrl+Shift+C | copies — see Copying |
A selection does not start on interactive elements: buttons, check boxes, text boxes, lists, scroll
bars. An element of yours that handles the mouse itself gets the same treatment with
sel:MdSelection.IsInteractive.
Your widget template (see Extensions):
<Canvas sel:MdSelection.IsInteractive="True" MouseLeftButtonDown="OnSketchMouseDown" />The selection is a range of positions in the text map — the text of the whole document as one
string, Viewer.TextMap.Text. It is the text you see: no Markdown markup, blocks separated by line
breaks, table cells by tabs; an image or an atomic widget is one character MdTextMap.ObjectMark. The
map covers the blocks that are not created too, so you search it with plain string methods. Every new
Markdown value builds a new map.
A position of the map leads back to the source: TextMap.SourceLineOf(position) is its source line,
TextMap.SourceOffsetOf(position) — its place in the source text. In text the source has as it is the
place is the same character; where the drawing differs from the source — escapes, entities, a link
without its address — it is the start of that piece; in a code block — the same line and column.
TextMap.PositionOfSource(offset) goes back: the position of the map at a place of the source, null
where the place is not drawn — the address of a link, a fence of code.
MainWindow.xaml.cs, the place in the source under the mouse:
var place = Viewer.GetPositionFromPoint(e.GetPosition(Viewer), snapToText: true) is { } position
? Viewer.TextMap.SourceOffsetOf(position)
: null;Select(start, length), SelectAll() and ClearSelection() change the selection;
ScrollToRange brings it into view.
MainWindow.xaml.cs, in the window class (using Beresta.Markdown.Wpf.Selection;):
private void SelectFirst(string word)
{
var index = Viewer.TextMap.Text.IndexOf(word, StringComparison.OrdinalIgnoreCase);
if (index >= 0)
{
Viewer.Select(index, word.Length);
Viewer.ScrollToRange(new MdTextRange(index, word.Length), 0.3);
}
}| Member | What it gives |
|---|---|
SelectionStart, SelectionLength
|
the range in the text map; dependency properties, so you can bind to them |
SelectedText |
the selected text as the user sees it |
SelectedMarkdown |
the selection written as Markdown — see Copying |
SelectionChanged |
the event after the selection moves |
MainWindow.xaml, a status line next to the viewer:
<TextBlock Text="{Binding SelectionLength, ElementName=Viewer, StringFormat='Selected: {0}'}" />A new text keeps the selection on its words while its blocks exist — see places that survive a new text; when they disappear, the selection is cleared.
A position of the text map is valid only in its own map, and every new Markdown builds a new one.
TextMap.Track(range) remembers a piece so that TextMap.Find(tracked) finds it in the map of any later
text — by the blocks its ends stand in and by the text around them. If the block is gone or its text is
rewritten so that neither end finds its words, the piece is lost: null. If only one end finds its
place or the text of the piece is deleted, an empty piece stays there. The selection of the viewer is
cleared in both cases.
MainWindow.xaml.cs, in the window class (using Beresta.Markdown.Wpf.Selection;):
private MdTrackedRange? _remembered;
private void Remember()
=> _remembered = Viewer.TextMap.Track(new MdTextRange(Viewer.SelectionStart, Viewer.SelectionLength));
private void ShowNewText(string text)
{
Viewer.Markdown = text;
if (_remembered is not null && Viewer.TextMap.Find(_remembered) is { } range)
{
Viewer.Select(range.Start, range.Length);
}
}Source lines are tracked the same way: TextMap.TrackSourceLines(start, end) remembers a range of lines,
and TextMap.Find(trackedLines) gives its lines in a new text — by the blocks they stand in and the text
of the lines. A layer of marks with FollowsText moves its marks
this way by itself.
IsSelectionEnabled="False" clears the selection, and neither the mouse, nor Ctrl+A, nor Select
selects anything until it is back. Ctrl+A then goes to the application: a command binding of
ApplicationCommands.SelectAll on a window or a panel around the viewer gets it.
<md:MarkdownViewer Markdown="{Binding Text}" IsSelectionEnabled="False" />The selection color is the theme key Md.Selection.Brush or the SelectionBrush property of a
viewer. The brush is drawn over the text, so keep it semi-transparent.
GetRangeRects(range) returns the rectangles of a range line by line, GetRangeBounds(range) their
common frame; both are in the viewer's coordinates. They exist only for created blocks: a range out of
view gives an empty list and Rect.Empty. That is enough to put a button next to the selection. The
same in the coordinates of an element of yours — see Coordinates.
MainWindow.xaml, the viewer and a canvas over it in one grid cell:
<ScrollViewer>
<Grid Margin="24,16">
<md:MarkdownViewer x:Name="Viewer"
Markdown="{Binding Text}"
SelectionChanged="OnSelectionMoved"
ViewportChanged="OnSelectionMoved" />
<Canvas>
<Button x:Name="AskButton" Content="Explain" Visibility="Collapsed" Focusable="False" />
</Canvas>
</Grid>
</ScrollViewer>MainWindow.xaml.cs, in the window class (using Beresta.Markdown.Wpf.Selection;):
private void OnSelectionMoved(object? sender, EventArgs e)
{
var bounds = Viewer.GetRangeBounds(new MdTextRange(Viewer.SelectionStart, Viewer.SelectionLength));
AskButton.Visibility = bounds.IsEmpty ? Visibility.Collapsed : Visibility.Visible;
if (!bounds.IsEmpty)
{
Canvas.SetLeft(AskButton, bounds.Left);
Canvas.SetTop(AskButton, bounds.Bottom + 4);
}
}The opposite direction is GetPositionFromPoint(point, snapToText): the text map position under a
point. With snapToText: false a point outside the text gives null; with true — the nearest text.
Together with the source lines of the map it tells what line of the source is under the mouse.
MainWindow.xaml.cs, a MouseMove handler of the viewer; StatusText is a TextBlock of the
window:
private void OnViewerMouseMove(object sender, MouseEventArgs e)
{
StatusText.Text = Viewer.GetPositionFromPoint(e.GetPosition(Viewer), snapToText: false) is { } position
&& Viewer.TextMap.SourceLineOf(position) is { } line
? $"Source line {line + 1}"
: string.Empty;
}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
Основы
- Начало работы
- Как рисует вьюер
- Что поддерживается
- Настройки и перехват
- Прокрутка и виртуализация
- Сравнение
Работа с текстом
Оформление
Встраивание в приложение
- Ссылки приложения
- Картинки
- Чужой текст
- Списки задач
- Строки исходника и две панели
- Координаты
- Живой предпросмотр
Правка
Свой синтаксис
Готовые расширения