sourceview

package module
v0.4.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 8, 2026 License: MIT Imports: 38 Imported by: 0

README

GOUI SourceView

A native code editor for Go applications

中文

GOUI SourceView brings source code editing to GOUI applications, with syntax highlighting, completion, matching brackets, and Modern light/dark appearances. It supports both imperative and declarative integration.

The project is under active development.

Installation

Requires Go 1.24 or newer. SourceView v0.3.0 depends on GOUI v0.6.0, which Go downloads automatically. The development branch targets GOUI v0.7.0; the released v0.3.0 remains unchanged.

go get github.com/golang-gui/goui-sourceview@v0.3.0

Features

  • Syntax highlighting for JSON/JSONC, JSON Lines, XML, HTML, Markdown, TOML, YAML, Shell, HTTP, Protobuf, Makefile, CMake, Nginx, INI, Dockerfile, SQL, Go, Python, JavaScript, TypeScript, JSX, TSX, CSS, C, C++, Java, Rust, C#, Lua, PowerShell, Ruby, PHP, Kotlin, Swift, Dart, R, Zig, Objective-C, Objective-C++, Scala, Perl, Diff/Patch, Windows Batch, HCL/Terraform, GraphQL, SCSS, Less, Dotenv, Java Properties, Git Ignore/Attributes, Starlark, Groovy, Go Template, Jinja2, systemd unit, Desktop Entry, Nix, jq, PromQL, F#, Elixir, Erlang, Julia, Clojure, Haskell, OCaml, CSV, TSV, AsciiDoc, reStructuredText, TeX/LaTeX, BibTeX, gettext PO/POT, EditorConfig, JSON5, EDN, Git config, SSH config, crontab, Mermaid, Graphviz DOT and Go module/workspace/checksum files.
  • Mixed documents with highlighted Markdown metadata and code fences, plus HTML, XML, YAML and TOML template hosts.
  • Folding and navigation for structured documents, Markdown headings and code fences, with line/column navigation.
  • Editing assistance with smart indentation, whitespace markers, indent guides and rulers.
  • Code editing with Unicode selection, clipboard, undo/redo, indentation and line operations.
  • Completion and brackets with suggestions, automatic pairs, matching-bracket navigation and linked tag names.
  • Custom languages with application-defined highlighting, editing rules and completion.
  • Find and replace in a floating panel, with multiline queries, regular expressions, capture replacements and selection scopes.
  • Light and dark appearances with syntax colors preserved in selections.
  • Multilingual controls with editor menus and find/replace available in eight languages.

Screenshots

Modern Light — JSON

GOUI SourceView editing JSON in Modern Light

Modern Dark — HTML

GOUI SourceView editing HTML in Modern Dark

Screenshots from the example running on Linux.

Build with an AI coding assistant

The SourceView application development Skill helps your AI integrate the editor and customize highlighting, editing rules, and completion. To install it, tell your AI:

Install the SourceView application development skill following https://github.com/golang-gui/goui-sourceview/blob/main/skills/INSTALL.md.

The installation guide uses your tool's native skill mechanism. Tools without Skill support can read the development guide directly. Installing the Skill does not install or upgrade your application's Go dependencies.

Try the example

Requires Go 1.24 or newer. Follow the example guide to prepare the development environment, then run from the repository root:

go run ./example/editor

The example includes editable samples for every built-in language, search and completion, and lets you switch between light and dark appearances. A declarative example and a custom Markdown editor are also available.

License

MIT

Documentation

Overview

Package sourceview provides a native GOUI code editor. All widget and document operations are sequential and, while mounted, belong on the GUI thread.

Index

Constants

View Source
const (
	WrapNone     = typography.WrapNone
	WrapChar     = typography.WrapChar
	WrapWordChar = typography.WrapWordChar
)

Variables

View Source
var (
	ErrReadOnly             = errors.New("sourceview: read only")
	ErrDisabled             = errors.New("sourceview: disabled")
	ErrNotMounted           = errors.New("sourceview: not mounted")
	ErrClipboardUnavailable = errors.New("sourceview: clipboard unavailable")
	ErrUnknownLanguage      = errors.New("sourceview: unknown language")
	ErrOperationLimit       = editor.ErrOperationLimit
	ErrOperationChanged     = errors.New("sourceview: operation context changed")
)

Functions

This section is empty.

Types

type CaseMode added in v0.4.0

type CaseMode uint8

CaseMode selects locale-independent Unicode case conversion.

const (
	CaseUpper CaseMode = iota
	CaseLower
)

type Command

type Command uint16

Command identifies an editor operation, not a global command registration. Zero and unknown values are invalid. Bindings do not change an operation's editing, focus, preedit or lifecycle requirements.

