loom & weft
Made for Swift.

YOUR FIRST THREAD

Swift 6.4+ • loom 0.2.1

On this page

Build with loom.

From a package dependency to your first interactive terminal app. loom is a Swift library for composing terminal interfaces from text, layouts, and widgets. Your application owns its state and input handling; loom turns that state into a frame and writes the changed cells through weft.

This guide targets the published loom 0.2.1 release and Swift 6.4+ on macOS 13+, Linux, and Windows. CI pins Swift 6.4.1. The matched weft 0.2.1 release supplies locale-independent Unicode widths, native Windows raw console sessions, and ConPTY child processes. See the platform guide for tested paths and Windows operation boundaries.

The feature guides cover the full widget and rendering surface. Unreleased PR #2 adds collection, text, plotting, and diff customization; those additions are not in 0.2.1. Browse the stable API or unreleased API for exact declarations and defaults.

Overview

loom is a library you add to a Swift project. It is not a command you install globally, and it does not require SwiftUI, AppKit, or an Xcode project.

Layer Responsibility
Your app State, commands, event handling, and when to redraw.
loom Frames, cell diffs, layouts, styled text, and widgets.
weft Terminal sessions, raw input, input events, and output.

The package and module name are lowercase: loom. Adding loom also brings in weft and Swift Markdown as dependencies. Common terminal types are available through import loom, so the first app needs only the loom product.

Installation

1. Install a compatible Swift toolchain

Follow the official Swift installation instructions for macOS , Linux, or Windows. Then check your active toolchain:

Terminal
swift --version

It must report Swift 6.4 or newer. For macOS projects, set your deployment target to macOS 13 or newer. Run interactive examples in Terminal, iTerm, or another terminal emulator with a real terminal attached to both input and output.

2. Add the package and its product

In Package.swift, add this entry to the package-level dependencies array:

Swift
.package(url: "https://github.com/standrze/loom.git", from: "0.2.1")

Then add the library product to the dependencies array of the target that will use it:

Swift
.product(name: "loom", package: "loom")

Import it in that target's Swift source:

Swift
import loom

SwiftPM downloads and builds the dependency when you run swift build or swift run. The from: requirement starts at 0.2.1 and allows versions from 0.2.1 up to, but excluding, 1.0.0; keep Package.resolved in version control for an executable app to record its selected versions. These are early APIs, so review release changes before updating.

Use loom in an existing project

Keep your existing targets and dependencies. Add loom to the package dependency list and to each target that imports it. Adding the repository alone does not make the module available to every target.

This complete manifest shows a command-line executable target named MyTerminalApp:

Swift
// swift-tools-version: 6.4

import PackageDescription

let package = Package(
    name: "MyTerminalApp",
    platforms: [.macOS(.v13)],
    dependencies: [
        .package(url: "https://github.com/standrze/loom.git", from: "0.2.1")
    ],
    targets: [
        .executableTarget(
            name: "MyTerminalApp",
            dependencies: [.product(name: "loom", package: "loom")]
        )
    ]
)

Place that target's Swift files under Sources/MyTerminalApp/. Build from the directory containing your manifest:

Terminal
swift build
swift run MyTerminalApp

If you use an Xcode project, add https://github.com/standrze/loom.git as a package dependency, select version 0.2.1 or later, and attach the loom product to your command-line target. The same import loom and API usage apply. Use a compatible Swift toolchain and launch the interactive executable in a terminal.

When to depend on weft directly

TerminalSession, TerminalEvents, ANSIBackend, Key, Point, and Rect are among the types exposed by loom. You do not need a second product dependency just to use those aliases.

If you need other weft APIs, such as TerminalCapabilities, add the weft package and its product explicitly to your target before writing import weft.

Your first loom app

Build a small counter that responds to keyboard input, redraws when the terminal is resized, and restores the terminal when it exits.

Download the complete first-loom-app project. It includes the source, manifest, resolved dependencies, and formatting settings. Unzip it, open its folder in a terminal, and run swift run first-loom-app. Or create the same project by following the steps below.

1. Create the project folders

Terminal
mkdir -p first-loom-app/Sources/FirstLoomApp
cd first-loom-app

The finished source tree is:

