Documentation
¶
Overview ¶
Package peb implements Pencode Extension Binary protocol version 20. Frames and payloads use little endian integers; stdout is reserved for frames.
Index ¶
- Constants
- Variables
- func DecodeFailure(data []byte) (string, error)
- func DecodeSetting[T any](values SettingValues, id string) (value T, err error)
- func EncodeActionChange(dst []byte, v ActionChange) ([]byte, error)
- func EncodeActionContext(dst []byte, v ActionContext) ([]byte, error)
- func EncodeContributions(dst []byte, v Contributions) ([]byte, error)
- func EncodeEditorMessage(dst []byte, v EditorMessage) ([]byte, error)
- func EncodeEditorReply(dst []byte, v EditorReply) ([]byte, error)
- func EncodeFailure(dst []byte, message string) ([]byte, error)
- func EncodeFileChanges(dst []byte, v FileChanges) ([]byte, error)
- func EncodeHello(dst []byte, v Hello) ([]byte, error)
- func EncodeLifecycleEvent(dst []byte, v LifecycleEvent) ([]byte, error)
- func EncodeLifecycleReply(dst []byte, v LifecycleReply) ([]byte, error)
- func EncodeSettingValues(dst []byte, values SettingValues) ([]byte, error)
- func EncodeUI(dst []byte, v UI) ([]byte, error)
- func EncodeUIEvent(dst []byte, v UIEvent) ([]byte, error)
- func Serve(input io.Reader, output io.Writer, contributions Contributions) error
- func ServeEditors(input io.Reader, output io.Writer, contributions Contributions, ...) error
- func ServeExtension(input io.Reader, output io.Writer, contributions Contributions, ...) error
- func ValidateSettings(settings []Setting) error
- type Action
- type ActionChange
- type ActionContext
- type ActionLocation
- type ActionPublisher
- type Capability
- type Contributions
- type DebugAdapter
- type DocumentSelector
- type EditorBinding
- type EditorEvent
- type EditorMessage
- type EditorReply
- type EditorView
- type FileChanges
- type FileEvent
- type FileOperation
- type Font
- type Frame
- type Handlers
- type Hello
- type IconRule
- type IconTheme
- type Kind
- type LanguagePack
- type LanguageServer
- type LifecycleEvent
- type LifecycleKind
- type LifecycleReply
- type Match
- type NotificationSeverity
- type Reader
- type Setting
- type SettingOption
- type SettingType
- type SettingValues
- type Shortcut
- type Theme
- type UI
- type UIEvent
- type UIKind
- type UIPlacement
- type UIPosition
- type ViewPatch
- type ViewReceiver
- type ViewRegion
- type ViewRegionSplitter
- type Writer
Constants ¶
const ( Version = 20 HeaderSize = 20 MaxPayload = 4 << 20 MaxString = 64 << 10 MaxItems = 16384 )
const MaxDocument = 2 << 20
const MaxSessions = 256
Variables ¶
var ErrProtocol = errors.New("peb: invalid protocol message")
var ErrViewBase = errors.New("peb: missing view patch base")
ErrViewBase asks the session to request a full view through resync.
Functions ¶
func DecodeFailure ¶
func DecodeSetting ¶
func DecodeSetting[T any](values SettingValues, id string) (value T, err error)
DecodeSetting reads a typed value from a complete settings snapshot.
func EncodeActionChange ¶
func EncodeActionChange(dst []byte, v ActionChange) ([]byte, error)
func EncodeActionContext ¶
func EncodeActionContext(dst []byte, v ActionContext) ([]byte, error)
func EncodeContributions ¶
func EncodeContributions(dst []byte, v Contributions) ([]byte, error)
func EncodeEditorMessage ¶
func EncodeEditorMessage(dst []byte, v EditorMessage) ([]byte, error)
func EncodeEditorReply ¶
func EncodeEditorReply(dst []byte, v EditorReply) ([]byte, error)
func EncodeFileChanges ¶
func EncodeFileChanges(dst []byte, v FileChanges) ([]byte, error)
func EncodeHello ¶
Encode functions reset and reuse dst. Decoders own their returned strings.
func EncodeLifecycleEvent ¶
func EncodeLifecycleEvent(dst []byte, v LifecycleEvent) ([]byte, error)
func EncodeLifecycleReply ¶
func EncodeLifecycleReply(dst []byte, v LifecycleReply) ([]byte, error)
func EncodeSettingValues ¶
func EncodeSettingValues(dst []byte, values SettingValues) ([]byte, error)
EncodeSettingValues reuses dst. Values must be validated against their schema before publication; the peer validates JSON when decoding the snapshot.
func Serve ¶
Serve registers static resources, then waits for Shutdown. Logs belong on stderr. The host closes the process after registration; no per-file RPC runs.
func ServeEditors ¶
func ServeEditors(input io.Reader, output io.Writer, contributions Contributions, handle func(EditorMessage) (EditorReply, error)) error
ServeEditors shares a stateless handler across document views until Shutdown. Stateful editors use Handlers.NewEditor with ServeExtension.
func ServeExtension ¶
func ServeExtension(input io.Reader, output io.Writer, contributions Contributions, handlers Handlers) error
ServeExtension supports static registration, editors and live actions. Logs belong on stderr. Action updates can be published independently of clicks.
func ValidateSettings ¶
Types ¶
type Action ¶
type Action struct {
ID, Text, Tooltip, Icon, Color, IconColor, IconStyle string
// Shortcut is a single chord, e.g. "Primary+Shift+B"; empty disables it.
Shortcut string
Selectors []DocumentSelector
Location ActionLocation
Disabled, Hidden bool
Default bool
}
Action is a complete button description. Updates replace the description; empty fields clear their previous values. Icon is an SVG resource path. OpenWith actions use Selectors to match documents and Default to opt into automatic activation. Their view is served by Handlers.Editor, not Action.
type ActionChange ¶
func DecodeActionChange ¶
func DecodeActionChange(data []byte) (ActionChange, error)
type ActionContext ¶
ActionContext uses absolute paths; Caret and Anchor are Unicode rune offsets.
func DecodeActionContext ¶
func DecodeActionContext(data []byte) (ActionContext, error)
type ActionLocation ¶
type ActionLocation uint32
ActionLocation identifies workbench button slots, including document views.
const ( StatusBar ActionLocation = iota LeftContextMenu RightContextMenu TitleBarRight OpenWith // Command registers an action without a workbench button. Command )
type ActionPublisher ¶
type ActionPublisher struct {
// contains filtered or unexported fields
}
ActionPublisher serializes unsolicited updates with request replies. It may be used from background goroutines until the activation context is canceled.
func (*ActionPublisher) CloseUI ¶
func (p *ActionPublisher) CloseUI(id string) error
func (*ActionPublisher) Remove ¶
func (p *ActionPublisher) Remove(id string) error
func (*ActionPublisher) Show ¶
func (p *ActionPublisher) Show(ui UI) error
Show opens or updates a surface from an action handler or background worker.
func (*ActionPublisher) Update ¶
func (p *ActionPublisher) Update(action Action) error
type Capability ¶
type Capability uint32
const ( FileIcons Capability = 1 << iota EditorThemes CustomEditors Fonts LanguageServers Actions ExtensionUI DebugAdapters ExtensionSettings LanguagePacks Capabilities = FileIcons | EditorThemes | CustomEditors | Fonts | LanguageServers | Actions | ExtensionUI | DebugAdapters | ExtensionSettings | LanguagePacks )
type Contributions ¶
type Contributions struct {
LanguagePacks []LanguagePack
Actions []Action
Themes []Theme
IconThemes []IconTheme
Fonts []Font
LanguageServers []LanguageServer
DebugAdapters []DebugAdapter
Settings []Setting
// ActionService keeps a live process even when no buttons are registered yet.
ActionService bool
}
func DecodeContributions ¶
func DecodeContributions(data []byte) (Contributions, error)
type DebugAdapter ¶
type DebugAdapter struct {
ID, Label, Command string
// Templates is a debug.json array copied into project configuration on demand.
Templates string
Args []string
}
DebugAdapter supplies an executable and argument prefix for an adapter ID (for example Delve). The workspace server owns its process and transport. Command follows the same path rules as LanguageServer.Command.
type DocumentSelector ¶
type EditorBinding ¶
type EditorBinding struct{ Ref, Kind string }
type EditorEvent ¶
type EditorMessage ¶
type EditorMessage struct {
Editor, Path, Content string
Event EditorEvent
Binary bool
}
EditorMessage contains a host-owned document snapshot. Binary files supply only Path and Binary=true; this first API permits text edits only.
func DecodeEditorMessage ¶
func DecodeEditorMessage(data []byte) (EditorMessage, error)
type EditorReply ¶
type EditorReply struct {
View *EditorView
Content *string
}
A nil View preserves the retained DOM, caret and scroll. A non-nil View replaces the fragment. Content=nil preserves the host document; &"" clears it.
func DecodeEditorReply ¶
func DecodeEditorReply(data []byte) (EditorReply, error)
type EditorView ¶
type EditorView struct {
HTML, CSS string
Events []EditorBinding
}
Extension UI fragments can use img with data-ref and data-pencode-icon="name" to reuse a built-in IDE icon with its theme color, raster scale and texture cache; omit src. Icons inside anchors or role="link" use textLink.foreground. UI surface anchors with data-ref and href open workspace files in permanent editor tabs or HTTP(S)/mailto links in the system browser. Relative paths in UI surfaces resolve against ActionContext.ProjectPath. File links accept :line[:column] and #Lline locations. An explicit click binding takes ownership of the link. Native buttons can use role="link" and data-pencode-href for the same navigation. pencode-diff:/absolute/path opens the host Source Control comparison for the file's current changes (working tree, staged, or merge), using its preview tab. EditorTab and Panel fragments can use data-pencode-layout="fill" without host padding or scrolling. A fill Panel supplies its own header; reserve 40px on the header's right for the workbench close button. An element with data-ref and data-pencode-scroll="end" follows new output until the user scrolls up; changing its data-pencode-scroll-key reveals the end of a different transcript. data-pencode-scroll="preserve" retains another scroll area's position while its data-pencode-scroll-key stays the same. A scroll container with data-ref and data-pencode-selectable supports native text selection, copy/select-all shortcuts, and the text context menu. Copy retains paragraph breaks, explicit br elements and preformatted text. Other containers with CSS white-space:pre-wrap can opt into preserving source whitespace when copied with data-pencode-preserve-whitespace. A custom editor container with data-ref and data-pencode-searchable enables the host find bar for its rendered text, including highlight and navigation. Find in a rendered view is read-only; replacement applies to source editors. An empty div with data-ref and data-pencode-grid carries an HTML-escaped JSON sparse grid: rows/columns (counts), rowHeight/columnWidth (pixels), optional rowSizes/columnSizes ([oneBasedIndex,pixels] overrides), styles (CSS strings), and cells ([row,column,text,styleIndex] tuples sorted by row then column). Within a searchable/selectable custom editor, the host mounts only the visible two-axis window plus overscan. Find indexes every value and reveals unmounted matches; selection/copy retains data offsets when cells are unmounted. Copy emits TSV data without row/column headings. Use .pencode-grid-cell and .pencode-grid-header CSS to style cells/headings. The outer editor scrolls. An optional grid source string defers cell transfer. The host sends internal EditorEvent{Kind:"grid",Ref:source,Value:JSON} requests with integer request, offset (UTF-8 bytes), firstRow/endRow and firstColumn/endColumn (half-open, one-based), plus all and metadata booleans. all loads a complete sparse index only for find/copy/select-all; metadata requests styles and size overrides. Reply with a standalone div whose data-pencode-grid-chunk is escaped JSON: {source,request,offset,done,data}, where data is base64 for up to 64 KiB of a UTF-8 JSON stream containing cells and optionally styles/rowSizes/columnSizes. The host requests consecutive offsets until done, then applies atomically; stale source/request IDs are discarded. Supply a new source on reload/switch. The 2 MiB per-view and 4 MiB message limits still apply to every reply. A button with data-ref and data-pencode-copy="text" copies that exact text to the local clipboard on click. An explicit click binding overrides this action. A container with data-ref and data-pencode-region updates its children independently. Changes confined to regions preserve the surrounding DOM, including native input focus and selection. Nested regions update together. A container with data-ref and data-pencode-focus="input-ref" focuses the named control when its blank area is clicked, preserving child control focus. A textarea with data-ref and data-pencode-autosize grows with its native text layout. Use border-box sizing and CSS min/max-height to bound its height. data-pencode-submit-on-enter="form" submits the named form binding on Enter; Shift+Enter inserts a newline, and IME confirmation keeps its native behavior. data-pencode-completion="true" routes unmodified Up/Down, Enter/Tab and Escape to EditorEvent{Kind:"completion", Ref:inputRef, Data:action}, with action "previous", "next", "accept" or "dismiss", and the current text/selection. data-pencode-caret="runeOffset:revision" restores focus and a collapsed caret when this attribute changes. Use a new revision for each programmatic edit. data-pencode-markdown-links displays inline [label](path) references using the theme link color and hides their syntax with a one-pixel inset. References behave as atomic tokens for selection, arrow navigation and deletion. Values, selection offsets, clipboard contents and undo retain Markdown source. A text control with data-pencode-paste-images receives images on the paste shortcut as Kind:"paste", InputType:"image/png", Data:a PNG data URL, with the current Value/Anchor/Focus. Text pastes retain native editing behavior. InputType:"error" reports an image paste failure in Data.
type FileChanges ¶
FileChanges comes from the host's unified file service, never a private extension watcher. Paths are relative to Root. Reset requests reconciliation after native, history or subscriber overflow; a rename may appear as remove and create. The batch owns its paths and may be retained by the handler.
func DecodeFileChanges ¶
func DecodeFileChanges(data []byte) (FileChanges, error)
type FileEvent ¶
type FileEvent struct {
Path string
Op FileOperation
Directory bool
}
type FileOperation ¶
type FileOperation uint8
const ( FileCreated FileOperation = 1 << iota FileWritten FileRemoved FileRenamed FileMetadataChanged )
type Font ¶
type Font struct{ ID, Label, Path, BoldPath string }
Font contributes a regular face and an optional bold face from resources/.
type Frame ¶
Frame.Payload is borrowed until the next Read. Session identifies a window action session or a document view; zero addresses the process control session. Request IDs correlate replies; Initialize/Register/Failure use the same nonzero ID. Shutdown, ActionActivate and unsolicited ActionUpdate/UIUpdate notifications use zero.
type Handlers ¶
type Handlers struct {
// NewEditor creates isolated document-view state. Its context ends when the view closes.
// Editor may instead be used for stateless handlers shared by all views.
NewEditor func(context.Context) func(EditorMessage) (EditorReply, error)
// Settings runs before activation/first document request and on each change.
// The snapshot owns its data and may be retained by the extension.
Settings func(SettingValues) error
Lifecycle func(LifecycleEvent) (LifecycleReply, error)
FileChanges func(FileChanges) error
Editor func(EditorMessage) (EditorReply, error)
Action func(ActionContext) error
UIEvent func(UIEvent) error
ActivateActions func(context.Context, *ActionPublisher)
}
Handlers shares one SDK for editor requests and persistent workbench actions. ActivateActions runs once in the window's workbench action session. Start any background work there; return promptly and stop when ctx is canceled.
type LanguagePack ¶
type LanguagePack struct{ ID, Label, Path string }
LanguagePack points to a JSON language pack under resources/.
type LanguageServer ¶
type LanguageServer struct {
ID, Label, LanguageID, Command string
InitializationOptions, Configuration string
Args []string
Selectors []DocumentSelector
}
LanguageServer contributes a standard stdio LSP server. Command is an executable from PATH, an absolute path, or an extension-relative path. JSON options are carried verbatim; the host validates them before activation.
type LifecycleEvent ¶
type LifecycleEvent struct {
ProjectPath string
Kind LifecycleKind
}
LifecycleEvent reaches the action process even when all its views are closed. ProjectPath is absolute for project events and empty for WindowClosing.
func DecodeLifecycleEvent ¶
func DecodeLifecycleEvent(data []byte) (LifecycleEvent, error)
type LifecycleKind ¶
type LifecycleKind uint32
LifecycleKind identifies a host close request or a completed project closure.
const ( WindowClosing LifecycleKind = iota ProjectClosing ProjectClosed )
type LifecycleReply ¶
type LifecycleReply struct{ Message string }
LifecycleReply asks the host to confirm closure before proceeding. Empty Message allows closure. ProjectClosed replies cannot prevent closure.
func DecodeLifecycleReply ¶
func DecodeLifecycleReply(data []byte) (LifecycleReply, error)
type Match ¶
type Match uint32
Match selects basenames or suffixes. Suffix includes its leading dot; the longest suffix wins, after an exact basename match. Directory names use FolderName.
type NotificationSeverity ¶
type NotificationSeverity uint32
NotificationSeverity selects the notification's theme colors and status icon.
const ( NotificationInfo NotificationSeverity = iota NotificationWarning NotificationError )
type Setting ¶
type Setting struct {
ID, Label, Description string
Default json.RawMessage
Options []SettingOption
Type SettingType
}
Setting IDs are local to an extension. Defaults are JSON scalar values; Options, when present, constrain a string setting to the listed values.
type SettingOption ¶
type SettingOption struct{ Value, Label string }
type SettingType ¶
type SettingType uint32
const ( SettingString SettingType = iota SettingBoolean SettingNumber SettingInteger )
type SettingValues ¶
type SettingValues map[string]json.RawMessage
func DecodeSettingValues ¶
func DecodeSettingValues(data []byte) (SettingValues, error)
func ResolveSettings ¶
func ResolveSettings(settings []Setting, saved SettingValues) SettingValues
ResolveSettings creates an immutable snapshot with defaults for missing or invalid saved values. Unknown keys remain in storage, outside this snapshot.
type Shortcut ¶
Shortcut is the parsed, platform-independent form of an Action.Shortcut. Primary means Command on macOS and Control elsewhere.
func ParseShortcut ¶
ParseShortcut accepts a single chord with case-sensitive key names. Successful parsing does not allocate.
type UI ¶
type UI struct {
Patch *ViewPatch
View *EditorView
ID, Title, Anchor string
Context ActionContext
Placement UIPlacement
// ViewVersion identifies a complete view or the result of Patch. Patches
// replace only existing region contents; structure, CSS or event changes
// require a full View. ActionPublisher manages these fields automatically.
ViewVersion uint32
Kind UIKind
// AutoCloseMS dismisses a Notification after this many milliseconds. Zero
// keeps it open until closed by the user or extension. Updates reset the timer.
AutoCloseMS uint32
// Severity applies only to Notification. Zero uses the information style.
Severity NotificationSeverity
Close bool
// CloseOnOutsideClick dismisses a Popup on an outside pointer press.
// False keeps it open. ContextMenu always dismisses on outside presses.
CloseOnOutsideClick bool
// Busy replaces an EditorTab's close icon with a processing animation.
Busy bool
// Unread marks an EditorTab with completed work that has not been viewed.
Unread bool
// InterceptClose keeps an EditorTab open on user close and emits
// "closerequest" instead. Call CloseUI after any confirmation succeeds.
InterceptClose bool
}
UI replaces a surface's description. A nil View retains its controls, focus and scroll. Anchor is a local action ID, or "ui:<surface ID>#<data-ref>" for a focusable control in another surface owned by this extension. Close removes the surface. Empty Context.ID inherits the current Action/UIEvent context; background workers should pass their saved Context explicitly. Title names the surface. EditorTab opens selected. Updates with a View retain selection; a nil View explicitly reveals an existing tab. Closing a tab emits the usual close event.
type UIEvent ¶
type UIEvent struct {
ID, Reason string
Context ActionContext
Event EditorEvent
}
UIEvent carries DOM events and "open", "closerequest", "close", "visibilitychange", "projectchange". visibilitychange uses Event.Value="visible" or "hidden". projectchange notifies EditorTab surfaces when the active project changes. Its Context contains the new ProjectPath and clears file-specific fields. Close reasons are "extension", "button", "escape", "outside", "replace", "timeout". Context is the action invocation that opened this surface, updated by projectchange.
func DecodeUIEvent ¶
type UIKind ¶
type UIKind uint32
UIKind selects a host-owned surface. Menus are anchored to an action; dialogs are modal; panels live in the resizable workbench bottom area.
type UIPlacement ¶
type UIPlacement struct {
Mode UIPosition
X, Y, Width, Height float32
}
UIPlacement controls an overlay's position and size. X/Y offset the selected origin. Zero Width/Height use the surface's default size. The host constrains overlays to the viewport. Panels use their workbench layout instead.
type UIPosition ¶
type UIPosition uint32
UIPosition selects the origin for Placement.X/Y, in workspace CSS pixels.
const ( PositionDefault UIPosition = iota // Center dialogs/popups; anchor context menus. PositionAbsolute // Workspace top-left. PositionAnchor // Action's bottom-left, falling back to its captured location. PositionAnchorAbove // Above the anchor's top-left; falls below when space is insufficient. )
type ViewPatch ¶
type ViewPatch struct {
Regions []ViewRegion
Base uint32
}
ViewPatch is relative to exactly one previously received view version. Nested regions belong to their outer region and cannot be patched separately.
type ViewReceiver ¶
type ViewReceiver struct {
// contains filtered or unexported fields
}
ViewReceiver reconstructs raw views on the session I/O worker, before asset preparation and UI validation. It owns at most 32 surface bases. A new session starts empty and its publisher sends a full view first. Apply is transactional. Do not share a receiver across processes or access it concurrently.
type ViewRegion ¶
type ViewRegion struct {
Ref, HTML string
// contains filtered or unexported fields
}
ViewRegion replaces the children of an existing data-pencode-region element.
func SplitViewRegions ¶
func SplitViewRegions(source string) (string, []ViewRegion, error)
SplitViewRegions separates outer region contents from their surrounding template. Nested regions remain part of their outer region's HTML.
type ViewRegionSplitter ¶
type ViewRegionSplitter struct {
// contains filtered or unexported fields
}
ViewRegionSplitter reuses region boundaries when an update changes only one region. The returned region slice is borrowed until the next successful Split. Strings remain immutable. A splitter must not be used concurrently.
func (*ViewRegionSplitter) Split ¶
func (s *ViewRegionSplitter) Split(source string) (string, []ViewRegion, error)