const (
	CommandUndo Command = iota + 1
	CommandRedo
	CommandCut
	CommandCopy
	CommandPaste
	CommandDeleteSelection
	CommandMoveLinesUp
	CommandMoveLinesDown
	CommandDuplicateLinesUp
	CommandDuplicateLinesDown
	CommandDeleteLines
	CommandSelectAll
	CommandFold
	CommandUnfold
	CommandFoldAll
	CommandUnfoldAll
	CommandComplete
	CommandToggleLineComment
	CommandToggleBlockComment
	CommandIndent
	CommandOutdent
	CommandInsertLineAbove
	CommandInsertLineBelow
	CommandSelectLine
	CommandJumpToBracket
	CommandMoveWordLeft
	CommandMoveWordRight
	CommandSelectWordLeft
	CommandSelectWordRight
	CommandDeleteWordLeft
	CommandDeleteWordRight
	CommandMoveLineStart
	CommandMoveLineEnd
	CommandSelectLineStart
	CommandSelectLineEnd
	CommandMoveDocumentStart
	CommandMoveDocumentEnd
	CommandSelectDocumentStart
	CommandSelectDocumentEnd
	CommandFindNext
	CommandFindPrevious
	// Find/Replace/GoTo are handled only by an attached companion bar.
	CommandFind
	CommandReplace
	CommandGoTo
	// Applications may bind F9; there is no default breakpoint binding.
	CommandToggleLineMark
	CommandMoveWordPartLeft
	CommandMoveWordPartRight
	CommandSelectWordPartLeft
	CommandSelectWordPartRight
	CommandDeleteWordPartLeft
	CommandDeleteWordPartRight
	CommandExpandSelection
	CommandShrinkSelection
	CommandReindentSelection
	CommandPasteReindented
	CommandJoinLines
	CommandUpperCase
	CommandLowerCase
	CommandTrimTrailingWhitespace
)

type Completion

type Completion struct {
	Label, Text, Detail string
	Range               *textedit.Range
	AdditionalEdits     []textedit.Edit
	Caret               *int
}

Completion is a literal edit. Nil Range uses the requested word range. Empty Text uses Label. Caret, when set, is a UTF-8 offset relative to inserted Text. AdditionalEdits use the same original document coordinates as the primary edit.

func DefaultCompletions

func DefaultCompletions(c CompletionContext) []Completion

DefaultCompletions explicitly combines language suggestions and nearby words, with case-insensitive prefix filtering, de-duplication and alphabetical order.

func DocumentCompletions

func DocumentCompletions(c CompletionContext) []Completion

DocumentCompletions returns whole words from the bounded nearby snapshot.

func LanguageCompletions

func LanguageCompletions(c CompletionContext) []Completion

LanguageCompletions returns the definition's static suggestions in code context.

type CompletionContext

type CompletionContext struct {
	DocumentID, Revision         uint64
	Language                     language.ID
	Definition                   *language.Language
	Range                        textedit.Range
	Caret                        int
	Prefix                       string
	Explicit                     bool
	Trigger                      string
	Lexical                      language.Context
	ContextKnown                 bool
	Before, After, NearbyText    string
	NearbyOffset, DocumentLength int
}

CompletionContext is an immutable, bounded snapshot, safe on a worker. It has no live Model, Document or Widget. Offsets are UTF-8 bytes. NearbyText has at most 32 KiB on either side; Before/After have at most 16 KiB of the current line. Language/Definition describe the effective language at the caret, including an explicit embedded language. DocumentID remains the outer document identity.

type CompletionProvider

type CompletionProvider struct {
	TriggerCharacters string
	Complete          func(context.Context, CompletionContext) ([]Completion, error)
}

CompletionProvider completely owns candidates, filtering and order. Treat this configuration as immutable; reuse its pointer across declarative updates. Complete runs on one worker per view, must honor cancellation, and must not touch GUI objects. Nil provider selects DefaultCompletions. Empty results stay empty. TriggerCharacters allows automatic requests even with an empty prefix.

type Document

type Document struct {
	// contains filtered or unexported fields
}

Document shares normalized text, language, history, output line endings and lexical analysis between views. It owns no native resources and needs no Destroy.

func NewDocument

func NewDocument(text string) *Document

NewDocument detects the source line ending before normalizing the editing model to UTF-8/LF. Mixed endings use the most frequent kind; ties use the first encountered kind. A document without line breaks defaults to LF.

func NewDocumentWithModel

func NewDocumentWithModel(model *textedit.Model) *Document

NewDocumentWithModel borrows a normalized model and defaults to LF output. Its original line endings cannot be recovered; use SetLineEnding when known.

func (*Document) AddLineMark added in v0.4.0

func (d *Document) AddLineMark(mark LineMark) (LineMarkID, error)

AddLineMark adds an independently tracked mark. It does not alter text or undo history. Multiple marks may occupy the same line.

func (*Document) ConnectLineEndingChanged added in v0.2.0

func (d *Document) ConnectLineEndingChanged(fn func(LineEnding)) signal.Handle

ConnectLineEndingChanged observes output configuration, separately from model edits. The caller owns the returned connection and disconnects it when done.

func (*Document) ConnectLineMarksChanged added in v0.4.0

func (d *Document) ConnectLineMarksChanged(fn func()) signal.Handle

ConnectLineMarksChanged observes additions, updates, removals and text-driven anchor changes. The caller owns the connection. Callbacks may edit the model.

func (*Document) ID

func (d *Document) ID() uint64

ID is stable for this document lifetime and unique within this process.

func (*Document) Language

func (d *Document) Language() language.ID

func (*Document) LanguageDefinition

func (d *Document) LanguageDefinition() *language.Language

LanguageDefinition returns the immutable definition shared by all views.