Output
first-loom-app/
├── Package.swift
└── Sources/
    └── FirstLoomApp/
        └── FirstLoomApp.swift

2. Create Package.swift

The package exposes an executable named first-loom-app. The executable target uses the lowercase loom library product.

Package.swift
// swift-tools-version: 6.4

import PackageDescription

let package = Package(
    name: "first-loom-app",
    platforms: [.macOS(.v13)],
    products: [
        .executable(name: "first-loom-app", targets: ["FirstLoomApp"])
    ],
    dependencies: [
        .package(url: "https://github.com/standrze/loom.git", from: "0.2.1")
    ],
    targets: [
        .executableTarget(
            name: "FirstLoomApp",
            dependencies: [.product(name: "loom", package: "loom")]
        )
    ]
)

3. Create Sources/FirstLoomApp/FirstLoomApp.swift

Copy the complete program below. It uses @main, so name the file FirstLoomApp.swift, not main.swift. If you started with swift package init, replace its generated entry point rather than keeping two.

FirstLoomApp.swift
import loom

@main
struct FirstLoomApp {
    @MainActor
    static func main() async throws {
        let session = try TerminalSession(
            options: TerminalOptions(alternateScreen: true, hideCursor: true))
        defer { session.close() }

        let input = TerminalEvents(session: session)
        defer { input.stop() }

        let size = TerminalSession.size()
        var terminal = Terminal(backend: ANSIBackend(), width: size.width, height: size.height)
        var count = 0

        func render(_ frame: inout Frame) {
            let text = """
                First loom app

                Count: \(count)

                Up / +: add   Down / -: subtract
                q / Esc / Ctrl-C: quit

                Terminal: \(frame.area.width) x \(frame.area.height) cells
                """
            let paragraph = Paragraph(
                TextLayout(text, width: frame.area.width),
                style: Style(foreground: .rgb(255, 189, 102)))
            frame.render(paragraph, in: frame.area)
        }

        // Return true when the user asks to quit.
        func handleKey(_ key: Key) -> Bool {
            switch key {
            case .up, .character("+"):
                count += 1
            case .down, .character("-"):
                count -= 1
            case .character("q"), .escape, .interrupt, .endOfInput:
                return true
            default:
                break
            }
            return false
        }

        try terminal.draw(render)
        for try await batch in input.events {
            for event in batch {
                switch event {
                case .signal:
                    return
                case let .resize(width, height):
                    terminal.resize(width: width, height: height)
                case let .text(text):
                    // A single read can contain several typed characters.
                    for character in text {
                        if handleKey(.character(String(character))) { return }
                    }
                default:
                    if let keyboard = event.keyboardEvent, keyboard.kind != .release {
                        if handleKey(keyboard.key) { return }
                    }
                }
            }
            try terminal.draw(render)
        }
    }
}

4. Run it

Terminal
swift run first-loom-app

The first run resolves and compiles the packages. After that, you should see a counter in amber text:

Output
First loom app

Count: 0

Up / +: add   Down / -: subtract
q / Esc / Ctrl-C: quit

Terminal: 80 x 24 cells

Press Up or + to increment, Down or - to decrement, and q, Escape, or Ctrl-C to quit. Resize the window to see the cell dimensions update. Your actual dimensions will depend on the terminal window.

5. Build a release executable

Terminal
swift build -c release
.build/release/first-loom-app

Run the binary on a compatible system. The platforms entry does not cross-compile the app; build for the operating system and architecture you intend to use.

How the app works

Open a session and arrange cleanup

TerminalSession owns the terminal modes. alternateScreen: true draws on a separate screen; hideCursor: true hides the cursor while the counter is active. session.close() restores the session on normal exits and thrown errors.

The example registers defer { session.close() } first and defer { input.stop() } second. Swift runs defers in reverse order, so input stops before the session closes. Keep that ordering when you extend the app.

Read input on the main actor

TerminalEvents exposes an asynchronous stream of batches of input events. The example uses @MainActor to match that API and keeps all app state in one serial flow. A read can contain several typed characters, which is why .text is processed character by character.

Use event.keyboardEvent to normalize keyboard events and ignore key-release events when responding to presses. Handle resize, paste, mouse, and signal events according to your application's needs. The counter deliberately does not interpret pasted text as commands.

