Skip to content

Search Highlighting

Porohkun edited this page Oct 23, 2026 · 9 revisions

English | Русский

The viewer finds places in the text and paints them: found text, changed lines, comments of your application. The search field, buttons and pop-ups stay yours; the viewer gives a ready search, layers of marks and the answer to what lies under the mouse.

Matches of a search with the current one in its own color

Search

MdSearch searches the text of a viewer: it marks every match, marks the current one in its own color and scrolls to it. The search field and the buttons are your controls; MdSearch reports the changes of its properties, so you can bind them to it.

MainWindow.xaml:

<DockPanel>
    <StackPanel x:Name="SearchBar" DockPanel.Dock="Top" Orientation="Horizontal">
        <TextBox Width="200"
                 Text="{Binding Query, UpdateSourceTrigger=PropertyChanged}"
                 KeyDown="OnSearchKeyDown" />
        <CheckBox Content="Match case" IsChecked="{Binding MatchCase}" />
        <CheckBox Content="Whole word" IsChecked="{Binding WholeWord}" />
        <TextBlock Text="{Binding Count, StringFormat='{}{0} found'}" />
    </StackPanel>
    <ScrollViewer>
        <md:MarkdownViewer x:Name="Viewer" Markdown="{Binding Text}" Margin="24,16" />
    </ScrollViewer>
</DockPanel>

MainWindow.xaml.cs, in the window class (using System.Windows.Input; using Beresta.Markdown.Wpf.Search;):

private readonly MdSearch _search;

public MainWindow()
{
    InitializeComponent();
    _search = new MdSearch(Viewer);
    SearchBar.DataContext = _search;
}

private void OnSearchKeyDown(object sender, KeyEventArgs e)
{
    if (e.Key != Key.Enter)
    {
        return;
    }

    if (Keyboard.Modifiers.HasFlag(ModifierKeys.Shift))
    {
        _search.Previous();
    }
    else
    {
        _search.Next();
    }
}
Member What it does
Query, MatchCase, WholeWord what to find; a new value searches at once, the match at the old place or after it becomes the current one, and the viewer scrolls to it if it is out of view
Next(), Previous() make the next or the previous match current, past the end — from the other end, and scroll to it if it is out of view
Matches, Count, CurrentIndex, Current the matches in the text map, their number, the current one; CurrentIndex counts from 0, -1 — no matches
Brush, CurrentBrush brushes of the matches; not set — the theme styles Found and Current
Dispose() removes the marks of the search from the viewer

A new text is searched again, and the current match stays near its old place. The search ignores case by its own rules, without a culture; a whole word has no letter, digit or _ on either side.

Search in a feed

In a chat or a feed every message is a viewer of its own. MdFeedSearch.Query set on the list marks the matches in every created viewer inside — without a current match and without scrolling: which message to go to, your application decides by its own data. MdFeedSearch.MatchCase and MdFeedSearch.WholeWord are set the same way.

MainWindow.xaml (xmlns:md="https://github.com/porohkun/Beresta.Markdown.Wpf"):

<DockPanel>
    <TextBox x:Name="SearchBox" DockPanel.Dock="Top" />
    <ListBox ItemsSource="{Binding Messages}"
             md:MdFeedSearch.Query="{Binding Text, ElementName=SearchBox}"
             VirtualizingPanel.ScrollUnit="Pixel">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <md:MarkdownViewer Markdown="{Binding Text}" />
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</DockPanel>

Search and replace in the editor

MdSourceSearch from the editor package searches the source of a MarkdownEditor, not its drawn text, so it finds what the drawing hides too: the address of a link, a sign of markup. The matches are painted under the source of the edited blocks and as marks in the drawing — where the found text is drawn — with the same theme styles Found and Current. It is bound like MdSearch, and it replaces.

MainWindow.xaml.cs, in the window class (using Beresta.Markdown.Wpf.Editor;):

private readonly MdSourceSearch _search;

public MainWindow()
{
    InitializeComponent();
    _search = new MdSourceSearch(Editor);
    SearchBar.DataContext = _search;
}

private void OnReplace(object sender, RoutedEventArgs e) => _search.Replace(ReplaceBox.Text);

private void OnReplaceAll(object sender, RoutedEventArgs e) => _search.ReplaceAll(ReplaceBox.Text);
Member What it does
Query, MatchCase, WholeWord what to find; a new value searches at once, and the match at the caret or after it becomes the current one
Next(), Previous() make the next or the previous match current: in Blocks and Full it is selected in the source and its blocks become edited, in View and Controls the drawing scrolls to it
Replace(text) replaces the current match and goes to the next one
ReplaceAll(text) replaces every match in one step of undo and returns how many were replaced
Matches, Count, CurrentIndex, Current the matches as places of the source — MdSourceSpan with lines from 0 —, their number, the current one
Dispose() removes the marks and the background of the search