func (*Document) LineEnding added in v0.2.0

func (d *Document) LineEnding() LineEnding

LineEnding returns the document's serialization format. Model always uses LF.

func (*Document) LineMarks added in v0.4.0

func (d *Document) LineMarks() []LineMarkInfo

LineMarks returns snapshots ordered by ID. During a reentrant model change, anchors awaiting a newer change notification are temporarily reported invalid. Callers should refresh on ConnectLineMarksChanged rather than retain line numbers.

func (*Document) Model

func (d *Document) Model() *textedit.Model

func (*Document) RemoveLineMark added in v0.4.0

func (d *Document) RemoveLineMark(id LineMarkID) bool

RemoveLineMark reports whether a mark existed. Removing the last mark also disconnects the model observer, independently of any mounted views.

func (*Document) SetFolds added in v0.4.0

func (d *Document) SetFolds(revision uint64, folds *Folds) (bool, error)

SetFolds publishes analysis for revision on the document's owning sequence. A non-nil empty snapshot suppresses built-in folds; nil restores them. Stale revisions return false, nil. Callers also check their own analysis generation.

func (*Document) SetHighlights added in v0.4.0

func (d *Document) SetHighlights(revision uint64, h *Highlights) (bool, error)

SetHighlights publishes a complete snapshot on the document's owning sequence. Revision must identify the exact text passed to NewHighlights; callers must also guard document identity and their own analysis/configuration generation. Stale publications (including nil clears) return false, nil. A current snapshot with a different length returns an error without changing existing colors. Nil clears the layer. Publishing changes neither revision nor editor behavior.

func (*Document) SetLanguage

func (d *Document) SetLanguage(id language.ID) error

func (*Document) SetLanguageDefinition

func (d *Document) SetLanguageDefinition(l *language.Language)

SetLanguageDefinition binds a definition directly. Nil selects plain text. Identity matters: a different definition with the same ID invalidates analysis.

func (*Document) SetLineEnding added in v0.2.0

func (d *Document) SetLineEnding(ending LineEnding) error

SetLineEnding configures serialization only. It changes neither text, revision nor undo history, and is not an undoable format-conversion command.

func (*Document) UpdateLineMark added in v0.4.0

func (d *Document) UpdateLineMark(id LineMarkID, mark LineMark) error

UpdateLineMark replaces a mark's description and anchor, including an invalid anchor. Unknown IDs and invalid descriptions leave the mark unchanged.

func (*Document) WriteTo added in v0.2.0

func (d *Document) WriteTo(w io.Writer) (int64, error)

WriteTo writes UTF-8 using LineEnding, preserving every logical newline, including their absence or repetition at EOF. It uses bounded chunks and returns bytes actually written. Output is not an atomic file replacement. Access is sequential like Model. If a writer callback changes the model or line-ending configuration, it stops with ErrOperationChanged after that write.

type FoldRange added in v0.4.0

type FoldRange = language.FoldRange

FoldRange uses zero-based logical lines and an inclusive final line.

type FoldRegion

type FoldRegion struct {
	StartLine, EndLine int
	Collapsed          bool
}

FoldRegion is a detached snapshot. Lines are zero-based and EndLine inclusive.

type Folds added in v0.4.0

type Folds struct {
	// contains filtered or unexported fields
}

Folds is an immutable, worker-safe folding snapshot. It retains ranges and normalized byte endpoints, never the source text or a mutable model.

func NewFolds added in v0.4.0

func NewFolds(text string, ranges []FoldRange) (*Folds, error)

NewFolds copies and validates candidates against normalized UTF-8/LF text. Duplicate headers retain their outermost range; crossing ranges are invalid.

type HighlightSpan added in v0.4.0

type HighlightSpan struct {
	Range textedit.Range
	Kind  language.Kind
}

HighlightSpan overrides foreground in a normalized document's UTF-8 byte range. KindPlain explicitly restores the ordinary foreground. It changes no lexical context, completion rules, diagnostics, or other editor behavior.

type Highlights added in v0.4.0

type Highlights struct {
	// contains filtered or unexported fields
}

Highlights is an immutable, indexed foreground snapshot, safe to build on a worker and share between documents. It retains no source text or native objects. Its zero value is an empty snapshot for an empty document.

func NewHighlights added in v0.4.0

func NewHighlights(text string, spans []HighlightSpan) (*Highlights, error)

NewHighlights validates and copies ordered, nonempty, nonoverlapping spans. Text must be the exact normalized UTF-8/LF snapshot analyzed by the caller. Spans may cross lines, but must begin and end at rune boundaries.

type IndentOptions

type IndentOptions struct {
	TabWidth, IndentWidth int
	InsertSpaces          bool
}

type KeyBindings

type KeyBindings map[Command][]gui.KeyGesture

KeyBindings maps editor commands to alternative single-key gestures. It covers command shortcuts, not text commits or transient popup navigation.

func DefaultKeyBindings

func DefaultKeyBindings() KeyBindings

DefaultKeyBindings returns a fresh, editable table for the current platform. Explicit completion has no default gesture; applications may bind it.

type LineEnding added in v0.2.0

type LineEnding uint8

LineEnding specifies the UTF-8 sequence used to serialize logical newlines. It never changes the model's normalized UTF-8/LF coordinate system.