Use one input source for a session. Do not call session.poll concurrently with TerminalEvents, and do not open a second terminal session while the first is active.

Draw the entire logical frame

Terminal.draw clears the next logical frame, calls your rendering closure, compares the result with the previous frame, and writes the difference. Each closure should describe the whole visible UI, including content that has not changed. Unchanged cells and an unchanged cursor produce no output.

Frame.area is the drawable rectangle. TextLayout wraps the string to its width; Paragraph paints that layout. The counter rebuilds its small text layout on each draw. Larger apps can cache layouts until the text or available width changes.

Resize and redraw

On .resize(width, height), call terminal.resize(width:height:), update any cached text or document layouts, and draw again. Recompute layout from frame.area rather than storing a fixed 80 × 24 size.

The sample draws once before waiting for input, then once after each batch. loom does not impose a frame timer or an application architecture. If you add animation, your app schedules the next draw.

Keep output under one owner

Avoid print() while loom is controlling the screen: extra output can move the cursor and invalidate its picture of the terminal. Render status messages inside the UI or write logs to a file. If something else writes to the terminal, call terminal.invalidate() before the next draw to force a full repaint.

Major features

Rendering and layout

Feature Main APIs What it gives you
Frame rendering Terminal, Frame, Buffer, CellDiff Build complete frames, send changed cells, place the cursor, and repaint after an output failure.
Draw statistics RenderStats.changedCells, RenderStats.bytes Inspect how much a draw changed and emitted.
Cell-based layouts Layout, Constraint, Rect Split horizontal or vertical regions using lengths, percentages, ratios, minimums, maximums, or weighted fills.
Styling Style, StylePatch, Color Color, inherited/reset attributes, underline color, hidden and blinking text.
Viewports and tests Viewport, RenderTerminal, TestBackend Fullscreen, fixed, inline/scrollback placement, snapshots, and headless presentation.
Layout detail Flex, LayoutCache, LayoutSpacing Flexible placement, bounded caller-owned caching, gaps, and overlap.
Custom widgets Widget.render(in:buffer:) Paint your own component into a bounded terminal region.

Coordinates and widths describe terminal cells, not pixels, bytes, or Swift string indices. A Unicode grapheme can occupy more than one cell. Use loom's text geometry instead of assuming String.count equals the displayed width.

Text and content

Feature Main APIs What it gives you
Styled text TextSpan, TextLayout, Paragraph Mixed styles, word or grapheme wrapping, scrolling, selection, and source-range mapping.
Markdown MarkdownText.spans, MarkdownPalette Headings, lists, quotes, fenced code, emphasis, and links, parsed with Swift Markdown.
Transcripts and documents TextDocument, DocumentView Append, replace, collapse, hide, search, select, and reflow entries with cached layouts.
Editing LineEditor, TextInput Cursor movement, selections, insertion, deletion, undo/redo, and a rendered input field.

Use the public MarkdownText.spans entry point. Markdown tables, HTML, and unsupported constructs remain literal; images are not fetched or drawn as graphics. Syntax highlighting for code is supplied by your application through MarkdownPalette.codeHighlighter.

Widgets and motion

Feature Main APIs What it gives you
Bordered regions Panel, PanelTitle, BorderLayer, BorderSymbols Rich top/bottom titles, custom/merged borders, padding, and shadows.
Collections List, Table, SelectionState, TableState Stable IDs, reverse lists, measured row heights, margins, shared hit testing, and multiselect.
Common controls Gauge, LineGauge, Tabs, Clear, Fill Progress, stable-ID tabs, and clipped background operations.
Plots and calendar Sparkline, BarChart, Chart, Canvas, MonthlyCalendar Trends, grouped bars, coordinate drawing, and Gregorian date grids.
Interaction FocusState, KeyMap, ScrollState, Scrollbar Nested focus scopes, remappable bindings/help, scrolling and dragging.
Menus Menu, PopupMenu Selected rows, item hit testing, and popup presentation; your app performs actions.
Optional desktop components Desktop, WindowFrame Icon and window geometry, hit testing, and window movement helpers.
Character art CharacterArt Preserve artwork spacing without paragraph wrapping.
Animation samples SymbolAnimation, DiagonalShine Spinner, activity, pulse, and sheen frames; your app owns timing and redraws.