The matches move with every edit of the source at once, without waiting for the drawing; a match the edit touches goes away, and the source is searched anew once the edits pause for a quarter of a second. In View nothing is replaced. A match is found in the drawing by TextMap.PositionOfSource(offset) — see Selection.

Layers of marks

A mark is a piece of the text map or a range of source lines with a look. The marks of one owner — the search, a diff, the comments of your application — live in their own layer, MdMarkLayer. The layers in MarkLayers are drawn in their order, and the selection is drawn over all of them. A mark has no controls in it: what reacts to the mouse is yours — see Coordinates.

The kinds of marks

Kind What is drawn
Fill the text is filled
Underline a line under the text
Frame a frame around the text, its own for every screen line
Row the lines across the whole width of the document; a row of a table — from its border to its border
Bar a bar in the margin, to the right of the line numbers
Icon a figure (Geometry) in the margin, to the left of the number of the first line
Caret a vertical line at the start of the piece; for an empty piece — at its place

A mark takes a piece of the text map — new MdMark(range, kind) — or source lines — new MdMark(startLine, endLine, kind); either fits any kind: lines of a fill become their text, a piece of a row becomes its lines. An empty piece is drawn only by a caret: it shows the place where the other version has text. Bars and icons are drawn only while the margin is shown, ShowSourceLineNumbers="True". Tag keeps any data of yours: it comes back with the mark from what is under the mouse.

MainWindow.xaml.cs, review comments that underline their text (using Beresta.Markdown.Wpf.Selection;):

private readonly MdMarkLayer _comments = new("Comments");

public MainWindow()
{
    InitializeComponent();
    Viewer.MarkLayers.Add(_comments);
}

private void AddComment(string comment)
{
    var range = new MdTextRange(Viewer.SelectionStart, Viewer.SelectionLength);
    _comments.Marks = [.. _comments.Marks, new MdMark(range, MdMarkKind.Underline) { Style = "Comment", Tag = comment }];
}

The look

A brush is set directly, Brush, or by the name of a theme style, Style. A name takes the brush of a fill and of rows from the key Md.Mark.<Name>.Brush, and the brush of underlines, frames, carets, bars and icons from Md.Mark.<Name>.LineBrush — without it, the same fill brush. Brushes of names follow a switch of the theme. The theme has the names Found, Current, Added, Removed, Changed and Comment; a name of your own is two keys in your resources. Marks are drawn over the text, so keep fill brushes semi-transparent.

App.xaml, in the resources of the application:

<SolidColorBrush x:Key="Md.Mark.Spelling.Brush" Color="#E53935" Opacity="0.15" />
<SolidColorBrush x:Key="Md.Mark.Spelling.LineBrush" Color="#E53935" />

The thickness of underlines, frames and carets, the width of bars and the size of icons are the theme keys Md.Mark.UnderlineThickness, Md.Mark.FrameThickness, Md.Mark.CaretThickness, Md.Mark.BarWidth, Md.Mark.IconSize.

When the text changes

A new Markdown builds a new text map. A layer with FollowsText = true moves its marks to the new text the way the selection moves — see places that survive a new text — and drops the marks whose text is gone; Changed of the layer tells about it. Other layers keep their marks as they are: their owner computes them again, as the search does.

Decorations

Decorations is the lowest layer: a list of MdDecoration(range, brush) that fill pieces of the text map; it is replaced as a whole. It stays for simple cases; a layer does all it does and more.

What is under the mouse

GetMarksAt(point) returns the marks under a point of the viewer in the order they are drawn, each with its layer: over the text — the marks of the text under the point and the rows of its line; in the margin — the bars and icons of its line. GetMarksAt(position) does the same for a position of the text map. That is how your application adds items to its context menu and shows tooltips; the viewer itself does not react to clicks on marks.

MainWindow.xaml.cs, the comment under the mouse in a tooltip; the viewer has MouseMove="OnViewerMouseMove":

private void OnViewerMouseMove(object sender, MouseEventArgs e)
{
    Viewer.ToolTip = Viewer.GetMarksAt(e.GetPosition(Viewer))
        .Where(hit => hit.Layer == _comments)
        .Select(hit => hit.Mark.Tag)
        .FirstOrDefault();
}

Beresta.Markdown.Wpf

Basics

Working with Text

Appearance

Integration

Editing

Your Own Syntax

Ready-made Extensions


По-русски

Основы

Работа с текстом

Оформление

Встраивание в приложение

Правка

Свой синтаксис

Готовые расширения

Clone this wiki locally