Skip to main content

Getting started with .NET

Twip.Core is the editor without a window: EditorSession owns one document, with its selection, undo history, state and events. Twip.WinForms adds DocumentEditor, a control that presents a session and takes its input. Install them first (see Installation).

A session​

// An unattached session is headless: a console app, a service, a test.
await using var session = new EditorSession(new EditorSessionOptions(Author: new Author("Report bot")));

var opened = await session.OpenAsync("template.docx");
foreach (var warning in opened.Warnings) Console.WriteLine($"{warning.Code}: {warning.Message}");

// One method per command. Each completes after its change commits, with State at that revision.
await session.Commands.MoveSelectionAsync(MoveUnit.Document, Direction.Forward);
await session.Commands.InsertTextAsync("Generated by Twip.");
await session.Commands.SelectAllAsync();
await session.Commands.SetBoldAsync(true);
Console.WriteLine(session.State.Formatting.Bold.IsOn); // True

// A batch is atomic: one transaction and one undo step, or nothing when an operation fails.
await session.BatchAsync([EditorOperation.SetBold(false), EditorOperation.SetAlignment(ParagraphAlignment.Center)], "Center");

await session.SaveAsync("report.docx");
await session.ExportPdfAsync("report.pdf");

OpenAsync and SaveAsync take a path or a Stream; saving to a path replaces the file safely. SaveAsync writes DOCX, and ExportPdfAsync writes PDF, with an optional open password and keywords (PdfOptions). Both return the revision they captured and any fidelity warnings. To convert documents without a session, on many threads at once, see PDF conversion.

Every command is one ...Async method on session.Commands, named after the command (setBold is SetBoldAsync). They act on the selection and complete after the change commits. Setters take a value: there are no toggles. Lengths are Length values in points (Length.FromInches(0.5), Length.FromCm(2)), colours are ColorValue, and option objects are records (IndentOptions, FieldOptions). EditorOperation has one factory per command, for BatchAsync.

session.State is the latest immutable EditorState: the selection, formatting, each command's availability, the undo history, page counts, view and review state. Values that can differ across the selection are FormatValue<T>: Kind is Uniform, Mixed or Unavailable, and IsOn is true only for a uniform true.

State.Pages.Count counts the pages laid out so far. The engine lays out the rest in the background, a few milliseconds at a time on the engine thread, attached or not; each slice that adds pages, and the last one, which sets Pages.Complete, raises StateChanged with the same revision. State.Dialogs says which dialogs open now (Table properties needs a table, Picture size and Alt text an object), and State.Selection.Text is the selection as plain text, or null past 10,000 characters.

Errors​

Expected failures throw EditorException, whose Code says why. A failed open keeps the current document. Cancellation throws OperationCanceledException, and file access keeps the usual IOException types.

try
{
await session.OpenAsync(upload);
}
catch (EditorException e) when (e.Code == EditorErrorCode.ImportFailed)
{
Console.WriteLine("Not a document Twip can read. The session keeps its current document.");
}

Events​

Events are standard EventHandler<T> events on the session. They're raised on the attached control's UI thread or, when no control is attached, on an SDK-owned serial executor, so handlers never race each other. Each event's arguments carry the Snapshot of state at its revision. See Events.

// Coalesced: the latest snapshot after one or more changes. Bind a toolbar here.
session.StateChanged += (_, e) => Console.WriteLine($"page {e.Snapshot.Pages.Current} of {e.Snapshot.Pages.Count}");

// Exactly one per commit, in order.
session.DocumentChanged += (_, e) => Console.WriteLine($"{e.Record.Revision} {e.Record.Origin} {e.Record.Label}");

// Keys the application owns, such as Ctrl+S.
session.HostCommandRequested += (_, e) =>
{
if (e.Command == HostCommand.Save) save();
};

session.Warning += (_, e) => Console.WriteLine(e.Warning.Message);

// A handler's exception lands here instead of breaking the session. A fault has IsFatal set.
session.Faulted += (_, e) => Console.Error.WriteLine($"{(e.IsFatal ? "fault" : "handler")}: {e.Exception.Message}");

WinForms​

DocumentEditor is a WinForms control. It creates its own session (or takes yours: then disposing the control only detaches it), draws the pages and the engine's rulers, and handles the keyboard, mouse, IME, clipboard, scrolling and accessibility. State is a DocumentEditorState: bindable properties for a toolbar and status bar, raised on the UI thread. Bind a toggle button's CheckState to BoldCheckState, ItalicCheckState or UnderlineCheckState (Indeterminate where the selection is mixed), and its Enabled to a command's Can property (CanSetBold, CanPaste, CanUndo, ...); IsEnabled(CommandId) covers every command.