const (
	LineEndingLF LineEnding = iota
	LineEndingCRLF
	LineEndingCR
)

func DetectLineEnding added in v0.2.0

func DetectLineEnding(text string) (ending LineEnding, mixed bool)

DetectLineEnding returns the most frequent line ending and whether two or more kinds occur. CRLF counts once, ties use the first encountered kind, and text without line breaks returns LF. It does not normalize or retain text.

func (LineEnding) String added in v0.2.0

func (ending LineEnding) String() string

String returns the format name for labels, not its encoded bytes.

type LineMark added in v0.4.0

type LineMark struct {
	Line  int
	Kind  LineMarkKind
	State LineMarkState
	Label string
}

LineMark describes a logical, zero-based line. Label is application-owned accessible text; an empty label uses the localized built-in description.

type LineMarkAction added in v0.4.0

type LineMarkAction uint8
const (
	LineMarkToggle LineMarkAction = iota
	LineMarkToggleEnabled
	LineMarkContextMenu
)

type LineMarkEvent added in v0.4.0

type LineMarkEvent struct {
	Document *Document
	Revision uint64
	Line     int
	Marks    []LineMarkInfo
	Action   LineMarkAction
	Position geometry.Point
}

LineMarkEvent is a request, not an automatic mutation. Line is the visible zero-based model line; Marks also includes marks hidden by its collapsed fold. Position is widget-local DIP, suitable for an application-owned popover.

type LineMarkID added in v0.4.0

type LineMarkID uint64

LineMarkID identifies a mark for the lifetime of its owning Document. Zero is never allocated. IDs are not reused after removal.

type LineMarkInfo added in v0.4.0

type LineMarkInfo struct {
	LineMark
	ID    LineMarkID
	Valid bool
}

LineMarkInfo is a detached snapshot. An invalid mark retains its identity and description but has Line=-1 until the application updates or removes it.

type LineMarkKind added in v0.4.0

type LineMarkKind uint8

LineMarkKind selects a built-in glyph, not debugger behavior.

const (
	MarkBreakpoint LineMarkKind = iota
	MarkConditionalBreakpoint
	MarkLogpoint
	MarkBookmark
)

type LineMarkState added in v0.4.0

type LineMarkState uint8

LineMarkState describes the state supplied by the application.

const (
	MarkEnabled LineMarkState = iota
	MarkDisabled
	MarkPending
	MarkRejected
)

type MinimapOptions added in v0.4.0

type MinimapOptions struct {
	Width      float32
	MaxColumns int
}

MinimapOptions controls the bounded color-block overview, not text layout. Zero fields select defaults: 120 DIP wide and at most 120 sampled columns.

type SearchQuery

type SearchQuery struct {
	Text                         string
	IgnoreCase, WholeWord, Regex bool
}

type SourceView

type SourceView struct {
	gui.WidgetBase
	// contains filtered or unexported fields
}

SourceView is an editable code control with built-in find, replace and go-to interfaces. Put it in gui.ScrollView to add scrollbars; set that host's StyleName to "source-view" for a shared outer frame. Construction owns no model/settings/root subscriptions.

func NewSourceView

func NewSourceView() *SourceView

func (*SourceView) AcceptsTab

func (v *SourceView) AcceptsTab() bool

func (*SourceView) ApplyEdits

func (v *SourceView) ApplyEdits(document *Document, revision uint64, edits []textedit.Edit, after textedit.Selection) error

ApplyEdits applies original-coordinate edits as one undo unit, with an explicit post-edit selection. Document identity and revision must match. All ranges and the selection are validated before mutation by textedit.

func (*SourceView) Arrange

func (v *SourceView) Arrange(rect geometry.Rectangle)

func (*SourceView) AutoPairs

func (v *SourceView) AutoPairs() bool

AutoPairs controls insertion, surrounding and deletion of generated pairs. It does not affect explicit ReplaceSelection, paste or composed IME commits.

func (*SourceView) AutomaticCompletion

func (v *SourceView) AutomaticCompletion() bool

func (*SourceView) ClearExecutionLine added in v0.4.0

func (v *SourceView) ClearExecutionLine()

func (*SourceView) ConnectChange

func (v *SourceView) ConnectChange(fn func(textedit.Change)) signal.Handle

func (*SourceView) ConnectError

func (v *SourceView) ConnectError(fn func(error)) signal.Handle

func (*SourceView) ConnectFoldingChanged

func (v *SourceView) ConnectFoldingChanged(fn func()) signal.Handle

func (*SourceView) ConnectLineMarkAction added in v0.4.0

func (v *SourceView) ConnectLineMarkAction(fn func(LineMarkEvent)) signal.Handle

ConnectLineMarkAction handles marker clicks, Shift-clicks, context requests and explicitly bound CommandToggleLineMark. The application owns breakpoints.

func (*SourceView) ConnectScrollIntoView

func (v *SourceView) ConnectScrollIntoView(fn func(geometry.Rectangle)) signal.Handle

func (*SourceView) ConnectSelection

func (v *SourceView) ConnectSelection(fn func(textedit.Selection)) signal.Handle

func (*SourceView) ContentSize

func (v *SourceView) ContentSize() geometry.Size

