Skip to content

Code Blocks

Pavel edited this page Oct 21, 2026 · 3 revisions

English | Русский

A fenced code block gets a header with its language — the first word after the opening fence — and monospace text that scrolls sideways instead of wrapping words. While the pointer is over the block, a copy button shows in its corner. Code indented by four spaces is drawn the same way, without the header. A block in csv or tsv can be drawn as a table by the ready-made tables from CSV.

A code block with the copy button

The copy button

The button copies the whole code, whatever is selected: as plain text, as a Markdown code block and as HTML <pre><code class="language-…">. Before that it raises DataObject.Copying, like the copying of a selection — see Copying. After a click the icon turns into a check mark for a moment.

ShowCodeCopyButton hides the button. It is an inherited attached property: set it on a viewer, or once on a window or a list of viewers.

A window or a user control:

<md:MarkdownViewer Markdown="{Binding Text}" ShowCodeCopyButton="False" />

<ItemsControl ItemsSource="{Binding Messages}" md:MarkdownViewer.ShowCodeCopyButton="False" />

The tooltip and the name for screen readers is the theme key Md.CodeBlock.CopyToolTip; the icons are the Geometry keys Md.CodeBlock.CopyIcon and Md.CodeBlock.CopiedIcon. In a template of your own the button is the part PART_Copy, and CodeBlockPresenter.IsCopied tells that the code has just been copied.

Line numbers inside code

ShowCodeLineNumbers numbers the lines of every code block from 1. It is inherited as well.

A window or a user control:

<md:MarkdownViewer Markdown="{Binding Text}" ShowCodeLineNumbers="True" />

Numbers of the source lines of the whole document are a separate feature — see Line Numbers.

The look

Colors, font and frame are the keys Md.CodeBlock.* — see Theming. The template is the style Md.CodeBlock.Style or the CodeBlockTemplate of a style provider — see Styles and Templates.

Syntax highlighting

A highlighter colors the pieces of the code by the language of the block — the first word after the opening fence: keywords, types, strings, numbers, comments. By default the viewer has no highlighter, and the code is drawn in one color; the editor highlights by itself.

Highlighted code

The highlighting does not change the text: selection, search and copying see the code as it is. A block is highlighted when the text is parsed, and a block that did not change is not highlighted again. If the highlighter throws, the exception goes to RenderFailed, and the block is drawn in one color.

The AvalonEdit highlighter

MdAvalonCodeHighlighter from the editor package highlights with the definitions built into AvalonEdit: C#, JavaScript, HTML, XML, CSS, C++, Java, PHP, PowerShell, Python, SQL, VB, JSON, diff and Markdown. It knows the usual names of these languages — cs, csharp, js, ts, xml, xaml, html, css, cpp, java, php, ps1, powershell, vb, py, sql, json, diff and others — and the file extensions AvalonEdit knows. TypeScript is highlighted as JavaScript, C — as C++.

The editor uses it unless CodeHighlighter is set. To use it in a viewer, add the package Beresta.Markdown.Wpf.Editor — see Editor — and set CodeHighlighter. It is an inherited attached property: set it on a viewer, or once on a window or a list of viewers.

A window or a user control:

<md:MarkdownViewer Markdown="{Binding Text}"
                   CodeHighlighter="{x:Static md:MdAvalonCodeHighlighter.Instance}" />

<ItemsControl ItemsSource="{Binding Messages}"
              md:MarkdownViewer.CodeHighlighter="{x:Static md:MdAvalonCodeHighlighter.Instance}" />

A highlighter of your own

A highlighter is an IMdCodeHighlighter: Highlight(language, code) returns the pieces of the code as MdCodeSpan — the start, the length and the look — or null when it does not know the language. Where pieces overlap, the later one wins. IMdBackgroundSafe tells that the highlighter may be called from a background thread: without it, a long text is parsed on the interface thread — see Live Preview.

LogHighlighter.cs, a class in your application; it colors the lines of a log with errors and leaves the other languages to AvalonEdit:

using Beresta.Markdown.Wpf;
using Beresta.Markdown.Wpf.Editor;
using Beresta.Markdown.Wpf.Extensions;

public sealed class LogHighlighter : IMdCodeHighlighter, IMdBackgroundSafe
{
    public IReadOnlyList<MdCodeSpan>? Highlight(string language, string code)
    {
        if (language != "log")
        {
            return MdAvalonCodeHighlighter.Instance.Highlight(language, code);
        }

        var spans = new List<MdCodeSpan>();
        var start = 0;
        foreach (var line in code.Split('\n'))
        {
            if (line.Contains("ERROR"))
            {
                spans.Add(new(start, line.Length, "Deleted"));
            }

            start += line.Length + 1;
        }

        return spans;
    }
}

A look X is drawn with the theme style Md.Code.X.Style, a style of Span. The theme has the looks Keyword, Type, String, Number, Comment, Preprocessor, Tag, Attribute, Punctuation, Inserted and Deleted; their colors are the keys Md.Code.<Look>.Foreground — see Theming. A look of your own needs its style.

App.xaml, after the theme of the viewer:

<Style x:Key="Md.Code.Warning.Style" TargetType="Span">
    <Setter Property="Foreground" Value="DarkOrange" />
    <Setter Property="FontWeight" Value="SemiBold" />
</Style>

The editor draws the source of the code with the same styles.

To draw code with a highlighting control of your own instead, replace CodeBlockTemplate with a template around it, or turn blocks of one language into a widget of yours with an extension — see Extensions. A block whose code is drawn without md:MdTextBlock is selected as a whole.

Beresta.Markdown.Wpf

Basics

Working with Text

Appearance

Integration

Editing

Your Own Syntax

Ready-made Extensions


По-русски

Основы

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

Оформление

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

Правка

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

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

Clone this wiki locally