Widgets paint; they do not run an event loop. Your application decides what a click means, which field has focus, and when menu selection changes.

Terminal capabilities

Rendering can be configured for color depth, synchronized output, and hyperlinks. Terminal defaults to true color, synchronized output enabled, and hyperlinks disabled; it does not infer these settings automatically. If your app needs environment-based choices, use weft's TerminalCapabilities.inferred() and pass the selected settings to the renderer. Capabilities are hints, and terminal/font behavior can differ.

Put the building blocks together

Add a bordered Markdown region

Inside a rendering closure, split the available cells, draw a panel, then render text into its inner rectangle:

Swift
let regions = Layout(.vertical, [.length(3), .fill(1)]).split(frame.area)
let panel = Panel(borderType: .rounded, title: "Messages")
frame.render(panel, in: regions[1])

let content = panel.inner(regions[1])
let spans = MarkdownText.spans("Hello, **Swift**.")
let text = TextLayout(spans, width: content.width, wrapping: .word)
frame.render(Paragraph(text), in: content)

The first region reserves three rows; the second takes the remaining rows. Paint your own header into regions[0] if needed. Panel.inner subtracts border and padding cells so content does not overwrite the border.

Render an editable field

Keep the editor in your application state, outside the draw closure:

Swift
var editor = LineEditor()
editor.insert("Hello, 世界")

Then render that state and expose its cursor inside the closure:

Swift
let input = TextInput(editor, placeholder: "Message")
frame.render(input, in: frame.area)
frame.cursor = input.cursor(in: frame.area)

Route text, paste, and .character events to editor.insert. editor.handle covers Left, Right, Home, End, Backspace, Delete, and newline; use moveVertical(by:width:) for vertical movement. Selection commands, undo/redo shortcuts, focus, and submission remain application decisions. A TextInput alone does not read the keyboard.

Troubleshooting

Symptom What to check
Package requires a newer Swift tools version Run swift --version and select a Swift 6.4+ toolchain. Installing a toolchain and selecting it are separate steps.
no such module 'loom' Add both the package dependency and the loom product to the target that imports it. Use lowercase import loom.
macOS deployment target mismatch Set the consuming target to macOS 13 or newer.
@main conflicts with top-level code Use FirstLoomApp.swift and remove the generated extra entry point. Do not combine this example with a main.swift entry point.
requiresTTY, no interactive input, or failure in an output pane Run the executable in a real terminal. Do not pipe its standard input or output.
Typed characters are ignored Handle .text batches as well as normalized keyboard events. Do not treat a whole batch as one key.
Old text stays on screen or output appears scrambled Describe the whole frame on every draw. Avoid outside writes, or call terminal.invalidate() after them.
Layout stops matching a resized window Resize the renderer and reflow cached text/documents before drawing again.
Terminal looks broken after a forced kill Try reset or stty sane. Normal cleanup cannot run after a force kill; retain the sample's deferred cleanup for normal exits.

For dependency issues, first inspect the SwiftPM error and your manifest. swift package resolve resolves dependencies; swift package clean clears build products without removing your source or dependency declaration.

Platform and release notes

loom 0.2.1 CI and weft 0.2.1 CI passed macOS, Linux under C and C.UTF-8, and Windows jobs. Interactive PTY checks run on macOS/Linux. weft separately exercises Windows console restoration/input and real ConPTY child processes. The downloadable starter is built and exercised locally on macOS; the library matrix does not establish starter behavior on every emulator. Windows canonical input and POSIX shell suspension are explicitly unsupported; native console input reconstructs UTF-8/VT rather than promising original Kitty or bracketed-paste framing.

The unreleased customization guide describes repeated list prefixes, column flex, border-independent titles, per-line alignment, additional markers, legend limits/positions, filled lines, and explicit diff policies. Existing defaults and shared Unicode geometry are preserved. No world-map dataset is bundled.

Where to go next

loom API documentationBrowse every type, method, property, and example. Search the full reference.

loom is licensed under Apache 2.0. Dependencies retain their own licenses. This guide documents the 0.2.1 API; check release notes before adopting a newer release.

Ready to make it yours?

Download the starter