func (*SourceView) Copy

func (v *SourceView) Copy() error

func (*SourceView) Cursor added in v0.2.0

func (v *SourceView) Cursor() gui.Cursor

Cursor resolves code, gutter and fold affordances without shaping text. A captured selection keeps the cursor chosen by its starting region.

func (*SourceView) Cut

func (v *SourceView) Cut() error

func (*SourceView) DeleteLines

func (v *SourceView) DeleteLines() error

DeleteLines deletes the current logical line or selected lines, placing the caret at the deletion boundary. Deleting an empty document is a no-op.

func (*SourceView) DeleteWord

func (v *SourceView) DeleteWord(forward bool) error

DeleteWord deletes the selection, a whitespace run or one code word. Each invocation has its own undo item. At a document edge it is a no-op.

func (*SourceView) DeleteWordPart added in v0.4.0

func (v *SourceView) DeleteWordPart(forward bool) error

DeleteWordPart deletes one component or the selection as one undo item.

func (*SourceView) Document

func (v *SourceView) Document() *Document

func (*SourceView) DuplicateLines

func (v *SourceView) DuplicateLines(down bool) error

DuplicateLines copies the current logical line or selected lines above/below, retaining the selection in the new copy. The clipboard is not involved.

func (*SourceView) ExecutionLine added in v0.4.0

func (v *SourceView) ExecutionLine() (int, bool)

ExecutionLine returns -1,false if absent, invalidated, or awaiting model changes.

func (*SourceView) ExpandSelection added in v0.4.0

func (v *SourceView) ExpandSelection() bool

ExpandSelection selects the smallest confirmed enclosing word, literal, bracket/tag region, logical line or document. Analysis never changes a later selection.

func (*SourceView) FindNext

func (v *SourceView) FindNext(backward bool) (textedit.Range, bool)

func (*SourceView) Fold

func (v *SourceView) Fold(line int) bool

func (*SourceView) FoldAll

func (v *SourceView) FoldAll()

func (*SourceView) FoldingEnabled

func (v *SourceView) FoldingEnabled() bool

func (*SourceView) FoldingRegions

func (v *SourceView) FoldingRegions() []FoldRegion

func (*SourceView) HidePanel added in v0.2.0

func (v *SourceView) HidePanel()

HidePanel hides the built-in find/replace or go-to UI. Query and replacement text survive. Focus returns to the editor only when it was inside that UI.

func (*SourceView) HighlightOccurrences

func (v *SourceView) HighlightOccurrences() bool

func (*SourceView) HighlightSearchMatches

func (v *SourceView) HighlightSearchMatches() bool

HighlightSearchMatches reports whether search backgrounds are drawn. New views highlight matches, including searches made without a findBar.

func (*SourceView) IMContext

func (v *SourceView) IMContext() gui.IMContext

func (*SourceView) Indent

func (v *SourceView) Indent(outdent bool) error

func (*SourceView) IndentOptions

func (v *SourceView) IndentOptions() IndentOptions

func (*SourceView) InsertLine

func (v *SourceView) InsertLine(below bool) error

InsertLine inserts an indented blank line above/below the caret's logical line. Existing text is preserved, including when there is a selection.

func (*SourceView) JoinLines added in v0.4.0

func (v *SourceView) JoinLines() error

JoinLines joins selected logical lines, or the current and following line. It is an explicit text operation; it does not preserve language semantics.

func (*SourceView) JumpToBracket

func (v *SourceView) JumpToBracket() bool

JumpToBracket jumps between a confirmed pair adjacent to the caret. Unknown, unmatched or out-of-budget pairs leave the selection unchanged.

func (*SourceView) KeyBindings

func (v *SourceView) KeyBindings() KeyBindings

KeyBindings returns a mutable deep copy, including when no keys are bound.

func (*SourceView) LayoutVisible

func (v *SourceView) LayoutVisible(viewport geometry.Size, offset geometry.Point)

func (*SourceView) LinkedTags

func (v *SourceView) LinkedTags() bool

LinkedTags controls typed/deleted name mirroring on confirmed markup pairs.

func (*SourceView) Measure

func (*SourceView) MinimapOptions added in v0.4.0

func (v *SourceView) MinimapOptions() MinimapOptions

func (*SourceView) MoveLines

func (v *SourceView) MoveLines(down bool) error

MoveLines moves the current logical line or selected lines one row up/down. It preserves indentation and selection direction. A document edge is a no-op.

func (*SourceView) MoveWord

func (v *SourceView) MoveWord(forward, extend bool)

MoveWord moves to the previous code-word start or next code-word end.

func (*SourceView) MoveWordPart added in v0.4.0

func (v *SourceView) MoveWordPart(forward, extend bool)

MoveWordPart moves across camel-case, acronym, digit and underscore boundaries. Without extension, a nonempty selection collapses towards the requested side.

func (*SourceView) Paint

func (v *SourceView) Paint(p gui.Painter)

func (*SourceView) Paste

func (v *SourceView) Paste() error

Paste accepts an asynchronous request. Delayed failures are reported through ConnectError. A changed document, selection or mount cancels the request.

func (*SourceView) PasteReindented added in v0.4.0

func (v *SourceView) PasteReindented() error