sealed class MainForm : Form
{
readonly DocumentEditor editor = new() { Dock = DockStyle.Fill, ShowHorizontalRuler = true };
readonly ToolStripButton bold = new("Bold");
readonly ToolStripStatusLabel page = new();

public MainForm()
{
var toolbar = new ToolStrip();
toolbar.Items.Add(bold);
var status = new StatusStrip();
status.Items.Add(page);
Controls.Add(editor);
Controls.Add(toolbar);
Controls.Add(status);

// DocumentEditorState raises PropertyChanged on the UI thread: bind to it, or read it there.
bold.DataBindings.Add(nameof(bold.CheckState), editor.State, nameof(editor.State.BoldCheckState));
bold.DataBindings.Add(nameof(bold.Enabled), editor.State, nameof(editor.State.CanSetBold));
editor.State.PropertyChanged += (_, _) => page.Text = $"Page {editor.State.CurrentPage} of {editor.State.PageCount}";
// Setters take a value: pass the opposite of what the state shows.
bold.Click += async (_, _) => await editor.Commands.SetBoldAsync(!editor.State.Bold.IsOn);

editor.Session.HostCommandRequested += async (_, e) =>
{
if (e.Command == HostCommand.Save) await editor.SaveAsync("report.docx");
};
editor.Session.ContextMenuRequested += (_, e) => ShowMenu(e.Menu, Point.Round(e.Location));
Load += async (_, _) => await editor.OpenAsync("report.docx");
}

void ShowMenu(Twip.ContextMenu menu, Point at)
{
var strip = new ContextMenuStrip();
foreach (var item in menu.Items.OfType<CommandItem>())
{
strip.Items.Add(item.Label, null, async (_, _) => await editor.Session.Menus.InvokeAsync(item.Action)).Enabled = item.Enabled;
}
strip.Show(editor, at);
}
}

The control's view settings are properties: ShowHorizontalRuler, ShowVerticalRuler, RulerUnit, TabSelector, MarkupPaneWidth, and BackColor for the background around the pages (the paper stays white). WinForms shows no system context menu, so ContextMenuRequested is where you show yours. Comment balloons are your own controls, placed by AttachBalloon: see Review. The caret blink, overlay colours and the GPU: see Rendering.

Hosting a session in another UI framework​

Twip.Hosting is the contract a control is built on, for WPF, WinUI, Avalonia or a custom surface. You implement IEditorHostAdapter: a dispatcher for the UI thread, and what the session needs from the window (present a frame, set the cursor, capture the pointer, the clipboard, the caret for the IME, scrolling, tooltips and accessibility).

// What a UI framework's control gives the session. The session calls these on the dispatcher's thread.
sealed class CanvasAdapter(IEditorDispatcher dispatcher, ICanvas canvas) : IEditorHostAdapter
{
public IEditorDispatcher Dispatcher => dispatcher;
public void RequestRender() => canvas.Invalidate(); // the control's paint then calls EditorHost.Render
public void Present(in FrameView frame) => canvas.Blit(frame.Pixels, frame.Width, frame.Height, frame.Stride);
public void SetCursor(EditorCursor cursor) => canvas.Cursor = cursor;
public void CapturePointer() => canvas.Capture(true);
public void ReleasePointer() => canvas.Capture(false);
public void SetClipboard(ClipboardContent content) => canvas.Clipboard = content;
public ValueTask<ClipboardContent?> GetClipboardAsync() => ValueTask.FromResult(canvas.Clipboard);
public void SetCaret(CaretInfo caret) => canvas.ImeWindow = caret.Bounds; // where the IME shows its candidates
public void ScrollTo(double x, double y) => canvas.ScrollTo(x, y);
public void ShowTooltip(TooltipInfo? tooltip) => canvas.Tooltip = tooltip;
public void UpdateAccessibility(AccessibleNode tree) => canvas.Accessibility = tree;
public void Announce(string text) => canvas.Announce(text);
}

session.Attach(adapter) returns an EditorHost. Forward raw input to it and call Render() from your paint. The engine recognises every gesture, draws the rulers into the frame and hit-tests them, so a control has no editing, gesture or ruler logic of its own. One host is attached at a time; disposing it detaches, and the session keeps its document, selection and history.

using EditorHost host = session.Attach(new CanvasAdapter(dispatcher, canvas));
host.OnResize(800, 600, 96);
host.OnFocus(true);

// Forward raw input. The engine does the rest: keys, gestures, rulers, IME.
host.OnKey(EditorKey.KeyB, KeyModifiers.Control, out bool handled); // Ctrl+B
host.OnText("Hello");
host.OnPointer(PointerKind.Down, 120, 80, PointerButton.Primary, clicks: 2, KeyModifiers.None);
host.OnWheel(0, -120, KeyModifiers.None);

host.Render(); // inside the control's paint: the session calls Present with the frame

Native AOT​

Both packages are trim and AOT safe. The native engine ships in Twip.Core for win-x64, win-arm64, linux-x64 and linux-arm64.