WinForms method reference
Documentation index · Properties · Types
Extensions and editorial review
ConfigureExtensionsAsync, RegisterTokensAsync, RegisterSuggestionsAsync, UnregisterSuggestionAsync, SetContextActionsAsync, SetCodeLanguageAsync, BeginContextActionAsync, ApplyContextActionAsync and CancelContextActionAsync provide embedded content and host actions. ConfigureReviewAsync, AddCommentAsync, ReplyToCommentAsync, ResolveCommentAsync, ReattachCommentAsync, AcceptChangeAsync, RejectChangeAsync, ShowReviewAsync, SetReviewViewAsync, GetReviewStateAsync, GetReviewPackageAsync, LoadReviewPackageAsync and ExportPublicationAsync provide the author/editor cycle. See the full contract and examples.
All methods below belong to CODE.Editor.WinForms.TextEditor unless otherwise noted. Call them from the owning UI thread and await them. Most return Task because they cross the WebView2 bridge; a Task return does not imply that long-running preview/image work has finished unless the method's contract says so. Rejections surface as task exceptions. Use ordinary try/catch in host event handlers rather than blocking the UI thread.
Initialization, loading and persistence
| Signature | Contract |
|---|---|
Task InitializeAsync() |
Idempotently await initialization; normally starts automatically with the control handle |
Task SetEditorTextAsync(string value) |
Load a serialized value with current options; await acceptance; resets history/bookmarks |
Task LoadAsync(string value, EditorFormat format = Markdown, EditorViewMode mode = Visual, EditorLanguage language = Markdown) |
Set format/view/language and load; PlainText/RichJson force their compatible view |
Task<string> GetEditorTextAsync() |
Retrieve committed serialization; no full policy save validation |
Task<EditorSnapshot> GetSnapshotAsync() |
Retrieve a validated save snapshot |
Task FlushAsync() |
Await current queue and request committed text; does not save to storage |
Task<bool> MarkSavedAsync(EditorSnapshot snapshot) |
Acknowledge a successful save; false if revision/session no longer current or content unsaveable |
Task ConvertFormatAsync(EditorFormat format, UnsupportedContentHandling handling = Reject) |
Convert Markdown/HTML, reset history, then synchronize accepted options through a snapshot |
For saving, always persist before calling MarkSavedAsync. ConvertFormatAsync supports Markdown/Html destinations, not arbitrary enum-to-enum conversion. Setting Format on its own is not an explicit conversion operation. See the save contract.
Selection and bookmarks
| Signature | Contract |
|---|---|
Task<EditorSelection> GetSelectionAsync() |
Flat UTF-16 endpoints for current view |
Task SetSelectionAsync(int anchor, int head) |
Select/focus a logical range |
Task<string> GetSelectedTextAsync() |
Selected plain model text |
Task<string> CaptureBookmarkAsync() |
Capture an opaque selection token |
Task<bool> RestoreBookmarkAsync(string token) |
Restore/focus if still valid |
Task ReleaseBookmarkAsync(string token) |
Release token when finished |
Rich offsets are not Markdown/HTML source offsets. A bookmark can map through edits but is invalid after load. A bookmark alone does not guard against asynchronously overwriting changed text.
Formatting and ordinary commands
| Signature | Contract |
|---|---|
Task ExecuteAsync(EditorCommand command) |
Run a parameterless typed command |
Task UndoAsync() |
Undo |
Task RedoAsync() |
Redo |
Task FormatSelectionAsync(TextMark mark, bool? enabled = null) |
Toggle bold/italic/underline/strike/code/superscript/subscript in Visual and Markdown Source; explicit on/off supported |
Task SetContentFontAsync(ContentFont font) |
Set curated content font in either view; Default clears |
Task SetContentColorAsync(ContentColor color) |
Set curated text color in either view; Default clears |
Task SetContentBackgroundColorAsync(ContentBackgroundColor color) |
Set highlight/background in either view; Default clears |
Task SetContentFontSizeAsync(ContentFontSize size) |
Set supported content size in either view; Default clears |
Task<SelectionFormattingState> GetSelectionFormattingAsync() |
Query inline formats, block/list context and indent/history capabilities together |
Task<CommandState> QueryCommandStateAsync(BlockStyle style) |
Query a heading, paragraph, list, quote or code block state |
Task SetLinkAsync(string? url) |
Set safe link URL; null removes |
Task SetBlockStyleAsync(BlockStyle style) |
Set supported rich block type |
Task ReplaceSelectionAsync(string text) |
Undoable literal replacement |
Task ReplaceSelectionSourceAsync(string source) |
Undoable native Markdown/HTML source insertion without text encoding; works in Source and Visual |
Task ReplaceRangeAsync(int from, int to, string text, int? expectedRevision = null) |
Replace flat range, optionally checking revision |
Task ApplyTransactionAsync(EditorTransaction transaction) |
Guarded atomic Source-only batch |
Task GoToLineAsync(int line) |
One-based line navigation, clamped to the document |
Source Markdown formatting supports Bold/Italic with toggle or explicit on/off semantics. Rich fonts/colors/sizes require compatible policy and Visual mode. Use DisplayFontFamily/DisplayFontSize for display-only changes.
Use ReplaceSelectionAsync("<img ...>") when the tag should appear as literal text. Use ReplaceSelectionSourceAsync("<img src=\"https://example.com/cover.jpg\" alt=\"Cover\">") when it is document markup. Source uses the document's storage syntax (Markdown or HTML), retains the supplied characters and replaces the current selection in one undo step. In Visual mode, the resulting source must satisfy the editing policy; unsupported content stays inert. PasteHtmlAsync imports supported HTML and converts it to the storage format, so it may normalize the original markup. SetSelectionAsync only selects a range.
EditorCommand includes Undo, Redo, Indent, Outdent, ClearFormatting, ToggleTask, ToggleComment, DeleteRow, DeleteColumn, DeleteTable, ExitStructure, and Newline. Parameter-bearing commands have typed methods rather than a magic string API in C#.
Omitting expectedRevision (or passing null) applies the range replacement without a revision guard. Supply a snapshot revision for delayed edits; stale guards reject without changing content. C# language enums use explicit wire mappings, including JavaScript → javascript.
Search
| Signature | Contract |
|---|---|
Task<SearchMatch[]> FindAsync(string query, SearchOptions? options = null) |
Literal matches with optional case/whole-word filtering |
Task SelectMatchAsync(SearchMatch match) |
Select and reveal a returned match |
Task ReplaceAllAsync(string query, string replacement, SearchOptions? options = null) |
Source-only literal replacement |
Task ShowFindAsync(bool replace = false, string? query = null) |
Open internal find/replace popup, optionally seed query |
Task CloseFindAsync() |
Close popup |
Ctrl+F and Ctrl+H invoke this internal UI. There is no built-in Ctrl+G dialog; a host can offer one and call GoToLineAsync. Find/replace policy flags affect the popup. No regular-expression search is implemented.
Lists and tables
| Signature | Contract |
|---|---|
Task InsertTableAsync(int rows = 2, int columns = 2) |
Insert rectangular table in Visual |
Task InsertRowAsync(bool before = false) |
Insert relative to current row |
Task InsertColumnAsync(bool before = false) |
Insert relative to current column |
Task AlignColumnAsync(TableAlignment alignment) |
Apply Left/Center/Right to current column |
Task RestartNumberingAsync(int start = 1) |
Restart supported ordered-list numbering |
Task PasteTsvAsync(string text) |
Import tab-separated rows/cells |
Delete row/column/table and indent/outdent use ExecuteAsync enum values. Table commands depend on the current cell; they do not accept a table ID. Refer to lists and tables for navigation and structural constraints.
Images and clipboard
| Signature | Contract |
|---|---|
Task InsertImageAsync(string source, string alternativeText = "") |
Insert a durable URL reference in Visual |
Task RemoveImageAsync(string id) |
Remove model image and cancel related pending work as appropriate |
Task RetryImageAsync(string id) |
Retry using retained file/external source; may fail if original unavailable |
Task PasteHtmlAsync(string html) |
Import supported HTML into Visual |
Task PasteTextAsync(string text) |
Paste literal text through current mode |
Task CopyAsync() |
Copy Unicode text and supported HTML; selected images can also supply binary representations |
Task CutAsync() |
Copy supported representations, then delete the unchanged selection; no-op for read-only |
Task PasteAsync() |
Paste supported image markup, image data, HTML or text; empty/unsupported clipboard is a no-op |
Task<JsonElement> GetPendingImagesAsync() |
Current non-ready image records, including errors |
PasteHtmlAsync is not a source HTML insertion method; use PasteTextAsync for literal markup in Source. Native clipboard helpers are text-only, while keyboard clipboard interaction can carry HTML/files. A completed paste method does not imply all image uploads are finished. Image file events and storage examples are documented in images and clipboard.
Querying state and managing the surface
| Signature | Contract |
|---|---|
Task<CommandState> QueryCommandStateAsync(TextMark mark) |
General enabled flag and bool/mixed mark state |
Task<CommandState> QueryCommandStateAsync(EditorCommand command) |
General command state, including history availability |
Task<JsonElement> GetCapabilitiesAsync() |
Effective policy including resolved feature flags |
Task<EditorDiagnostic[]> GetDiagnosticsAsync() |
Current policy violations |
Task RebuildSurfaceAsync() |
Replace DOM adapter while keeping model/history/selection |
Task FocusEditorAsync() |
Focus editor |
Task ResizeEditorAsync() |
Schedule layout measurement |
The enabled flag is not a complete structural preflight for every operation. Still handle exceptions and unsupported/no-op results. CommandState.Active is JsonElement; inspect its ValueKind rather than assuming every state is Boolean.
Preview
| Signature | Contract |
|---|---|
Task RefreshPreviewAsync() |
Schedule new preview for current content/external data |
Task<string?> GetPreviewHtmlAsync() |
Last accepted preview body HTML, or null before a render |
RefreshPreviewAsync completes after scheduling, not after the renderer and image loads complete. Observe PreviewRendered for an accepted result. Preview HTML is not the stored document and can include internal anchors. Use the preview hook to preprocess or provide custom HTML, and PreviewCss to style it.
Methods on EditorOptions
SetFeature(EditorFeature feature, bool enabled) sets an explicit override; ResetFeatures() removes all explicit overrides. These are synchronous settings mutations whose application to an initialized editor is queued. ToString() returns a format/view label. PropertyChanged follows INotifyPropertyChanged. Other options are properties described in the property reference.
Image and annotation methods: ResizeImageAsync(blockId, width?, height?), MoveImageAsync(blockId, targetId, after), GetReviewAnnotationsAsync(), GetReviewAnchorRectsAsync(id) and SelectReviewAnnotationAsync(id). CopyAsync publishes Unicode text and Windows HTML; PasteAsync offers both representations. See chapter 20.
UI theme and bubble methods: SetUIThemeAsync(theme?), GetUIThemeAsync(), SetCommentExpandedAsync(id, expanded), ToggleCommentAsync(id) and GetCommentPresentationAsync(). A null/omitted theme resets to defaults. Examples and styling hooks.
SetUIStringsAsync(EditorUIStrings? strings = null) validates and applies wording (null resets); GetUIStringsAsync() returns current overrides; GetUIStringCatalogAsync() returns the complete shared English catalog. See localization.