PasteReindented explicitly shifts a multiline paste's common indentation to the target line. Ordinary Paste is unchanged. Unknown/literal contexts and languages without a reindent provider use literal paste.

func (*SourceView) ReadOnly

func (v *SourceView) ReadOnly() bool

func (*SourceView) Redo

func (v *SourceView) Redo() bool

func (*SourceView) RefreshCompletion added in v0.4.0

func (v *SourceView) RefreshCompletion() error

RefreshCompletion re-queries an existing visible or pending completion session. It does nothing when no session exists. The original explicit intent is kept; Trigger is empty because no character caused this refresh. Pending preview items remain visible but cannot be accepted. Async errors use ConnectError.

func (*SourceView) ReindentSelection added in v0.4.0

func (v *SourceView) ReindentSelection() error

ReindentSelection requests language indentation for selected logical lines, or the current line. Nil means accepted (or no provider); delayed errors use ConnectError. Any change of revision, selection, options or mount cancels it.

func (*SourceView) ReplaceAll

func (v *SourceView) ReplaceAll(text string) (int, error)

func (*SourceView) ReplaceCurrent

func (v *SourceView) ReplaceCurrent(text string) (bool, error)

func (*SourceView) ReplaceSelection

func (v *SourceView) ReplaceSelection(text string) error

func (*SourceView) RevealLine added in v0.4.0

func (v *SourceView) RevealLine(line int) error

RevealLine expands containing folds and requests visibility using the current height index, without moving the caret or synchronously measuring the document.

func (*SourceView) RevealSelection

func (v *SourceView) RevealSelection()

func (*SourceView) Rulers

func (v *SourceView) Rulers() []int

func (*SourceView) Search

func (v *SourceView) Search() SearchQuery

func (*SourceView) SearchError

func (v *SourceView) SearchError() error

SearchError reports a malformed regular expression. Invalid queries retain their text for editing, produce no matches and never mutate the document.

func (*SourceView) SearchRange

func (v *SourceView) SearchRange() (textedit.Range, bool)

SearchRange is independent of the current selection and FindNext results.

func (*SourceView) SelectLine

func (v *SourceView) SelectLine()

SelectLine expands to whole logical lines, including the following LF. Repeating the command extends the selection one more line downward.

func (*SourceView) Selection

func (v *SourceView) Selection() textedit.Selection

func (*SourceView) SetAcceptsTab

func (v *SourceView) SetAcceptsTab(value bool)

func (*SourceView) SetAutoPairs

func (v *SourceView) SetAutoPairs(enabled bool)

func (*SourceView) SetAutomaticCompletion

func (v *SourceView) SetAutomaticCompletion(enabled bool)

func (*SourceView) SetCompletionProvider

func (v *SourceView) SetCompletionProvider(provider *CompletionProvider)

func (*SourceView) SetDocument

func (v *SourceView) SetDocument(d *Document)

func (*SourceView) SetExecutionLine added in v0.4.0

func (v *SourceView) SetExecutionLine(line int) error

SetExecutionLine sets a view-local, zero-based execution anchor. It neither moves the selection nor scrolls; use RevealLine separately. -1 clears it.

func (*SourceView) SetFoldingEnabled

func (v *SourceView) SetFoldingEnabled(enabled bool)

func (*SourceView) SetHighlightOccurrences

func (v *SourceView) SetHighlightOccurrences(b bool)

func (*SourceView) SetHighlightSearchMatches

func (v *SourceView) SetHighlightSearchMatches(highlight bool)

SetHighlightSearchMatches changes presentation only. Query, navigation, replacement and ordinary text selection are unaffected. findBar enables it on open and disables it when closing or releasing an open search session.

func (*SourceView) SetIndentOptions

func (v *SourceView) SetIndentOptions(o IndentOptions) error

func (*SourceView) SetKeyBindings

func (v *SourceView) SetKeyBindings(bindings KeyBindings) error

SetKeyBindings validates and copies a complete replacement table. nil/empty removes all command shortcuts; absent commands have no fallback binding. Gestures require a non-Shift modifier or a function key. Unmodified/Shift-only text, navigation and editing keys belong to ordinary input and popup control. Invalid commands, unsupported gestures or conflicting commands return an error without changing the old table. Same-command aliases are deduplicated. Menu hints follow the configured bindings; ordinary input, IME, menu actions and direct method calls retain their existing behavior.

func (*SourceView) SetLinkedTags

func (v *SourceView) SetLinkedTags(b bool)

func (*SourceView) SetMinimapOptions added in v0.4.0

func (v *SourceView) SetMinimapOptions(o MinimapOptions) error

func (*SourceView) SetReadOnly

func (v *SourceView) SetReadOnly(value bool)

func (*SourceView) SetRulers

func (v *SourceView) SetRulers(columns []int) error

func (*SourceView) SetScheme

func (v *SourceView) SetScheme(s *scheme.Scheme)

SetScheme overrides code-area colors only. nil uses the owning stylesheet.

func (*SourceView) SetSearch

func (v *SourceView) SetSearch(q SearchQuery)

func (*SourceView) SetSearchRange

func (v *SourceView) SetSearchRange(r *textedit.Range) error

SetSearchRange copies a validated byte range. nil searches the whole document. Regex anchors retain the full-document context. Empty ranges may match empty expressions; no caller-owned pointer is retained.

func (*SourceView) SetSelection

func (v *SourceView) SetSelection(s textedit.Selection)

func (*SourceView) SetShowIndentGuides

func (v *SourceView) SetShowIndentGuides(b bool)

func (*SourceView) SetShowLineEndings

func (v *SourceView) SetShowLineEndings(b bool)

func (*SourceView) SetShowLineMarks added in v0.4.0

func (v *SourceView) SetShowLineMarks(show bool)

func (*SourceView) SetShowLineNumbers

func (v *SourceView) SetShowLineNumbers(show bool)

func (*SourceView) SetShowMinimap added in v0.4.0

func (v *SourceView) SetShowMinimap(show bool)

func (*SourceView) SetSmartBackspace

func (v *SourceView) SetSmartBackspace(b bool)

func (*SourceView) SetSmartHomeEnd

func (v *SourceView) SetSmartHomeEnd(b bool)

func (*SourceView) SetWhitespaceMode

func (v *SourceView) SetWhitespaceMode(mode WhitespaceMode) error

func (*SourceView) SetWrapMode

func (v *SourceView) SetWrapMode(w WrapMode)

func (*SourceView) ShowCompletion

func (v *SourceView) ShowCompletion() error

ShowCompletion requests suggestions at the current caret. No proposals is a normal result. Asynchronous failures are delivered once through ConnectError.

func (*SourceView) ShowFind added in v0.2.0

func (v *SourceView) ShowFind() error

ShowFind opens the built-in find UI and focuses its query. A short, single-line editor selection seeds the query. It requires a mounted view.

func (*SourceView) ShowGoTo added in v0.2.0

func (v *SourceView) ShowGoTo() error

ShowGoTo opens the built-in line/column input, initialized from the caret. It requires a mounted view and closes the find/replace UI.

func (*SourceView) ShowIndentGuides

func (v *SourceView) ShowIndentGuides() bool

func (*SourceView) ShowLineEndings

func (v *SourceView) ShowLineEndings() bool

func (*SourceView) ShowLineMarks added in v0.4.0

func (v *SourceView) ShowLineMarks() bool

func (*SourceView) ShowLineNumbers

func (v *SourceView) ShowLineNumbers() bool

func (*SourceView) ShowMinimap added in v0.4.0

func (v *SourceView) ShowMinimap() bool

func (*SourceView) ShowReplace added in v0.2.0

func (v *SourceView) ShowReplace() error

ShowReplace opens the built-in find UI with replacement controls visible. It otherwise follows ShowFind's selection and focus rules.

func (*SourceView) ShrinkSelection added in v0.4.0

func (v *SourceView) ShrinkSelection() bool

ShrinkSelection restores the preceding actual selection, including direction.

func (*SourceView) SmartBackspace

func (v *SourceView) SmartBackspace() bool

func (*SourceView) SmartHomeEnd

func (v *SourceView) SmartHomeEnd() bool

func (*SourceView) Snapshot

func (v *SourceView) Snapshot() gui.WidgetInfo

func (*SourceView) StyleChanged

func (v *SourceView) StyleChanged()

func (*SourceView) ToggleBlockComment

func (v *SourceView) ToggleBlockComment() error

ToggleBlockComment wraps the selection or removes its exact configured wrapper. Content is literal; this does not parse or nest block comments.

func (*SourceView) ToggleFold

func (v *SourceView) ToggleFold(line int) bool

func (*SourceView) ToggleLineComment

func (v *SourceView) ToggleLineComment() error

ToggleLineComment uses the language's line marker. Empty configuration is a normal no-op. A selection ending at the next line start excludes that line.

func (*SourceView) Tooltip added in v0.4.0

func (v *SourceView) Tooltip() string

Tooltip resolves marker help without replacing an application tooltip.

func (*SourceView) TransformCase added in v0.4.0

func (v *SourceView) TransformCase(mode CaseMode) error

TransformCase converts the selection, or the language word at the caret. Unicode conversion may change byte length; the result is one undo item.

func (*SourceView) TrimTrailingWhitespace added in v0.4.0

func (v *SourceView) TrimTrailingWhitespace() error

TrimTrailingWhitespace removes ASCII space/tab suffixes from selected logical lines, or the whole document for an empty selection. LF and NBSP are retained.

func (*SourceView) Undo

func (v *SourceView) Undo() bool

func (*SourceView) Unfold

func (v *SourceView) Unfold(line int) bool

func (*SourceView) UnfoldAll

func (v *SourceView) UnfoldAll()

func (*SourceView) WhitespaceMode

func (v *SourceView) WhitespaceMode() WhitespaceMode

func (*SourceView) WrapMode

func (v *SourceView) WrapMode() WrapMode

type WhitespaceMode

type WhitespaceMode uint8

WhitespaceMode controls decorative markers without changing source text.

const (
	WhitespaceNone      WhitespaceMode = iota // Hide whitespace markers.
	WhitespaceSelection                       // Mark whitespace contained in the selection.
	WhitespaceTrailing                        // Mark whitespace at the end of a logical line.
	WhitespaceAll                             // Mark all supported whitespace.
	WhitespaceBoundary                        // Mark indentation, trailing/repeated spaces, Tabs and special spaces.
)

type WrapMode

type WrapMode = typography.WrapMode

Directories

Path Synopsis
example
debug command
Run: go run ./example/debug [-dark].
Run: go run ./example/debug [-dark].
declarative command
Run: go run ./example/declarative.
Run: go run ./example/declarative.
editor command
Run: go run ./example/editor [-theme system|light|dark] [file].
Run: go run ./example/editor [-theme system|light|dark] [file].
markdown command
Run: go run ./example/markdown [-dark].
Run: go run ./example/markdown [-dark].
markdown/markdown
Package markdown demonstrates an application-owned SourceView language.
Package markdown demonstrates an application-owned SourceView language.
semantic command
Run: go run ./example/semantic [-dark].
Run: go run ./example/semantic [-dark].
semantic/analysis
Package analysis is an application-owned, single-file Go analysis service.
Package analysis is an application-owned, single-file Go analysis service.
internal
editor
Package editor plans source edits without depending on Widgets or native resources.
Package editor plans source edits without depending on Widgets or native resources.
resource
Package resource contains SourceView-owned presentation text.
Package resource contains SourceView-owned presentation text.
Package language describes the languages and lexical styles supported by SourceView.
Package language describes the languages and lexical styles supported by SourceView.
Package scheme provides immutable source-code color schemes.
Package scheme provides immutable source-code color schemes.
tests
window/editor command
SourceView desktop verification.
SourceView desktop verification.
window/editor/assistance command
编辑辅助和空白外观的原生窗口验证,需要桌面及窗口管理器。
编辑辅助和空白外观的原生窗口验证,需要桌面及窗口管理器。
window/editor/binding command
SourceView 选区属性绑定与局部更新验收,需要桌面、原生排版和字体。
SourceView 选区属性绑定与局部更新验收,需要桌面、原生排版和字体。
window/editor/brackets command
Bracket decoration visual verification.
Bracket decoration visual verification.
window/editor/completion command
Completion panel verification.
Completion panel verification.
window/editor/corpus command
Downloaded-corpus verification.
Downloaded-corpus verification.
window/editor/extensions command
Public extension verification.
Public extension verification.
window/editor/find command
内置查找、替换和声明式生命周期验证。
内置查找、替换和声明式生命周期验证。
window/editor/find_appearance command
Find overlay appearance and isolation verification.
Find overlay appearance and isolation verification.
window/editor/folding command
Folding integration verification.
Folding integration verification.
window/editor/frame command
编辑器外框与滚动条组合验证。
编辑器外框与滚动条组合验证。
window/editor/highlight command
连续输入的着色稳定性,需要桌面、原生排版及正常事件循环。
连续输入的着色稳定性,需要桌面、原生排版及正常事件循环。
window/editor/interaction command
Real desktop input verification; requires a desktop and native typography.
Real desktop input verification; requires a desktop and native typography.
window/editor/keybindings command
Command binding integration verification.
Command binding integration verification.
window/editor/languages command
内置语言集成验证,需要桌面、窗口管理器、原生排版及字体。
内置语言集成验证,需要桌面、窗口管理器、原生排版及字体。
window/editor/largefiles command
Medium/large-file functional verification.
Medium/large-file functional verification.
window/editor/line_marks command
行标记窗口验收,需要桌面、窗口管理器、原生排版与字体。
行标记窗口验收,需要桌面、窗口管理器、原生排版与字体。
window/editor/lines command
Logical line editing verification.
Logical line editing verification.
window/editor/localization command
Eight-language editor UI verification.
Eight-language editor UI verification.
window/editor/longlines command
Long-line rasterization regression.
Long-line rasterization regression.
window/editor/markup command
Native markup verification; desktop/window manager required.
Native markup verification; desktop/window manager required.
window/editor/menus command
Menu command/hint integration.
Menu command/hint integration.
window/editor/minimap command
色块地图窗口验收:go run ./tests/window/editor/minimap [-theme basic|light|dark]。
色块地图窗口验收:go run ./tests/window/editor/minimap [-theme basic|light|dark]。
window/editor/paragraph command
超大单行文本交互验证,需要独立桌面、原生排版和字体,不使用 DevServer。
超大单行文本交互验证,需要独立桌面、原生排版和字体,不使用 DevServer。
window/editor/resize_cache command
Recent-width layout cache verification.
Recent-width layout cache verification.
window/editor/search command
Native search enhancements verification; desktop/window manager required.
Native search enhancements verification; desktop/window manager required.
window/editor/selection command
Syntax-preserving selection verification.
Syntax-preserving selection verification.
window/editor/semantic command
外部语义分析验收:go run ./tests/window/editor/semantic [-dark]。
外部语义分析验收:go run ./tests/window/editor/semantic [-dark]。
window/editor/shortcuts command
Editor shortcut verification.
Editor shortcut verification.
window/editor/structural command
P0 编辑辅助与大折叠结果的窗口验证。
P0 编辑辅助与大折叠结果的窗口验证。
window/experience command
Editor experience verification.
Editor experience verification.
Package ui provides thin GOUI declarative bindings for SourceView.
Package ui provides thin GOUI declarative bindings for SourceView.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL