godemirror

package module
v0.12.0 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2026 License: MIT Imports: 54 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

godemirror

CodeMirror, native to Go.

A code view and a diff view for Gio: syntax-highlighted code with a line gutter, wrapping or sideways scrolling, selection and copy, line decorations, widgets on and between lines, diffs unified or side by side, and an opt-in editor. Drawn as one image per visible row, so a full screen of code costs a handful of quads.

Go Reference CI Go Gio Platform License

Why godemirror

On the web, an app that shows code reaches for CodeMirror: highlighting, decorations, widgets between lines, a merge view. A native Go app has had nothing like it, and drawing code with a GUI toolkit's text stack is slow at full screen. godemirror brings that experience to Go: file previews, diffs, code review, logs, and, when you ask for it, an editor whose document and selection follow CodeMirror 6's own rules.

godemirror lets you:

  • Show code that reads like code. Monospace rows highlighted from the file name and colored by a HighlightStyle, as in CodeMirror. CSS, Go, HTML, Java, JavaScript, TypeScript, Python and Rust are parsed by a Go port of CodeMirror's own Lezer parser and grammars, and Kotlin and shell scripts by a port of the @codemirror/legacy-modes modes CodeMirror reads them with, so they are tagged exactly as CodeMirror tags them; other languages are read by chroma and tagged with the CodeMirror tags their Lezer grammars give the same constructs. StyleTags make a Lezer grammar's tags finer, as CodeMirror's styleTags does (RicherJavaTags, RicherGoTags, RicherJavaScriptTags, RicherPythonTags, RicherRustTags), and StyleRule.Names tags a name by its text, as GoBuiltinTags and its siblings do for builtins. The themes: DarkTheme, LightTheme, a ported CodeMirror theme (OneDark, Dracula, GitHubLight, GitHubDark, Nord) or a theme of your own. Highlighting runs off the UI goroutine: a 13,000-line file shows at once and takes its colors when they are ready.
  • Wrap, or don't. Lines break after spaces the way CSS pre-wrap does, each continuation row hanging under its line's own indentation, or scroll sideways with Shift and the wheel.
  • Decorate lines. Tint a line and its gutter cell, put a strip down the gutter, rule a separator, hatch a filler row, and replace the line numbers with labels of your own: everything a diff needs.
  • Put widgets on lines. Any Gio widget after a line's text or against the right edge (an Expand 44 unchanged lines button, a Revert), optionally shown only while the pointer is over the line's hover group.
  • Open space between lines. A BlockWidget lays out any Gio widget under a line: a review thread, a comment box with an Editor. Its state is yours, so rebuilding the content around it never loses what was being typed.
  • Split side by side. Two documents row for row, scrolling down together and sideways each on its own. Unlike two CodeMirror editors, the split can wrap: a pair of lines takes the taller side's rows, and a block on one side leaves the same room on the other.
  • Show a diff. DiffView diffs two documents itself or shows a file of a git diff patch: unified with old and new line numbers, or side by side, unchanged runs collapsed behind an expander, a Revert on each chunk, and review threads anchored to file lines. Its colors are part of the theme.
  • Search. SetSearch highlights every match of a literal or a regexp, case-sensitive or not, whole words or not; FindNext and FindPrevious walk the matches, wrapping, selecting each one and scrolling it into view. The search box is yours to draw. In a DiffView one query looks through the unified view and both sides of the split.
  • Edit, when asked. An Editor holds an EditorState, a port of @codemirror/state: a document, a selection of one or more ranges, and transactions you Dispatch to change them, as one change set each. The user types (input methods included), moves and selects with CodeMirror's standard keymap and its mouse selection, adds cursors above and below, at the next occurrence (Ctrl+D) or at every one, or drags a rectangle with Alt, copies, cuts and pastes, and undoes and redoes as CodeMirror's history groups the changes; Enter keeps the line's indentation in your IndentUnit. It reports what changed through OnUpdate, after the frame, so you can read the new document and map your own positions through the changes. Everything else stays read-only.
  • Select and copy. Drag (past an edge the view scrolls along), double click for a word, triple click for a line, Shift+click to extend, Ctrl+A and Ctrl+C. Copying gives back the text as it was, tabs included, and SelectedLines turns the selection into the line span an action works on.
  • Jumps glide. A scroll the program makes (SetScrollTop, ScrollToLine, PageDown, a far cursor move in an Editor) slides there in 140 ms, eased out; a jump of a few rows, the wheel and the touchpad stay direct. SnapScrollTop and ReduceMotion land at once, and OnScroll hears only the user's own scrolls.

Getting started

godemirror needs Go 1.27 or later.

go get github.com/lichdotdev/godemirror
view, err := godemirror.New("JetBrainsMono Nerd Font", unit.Sp(13))
if err != nil {
	return err
}
view.SetContent(godemirror.Content{Filename: "main.go", Text: source})

// in your frame loop
if _, err := view.Layout(gtx); err != nil {
	return err
}

To edit, build an Editor instead and change its document with transactions:

editor, err := godemirror.NewEditor("JetBrainsMono Nerd Font", unit.Sp(13))
if err != nil {
	return err
}
if err := editor.SetState(godemirror.EditorStateConfig{Filename: "main.go", Doc: source}); err != nil {
	return err
}
editor.OnUpdate = func(u godemirror.Update) {
	if u.DocChanged() {
		save(u.State.Doc())
	}
}
// replace bytes [from, to) of the document, as one transaction
err = editor.Dispatch(godemirror.TransactionSpec{
	Changes: []godemirror.ChangeSpec{{From: from, To: to, Insert: "resolved"}},
})

An editor's positions are byte offsets into EditorState.Doc, whose lines are joined by "\n" (LineSeparator keeps a CRLF file CRLF in SliceDoc); the read-only views count a Pos column in runes.

Content also carries Labels, Decorations, Widgets and Blocks, indexed by document line. SetContent shows a new document from its top; UpdateContent swaps in a new version of the same one (a diff with lines pulled in) without moving the scroll. For two sides, build a godemirror.Split and give Left and Right their own content.

Language servers

lsp is a Language Server Protocol client: start a server, attach an Editor to a document, and the editor shows the server's diagnostics and offers its completions, hover and go to definition.

client, err := lsp.Start(ctx, lsp.Config{Command: []string{"gopls"}, RootDir: root})
if err != nil {
	return err
}
doc, err := lsp.Attach(client, editor, lsp.FileURI(path), lsp.Options{
	LanguageID: "go",
	Invalidate: window.Invalidate, // diagnostics arrive between frames
})
editor.OnDefinition = func(l godemirror.Location) { open(l.URI, l.Start) }
// doc.Save() after writing the file, doc.Close() when it closes

The editor's hooks (SetDiagnostics, Complete, Hover, SignatureHelp, Definition, References, Rename, CodeActions and the rest) take any source, not only a language server; doc.Format(ctx) and doc.Symbols(ctx) format the document and list its outline. lsp/servers is a catalog of servers converted from nvim-lspconfig and mason-registry: servers.Lookup("main.go") returns the candidates for a file, the common one first, with its command, root markers, default settings and an install recipe. It only describes; it never runs a server or an install.

The deliberate limits, and what they mean for a caller, are in docs/ceilings.md.

Coming from CodeMirror

CodeMirror 6 godemirror
EditorView with EditorState.readOnly View
EditorView, EditorState.create Editor, NewEditor, SetState(EditorStateConfig)
view.dispatch(spec), updateListener Dispatch(TransactionSpec), OnUpdate
ChangeSet, mapPos, MapMode ChangeSet, MapPos, MapPosTrack
EditorSelection, SelectionRange, allowMultipleSelections EditorSelection, SelectionRange, EditorStateConfig.AllowMultipleSelections
changeByRange, replaceSelection ChangeByRange, ReplaceSelection
standardKeymap, drawSelection, indentUnit, view.focus() built into Editor, Theme.Cursor, EditorStateConfig.IndentUnit, Focus
addCursorAbove, addCursorBelow, simplifySelection built into Editor (Ctrl+Alt+Up/Down, Escape)
EditorView.domEventHandlers({keydown}), coordsAtPos Editor.OnKey, Editor.CoordsAtPos
rectangularSelection(), crosshairCursor() Editor.RectangularSelection, Editor.CrosshairCursor
selectNextOccurrence, selectSelectionMatches built into Editor (Ctrl+D, Ctrl+Shift+L)
history(), undo, redo, undoDepth, redoDepth built into Editor, Undo, Redo, UndoDepth, RedoDepth
isolateHistory, Transaction.addToHistory, Transaction.time TransactionSpec.IsolateHistory, SkipHistory, Time
Decoration.line, Decoration.widget in a state field, RangeSet.map LineDecorationAt, LineWidgetAt in Decorations, set by EditorStateConfig or TransactionSpec.Decorations and mapped through every change
EditorView.lineWrapping View.Wrap
EditorView.theme Theme
tags (@lezer/highlight), HighlightStyle.define package tags, NewHighlightStyle
highlightCode (@lezer/highlight) Highlight
lineNumbers({formatNumber}) Content.Labels
Decoration.line, gutterLineClass LineDecoration
Decoration.mark LineDecoration.Spans
Decoration.widget LineWidget (on a line), BlockWidget (between lines)
state.selection, dispatch({selection}) Selection, Select, SelectLines
SearchQuery, findNext, findPrevious SearchQuery, SetSearch, FindNext, FindPrevious, Matches (no panel: draw your own search box)
EditorView.scrollIntoView ScrollToLine
scrollDOM.scrollTop, lineBlockAt, lineBlockAtHeight, contentHeight ScrollTop, SetScrollTop (SnapScrollTop, ScrollTarget), LineBlock (LineBlockAt on an Editor), LineAtHeight (LineBlockAtHeight), ContentHeight, and OnScroll
state.doc.lines, doc.line(n) LineCount, LineText
MergeView, unifiedMergeView DiffView (Split on or off)
collapseUnchanged DiffOptions.Collapse, or the gaps of a patch
mergeControls DiffOptions.Revert, Chunks
highlightChanges DiffOptions.HighlightChanges

The diff view

DiffView shows the difference between two versions of a file, the way CodeMirror's merge view does: unified, with the old and the new line number side by side in the gutter, or side by side, with each deletion paired with the addition that replaced it.

diff, err := godemirror.NewDiffView("JetBrainsMono Nerd Font", unit.Sp(13), godemirror.DiffOptions{
	Collapse:         &godemirror.Collapse{Margin: 3, MinSize: 4},
	HighlightChanges: true,
	Revert:           func(c godemirror.Chunk) { /* put c.Lines back in the file */ },
})
if err != nil {
	return err
}
diff.SetDocs("main.go", original, modified)

// in your frame loop
if _, err := diff.Layout(gtx); err != nil {
	return err
}

SetDocs diffs two documents itself. To show what git already diffed, read the patch with ParsePatch and pass a file to SetPatch; the unchanged lines git left out are asked for through DiffOptions.Expand and laid in with FillGap, in as many parts as your backend answers in. Chunks, SelectedRange and SelectedChanges read the diff in file line numbers, and SetBlocks anchors a review thread to a line of either file. The colors live in Theme.Diff, in both DarkTheme and LightTheme.

For a narrow view, DiffOptions.UnifiedGutter set to OneColumnGutter numbers a unified diff's rows once (the new file's number, or the old one's for a deleted line), and RevertPlacement set to RevertInGutter puts the revert over the chunk's first line number instead of over the end of the code. Height(gtx, width) is how tall the rows are at a width, wrapped or not, unified or split, for a caller that gives each diff exactly the room it needs.

The demo

cmd/godemirror-demo shows what the library draws, in a window or headless: a file in a View or an Editor, or a diff in a DiffView, with expandable gaps, Revert on hover and comments anchored to lines as DiffBlocks.

go run ./cmd/godemirror-demo -file view.go                   # a file
go run ./cmd/godemirror-demo -old a.go -file b.go -changes   # a diff of two files
git diff > /tmp/change.patch
go run ./cmd/godemirror-demo -diff /tmp/change.patch -new path/to/changed/file -split

In the window: Alt+W toggles wrapping, Alt+S switches a diff between unified and side by side, and Alt+N opens a comment under the selected lines. Reverting a chunk of two files puts it back and shows the diff again. -narrow uses the narrow gutter, -search text highlights its matches and selects the first (with -edit, which shows the file in an Editor, it selects them all), -light uses LightTheme, and -bench N with -shot out.png runs it headless and reports frame times. With -edit, -lsp gopls attaches a language server started in the file's directory; headless, -at line:col and -type text type at a place, -hover x,y rests the pointer (with -ctrl, Ctrl held), and -wait 4s keeps drawing until the server has answered, and -key Shift+F12 then presses a key; -format formats the file through the server, and -settings '{"gopls":{...}}' gives the server its settings, and -symbols prints the file's outline.

Requirements

  • Go 1.27. The library is pure Go and builds with CGO_ENABLED=0; the demo opens a window through Gio's app package, which needs a C toolchain on Linux.
  • Gio's system libraries for your platform (on Linux: Wayland or X11, libxkbcommon, EGL and Vulkan headers), as listed in Gio's install guide.
  • fontconfig (fc-match, fc-list), where it is installed, to resolve font families and fall back for missing characters. Without it (stock Windows and macOS, a bare Linux), New reads the fonts in the platform's font directories instead and matches the family by the name each font carries, failing with ErrFontNotFound when none has it; NewFromFonts takes the font files' contents and draws a character they lack as a box.

Build from source

go build ./...
go test ./...

CONTRIBUTING.md has the gate a change goes through, how to run the demo headless, and how to report a bug or propose a change.

License

MIT © 2026 omartelo

internal/lezer ports Lezer and its CSS, Go, HTML, Java, JavaScript, Python and Rust grammars, MIT licensed © 2018 Marijn Haverbeke and others: see its license. internal/stream ports @codemirror/language's stream parser and the Kotlin and shell modes of @codemirror/legacy-modes, MIT licensed © 2018-2021 Marijn Haverbeke and others: see its license. The editor (Editor, EditorState, ChangeSet, EditorSelection) ports @codemirror/state, @codemirror/view, @codemirror/commands, @codemirror/language and @marijn/find-cluster-break, MIT licensed © 2018-2024 Marijn Haverbeke and others: see their license.

lsp/servers holds data converted from nvim-lspconfig and mason-registry, Apache-2.0: see its license and notice; its filetype tables come from Vim by way of Neovim, under the Vim license.

Documentation

Overview

Package godemirror is CodeMirror for Gio: a monospace document with a line-number gutter, wrapping or horizontal scrolling, drawn as one image per visible row so a full screen of code costs a handful of quads.

A View shows one document and a Split shows two side by side, read-only. Build them with New or NewSplit, which resolve a font family among the installed fonts, or with NewFromFonts, which takes the font files themselves. Give them a Content and call Layout every frame. An Editor is the opt-in editable view, a port of CodeMirror's EditorState and its transactions.

A View or a Split belongs to the goroutine that lays it out: call its methods and set its fields there, between frames. Only highlighting runs on a goroutine of its own, and its result is taken in by a later Layout.

The view's deliberate limits, and the traps they set for a caller, are in docs/ceilings.md.

Index

Examples

Constants

View Source
const DefaultDefinitionHint = "Ctrl+click to go to definition"

DefaultDefinitionHint is the hint a new Editor shows under a hover while it has a Definition.

Variables

View Source
var (
	DefaultTypeDefinitionKey = Shortcut{key.NameF12, key.ModShortcut | key.ModShift}
	DefaultImplementationKey = Shortcut{key.NameF12, key.ModShortcut}
	DefaultReferencesKey     = Shortcut{key.NameF12, key.ModShift}
)

The keys a new Editor goes to a type definition, an implementation and the references with, as VS Code binds the last two.

View Source
var DarkTheme = Theme{
	Background:       rgb(0x09090b),
	Border:           over(color.NRGBA{R: 0xff, G: 0xff, B: 0xff, A: 26}, rgb(0x09090b)),
	Selection:        color.NRGBA{R: 0x3b, G: 0x82, B: 0xf6, A: 90},
	Cursor:           rgb(0xfafafa),
	SearchMatch:      percent(amber400, 30),
	SearchCurrent:    percent(orange500, 60),
	GutterBackground: rgb(0x09090b),
	GutterForeground: rgb(0x9f9fa9),
	Foreground:       rgb(0xfafafa),
	Highlight: zincHighlight(zincColors{
		keyword: rgb(0xc396f5), str: rgb(0x82cb92), comment: rgb(0x9f9fa9), literal: rgb(0xeca760),
		typeName: rgb(0x71d0d5), property: rgb(0x82b1ed), definition: rgb(0x82b1ed),
		punctuation: rgb(0x9f9fa9), invalid: rgb(0xff6467),
	}),
	Diff: DiffColors{
		Added: ChangeColors{
			Background: percent(emerald400, 14), HoverBackground: percent(emerald500, 20),
			GutterBackground: percent(emerald500, 18), Strip: emerald500,
			Changed: percent(emerald400, 30),
		},
		Deleted: ChangeColors{
			Background: percent(red400, 12), HoverBackground: percent(red500, 17),
			GutterBackground: percent(red500, 15), Strip: red500,
			Changed: percent(red400, 30),
		},
		Separator:       percent(rgb(0xffffff), 10),
		Filler:          percent(rgb(0xffffff), 7),
		AffordanceHover: zinc800,
	},
	Diagnostics: DiagnosticColors{Error: red400, Warning: amber400, Info: blue400, Hint: rgb(0x9f9fa9)},
	Occurrence:  percent(blue400, 22),
	Popup: PopupColors{
		Background: zinc900, Border: over(percent(rgb(0xffffff), 10), zinc900),
		Foreground: rgb(0xfafafa), Muted: rgb(0x9f9fa9),
		Selected: zinc800, SelectedForeground: rgb(0xfafafa),
	},
}

DarkTheme is the palette a new View starts with: zinc greys under an oklch syntax palette, converted to sRGB. A theme of your own starts as a copy of DarkTheme or LightTheme with the fields you want changed.

View Source
var Dracula = cmTheme(true, Theme{
	Background:       rgb(0x282a36),
	Cursor:           rgb(0xf8f8f0),
	Foreground:       rgb(0xf8f8f2),
	Selection:        rgba(0xffffff1a),
	GutterBackground: rgb(0x282a36),
	GutterForeground: rgb(0x6d8a88),
	Occurrence:       rgba(0xffffff33),
	Highlight: NewHighlightStyle(
		TagStyle{Tags: []*tags.Tag{tags.Comment}, Color: rgb(0x6272a4)},
		TagStyle{Tags: []*tags.Tag{tags.String}, Color: rgb(0xf1fa8c)},
		TagStyle{Tags: []*tags.Tag{tags.Atom}, Color: rgb(0xbd93f9)},
		TagStyle{Tags: []*tags.Tag{tags.Meta}, Color: rgb(0xf8f8f2)},
		TagStyle{Tags: []*tags.Tag{tags.Keyword, tags.Operator, tags.TagName}, Color: rgb(0xff79c6)},
		TagStyle{Tags: []*tags.Tag{tags.Function(tags.PropertyName), tags.PropertyName}, Color: rgb(0x66d9ef)},
		TagStyle{Tags: []*tags.Tag{tags.Definition(tags.VariableName), tags.Function(tags.VariableName), tags.ClassName, tags.AttributeName}, Color: rgb(0x50fa7b)},
		TagStyle{Tags: []*tags.Tag{tags.Atom}, Color: rgb(0xbd93f9)},
	),
})

Dracula is @uiw/codemirror-theme-dracula 4.25.12.

View Source
var ErrFontNotFound = glyphs.ErrFontNotFound

ErrFontNotFound is what New fails with, on a machine without fontconfig, when no font in the platform's font directories is of the family it was asked for. Where fontconfig is installed, fc-match picks its closest font instead.

View Source
var ErrNoFontconfig = glyphs.ErrNoFontconfig

ErrNoFontconfig was what New failed with on a machine without fontconfig.

Deprecated: New resolves a family without fontconfig and never fails with it; test for ErrFontNotFound instead.

View Source
var GitHubDark = cmTheme(true, Theme{
	Background:       rgb(0x0d1117),
	Cursor:           rgb(0xc9d1d9),
	Foreground:       rgb(0xc9d1d9),
	Selection:        rgb(0x003d73),
	GutterBackground: rgb(0x333338),
	GutterForeground: rgb(0xcccccc),
	Occurrence:       rgb(0x003d73),
	Highlight: NewHighlightStyle(
		TagStyle{Tags: []*tags.Tag{tags.Standard(tags.TagName), tags.TagName}, Color: rgb(0x7ee787)},
		TagStyle{Tags: []*tags.Tag{tags.Comment, tags.Bracket}, Color: rgb(0x8b949e)},
		TagStyle{Tags: []*tags.Tag{tags.ClassName, tags.PropertyName}, Color: rgb(0xd2a8ff)},
		TagStyle{Tags: []*tags.Tag{tags.VariableName, tags.AttributeName, tags.Number, tags.Operator}, Color: rgb(0x79c0ff)},
		TagStyle{Tags: []*tags.Tag{tags.Keyword, tags.TypeName, tags.TypeOperator}, Color: rgb(0xff7b72)},
		TagStyle{Tags: []*tags.Tag{tags.String, tags.Meta, tags.Regexp}, Color: rgb(0xa5d6ff)},
		TagStyle{Tags: []*tags.Tag{tags.Name, tags.Quote}, Color: rgb(0x7ee787)},
		TagStyle{Tags: []*tags.Tag{tags.Heading, tags.Strong}, Color: rgb(0xd2a8ff), Bold: true},
		TagStyle{Tags: []*tags.Tag{tags.Emphasis}, Color: rgb(0xd2a8ff), Italic: true},
		TagStyle{Tags: []*tags.Tag{tags.Deleted}, Color: rgb(0xffdcd7)},
		TagStyle{Tags: []*tags.Tag{tags.Atom, tags.Bool, tags.Special(tags.VariableName)}, Color: rgb(0xffab70)},
		TagStyle{Tags: []*tags.Tag{tags.Link}, Underline: true},
		TagStyle{Tags: []*tags.Tag{tags.Strikethrough}, Strikethrough: true},
		TagStyle{Tags: []*tags.Tag{tags.Invalid}, Color: rgb(0xf97583)},
	),
})

GitHubDark is githubDark from @uiw/codemirror-theme-github 4.25.12. It sets no gutter colors, so its gutter is @codemirror/view's dark one.

View Source
var GitHubLight = cmTheme(false, Theme{
	Background:       rgb(0xffffff),
	Foreground:       rgb(0x24292e),
	Selection:        rgb(0xbbdfff),
	GutterBackground: rgb(0xffffff),
	GutterForeground: rgb(0x6e7781),
	Occurrence:       rgb(0xbbdfff),
	Highlight: NewHighlightStyle(
		TagStyle{Tags: []*tags.Tag{tags.Standard(tags.TagName), tags.TagName}, Color: rgb(0x116329)},
		TagStyle{Tags: []*tags.Tag{tags.Comment, tags.Bracket}, Color: rgb(0x6a737d)},
		TagStyle{Tags: []*tags.Tag{tags.ClassName, tags.PropertyName}, Color: rgb(0x6f42c1)},
		TagStyle{Tags: []*tags.Tag{tags.VariableName, tags.AttributeName, tags.Number, tags.Operator}, Color: rgb(0x005cc5)},
		TagStyle{Tags: []*tags.Tag{tags.Keyword, tags.TypeName, tags.TypeOperator}, Color: rgb(0xd73a49)},
		TagStyle{Tags: []*tags.Tag{tags.String, tags.Meta, tags.Regexp}, Color: rgb(0x032f62)},
		TagStyle{Tags: []*tags.Tag{tags.Name, tags.Quote}, Color: rgb(0x22863a)},
		TagStyle{Tags: []*tags.Tag{tags.Heading, tags.Strong}, Color: rgb(0x24292e), Bold: true},
		TagStyle{Tags: []*tags.Tag{tags.Emphasis}, Color: rgb(0x24292e), Italic: true},
		TagStyle{Tags: []*tags.Tag{tags.Deleted}, Color: rgb(0xb31d28)},
		TagStyle{Tags: []*tags.Tag{tags.Atom, tags.Bool, tags.Special(tags.VariableName)}, Color: rgb(0xe36209)},
		TagStyle{Tags: []*tags.Tag{tags.URL, tags.Escape, tags.Regexp, tags.Link}, Color: rgb(0x032f62)},
		TagStyle{Tags: []*tags.Tag{tags.Link}, Underline: true},
		TagStyle{Tags: []*tags.Tag{tags.Strikethrough}, Strikethrough: true},
		TagStyle{Tags: []*tags.Tag{tags.Invalid}, Color: rgb(0xcb2431)},
	),
})

GitHubLight is githubLight from @uiw/codemirror-theme-github 4.25.12. Its deleted text's background is not drawn, nor would CodeMirror draw it: the theme writes it without a #.

View Source
var LightTheme = Theme{
	Background:       rgb(0xebebed),
	Border:           rgb(0xdadadd),
	Selection:        color.NRGBA{R: 0x3b, G: 0x82, B: 0xf6, A: 90},
	Cursor:           rgb(0x18181b),
	SearchMatch:      percent(amber400, 55),
	SearchCurrent:    percent(orange500, 60),
	GutterBackground: rgb(0xebebed),
	GutterForeground: rgb(0x64636e),
	Foreground:       rgb(0x18181b),
	Highlight: zincHighlight(zincColors{
		keyword: rgb(0x6c329f), str: rgb(0x206b38), comment: rgb(0x64636e), literal: rgb(0x9d5300),
		typeName: rgb(0x006e74), property: rgb(0x17559b), definition: rgb(0x17559b),
		punctuation: rgb(0x64636e), invalid: rgb(0xe7000b),
	}),
	Diff: DiffColors{
		Added: ChangeColors{
			Background: percent(emerald500, 12), HoverBackground: percent(emerald500, 20),
			GutterBackground: percent(emerald500, 18), Strip: emerald500,
			Changed: percent(emerald500, 25),
		},
		Deleted: ChangeColors{
			Background: percent(red500, 10), HoverBackground: percent(red500, 17),
			GutterBackground: percent(red500, 15), Strip: red500,
			Changed: percent(red500, 22),
		},
		Separator:       rgb(0xdadadd),
		Filler:          percent(rgb(0x18181b), 7),
		AffordanceHover: rgb(0xdedee0),
	},
	Diagnostics: DiagnosticColors{Error: rgb(0xe7000b), Warning: amber600, Info: blue600, Hint: rgb(0x64636e)},
	Occurrence:  percent(blue600, 15),
	Popup: PopupColors{
		Background: rgb(0xfafafa), Border: rgb(0xdadadd),
		Foreground: zinc900, Muted: rgb(0x64636e),
		Selected: rgb(0xdedee0), SelectedForeground: zinc900,
	},
}

LightTheme is DarkTheme's light counterpart, from the same oklch palette. Its selection is DarkTheme's blue.

View Source
var Nord = cmTheme(true, Theme{
	Background:       rgb(0x2e3440),
	Cursor:           rgb(0xffffff),
	Foreground:       rgb(0xffffff),
	Selection:        rgba(0x00000073),
	GutterBackground: rgb(0x2e3440),
	GutterForeground: rgb(0x4c566a),
	Occurrence:       rgba(0x00000073),
	Highlight: NewHighlightStyle(
		TagStyle{Tags: []*tags.Tag{tags.Keyword}, Color: rgb(0x5e81ac)},
		TagStyle{Tags: []*tags.Tag{tags.Name, tags.Deleted, tags.Character, tags.PropertyName, tags.MacroName}, Color: rgb(0x88c0d0)},
		TagStyle{Tags: []*tags.Tag{tags.VariableName}, Color: rgb(0x8fbcbb)},
		TagStyle{Tags: []*tags.Tag{tags.Function(tags.VariableName)}, Color: rgb(0x8fbcbb)},
		TagStyle{Tags: []*tags.Tag{tags.LabelName}, Color: rgb(0x81a1c1)},
		TagStyle{Tags: []*tags.Tag{tags.Color, tags.Constant(tags.Name), tags.Standard(tags.Name)}, Color: rgb(0x5e81ac)},
		TagStyle{Tags: []*tags.Tag{tags.Definition(tags.Name), tags.Separator}, Color: rgb(0xa3be8c)},
		TagStyle{Tags: []*tags.Tag{tags.Brace}, Color: rgb(0x8fbcbb)},
		TagStyle{Tags: []*tags.Tag{tags.Annotation}, Color: rgb(0xd30102)},
		TagStyle{Tags: []*tags.Tag{tags.Number, tags.Changed, tags.Annotation, tags.Modifier, tags.Self, tags.Namespace}, Color: rgb(0xb48ead)},
		TagStyle{Tags: []*tags.Tag{tags.TypeName, tags.ClassName}, Color: rgb(0xebcb8b)},
		TagStyle{Tags: []*tags.Tag{tags.Operator, tags.OperatorKeyword}, Color: rgb(0xa3be8c)},
		TagStyle{Tags: []*tags.Tag{tags.TagName}, Color: rgb(0xb48ead)},
		TagStyle{Tags: []*tags.Tag{tags.SquareBracket}, Color: rgb(0xbf616a)},
		TagStyle{Tags: []*tags.Tag{tags.AngleBracket}, Color: rgb(0xd08770)},
		TagStyle{Tags: []*tags.Tag{tags.AttributeName}, Color: rgb(0xebcb8b)},
		TagStyle{Tags: []*tags.Tag{tags.Regexp}, Color: rgb(0x5e81ac)},
		TagStyle{Tags: []*tags.Tag{tags.Quote}, Color: rgb(0xb48ead)},
		TagStyle{Tags: []*tags.Tag{tags.String}, Color: rgb(0xa3be8c)},
		TagStyle{Tags: []*tags.Tag{tags.Link}, Color: rgb(0xa3be8c), Underline: true},
		TagStyle{Tags: []*tags.Tag{tags.URL, tags.Escape, tags.Special(tags.String)}, Color: rgb(0x8fbcbb)},
		TagStyle{Tags: []*tags.Tag{tags.Meta}, Color: rgb(0x88c0d0)},
		TagStyle{Tags: []*tags.Tag{tags.Monospace}, Color: rgb(0xd8dee9), Italic: true},
		TagStyle{Tags: []*tags.Tag{tags.Comment}, Color: rgb(0x4c566a), Italic: true},
		TagStyle{Tags: []*tags.Tag{tags.Strong}, Color: rgb(0x5e81ac), Bold: true},
		TagStyle{Tags: []*tags.Tag{tags.Emphasis}, Color: rgb(0x5e81ac), Italic: true},
		TagStyle{Tags: []*tags.Tag{tags.Strikethrough}, Strikethrough: true},
		TagStyle{Tags: []*tags.Tag{tags.Heading}, Color: rgb(0x5e81ac), Bold: true},
		TagStyle{Tags: []*tags.Tag{tags.Special(tags.Heading1)}, Color: rgb(0x5e81ac), Bold: true},
		TagStyle{Tags: []*tags.Tag{tags.Heading1}, Color: rgb(0x5e81ac), Bold: true},
		TagStyle{Tags: []*tags.Tag{tags.Heading2, tags.Heading3, tags.Heading4}, Color: rgb(0x5e81ac), Bold: true},
		TagStyle{Tags: []*tags.Tag{tags.Heading5, tags.Heading6}, Color: rgb(0x5e81ac)},
		TagStyle{Tags: []*tags.Tag{tags.Atom, tags.Bool, tags.Special(tags.VariableName)}, Color: rgb(0xd08770)},
		TagStyle{Tags: []*tags.Tag{tags.ProcessingInstruction, tags.Inserted}, Color: rgb(0x8fbcbb)},
		TagStyle{Tags: []*tags.Tag{tags.ContentSeparator}, Color: rgb(0xebcb8b)},
		TagStyle{Tags: []*tags.Tag{tags.Invalid}, Color: rgb(0x434c5e)},
	),
})

Nord is @uiw/codemirror-theme-nord 4.25.12. The dotted border under invalid code is not drawn.

View Source
var OneDark = cmTheme(true, Theme{
	Background:       rgb(0x282c34),
	Cursor:           rgb(0x528bff),
	Foreground:       rgb(0xabb2bf),
	Selection:        rgb(0x3e4451),
	GutterBackground: rgb(0x282c34),
	GutterForeground: rgb(0x7d8799),
	SearchMatch:      rgba(0x72a1ff59),
	SearchCurrent:    rgba(0x6199ff2f),
	Popup: PopupColors{
		Background: rgb(0x353a42), Border: rgb(0x353a42),
		Selected: rgb(0x2c313a), SelectedForeground: rgb(0xabb2bf),
	},
	Occurrence: rgba(0xaafe661a),
	Highlight: func() *HighlightStyle {
		chalky, coral, cyan, ivory := rgb(0xe5c07b), rgb(0xe06c75), rgb(0x56b6c2), rgb(0xabb2bf)
		stone, malibu, sage, whiskey := rgb(0x7d8799), rgb(0x61afef), rgb(0x98c379), rgb(0xd19a66)
		violet, invalid := rgb(0xc678dd), rgb(0xffffff)
		return NewHighlightStyle(
			TagStyle{Tags: []*tags.Tag{tags.Keyword}, Color: violet},
			TagStyle{Tags: []*tags.Tag{tags.Name, tags.Deleted, tags.Character, tags.PropertyName, tags.MacroName}, Color: coral},
			TagStyle{Tags: []*tags.Tag{tags.Function(tags.VariableName), tags.LabelName}, Color: malibu},
			TagStyle{Tags: []*tags.Tag{tags.Color, tags.Constant(tags.Name), tags.Standard(tags.Name)}, Color: whiskey},
			TagStyle{Tags: []*tags.Tag{tags.Definition(tags.Name), tags.Separator}, Color: ivory},
			TagStyle{Tags: []*tags.Tag{tags.TypeName, tags.ClassName, tags.Number, tags.Changed, tags.Annotation, tags.Modifier, tags.Self, tags.Namespace}, Color: chalky},
			TagStyle{Tags: []*tags.Tag{tags.Operator, tags.OperatorKeyword, tags.URL, tags.Escape, tags.Regexp, tags.Link, tags.Special(tags.String)}, Color: cyan},
			TagStyle{Tags: []*tags.Tag{tags.Meta, tags.Comment}, Color: stone},
			TagStyle{Tags: []*tags.Tag{tags.Strong}, Bold: true},
			TagStyle{Tags: []*tags.Tag{tags.Emphasis}, Italic: true},
			TagStyle{Tags: []*tags.Tag{tags.Strikethrough}, Strikethrough: true},
			TagStyle{Tags: []*tags.Tag{tags.Link}, Color: stone, Underline: true},
			TagStyle{Tags: []*tags.Tag{tags.Heading}, Color: coral, Bold: true},
			TagStyle{Tags: []*tags.Tag{tags.Atom, tags.Bool, tags.Special(tags.VariableName)}, Color: whiskey},
			TagStyle{Tags: []*tags.Tag{tags.ProcessingInstruction, tags.String, tags.Inserted}, Color: sage},
			TagStyle{Tags: []*tags.Tag{tags.Invalid}, Color: invalid},
		)
	}(),
})

OneDark is @codemirror/theme-one-dark 6.1.3.

Functions

func Highlight added in v0.11.0

func Highlight(filename, text string, styles []StyleTags, theme Theme) ([][]Run, error)

Highlight is text colored as a View with theme colors it, for a caller that draws the text itself, a code block in Markdown, say: the language picked by filename as Content.Filename picks it, styles adding rules as Content.StyleTags do. It returns the runs of each line, a line's tabs expanded to the View's stops. Each Run's Style has its Tags left empty and a Color, theme.Foreground where no spec gives one. A filename no language claims gives each line one run in theme.Foreground. Highlighting runs on the calling goroutine.

Types

type Align

type Align int

Align is where ScrollToLine puts its line in the view.

const (
	// AlignNearest scrolls as little as brings the whole line into view, and
	// not at all when it is already in view.
	AlignNearest Align = iota
	// AlignCenter puts the line in the middle of the view.
	AlignCenter
	// AlignTop puts the line at the top of the view.
	AlignTop
)

type BlockWidget

type BlockWidget struct {
	// After is the document line (0-based) the block opens under.
	After int
	// Widget is laid out exactly once every frame, on screen or not, so the
	// document's height is known; its height is the one it lays itself out
	// at, and its width the code area's.
	Widget layout.Widget
}

BlockWidget is a Gio widget laid out between two lines, across the code area, as tall as it lays itself out: a review thread under the line it is about, or the box a comment is being typed into. It takes the pointer over it; the view does not select or hover there.

Its state is the caller's, held outside the view, so rebuilding the content around it (a gap pulled in, a thread resolved) never loses what is half typed inside.

type ChangeColors

type ChangeColors struct {
	Background, HoverBackground, GutterBackground, Strip, Changed color.NRGBA
}

ChangeColors are how an added or a deleted line is drawn: its Background, and HoverBackground while the pointer is over its chunk; its gutter cell's GutterBackground, and a Strip down that cell's left edge. Changed tints the words that changed within the line (DiffOptions.HighlightChanges), over its background.

type ChangeSet added in v0.9.0

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

ChangeSet is a group of changes to a document of one length, as CodeMirror's ChangeSet: an Update carries the one that took the document before it to the one after.

func (ChangeSet) Empty added in v0.9.0

func (c ChangeSet) Empty() bool

Empty reports whether the set changes nothing.

func (ChangeSet) IterChanges added in v0.9.0

func (c ChangeSet) IterChanges(f func(fromA, toA, fromB, toB int, inserted string))

IterChanges calls f for each changed range, in document order: [fromA, toA) in the old document is replaced by [fromB, toB) in the new one, which holds inserted. Adjacent changes are reported as one.

func (ChangeSet) IterGaps added in v0.9.0

func (c ChangeSet) IterGaps(f func(posA, posB, length int))

IterGaps calls f for each stretch the changes leave alone: where it starts in the old document (posA) and in the new one (posB), and its length.

func (ChangeSet) Len added in v0.9.0

func (c ChangeSet) Len() int

Len is the length of the document before the changes.

func (ChangeSet) MapPos added in v0.9.0

func (c ChangeSet) MapPos(pos, assoc int) int

MapPos is where pos, a position in the document before the changes, ends up after them. assoc decides a position that text was inserted at or that a replacement spans: negative keeps it with the character before it (before the insertion), zero or positive with the character after. pos must be in [0, Len()].

func (ChangeSet) MapPosTrack added in v0.9.0

func (c ChangeSet) MapPosTrack(pos, assoc int, mode MapMode) (mapped int, ok bool)

MapPosTrack is MapPos, but ok is false when the changes deleted what mode tracks around pos.

func (ChangeSet) NewLen added in v0.9.0

func (c ChangeSet) NewLen() int

NewLen is the length of the document after the changes.

func (ChangeSet) String added in v0.9.0

func (c ChangeSet) String() string

String lists the sections as CodeMirror's ChangeDesc.toString does: "5" for five bytes kept, "2:3" for two replaced by three.

type ChangeSpec added in v0.9.0

type ChangeSpec struct {
	From, To int
	Insert   string
}

ChangeSpec replaces the bytes [From, To) of a document with Insert. An insertion has To == From, a deletion an empty Insert. Line breaks in Insert (LF, CRLF or CR, or only the editor's LineSeparator when it has one) become the document's line breaks.

type ChangedLine

type ChangedLine struct {
	Side Side
	// Line is 1-based.
	Line int
	Text string
}

ChangedLine is a deleted line (OldSide, numbered in the original file) or an added one (NewSide, numbered in the modified file), with its text.

type Chunk

type Chunk struct {
	OldStart, OldCount, NewStart, NewCount int
	// Lines are the chunk's lines in diff order: its deletions, then its
	// additions.
	Lines []ChangedLine
}

Chunk is a run of changed lines with no unchanged line between them. Each side's start is the 1-based number of its first line there; a side the chunk has no lines in (Count 0) starts at the line the chunk sits before.

type CodeAction added in v0.12.0

type CodeAction struct {
	Title, Kind string
	Data        any
}

CodeAction is an action CodeActions offers on a range: Title is what the list shows, Kind what it is ("quickfix", "refactor"...), and Data the hook's own, for ApplyCodeAction to read.

type Collapse

type Collapse struct{ Margin, MinSize int }

Collapse leaves unchanged runs out of a diff of two documents, the way CodeMirror's collapseUnchanged does: Margin lines stay next to each change, and a run is left out only when that hides at least MinSize lines (and at least one).

type CompletionItem added in v0.12.0

type CompletionItem struct {
	Label string
	Kind  CompletionKind
	// Detail, a type or a signature, shows at the right of the menu and
	// over Documentation, Markdown, beside it, while the item is chosen.
	Detail, Documentation string
	// From and To are the range Insert replaces, positions in the state
	// the completions were asked in; To grows to the cursor as the user
	// types on. A hook with nothing better takes CompletionRequest.From and
	// Pos.
	From, To int
	// Insert replaces the range when the item is taken; empty inserts
	// Label. With Snippet set it is a snippet, inserted as InsertSnippet
	// inserts one.
	Insert  string
	Snippet bool
	// Filter is what the text typed is matched against; empty matches
	// Label.
	Filter string
	// Data is the hook's own, for ResolveCompletion to read.
	Data any
}

CompletionItem is one completion an Editor offers.

type CompletionKind added in v0.12.0

type CompletionKind string

CompletionKind is what a completion names, which picks the badge before its label: one of the kinds below, those of @codemirror/autocomplete's Completion.type, or "" for none.

const (
	CompletionClass     CompletionKind = "class"
	CompletionConstant  CompletionKind = "constant"
	CompletionEnum      CompletionKind = "enum"
	CompletionFunction  CompletionKind = "function"
	CompletionInterface CompletionKind = "interface"
	CompletionKeyword   CompletionKind = "keyword"
	CompletionMethod    CompletionKind = "method"
	CompletionNamespace CompletionKind = "namespace"
	CompletionProperty  CompletionKind = "property"
	CompletionText      CompletionKind = "text"
	CompletionType      CompletionKind = "type"
	CompletionVariable  CompletionKind = "variable"
)

The kinds of completion.

type CompletionRequest added in v0.12.0

type CompletionRequest struct {
	State    EditorState
	Pos      int
	From     int
	Trigger  string
	Explicit bool
}

CompletionRequest is what Complete is asked: the completions at Pos, in State, where the word being typed starts at From. Trigger is the trigger character just typed (CompletionTriggers), empty when the user asked with Ctrl+Space (Explicit) or typed a word.

type CompletionResult added in v0.12.0

type CompletionResult struct {
	Items      []CompletionItem
	Incomplete bool
}

CompletionResult is what Complete answers. Incomplete asks Complete again as the user types on, instead of filtering Items.

type Content

type Content struct {
	// Filename picks the language Text is highlighted as, by its name or
	// extension; a name no lexer claims is shown plain.
	Filename string
	// Text is the document. Lines end in LF or CRLF, and a final line end
	// does not start an empty line.
	Text string
	// Labels replace the gutter's line numbers; nil numbers the lines from 1.
	Labels      []string
	Decorations []LineDecoration
	// Widgets are drawn on lines, and Blocks between them, in slice order.
	Widgets []LineWidget
	Blocks  []BlockWidget
	// StyleTags add rules to the Lezer grammars they name, for finer tags
	// than CodeMirror's own. A StyleTags naming no Lezer grammar, or a
	// rule whose path does not parse, makes Layout return an error.
	StyleTags []StyleTags
	// contains filtered or unexported fields
}

Content is everything a View shows of one document. Labels and Decorations are indexed by document line (0-based); a line past the end of either has no label or decoration.

type Decorations added in v0.9.0

type Decorations struct {
	Lines   []LineDecorationAt
	Widgets []LineWidgetAt
}

Decorations are an Editor's line decorations and widgets. Several line decorations on one line merge in order: each field one of them sets wins over the ones before, and their Spans join.

type Diagnostic added in v0.12.0

type Diagnostic struct {
	From, To int
	Severity Severity
	Message  string
	// Source names what found the problem (a server, a linter) and Code
	// its name for it; the popup shows them under Message.
	Source, Code string
	// Data is the source's own, for CodeActions to read.
	Data any
}

Diagnostic is a problem in an Editor's document, from a language server or any checker: From and To are positions in the document, in UTF-8 bytes, as every position of an Editor.

type DiagnosticColors added in v0.12.0

type DiagnosticColors struct {
	Error, Warning, Info, Hint color.NRGBA
}

DiagnosticColors are the colors of a diagnostic of each severity.

type DiffBlock

type DiffBlock struct {
	At     LineRef
	Widget layout.Widget
}

DiffBlock is a BlockWidget anchored to a line of a file instead of a row of the layout: a review thread under the line it is about, wherever unified or side by side puts that line. Side by side, it opens on its line's side and leaves the same room on the other.

type DiffColors

type DiffColors struct {
	Added, Deleted ChangeColors
	// Separator rules the row standing for lines a diff leaves out, when it
	// offers nothing to expand them with.
	Separator color.NRGBA
	// Filler hatches the row that, side by side, stands for a line only the
	// other side has.
	Filler color.NRGBA
	// AffordanceHover is the background of the default expand and revert
	// affordances under the pointer. Their text takes GutterForeground.
	AffordanceHover color.NRGBA
}

DiffColors are the colors of a diff. Like a LineDecoration's, each may be translucent and is mixed over the theme's background.

type DiffOptions

type DiffOptions struct {
	// Collapse leaves unchanged runs out of a diff set with SetDocs; nil shows
	// every line. A patch set with SetPatch leaves out what git left out.
	Collapse *Collapse

	// Expand asks for the lines of a gap of a patch, which the DiffView does
	// not have; hand them back with FillGap. nil offers no way to expand a
	// patch's gaps. A diff set with SetDocs fills its gaps itself.
	Expand func(Gap)
	// Revert asks to put a chunk back the way the original had it. The
	// DiffView changes nothing itself: set the diff again once the files
	// have changed. nil offers no revert.
	Revert func(Chunk)
	// ExpandLabel is the text of the default expand affordance for a gap of
	// hidden lines; nil is "N unchanged lines".
	ExpandLabel func(hidden int) string
	// ExpandWidget and RevertWidget replace the default affordances: each
	// gets what it acts on and the function its click calls.
	ExpandWidget func(g Gap, expand func()) layout.Widget
	RevertWidget func(c Chunk, revert func()) layout.Widget

	// UnifiedGutter is how a unified diff numbers its rows; the zero value
	// is TwoColumnGutter. A side-by-side diff always has one number per
	// row, each side's own.
	UnifiedGutter UnifiedGutter
	// RevertPlacement is where Revert's default and RevertWidget's widget
	// sit; the zero value is RevertAtRightEdge.
	RevertPlacement RevertPlacement

	// HighlightChanges tints the words that changed within a line, in each
	// deleted line and the added line it pairs with by position in its
	// chunk, with the theme's ChangeColors.Changed. Lines with no word in
	// common are left whole.
	HighlightChanges bool

	// StyleTags add rules to the Lezer grammars they name, on both sides,
	// as Content.StyleTags does for a View.
	StyleTags []StyleTags
}

DiffOptions are what a DiffView asks of its caller. Every field may be left zero.

type DiffRange

type DiffRange struct {
	OldFrom, OldTo, NewFrom, NewTo int
}

DiffRange is a span of lines in each file, 1-based and inclusive; a side with no line in the span has From and To 0.

type DiffView

type DiffView struct {
	// Split shows the diff side by side, the original on the left; otherwise
	// it is one column with the deletions above the additions.
	Split bool
	// Wrap breaks long lines instead of scrolling them sideways.
	Wrap bool
	// Nested is View.Nested: the diff sits in a parent that scrolls
	// vertically.
	Nested bool
	// contains filtered or unexported fields
}

DiffView shows the difference between two versions of a file, unified in one column or side by side, the way CodeMirror's merge view does: changed lines tinted in the theme's Diff colors, each run of them a chunk that lights up under the pointer. Build one with NewDiffView or NewDiffViewFromFonts, give it a diff with SetDocs or SetPatch, and call Layout every frame. Like a View, it belongs to the goroutine that lays it out.

func NewDiffView

func NewDiffView(family string, size unit.Sp, opts DiffOptions) (*DiffView, error)

NewDiffView builds a diff view drawing family at size, resolved as New resolves it. It fails as New does.

func NewDiffViewFromFonts

func NewDiffViewFromFonts(fonts Fonts, size unit.Sp, opts DiffOptions) (*DiffView, error)

NewDiffViewFromFonts builds a diff view drawing fonts at size, without looking for installed fonts. It fails as NewFromFonts does.

func (*DiffView) Chunks

func (d *DiffView) Chunks() []Chunk

Chunks are the runs of changed lines of the diff set last, in order, with lines filled into a gap counted. Like everything set on a DiffView, they reach the screen once highlighted (see UpdateContent).

func (*DiffView) FillGap

func (d *DiffView) FillGap(g Gap, lines []string)

FillGap lays lines into g, the gap DiffOptions.Expand asked for, in place. They may come in parts: a later part is FillGap(g2, more), with g2 a copy of g whose From has moved past the lines filled so far. A part that does not start where the gap now starts (two expands of one gap in flight), or that answers a diff since replaced, is dropped; lines past the gap's end are ignored.

func (*DiffView) FindNext

func (d *DiffView) FindNext() (Match, bool)

FindNext is View.FindNext in the view on screen: the unified one, or, side by side, the side that holds the selection, or else the right one. A match lies in one side, so a search that wraps never leaves it.

func (*DiffView) FindPrevious

func (d *DiffView) FindPrevious() (Match, bool)

FindPrevious is View.FindPrevious in the view FindNext searches.

func (*DiffView) Height added in v0.12.0

func (d *DiffView) Height(gtx layout.Context, width int) (int, error)

Height is how tall the diff's rows are when laid out width pixels wide, in the mode it is in now (Split, Wrap) at the size and scale of gtx, so a caller can give a DiffView exactly the room it needs, a file's diff in a list of them, say, without laying it out. With Wrap, a line takes as many rows as it wraps into at that width, and a side-by-side row is as tall as the taller of its two sides.

It counts the diff as set, each gap filled so far included, but not the BlockWidgets, whose height only their own layout knows: the caller adds what it knows of them. Without Wrap it is the row count times the row height; with it, every row is measured, a cost to keep off the frame path of a very long diff by calling it only when the diff, the width or Wrap change. Its error means what View.Layout's does for the font size.

func (*DiffView) Layout

func (d *DiffView) Layout(gtx layout.Context) (layout.Dimensions, error)

Layout draws the diff into the whole of gtx.Constraints.Max, unified or side by side, and then runs what its affordances were clicked for: DiffOptions.Expand and Revert are called from here, after the frame is drawn. Its error means what View.Layout's does.

func (*DiffView) Matches

func (d *DiffView) Matches() []Match

Matches are View.Matches of the view FindNext searches: what a search box counts ("3 of 12"). Their lines are that view's rows, not file lines.

func (*DiffView) SelectedChanges

func (d *DiffView) SelectedChanges() []ChangedLine

SelectedChanges are the changed lines the selection covers, in diff order and as Chunk.Lines names them, ready for DiffOptions.Revert's caller to revert just those; nil when nothing changed is selected.

func (*DiffView) SelectedRange

func (d *DiffView) SelectedRange() (r DiffRange, ok bool)

SelectedRange is the span of each file's lines the selection covers, in whichever layout shows it, or ok false when nothing is selected. Side by side, a selection lives on one side, which shows one file, so the other's span is 0.

func (*DiffView) SetBlocks

func (d *DiffView) SetBlocks(blocks []DiffBlock)

SetBlocks lays blocks out under their lines, replacing those set before, from the next Layout once highlighting allows (as UpdateContent does). A block whose line is in a gap, or not in the diff, is not shown until the line is. Its Widget is laid out as a BlockWidget's is: once a frame.

func (*DiffView) SetDocs

func (d *DiffView) SetDocs(filename, original, modified string)

SetDocs shows the diff between two versions of a document, worked out here line by line. filename picks the language both are highlighted as, and names the file: a diff of the same filename replaces the one shown in place, keeping the scroll, and another opens from its top. Either way, what was expanded is collapsed again. Two documents more than 10,000 lines of edits apart in one stretch show that stretch as a single chunk.

func (*DiffView) SetPatch

func (d *DiffView) SetPatch(p FilePatch)

SetPatch shows one file of a patch. Like SetDocs, a new version of the file shown (the same Path, another diff) replaces it in place, and another file opens from its top.

func (*DiffView) SetSearch

func (d *DiffView) SetSearch(q SearchQuery) error

SetSearch is View.SetSearch for the diff: the same query looks through every view it has, unified and both sides of the split, and follows the diff as it is replaced, expanded or given blocks. A Match's Pos counts the rows of the view on screen, deletions and additions included, not file lines; select it with FindNext and read the file lines off SelectedRange.

func (*DiffView) SetTheme

func (d *DiffView) SetTheme(t Theme)

SetTheme colors the diff with t, its code and its changes (t.Diff), from the next Layout. A DiffView starts in DarkTheme.

type DocumentEdit added in v0.12.0

type DocumentEdit struct {
	URI   string
	Edits []TextEdit
}

DocumentEdit are edits to one document, as a rename or a code action makes them: URI names the document, empty for the editor's own; the edits' spans are all in the document before them.

type Editor added in v0.9.0

type Editor struct {
	// Wrap breaks lines at the editor's width instead of scrolling sideways.
	Wrap bool
	// Theme colors the editor; it starts as DarkTheme.
	Theme Theme
	// RectangularSelection makes a drag with Alt held select a rectangle, a
	// range per line, as CodeMirror's rectangularSelection does; it needs
	// AllowMultipleSelections to keep more than one.
	RectangularSelection bool
	// CrosshairCursor turns the pointer into a crosshair while Alt is held,
	// as CodeMirror's crosshairCursor does, a hint that a drag selects a
	// rectangle.
	CrosshairCursor bool
	// OnScroll is View.OnScroll of the editor: a cursor kept in view is the
	// program's scroll, and does not call it.
	OnScroll func()
	// ReduceMotion is View.ReduceMotion of the editor: page motions and far
	// cursor moves scroll at once instead of gliding.
	ReduceMotion bool
	// FormatNumber, when set, spells the gutter's number of line lineNo
	// (counted from 1) in state, the one on screen, as the formatNumber
	// option of @codemirror/view 6.43.15's lineNumbers: relative numbers
	// read the cursor's line from it. The gutter stays as wide as the line
	// count's own number, so a longer text is cut.
	FormatNumber func(lineNo int, state EditorState) string
	// OnUpdate, when set, is called at the end of Layout with the
	// transactions dispatched since the last call, if any, as CodeMirror's
	// updateListener: never while the editor paints, so it may dispatch
	// again, and that transaction is reported after the next frame.
	OnUpdate func(Update)
	// OnKey, when set, sees every key the editor takes, pressed or
	// released, and every text Gio's text input types into it, before the
	// editor acts on it, as a keydown handler of @codemirror/view 6.43.15's
	// EditorView.domEventHandlers: returning true keeps the editor from
	// acting (no keymap command, no clipboard key, no typed text), as the
	// handler's true prevents the default. ev is a key.Event or a
	// key.EditEvent, and Gio sends a key's text apart from the key: taking
	// the key does not take the text, so a caller that types for itself
	// takes both. While OnKey is set the focused editor takes every key, Tab
	// and Shift+Tab included, which then stop moving focus; a key the app
	// binds for itself reaches the app only when the app reads it before
	// the editor's Layout. OnKey may Dispatch.
	OnKey func(gtx layout.Context, ev event.Event) bool
	// Hover, when set, tells what to show over the name at pos, a position
	// in s, once the pointer has rested on it for half a second, as
	// Markdown: the popup shows it above the name, with the diagnostics
	// there. It runs on a goroutine of its own, and ctx is cancelled when the
	// pointer leaves first; an empty answer shows nothing.
	Hover func(ctx context.Context, s EditorState, pos int) (markdown string)
	// Definition, when set, finds where the name at pos, a position in s,
	// is defined, for Ctrl+click and F12; ok false finds nothing. It runs on
	// a goroutine of its own. A Location in the editor's own document
	// moves the cursor there; one in another goes to OnDefinition. While it
	// is set, the name under the pointer shows as a link with Ctrl held,
	// and Ctrl+click goes to its definition instead of adding a cursor.
	Definition GoTo
	// TypeDefinition and Implementation, when set, find where the type of
	// the name at pos is defined, and an implementation of it, for their
	// keys (TypeDefinitionKey, ImplementationKey); they go where they find
	// as Definition goes.
	TypeDefinition, Implementation GoTo
	// OnDefinition, when set, is called at the end of Layout with a place
	// Definition, TypeDefinition or Implementation found in another
	// document, for the app to open.
	OnDefinition func(Location)
	// References, when set, finds the references to the name at pos, a
	// position in s, for ReferencesKey, on a goroutine of its own. Those in
	// the editor's own document (URI empty) are highlighted in the Theme's
	// Occurrence color until the document changes or Escape is pressed, and
	// all of them go to OnReferences at the end of Layout, for the app to
	// list.
	References   func(ctx context.Context, s EditorState, pos int) []Location
	OnReferences func([]Location)
	// TypeDefinitionKey, ImplementationKey and ReferencesKey run
	// TypeDefinition, Implementation and References at the cursor; they
	// start as the Default ones, and the zero Shortcut binds none.
	TypeDefinitionKey, ImplementationKey, ReferencesKey Shortcut
	// DefinitionHint is shown under a hover while Definition is set; it
	// starts as DefaultDefinitionHint, and empty shows none.
	DefinitionHint string
	// Complete, when set, offers completions: the editor asks it after one
	// of CompletionTriggers is typed, after two characters of a word typed
	// in a row, and on Ctrl+Space, and shows the items it answers in a
	// menu under the cursor, filtered by what is typed on. Up and Down
	// choose, Enter and Tab take the chosen item, Escape closes the menu.
	// It runs on a goroutine of its own, with ctx cancelled when its answer
	// is no longer wanted.
	Complete func(ctx context.Context, req CompletionRequest) CompletionResult
	// ResolveCompletion, when set, fills in a chosen item that has no
	// Documentation, on a goroutine of its own; the menu shows what it
	// gives back beside the item.
	ResolveCompletion func(ctx context.Context, item CompletionItem) CompletionItem
	// CompletionTriggers are the characters that ask Complete for
	// completions when typed, "." say.
	CompletionTriggers []string
	// SignatureHelp, when set, tells the signature of the call around pos,
	// a position in s, on a goroutine of its own: the editor asks it after
	// one of SignatureTriggers is typed, trigger, and then after every
	// transaction, trigger empty, while it answers; ok false, past the call
	// say, closes the popup it shows above the cursor, as Escape does.
	SignatureHelp func(ctx context.Context, s EditorState, pos int, trigger string) (sig Signature, ok bool)
	// Rename, when set, makes the edits that rename the symbol at pos, a
	// position in s, to name, on a goroutine of its own. F2 opens an input
	// over the name at the cursor, holding it; Enter renames to what is
	// typed there, Escape closes it. The edits to the editor's own document
	// (URI empty) are made as one transaction, if it has not changed since;
	// those to other documents go to OnWorkspaceEdit at the end of Layout.
	// An error shows at the symbol until the next transaction.
	Rename func(ctx context.Context, s EditorState, pos int, name string) ([]DocumentEdit, error)
	// CodeActions, when set, finds the actions on from, to, positions in s,
	// where diags are, on a goroutine of its own: the editor asks it when the
	// cursor reaches a line with a diagnostic (a bulb in the gutter shows
	// there are some) and on Ctrl+., which lists them under the cursor, as a
	// click on the bulb does. Up and Down choose, Enter takes the action,
	// Escape closes the list.
	CodeActions func(ctx context.Context, s EditorState, from, to int, diags []Diagnostic) []CodeAction
	// ApplyCodeAction makes the edits of an action taken, on a goroutine of
	// its own; they are made as Rename's are, an error shown at the cursor.
	ApplyCodeAction func(ctx context.Context, s EditorState, a CodeAction) ([]DocumentEdit, error)
	// OnWorkspaceEdit, when set, gets the edits a rename or a code action
	// makes to documents other than the editor's, for the app to apply.
	OnWorkspaceEdit func([]DocumentEdit)
	// SignatureTriggers are the characters that ask SignatureHelp when
	// typed, "(" and "," say.
	SignatureTriggers []string
	// contains filtered or unexported fields
}

Editor is a View whose document can be changed, CodeMirror's EditorView over an EditorState: the user types, selects, and copies, cuts and pastes with the keys of CodeMirror's standard keymap; a caller changes it with Dispatch, and hears of every change through OnUpdate. Its zero value is not usable; build one with NewEditor or NewEditorFromFonts.

Like a View, an Editor belongs to the goroutine that lays it out.

func NewEditor added in v0.9.0

func NewEditor(family string, size unit.Sp) (*Editor, error)

NewEditor builds an empty editor drawing family at size, resolved as New resolves it.

func NewEditorFromFonts added in v0.9.0

func NewEditorFromFonts(fonts Fonts, size unit.Sp) (*Editor, error)

NewEditorFromFonts builds an empty editor drawing fonts at size, as NewFromFonts does.

func (*Editor) ApplyEdits added in v0.12.0

func (e *Editor) ApplyEdits(edits []DocumentEdit)

ApplyEdits makes edits as a rename makes them: those to the editor's own document (URI empty) one transaction, their spans in the document as it is, and those to others go to OnWorkspaceEdit at the end of the next Layout. It runs on the goroutine that lays the editor out.

func (*Editor) ContentHeight added in v0.9.0

func (e *Editor) ContentHeight() int

ContentHeight is View.ContentHeight of the editor.

func (*Editor) CoordsAtPos added in v0.12.0

func (e *Editor) CoordsAtPos(pos, side int) (image.Rectangle, bool)

CoordsAtPos is where pos shows, as CodeMirror's coordsAtPos: a rectangle of no width from the top to the bottom of its row, in pixels from the editor's top left, as the last Layout placed it with its gutter and scrolling. A negative side puts pos with the character before it, any other with the one after, which tells where a line breaks under Wrap: at the end of the row above or the start of the next. pos is a position in the document the last Layout showed, which a Dispatch since does not change. It reports false, where CodeMirror returns null, before the first Layout, for a state set since, and for pos outside the document or inside a character. Scrolled away, the rectangle lies outside the editor.

func (*Editor) Diagnostics added in v0.12.0

func (e *Editor) Diagnostics() []Diagnostic

Diagnostics are the editor's diagnostics, mapped through every edit since they were set, in document order. It is a copy.

func (*Editor) Dispatch added in v0.9.0

func (e *Editor) Dispatch(spec TransactionSpec) error

Dispatch applies spec to the editor's state as one transaction. The new state is State at once and shows on the next Layout, which reports it to OnUpdate; outside of OnUpdate, ask the window for that frame. It fails, changing nothing, when a change or a selection range of spec is outside the document, inside a character, or a change's From is after its To.

func (*Editor) Focus added in v0.9.0

func (e *Editor) Focus(gtx layout.Context)

Focus gives the editor the keyboard, as CodeMirror's EditorView.focus: it takes keys and text from the next frame on, and shows its carets.

func (*Editor) Geometry added in v0.10.0

func (e *Editor) Geometry() Geometry

Geometry is View.Geometry of the editor.

func (*Editor) HasFocus added in v0.12.0

func (e *Editor) HasFocus(gtx layout.Context) bool

HasFocus reports whether the editor has the keyboard in gtx, as @codemirror/view 6.43.15's EditorView.hasFocus. It answers before the editor's Layout in a frame as well as after, so an app that reads its own shortcuts first can leave the keys to a focused editor.

func (*Editor) InsertSnippet added in v0.12.0

func (e *Editor) InsertSnippet(from, to int, snippet string) error

InsertSnippet replaces from, to with snippet, positions in the document and the snippet in the syntax above, each of its lines after the first indented as the line from is on; it selects the first field, and Tab and Shift+Tab then go from field to field until the last, $0 or the snippet's end. Escape, or a selection out of the snippet, ends it. It fails as Dispatch fails.

func (*Editor) Layout added in v0.9.0

func (e *Editor) Layout(gtx layout.Context) (layout.Dimensions, error)

Layout draws the editor into the whole of gtx.Constraints.Max, as View.Layout draws a view; takes the keys, text, clipboard contents and pointer addressed to it and dispatches what they do; and then reports what was dispatched to OnUpdate. While it has focus, the caret of every range blinks, and Layout asks for a frame at each blink. The errors are View.Layout's.

func (*Editor) LineBlockAt added in v0.9.0

func (e *Editor) LineBlockAt(pos int) (top, bottom int)

LineBlockAt is where the line pos is on shows, as View.LineBlock and CodeMirror's lineBlockAt. pos is a position in the document the last Layout showed, which a Dispatch since does not change.

func (*Editor) LineBlockAtHeight added in v0.9.0

func (e *Editor) LineBlockAtHeight(y int) Line

LineBlockAtHeight is the line at y pixels from the top of the document, as View.LineAtHeight and CodeMirror's lineBlockAtHeight, a line of the document the last Layout showed.

func (*Editor) NextDiagnostic added in v0.12.0

func (e *Editor) NextDiagnostic(severity Severity) bool

NextDiagnostic moves the cursor to the start of the next diagnostic of severity after it, wrapping around to the first, and shows its message there until the selection moves; severity 0 takes any. It reports whether there was one. F8 runs it for any severity.

func (*Editor) Post added in v0.12.0

func (e *Editor) Post(f func())

Post runs f on the goroutine that lays the editor out, at the start of its next Layout, where f may call any of the editor's methods. It may be called from any goroutine, a language client's say; the caller asks the window for that frame (app.Window.Invalidate).

func (*Editor) PrevDiagnostic added in v0.12.0

func (e *Editor) PrevDiagnostic(severity Severity) bool

PrevDiagnostic is NextDiagnostic backwards: the last diagnostic of severity before the cursor, wrapping around to the last. Shift+F8 runs it for any severity.

func (*Editor) Redo added in v0.9.0

func (e *Editor) Redo() bool

Redo makes the last undone event again, as CodeMirror's redo, and reports whether there was one.

func (*Editor) RedoDepth added in v0.9.0

func (e *Editor) RedoDepth() int

RedoDepth is how many events Redo can make again, as CodeMirror's redoDepth.

func (*Editor) ScrollTarget added in v0.12.0

func (e *Editor) ScrollTarget() int

ScrollTarget is View.ScrollTarget of the editor.

func (*Editor) ScrollTop added in v0.9.0

func (e *Editor) ScrollTop() int

ScrollTop is View.ScrollTop of the editor.

func (*Editor) SetDiagnostics added in v0.12.0

func (e *Editor) SetDiagnostics(d []Diagnostic)

SetDiagnostics replaces the editor's diagnostics with d, positions in its current document. From then on they follow edits as text does: a diagnostic whose whole range is deleted is dropped. A position outside the document is clamped to it, and one inside a character goes to its start. The editor draws them from its next Layout: a wavy underline in the Theme's Diagnostics color of each one's severity, a dot in the gutter of the line each starts on (the worst severity's), and the messages in a popup while the pointer rests over a range. Like Dispatch, it is called on the goroutine that lays the editor out.

func (*Editor) SetScrollTop added in v0.9.0

func (e *Editor) SetScrollTop(y int)

SetScrollTop is View.SetScrollTop of the editor.

func (*Editor) SetState added in v0.9.0

func (e *Editor) SetState(c EditorStateConfig) error

SetState replaces the editor's state with a new one made from c, shown from its top, as CodeMirror's EditorView.setState: OnUpdate does not hear of it, and transactions not yet reported are dropped. It fails, leaving the editor as it was, when c.Selection is outside c.Doc or inside one of its characters.

func (*Editor) SnapScrollTop added in v0.12.0

func (e *Editor) SnapScrollTop(y int)

SnapScrollTop is View.SnapScrollTop of the editor.

func (*Editor) State added in v0.9.0

func (e *Editor) State() EditorState

State is the editor's current state, with every transaction dispatched so far, shown or not.

func (*Editor) Undo added in v0.9.0

func (e *Editor) Undo() bool

Undo takes the last undo event back, as CodeMirror's undo: changes made close together are one event, unless a transaction isolated them. It reports whether there was one to undo.

func (*Editor) UndoDepth added in v0.9.0

func (e *Editor) UndoDepth() int

UndoDepth is how many events Undo can take back, as CodeMirror's undoDepth.

type EditorSelection added in v0.9.0

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

EditorSelection is one or more ranges, sorted and never overlapping (two non-empty ranges may touch), one of them the main range, as CodeMirror's EditorSelection. Its zero value has no ranges: a TransactionSpec or EditorStateConfig takes it as no selection given.

func NewSelection added in v0.9.0

func NewSelection(ranges []SelectionRange, main int) EditorSelection

NewSelection is a selection of ranges with ranges[main] as its main range. Ranges are sorted, and those that overlap merged, as CodeMirror's EditorSelection.create does: two cursors at one place become one, and a range merged into another takes the direction of the later of the two. It panics when ranges is empty or main is not one of its indices.

func SingleSelection added in v0.9.0

func SingleSelection(anchor, head int) EditorSelection

SingleSelection is a selection of the one range from anchor to head.

func (EditorSelection) AddRange added in v0.9.0

AddRange is the selection with r added as its main range, merged with any range it overlaps.

func (EditorSelection) AsSingle added in v0.9.0

func (s EditorSelection) AsSingle() EditorSelection

AsSingle is the selection of the main range alone.

func (EditorSelection) Main added in v0.9.0

Main is the main range, usually the one added last.

func (EditorSelection) MainIndex added in v0.9.0

func (s EditorSelection) MainIndex() int

MainIndex is the index of the main range in Ranges.

func (EditorSelection) Map added in v0.9.0

Map is the selection moved through changes, which start from the document it is in: a cursor keeps to the character before it.

func (EditorSelection) Ranges added in v0.9.0

func (s EditorSelection) Ranges() []SelectionRange

Ranges are the selection's ranges in document order. It is a copy.

func (EditorSelection) ReplaceRange added in v0.9.0

func (s EditorSelection) ReplaceRange(r SelectionRange, which int) EditorSelection

ReplaceRange is the selection with its range at index which replaced by r, merged with any range it then overlaps.

type EditorState added in v0.9.0

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

EditorState is a document and its selection at one moment. It never changes: a transaction makes a new one. Positions are byte offsets into Doc, whose lines are joined by "\n". Where the read-only views count a column in runes (Pos), an EditorState counts bytes.

func (EditorState) ChangeByRange added in v0.9.0

func (s EditorState) ChangeByRange(f func(SelectionRange) RangeChange) TransactionSpec

ChangeByRange runs f for each range of the selection and merges what it returns into one transaction, each range's changes mapped through the others, as CodeMirror's EditorState.changeByRange does.

func (EditorState) Decorations added in v0.9.0

func (s EditorState) Decorations() Decorations

Decorations are the editor state's decorations, mapped through every change since they were set. It is a copy.

func (EditorState) Doc added in v0.9.0

func (s EditorState) Doc() string

Doc is the document, its lines joined by "\n" whatever LineSeparator is: a position is a byte offset into it.

func (EditorState) IndentUnit added in v0.12.0

func (s EditorState) IndentUnit() string

IndentUnit is one level of indentation in s, as CodeMirror's getIndentUnit reads the indentUnit facet: spaces or tabs.

func (EditorState) Line added in v0.9.0

func (s EditorState) Line(n int) Line

Line is line n, counted from 1 as CodeMirror's Text.line counts. n must be in [1, Lines()].

func (EditorState) LineAt added in v0.9.0

func (s EditorState) LineAt(pos int) Line

LineAt is the line pos is on. pos must be in [0, len(Doc())].

func (EditorState) Lines added in v0.9.0

func (s EditorState) Lines() int

Lines is the number of lines, at least one.

func (EditorState) ReplaceSelection added in v0.9.0

func (s EditorState) ReplaceSelection(text string) TransactionSpec

ReplaceSelection replaces every range of the selection with text, leaving a cursor after each, as CodeMirror's EditorState.replaceSelection does.

func (EditorState) Selection added in v0.9.0

func (s EditorState) Selection() EditorSelection

Selection is the selection.

func (EditorState) SliceDoc added in v0.9.0

func (s EditorState) SliceDoc(from, to int) string

SliceDoc is the document's bytes [from, to), its lines joined by LineSeparator, or by "\n" without one.

type EditorStateConfig added in v0.9.0

type EditorStateConfig struct {
	// Doc is the document. Its line breaks (LF, CRLF or CR, or only
	// LineSeparator when set) become "\n" in EditorState.Doc, and a final
	// line break starts an empty last line, as in CodeMirror.
	Doc string
	// Selection is where the selection starts; the zero EditorSelection puts
	// a cursor at the start.
	Selection EditorSelection
	// AllowMultipleSelections keeps every range of a selection, as
	// CodeMirror's facet of the same name does; without it a selection is
	// cut to its main range.
	AllowMultipleSelections bool
	// LineSeparator, when set, is the only line break Doc and inserted text
	// are split on, and what SliceDoc joins lines with: "\r\n" keeps a CRLF
	// file CRLF.
	LineSeparator string
	// IndentUnit is one level of indentation, as CodeMirror's indentUnit
	// facet: a run of spaces, or of tabs, and two spaces when empty. Enter
	// writes a new line's indentation in it.
	IndentUnit string
	// Filename picks the language Doc is highlighted as, as Content.Filename.
	Filename string
	// StyleTags add rules to the Lezer grammars they name, as
	// Content.StyleTags.
	StyleTags []StyleTags
	// Decorations are the line decorations and widgets the editor starts
	// with.
	Decorations Decorations
	// contains filtered or unexported fields
}

EditorStateConfig is what an Editor starts from, as CodeMirror's EditorState.create takes it.

type FilePatch

type FilePatch struct {
	// Path is the file's path on the new side, or on the old side for a
	// deleted file; it also picks the language the diff is highlighted as.
	Path string
	// OldPath is the file's path on the old side, "" for an added file.
	OldPath        string
	Added, Deleted int
	// contains filtered or unexported fields
}

FilePatch is one file of a unified diff in git's format, as ParsePatch reads it. DiffView.SetPatch shows it.

func ParsePatch

func ParsePatch(patch string) ([]FilePatch, error)

ParsePatch reads every file of a unified diff in git's format (the output of git diff), in order. Text before the first "diff --git" line is skipped. It fails on a hunk header it cannot read.

type Fonts

type Fonts struct {
	Regular, Bold, Italic, BoldItalic []byte
}

Fonts are the contents of a monospace family's font files (TrueType, OpenType or a collection, whose first font is used). Regular is required; a style left nil is drawn with Regular.

type Gap

type Gap struct {
	From, To, OldFrom int
	// contains filtered or unexported fields
}

Gap is an unchanged run of lines a diff leaves out: new-file lines From to To (1-based, inclusive), with OldFrom the old-file line that pairs with From. A DiffView hands one to DiffOptions.Expand and takes the lines back through FillGap.

type Geometry added in v0.10.0

type Geometry struct {
	// GutterWidth is the gutter's width; the code area starts where it ends.
	GutterWidth int
	// TextX is where a line's first cell starts while the view is not
	// scrolled sideways.
	TextX int
	// CellWidth is one cell's width; a wide character takes two.
	CellWidth int
}

Geometry is where a view's last Layout put its gutter and its text across, in pixels from the view's left edge: what a caller needs to draw beside the gutter or past a line's text, which CodeMirror leaves to the DOM.

type GoTo added in v0.12.0

type GoTo func(ctx context.Context, s EditorState, pos int) (loc Location, ok bool)

GoTo finds where to go from the name at pos, a position in s: a definition, a type definition, an implementation. ok false finds nothing.

type HighlightStyle added in v0.2.0

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

HighlightStyle maps highlighting tags to styles, as CodeMirror's does. Each of a token's tags takes the spec of the most specific tag in its Set that has one. A token can have several tags (a grammar gives some nodes more than one, and a node's tags can apply to everything inside it): it is drawn with every spec its tags take, merged in spec order, a later spec's color, bold, italic, underline or line-through winning over an earlier one's, as CSS cascades the classes CodeMirror gives such a token. A token no style reaches is drawn plain in Theme.Foreground. A HighlightStyle is immutable, so a Theme holding it compares equal exactly while it draws the same.

func NewHighlightStyle added in v0.2.0

func NewHighlightStyle(specs ...TagStyle) *HighlightStyle

NewHighlightStyle builds a HighlightStyle from specs, in CodeMirror's order: when two specs name the same tag, the later one is the tag's style and the earlier one no longer applies to it.

func (*HighlightStyle) Specs added in v0.2.0

func (h *HighlightStyle) Specs() []TagStyle

Specs are the specs h was built from, in their order: a copy, so changing them leaves h as it is. A theme of your own can start from another's style with specs of its own appended, which win over the ones they name the same tags as:

t := godemirror.OneDark
t.Highlight = godemirror.NewHighlightStyle(append(t.Highlight.Specs(),
	godemirror.TagStyle{Tags: []*tags.Tag{tags.Keyword}, Color: pink, Bold: true})...)

type IsolateHistory added in v0.9.0

type IsolateHistory int

IsolateHistory keeps a transaction's changes out of the undo event before it, after it, or both, as CodeMirror's isolateHistory annotation.

const (
	// IsolateBefore starts a new undo event with the transaction.
	IsolateBefore IsolateHistory = iota + 1
	// IsolateAfter starts a new undo event after the transaction.
	IsolateAfter
	// IsolateFull makes the transaction an undo event of its own.
	IsolateFull
)

type Line added in v0.9.0

type Line struct {
	Number   int
	From, To int
	Text     string
}

Line is a line of the document: its number, from 1, and the bytes [From, To) of Doc that hold its Text, its line break left out.

type LineColumn added in v0.12.0

type LineColumn struct {
	Line, Column int
}

LineColumn is a place in a document: Line counted from 0, and Column in UTF-8 bytes from the start of the line.

type LineDecoration

type LineDecoration struct {
	// Background tints the code area behind the line.
	Background color.NRGBA
	// GutterBackground tints the line's gutter cell.
	GutterBackground color.NRGBA
	// GutterStrip is a bar down the left edge of the gutter cell.
	GutterStrip color.NRGBA
	// Rule is a hairline through the middle of the line, across the code area.
	Rule color.NRGBA
	// Hatch strikes thin diagonal lines across the code area: the row a
	// side-by-side diff stands in for a line only the other side has.
	Hatch color.NRGBA
	// HoverGroup groups lines that light up together: while the pointer is
	// over any line of a group, every line of it takes HoverBackground in
	// place of Background. 0 is no group.
	HoverGroup int
	// HoverBackground replaces Background while the line's group is under
	// the pointer; zero keeps Background.
	HoverBackground color.NRGBA
	// Spans tint stretches of the line's characters over its background:
	// the words that changed in a diff, say.
	Spans []Span
	// contains filtered or unexported fields
}

LineDecoration styles one document line across every visual row it wraps into. A zero color draws nothing; a translucent one is mixed over the theme's background in sRGB, the way a browser mixes CSS colors.

type LineDecorationAt added in v0.9.0

type LineDecorationAt struct {
	Pos        int
	Decoration LineDecoration
}

LineDecorationAt is a LineDecoration on the line that starts at Pos, as CodeMirror's Decoration.line: text typed at the line's start, a line break included, leaves it where it is, and deleting the line break before the line drops it.

type LineRef

type LineRef struct {
	Side Side
	Line int
}

LineRef names a line of one file of a diff, 1-based.

type LineWidget

type LineWidget struct {
	// Line is the document line (0-based) the widget sits on.
	Line      int
	Placement Placement
	// WhileHovered shows the widget only while the pointer is over its line's
	// hover group (LineDecoration.HoverGroup).
	WhileHovered bool
	// Widget is laid out once in every frame its line is on screen and
	// shown, and not at all in the others.
	Widget layout.Widget
}

LineWidget is a Gio widget drawn on a line of the document: a button on a diff's hunk separator, say. It is laid out with at most the code area's width and one row's height. A press on it is the widget's, never the start of a selection.

type LineWidgetAt added in v0.9.0

type LineWidgetAt struct {
	Pos       int
	Side      int
	Placement Placement
	// WhileHovered shows the widget only while the pointer is over its
	// line's hover group, as LineWidget.WhileHovered.
	WhileHovered bool
	Widget       layout.Widget
}

LineWidgetAt is a LineWidget on the line Pos is on, mapped as CodeMirror maps Decoration.widget at Pos: with Side zero or below, text typed at Pos goes after it; above zero, before it. A deletion across Pos drops it.

type Location added in v0.12.0

type Location struct {
	URI        string
	Start, End LineColumn
}

Location is a span of a document: URI names the document, empty for the editor's own, and Start and End are its ends.

type MapMode added in v0.9.0

type MapMode int

MapMode is how ChangeSet.MapPosTrack reports a position whose surroundings were deleted, as CodeMirror's MapMode does.

const (
	// MapTrackDel reports a position that a deletion spans: the characters
	// on both of its sides are gone.
	MapTrackDel MapMode = iota + 1
	// MapTrackBefore reports a position whose character before it is gone.
	MapTrackBefore
	// MapTrackAfter reports a position whose character after it is gone.
	MapTrackAfter
)

type Match

type Match struct{ From, To Pos }

Match is one match of a search: the runes from From to To (To excluded), counted as Pos counts them, so a tab is one. A match never spans lines.

type Placement

type Placement int

Placement is where on its line a LineWidget sits.

const (
	// AfterText puts the widget one cell past the line's last character, on
	// the last row the line wraps into.
	AfterText Placement = iota
	// RightEdge puts the widget against the code area's right edge, on the
	// line's first row.
	RightEdge
	// GutterCell draws the widget over the line's gutter cell, on the line's
	// first row, in place of its label: the label is not drawn while the
	// widget is. It is laid out with at most the gutter's width and one
	// row's height, and centered in the cell.
	GutterCell
)

type PopupColors added in v0.12.0

type PopupColors struct {
	Background, Border, Foreground, Muted color.NRGBA
	Selected, SelectedForeground          color.NRGBA
}

PopupColors are how an Editor's popups are drawn: a box of Background edged with Border, text in Foreground, and what is secondary (a diagnostic's source, a completion's detail, a hover's documentation) in Muted. The chosen completion is filled with Selected and drawn in SelectedForeground.

type Pos

type Pos struct{ Line, Col int }

Pos is a place in the document between two characters: Line is 0-based, and Col counts the runes of the line's text before it, a tab or a wide character as one. An Editor counts bytes instead (EditorState).

type RangeChange added in v0.9.0

type RangeChange struct {
	Changes []ChangeSpec
	Range   SelectionRange
}

RangeChange is what the function ChangeByRange runs for each range returns: the changes it makes, as positions in the document before any of them, and where the range goes, in the document those changes alone make.

type RevertPlacement added in v0.12.0

type RevertPlacement uint8

RevertPlacement is where a DiffView puts its revert affordance.

const (
	// RevertAtRightEdge puts it against the code area's right edge on the
	// chunk's first row, over the end of the code, with the label "Revert".
	RevertAtRightEdge RevertPlacement = iota
	// RevertInGutter puts it over the chunk's first row's gutter cell, in
	// place of its line number, for a view too narrow to give up the code
	// area's edge. The default affordance there is the compact "↩", which
	// fits the cell; a side-by-side diff uses the new side's gutter.
	RevertInGutter
)

type Run added in v0.11.0

type Run struct {
	Text  string
	Style TagStyle
}

Run is a stretch of one line of highlighted text drawn in one style.

type SearchQuery

type SearchQuery struct {
	Text string
	// CaseSensitive makes a letter match only itself; otherwise Unicode simple
	// case folding applies.
	CaseSensitive bool
	// Regexp reads Text as a Go regular expression (regexp/syntax), matched
	// against one line at a time; otherwise Text is looked for as written.
	Regexp bool
	// WholeWord keeps only the matches that do not cut a word in two: no word
	// character, as the double click reads one (letters, digits and
	// underscore), sits against a match's first or last character when that
	// character is one too.
	WholeWord bool
}

SearchQuery is what SetSearch looks for. Text "" clears the search.

type SelectionRange added in v0.9.0

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

SelectionRange is one range of an EditorSelection, from its anchor, the side that stays put when the range is extended, to its head. Positions are byte offsets into EditorState.Doc. Build one with Cursor or Range.

func Cursor added in v0.9.0

func Cursor(pos int) SelectionRange

Cursor is an empty range at pos.

func Range added in v0.9.0

func Range(anchor, head int) SelectionRange

Range is the range from anchor to head, in either order.

func (SelectionRange) Anchor added in v0.9.0

func (r SelectionRange) Anchor() int

Anchor is the side of the range that stays put when it is extended.

func (SelectionRange) Assoc added in v0.9.0

func (r SelectionRange) Assoc() int

Assoc is the side a cursor sticks to: -1 the character before it, 1 the one after, 0 neither.

func (SelectionRange) Empty added in v0.9.0

func (r SelectionRange) Empty() bool

Empty reports whether the range is a cursor: its anchor is its head.

func (SelectionRange) Extend added in v0.9.0

func (r SelectionRange) Extend(from, to int) SelectionRange

Extend is the range grown to cover at least [from, to], keeping its anchor unless that falls inside.

func (SelectionRange) From added in v0.9.0

func (r SelectionRange) From() int

From is the lower of the range's bounds.

func (SelectionRange) GoalColumn added in v0.9.0

func (r SelectionRange) GoalColumn() (col int, ok bool)

GoalColumn is the column, in cells, a cursor moving up or down keeps aiming for across shorter lines, ok false when it has none.

func (SelectionRange) Head added in v0.9.0

func (r SelectionRange) Head() int

Head is the side of the range that moves when it is extended.

func (SelectionRange) Map added in v0.9.0

Map is the range moved through changes, which start from the document it is in: a cursor keeps to the character before it.

func (SelectionRange) To added in v0.9.0

func (r SelectionRange) To() int

To is the upper of the range's bounds.

type Severity added in v0.12.0

type Severity int

Severity is how bad a Diagnostic is, from SeverityError, the worst, to SeverityHint, numbered as LSP numbers them.

const (
	SeverityError Severity = iota + 1
	SeverityWarning
	SeverityInfo
	SeverityHint
)

The severities of a diagnostic. The zero Severity, in NextDiagnostic and PrevDiagnostic, stands for any.

type Shortcut added in v0.12.0

type Shortcut struct {
	Name      key.Name
	Modifiers key.Modifiers
}

Shortcut is a key pressed with exactly Modifiers held; the zero Shortcut is no key.

type Side

type Side uint8

Side is which file of a diff a line is in.

const (
	// OldSide is the original file, the one a deletion is taken from.
	OldSide Side = iota
	// NewSide is the modified file, the one an addition is put in.
	NewSide
)

type Signature added in v0.12.0

type Signature struct {
	Label  string
	Params []SignatureParam
	Active int
	Doc    string
}

Signature is the signature of the call being typed, as SignatureHelp tells it: Label, code, with the ranges of its parameters in Params, in bytes of Label, Active the one being typed (-1 for none), and Doc, Markdown, under it.

type SignatureParam added in v0.12.0

type SignatureParam struct {
	From, To int
}

SignatureParam is a parameter's range in a Signature's Label.

type Span

type Span struct {
	From, To int
	Color    color.NRGBA
}

Span is a stretch of a line's characters, From to To in rune columns (0-based, To excluded, a tab or a wide character one column), and the Color it is tinted with.

type Split

type Split struct {
	// Left and Right are the two sides. Each is a View, but it is laid out
	// by the Split's Layout, never its own.
	Left, Right *View
	// Wrap breaks both sides' lines instead of scrolling them sideways.
	Wrap bool
	// Nested is View.Nested for both sides.
	Nested bool
}

Split shows two documents side by side whose line i pairs with line i of the other: the two sides of a diff. Each pair of lines starts on the same row: unwrapped that holds by itself, and when the sides wrap, the side that wraps into fewer rows is padded to the other's. A block under a line on one side leaves as much room under its pair on the other. They scroll down together and sideways each on its own.

Content, Theme and selection are each side's own, set on Left and Right; Wrap is the split's, and Layout sets it on both sides.

func NewSplit

func NewSplit(family string, size unit.Sp) (*Split, error)

NewSplit builds a split view whose two sides draw family at size, from one set of loaded fonts. It fails as New does.

func (*Split) Layout

func (s *Split) Layout(gtx layout.Context) (layout.Dimensions, error)

Layout draws both sides into the whole of gtx.Constraints.Max, halved, with a 1dp Border between them. Its error means what View.Layout's does, for either side.

func (*Split) SetTheme

func (s *Split) SetTheme(t Theme)

SetTheme gives both sides t. The divider between them takes the left side's Theme.Border.

type StyleRule added in v0.5.0

type StyleRule struct {
	Selector string
	Tags     []*tags.Tag
	Names    []string
}

StyleRule is one styleTags entry: space-separated paths and the tags the nodes they name take. A path is a node name or group, optionally under its parents ("ArgumentList/Identifier", "*" for any parent), ending in "/..." to give the tags to everything inside the node too, or in "!" to stop matching inside it. A name with "/" or "!" in it is quoted, as in JSON.

Names, when set, limit the rule to nodes whose text is exactly one of them, as the builtin sets (GoBuiltinTags) use it. A node whose text is not among them falls through to the next rule that matches it, a rule with Names being tried before any as deep without. CodeMirror's styleTags cannot read a node's text, so a rule with Names has no CodeMirror equivalent.

type StyleTags added in v0.5.0

type StyleTags struct {
	// Language names the grammar by its @lezer package: "css", "go",
	// "html", "java", "javascript" (JavaScript, JSX, TypeScript and TSX
	// alike), "python" or "rust". Kotlin and shell have no Lezer grammar,
	// so no rules.
	Language string
	// Rules are styleTags' entries, in the order the object would list
	// them.
	Rules []StyleRule
}

StyleTags adds styleTags rules to one language's Lezer grammar, as a CodeMirror caller does with language.configure({props: [styleTags({...})]}): a node the rules match takes their tags, and a rule wins over the grammar's own when its path is at least as deep. It is how the tags a grammar gives can be made finer, telling apart what the tree tells apart and the grammar's own rules do not, as RicherJavaTags does.

func GoBuiltinTags added in v0.6.0

func GoBuiltinTags() StyleTags

GoBuiltinTags tags Go's predeclared identifiers: a type is standard(typeName), a call of a builtin function function(standard(variableName)), a conversion to a builtin type, as in int(x), standard(typeName), and iota standard(variableName). true, false and nil are already literals in @lezer/go, and make before a type is a keyword RicherGoTags tags.

func JavaScriptBuiltinTags added in v0.6.0

func JavaScriptBuiltinTags() StyleTags

JavaScriptBuiltinTags tags JavaScript's and TypeScript's builtins: a global constructor is standard(className), a global function called function(standard(variableName)), any other global standard(variableName), and a TypeScript primitive type standard(typeName).

func PythonBuiltinTags added in v0.6.0

func PythonBuiltinTags() StyleTags

PythonBuiltinTags tags Python's built-in functions and types: called, function(standard(variableName)), and standard(variableName) anywhere else (isinstance(x, int)).

func RicherGoTags added in v0.6.0

func RicherGoTags() StyleTags

RicherGoTags tags Go finer than @lezer/go does: a parameter, receiver or named result is definition(local(variableName)), and make, which the grammar parses as a keyword and leaves untagged when its first argument is a type, function(standard(variableName)). The other builtins (len, append, new, int, error) are names like any other in the tree, so they stay as @lezer/go tags them.

func RicherJavaScriptTags added in v0.6.0

func RicherJavaScriptTags() StyleTags

RicherJavaScriptTags tags JavaScript and TypeScript finer than @lezer/javascript does: a function's, method's or arrow function's parameter is definition(local(variableName)), and so is a name bound by a destructuring pattern one level inside the parameter list.

func RicherJavaTags added in v0.5.0

func RicherJavaTags() StyleTags

RicherJavaTags tags Java finer than @lezer/java does, where its tree tells more than its styleTags do: an enum constant is constant(variableName), an annotation's "@" and name annotation, a field definition(propertyName), a package or import path namespace, and a method's, constructor's or lambda's parameter definition(local(variableName)). A field read, as in a.b, stays variableName: a path cannot tell its object from its field, both being an Identifier under FieldAccess.

func RicherPythonTags added in v0.6.0

func RicherPythonTags() StyleTags

RicherPythonTags tags Python finer than @lezer/python does: a function's or lambda's parameter, self included, is definition(local(variableName)). A default value that is a bare name (x=DEFAULT) is tagged so too: the tree puts it under the parameter list beside the parameter, and a path cannot tell the two apart.

func RicherRustTags added in v0.6.0

func RicherRustTags() StyleTags

RicherRustTags tags Rust finer than @lezer/rust does: a function's or closure's parameter is definition(local(variableName)), and so is a name bound one pattern deep in it ((a, b): (u8, u8), &c: &u8).

func RustBuiltinTags added in v0.6.0

func RustBuiltinTags() StyleTags

RustBuiltinTags tags Rust's primitive types standard(typeName). The prelude (Vec, Option, Some) is ordinary library code and stays as @lezer/rust tags it, as does a primitive type used as a path (i32::MAX), which the grammar parses as a namespace.

type TagStyle added in v0.2.0

type TagStyle struct {
	Tags                                   []*tags.Tag
	Color                                  color.NRGBA
	Bold, Italic, Underline, Strikethrough bool
}

TagStyle is how the code under some tags is drawn, as one spec of CodeMirror's HighlightStyle.define: a color, the CSS fontWeight bold and fontStyle italic, and the textDecoration underline and line-through. A zero Color leaves the text in Theme.Foreground, the way a CSS rule with no color leaves the editor's.

type TextEdit added in v0.12.0

type TextEdit struct {
	Start, End LineColumn
	Text       string
}

TextEdit replaces the span Start, End of a document with Text.

type Theme

type Theme struct {
	// Background fills the code area.
	Background color.NRGBA
	// Selection fills the selected cells.
	Selection color.NRGBA
	// Cursor draws an Editor's caret.
	Cursor color.NRGBA
	// Border divides the two sides of a Split.
	Border color.NRGBA
	// GutterBackground fills the gutter, and GutterForeground draws the line
	// numbers or Content.Labels in it.
	GutterBackground color.NRGBA
	GutterForeground color.NRGBA
	// Foreground is the code's color where Highlight gives it none, as the
	// color of CodeMirror's editor theme is.
	Foreground color.NRGBA
	// Highlight styles the code by its highlighting tags; nil draws it all in
	// Foreground.
	Highlight *HighlightStyle
	// SearchMatch tints every match of the search (SetSearch), and
	// SearchCurrent the one that is selected, the current match. Like
	// Selection they may be translucent: they are mixed over the line's
	// background in sRGB. Zero highlights nothing.
	SearchMatch, SearchCurrent color.NRGBA
	// Diff colors a DiffView's changes and the rows around them.
	Diff DiffColors
	// Diagnostics colors an Editor's diagnostics, their wavy underline and
	// their dot in the gutter, by severity.
	Diagnostics DiagnosticColors
	// Popup draws the boxes an Editor shows over its text: a diagnostic's
	// message, a hover, the completions.
	Popup PopupColors
	// Occurrence tints the references an Editor's References found in its
	// document, as CodeMirror's selectionMatch tints a selection's
	// matches. Like Selection it may be translucent.
	Occurrence color.NRGBA
}

Theme is the view's palette. Selection may be translucent, as may the colors of a LineDecoration: they are mixed over Background in sRGB, the way a browser mixes CSS colors. The other colors are painted as they are and should be opaque, since Gio blends alpha in linear light.

type Transaction added in v0.9.0

type Transaction struct {
	StartState EditorState
	// State is the state the transaction makes.
	State EditorState
	// Changes take the document of StartState to the one of State.
	Changes ChangeSet
	// Selection is the selection the transaction set, or the zero
	// EditorSelection when it only mapped the one before.
	Selection      EditorSelection
	UserEvent      string
	ScrollIntoView bool
	// SkipHistory, IsolateHistory and Time are the spec's, Time now when it
	// gave none.
	SkipHistory    bool
	IsolateHistory IsolateHistory
	Time           time.Time
	// contains filtered or unexported fields
}

Transaction is one update of an EditorState, as CodeMirror's Transaction.

func (Transaction) DocChanged added in v0.9.0

func (t Transaction) DocChanged() bool

DocChanged reports whether the transaction changes the document.

func (Transaction) IsUserEvent added in v0.9.0

func (t Transaction) IsUserEvent(event string) bool

IsUserEvent reports whether the transaction's UserEvent is event or one of its subevents: "select" covers "select.pointer".

type TransactionSpec added in v0.9.0

type TransactionSpec struct {
	// Changes are made to the document at once, positions all in the
	// document before them. Changes given out of order are applied in the
	// order given, each mapped over those before it.
	Changes []ChangeSpec
	// Selection is the selection after the transaction, in the document
	// after the changes. The zero EditorSelection maps the one before through
	// the changes.
	Selection EditorSelection
	// UserEvent names what made the transaction, in CodeMirror's dotted
	// names ("input.type", "delete.backward", "select.pointer"), for
	// Transaction.IsUserEvent.
	UserEvent string
	// ScrollIntoView scrolls the main range's head into view on the next
	// Layout.
	ScrollIntoView bool
	// SkipHistory keeps the transaction out of the undo history, as
	// CodeMirror's Transaction.addToHistory set to false: undo does not
	// take its changes back, and maps the history through them.
	SkipHistory bool
	// IsolateHistory keeps the transaction's changes out of the undo events
	// next to it; by default, changes made close together in time and place
	// are undone as one, as CodeMirror's history groups them.
	IsolateHistory IsolateHistory
	// Time is when the transaction happened, which groups undo events; zero
	// is now.
	Time time.Time
	// Decorations, when set, replace the editor's decorations after the
	// changes, at positions in the document they make; when nil, the
	// decorations are mapped through the changes. A caller recomputes them
	// in OnUpdate, as a CodeMirror state field does with its effects.
	Decorations *Decorations
	// contains filtered or unexported fields
}

TransactionSpec describes a transaction for Editor.Dispatch, as CodeMirror's TransactionSpec.

type UnifiedGutter added in v0.12.0

type UnifiedGutter uint8

UnifiedGutter is what a unified DiffView numbers its rows with.

const (
	// TwoColumnGutter shows the old line number and then the new one, each
	// blank on a row that is not in that file, as `git diff` viewers do.
	TwoColumnGutter UnifiedGutter = iota
	// OneColumnGutter shows one number per row: the line's number in the
	// modified file, or, for a deleted line, in the original. It takes about
	// half the width of TwoColumnGutter, for a narrow view.
	OneColumnGutter
)

type Update added in v0.9.0

type Update struct {
	StartState, State EditorState
	// Changes take the document of StartState to the one of State.
	Changes      ChangeSet
	Transactions []Transaction
}

Update is what an Editor reports after a frame, as CodeMirror's ViewUpdate: the transactions dispatched since the last one, and the changes they made together.

func (Update) DocChanged added in v0.9.0

func (u Update) DocChanged() bool

DocChanged reports whether the document changed.

func (Update) SelectionSet added in v0.9.0

func (u Update) SelectionSet() bool

SelectionSet reports whether a transaction set the selection.

type View

type View struct {
	// Wrap breaks lines at the view's width instead of scrolling sideways.
	Wrap bool
	// Nested is a view laid out inside a parent that scrolls vertically, a
	// panel listing several: a vertical wheel the view cannot scroll down by
	// goes on to the parent, and turns sideways only while the pointer last
	// reported Shift held.
	Nested bool
	// Theme colors the view; it starts as DarkTheme. A change shows on the
	// next Layout, which composes the rows on screen again.
	Theme Theme
	// OnScroll, when set, is called at the end of a Layout in which the
	// user scrolled the view, with the wheel, the touchpad or a selection
	// dragged past an edge; never while the view paints. What the program
	// scrolls (SetScrollTop, SnapScrollTop, ScrollToLine, an Editor keeping
	// its cursor in view) and every frame of a glide does not call it, so a
	// caller that mirrors the scroll elsewhere hears no echo of its own:
	// ScrollTarget says where a glide lands, and ScrollTop, read after each
	// Layout, where the view is. A Split or a DiffView does not call it.
	OnScroll func()
	// ReduceMotion makes every scroll the program asks for land at once
	// instead of gliding there; Gio reports no platform preference for it.
	ReduceMotion bool
	// contains filtered or unexported fields
}

View shows a document. Its zero value is not usable; build one with New or NewFromFonts.

Example
package main

import (
	"errors"
	"fmt"
	"image"
	"log"

	"gioui.org/layout"
	"gioui.org/op"
	"gioui.org/unit"
	"golang.org/x/image/font/gofont/gomono"

	"github.com/lichdotdev/godemirror"
)

func main() {
	view, err := godemirror.New("monospace", unit.Sp(13))
	if errors.Is(err, godemirror.ErrFontNotFound) {
		// Without an installed monospace font, hand the view the font files instead.
		view, err = godemirror.NewFromFonts(godemirror.Fonts{Regular: gomono.TTF}, unit.Sp(13))
	}
	if err != nil {
		log.Fatal(err)
	}
	view.SetContent(godemirror.Content{
		Filename: "main.go",
		Text:     "package main\n\nfunc main() {\n\tprintln(\"hi\")\n}\n",
	})
	view.SelectLines(2, 4)
	view.ScrollToLine(2, godemirror.AlignNearest)

	// In an app, gtx comes from each app.FrameEvent of the window.
	var ops op.Ops
	gtx := layout.Context{
		Ops:         &ops,
		Metric:      unit.Metric{PxPerDp: 1, PxPerSp: 1},
		Constraints: layout.Exact(image.Pt(640, 480)),
	}
	if _, err := view.Layout(gtx); err != nil {
		log.Fatal(err)
	}

	from, to, _ := view.SelectedLines()
	fmt.Printf("%d lines; lines %d-%d selected:\n%s", view.LineCount(), from, to, view.SelectedText())
}
Output:
5 lines; lines 2-4 selected:
func main() {
	println("hi")
}

func New

func New(family string, size unit.Sp) (*View, error)

New builds a view drawing family at size, as in "JetBrains Mono" or "monospace", and a character family lacks is drawn from whichever installed font covers it. Where fontconfig is installed, family is a fontconfig name resolved with fc-match. Elsewhere (Windows, macOS, a Linux without it) it is the family name a font file in the platform's font directories carries, and "monospace" is the platform's own: Cascadia Mono or Consolas on Windows, Menlo on macOS. New fails with ErrFontNotFound when no such font is installed, and with another error when a font file cannot be read.

func NewFromFonts

func NewFromFonts(fonts Fonts, size unit.Sp) (*View, error)

NewFromFonts builds a view drawing fonts at size, without looking for installed fonts. A character the fonts do not cover is drawn as a box, since there is no installed font to fall back to. It fails when Regular is nil or a style is not a font.

func (*View) ClearSelection

func (v *View) ClearSelection()

ClearSelection drops the selection.

func (*View) ContentHeight added in v0.9.0

func (v *View) ContentHeight() int

ContentHeight is the document's height in pixels as the last Layout placed it, blocks included, as CodeMirror's contentHeight. It estimates as LineBlock does.

func (*View) FindNext

func (v *View) FindNext() (m Match, ok bool)

FindNext selects the first match that starts at or after the end of the selection (or the first one, with nothing selected), wrapping around the document, and scrolls it into view as little as it takes. ok is false when there is no match. The match is the current one: lit in Theme.SearchCurrent for as long as it stays selected.

func (*View) FindPrevious

func (v *View) FindPrevious() (m Match, ok bool)

FindPrevious is FindNext backwards: the last match that ends at or before the start of the selection (with nothing selected, the last one), wrapping around the document.

func (*View) Geometry added in v0.10.0

func (v *View) Geometry() Geometry

Geometry is the gutter and the cells of the last Layout, all 0 before any. A Split's or a DiffView's views measure their own.

func (*View) Layout

func (v *View) Layout(gtx layout.Context) (layout.Dimensions, error)

Layout draws the view into the whole of gtx.Constraints.Max, takes the pointer and key events addressed to it (scroll, select, copy), and lays out each LineWidget on screen and every BlockWidget exactly once.

While a selection is dragged beyond the view's top or bottom edge, or, when unwrapped, its left or right, Layout scrolls the view by the time since its last frame (gtx.Now) and asks for the next frame, faster the farther the pointer is beyond the edge. It scrolls no more at the document's ends, on release, or once the pointer is back inside.

An error means nothing was drawn this frame: either the fonts could not be scaled to the size gtx asks for, or the content last set could not be highlighted. In the second case the error is reported once; that content stays plain after SetContent, and is never swapped in after UpdateContent.

func (*View) LineAtHeight added in v0.9.0

func (v *View) LineAtHeight(y int) int

LineAtHeight is the line (0-based) at y pixels from the top of the document, as CodeMirror's lineBlockAtHeight: the first line above the document, the last below it, and the line a block sits under over the block. It estimates as LineBlock does.

func (*View) LineBlock added in v0.9.0

func (v *View) LineBlock(line int) (top, bottom int)

LineBlock is where line (0-based) shows, as CodeMirror's lineBlockAt: the top and bottom of its rows, wrapped ones included, in pixels from the top of the document, as the last Layout placed them; blocks under the line are not part of it. For content set since the last Layout, it is an estimate, as CodeMirror's height map estimates lines it has not measured: a row a line and no blocks. Before any Layout, both are 0. line must be in [0, LineCount()).

func (*View) LineCount

func (v *View) LineCount() int

LineCount is the number of lines shown. A final newline does not start a line of its own. Between UpdateContent and the swap it describes (see UpdateContent), it is the old content's.

func (*View) LineText

func (v *View) LineText(i int) string

LineText is line i (0-based) as written, tabs and all, without its line end. i must be in [0, LineCount()). Like LineCount, it reads the content on screen, which UpdateContent replaces only once highlighted.

func (*View) Matches

func (v *View) Matches() []Match

Matches are the matches of the search, in document order, in the content on screen: between UpdateContent and its swap, the old content's (see UpdateContent). It is a copy.

func (*View) ScrollTarget added in v0.12.0

func (v *View) ScrollTarget() int

ScrollTarget is where the view lands once its glide is over, ScrollTop when it is not gliding. A target SetScrollTop set since the last Layout is not yet kept within the document.

func (*View) ScrollToLine

func (v *View) ScrollToLine(line int, align Align)

ScrollToLine scrolls the view down or up so that line (0-based) sits where align says, as far as the document's ends allow. It takes effect on the next Layout, against the content shown then; a line past the end is the last line. It never scrolls sideways. A View glides there as SetScrollTop does; on either side of a Split it scrolls both, at once.

func (*View) ScrollTop added in v0.9.0

func (v *View) ScrollTop() int

ScrollTop is how far the view is scrolled down, in pixels from the top of the document, as CodeMirror's scrollDOM.scrollTop: where the last Layout drew it, partway through a glide.

func (*View) Select

func (v *View) Select(from, to Pos)

Select selects the text between from and to, in either order, as a drag between them would. A position past the document's start or end, or past its line's end, is clamped to it. The view does not scroll to it.

func (*View) SelectLines

func (v *View) SelectLines(from, to int)

SelectLines selects lines from to to (0-based, inclusive) whole, with the newline after the last of them, as a triple click selects one line; it is the span SelectedLines then reports. Lines past the document are clamped.

func (*View) SelectedLines

func (v *View) SelectedLines() (from, to int, ok bool)

SelectedLines is the span of document lines (0-based, inclusive) the selection covers. A selection that ends at the very start of a line does not take that line in. ok is false when nothing is selected.

func (*View) SelectedText

func (v *View) SelectedText() string

SelectedText is the selected text as the document had it, tabs and all, or "" when nothing is selected.

func (*View) Selection

func (v *View) Selection() (from, to Pos, ok bool)

Selection is the selection's start and end, from before to, or ok false when nothing is selected. A selection made with the pointer that starts or ends inside a tab is read as starting or ending after it.

func (*View) SetContent

func (v *View) SetContent(c Content)

SetContent shows c from its top, with nothing selected. Its text shows at once; its highlighting is worked out off the UI goroutine and swapped in by a later Layout.

func (*View) SetScrollTop added in v0.9.0

func (v *View) SetScrollTop(y int)

SetScrollTop scrolls the view to y pixels from the top of the document, as setting CodeMirror's scrollDOM.scrollTop does, but glides there over the next frames, eased out, unless the jump is a few rows or ReduceMotion is set. The next Layout keeps it within the document. A wheel during the glide stops it where the view is.

func (*View) SetSearch

func (v *View) SetSearch(q SearchQuery) error

SetSearch highlights every match of q in the content shown, and keeps doing so as the content changes (SetContent, and UpdateContent once its content is on screen). Matches are looked for line by line. An empty q.Text clears the search; a Text that is not a valid regexp clears it too and is the only error. A theme with no SearchMatch color highlights nothing.

Example
package main

import (
	"errors"
	"fmt"
	"log"

	"gioui.org/unit"
	"golang.org/x/image/font/gofont/gomono"

	"github.com/lichdotdev/godemirror"
)

func main() {
	view, err := godemirror.New("monospace", unit.Sp(13))
	if errors.Is(err, godemirror.ErrFontNotFound) {
		view, err = godemirror.NewFromFonts(godemirror.Fonts{Regular: gomono.TTF}, unit.Sp(13))
	}
	if err != nil {
		log.Fatal(err)
	}
	view.SetContent(godemirror.Content{Text: "foo bar\nFoo(bar)\nbaz foo"})

	// A search box calls SetSearch as its text changes, and FindNext on Enter.
	if err := view.SetSearch(godemirror.SearchQuery{Text: "foo", WholeWord: true}); err != nil {
		log.Fatal(err)
	}
	for range 4 {
		m, _ := view.FindNext()
		fmt.Println(m.From, m.To)
	}
}
Output:
{0 0} {0 3}
{1 0} {1 3}
{2 4} {2 7}
{0 0} {0 3}

func (*View) SnapScrollTop added in v0.12.0

func (v *View) SnapScrollTop(y int)

SnapScrollTop is SetScrollTop without the glide: the next Layout draws the view at y, within the document, and stops any glide.

func (*View) UpdateContent

func (v *View) UpdateContent(c Content)

UpdateContent replaces what is shown with a new version of it (a diff with lines pulled in, say), keeping the scroll position. The current content stays on screen until c's highlighting is ready, and then c takes its place whole, so text, labels and decorations never show out of step. Until then, whatever reads or addresses the view by line (SelectedLines, Selection, Select, SelectLines, ScrollToLine, LineCount, LineText) works on the old content. The selection is dropped, since its lines may no longer be where they were.

Directories

Path Synopsis
cmd
godemirror-demo command
Demo of godemirror: a file in a View or an Editor, or a diff in a DiffView, in a window or, with -bench or -shot, headless.
Demo of godemirror: a file in a View or an Editor, or a diff in a DiffView, in a window or, with -bench or -shot, headless.
internal
glyphs
Package glyphs rasterizes a monospace font family into per-character coverage masks, for Gio views that compose text into images on the CPU instead of drawing Gio text paths.
Package glyphs rasterizes a monospace font family into per-character coverage masks, for Gio views that compose text into images on the CPU instead of drawing Gio text paths.
lezer/css
Package css is @lezer/css's CSS grammar for internal/lezer: its parse tables and styleTags rules, generated from the npm package, and the Go ports of its external tokenizers.
Package css is @lezer/css's CSS grammar for internal/lezer: its parse tables and styleTags rules, generated from the npm package, and the Go ports of its external tokenizers.
lezer/golang
Package golang is @lezer/go's Go grammar for internal/lezer: its parse tables and styleTags rules, generated from the npm package, and the ports of its external tokenizer and context tracker (tokens.go).
Package golang is @lezer/go's Go grammar for internal/lezer: its parse tables and styleTags rules, generated from the npm package, and the ports of its external tokenizer and context tracker (tokens.go).
lezer/html
Package html is @lezer/html's HTML grammar for internal/lezer: its parse tables and styleTags rules, generated from the npm package, the Go ports of its external tokenizers and context tracker, and the nesting of JavaScript and CSS that @codemirror/lang-html sets up by default.
Package html is @lezer/html's HTML grammar for internal/lezer: its parse tables and styleTags rules, generated from the npm package, the Go ports of its external tokenizers and context tracker, and the nesting of JavaScript and CSS that @codemirror/lang-html sets up by default.
lezer/java
Package java is @lezer/java's Java grammar for internal/lezer: its parse tables and styleTags rules, generated from the npm package.
Package java is @lezer/java's Java grammar for internal/lezer: its parse tables and styleTags rules, generated from the npm package.
lezer/javascript
Package javascript is @lezer/javascript's JavaScript grammar for internal/lezer: its parse tables and styleTags rules, generated from the npm package, and ports of its external tokenizers and context tracker.
Package javascript is @lezer/javascript's JavaScript grammar for internal/lezer: its parse tables and styleTags rules, generated from the npm package, and ports of its external tokenizers and context tracker.
lezer/lezertest
Package lezertest checks a port against what the real Lezer gives: the goldens internal/lezer/gen/golden.mjs writes, one per fixture.
Package lezertest checks a port against what the real Lezer gives: the goldens internal/lezer/gen/golden.mjs writes, one per fixture.
lezer/python
Package python is @lezer/python's Python grammar for internal/lezer: its parse tables and styleTags rules, generated from the npm package, and the ports of its external tokenizers and indentation tracker (tokens.go).
Package python is @lezer/python's Python grammar for internal/lezer: its parse tables and styleTags rules, generated from the npm package, and the ports of its external tokenizers and indentation tracker (tokens.go).
lezer/rust
Package rust is @lezer/rust's Rust grammar for internal/lezer: its parse tables and styleTags rules, generated from the npm package, and the ports of its external tokenizers (tokens.go).
Package rust is @lezer/rust's Rust grammar for internal/lezer: its parse tables and styleTags rules, generated from the npm package, and the ports of its external tokenizers (tokens.go).
shot
Package shot writes a PNG of a Gio frame, drawn again off screen, so a run can be checked visually without a screen grabber.
Package shot writes a PNG of a Gio frame, drawn again off screen, so a run can be checked visually without a screen grabber.
stream
Package stream highlights a document with a CodeMirror 5-style stream mode, as CodeMirror's StreamLanguage does for the languages @codemirror/legacy-modes covers and Lezer does not.
Package stream highlights a document with a CodeMirror 5-style stream mode, as CodeMirror's StreamLanguage does for the languages @codemirror/legacy-modes covers and Lezer does not.
stream/kotlin
Package kotlin is the Kotlin mode of @codemirror/legacy-modes, the one CodeMirror highlights Kotlin with.
Package kotlin is the Kotlin mode of @codemirror/legacy-modes, the one CodeMirror highlights Kotlin with.
stream/shell
Package shell is the shell mode of @codemirror/legacy-modes, the one CodeMirror highlights shell scripts with.
Package shell is the shell mode of @codemirror/legacy-modes, the one CodeMirror highlights shell scripts with.
stream/streamtest
Package streamtest checks a mode's port against what CodeMirror gives: the goldens internal/stream/gen/golden.mjs writes, one per fixture.
Package streamtest checks a mode's port against what CodeMirror gives: the goldens internal/stream/gen/golden.mjs writes, one per fixture.
lsp
Package lsp is a client of the Language Server Protocol 3.17: it starts a language server, keeps it in step with the documents an Editor edits, and asks it for diagnostics, completions, hovers and definitions.
Package lsp is a client of the Language Server Protocol 3.17: it starts a language server, keeps it in step with the documents an Editor edits, and asks it for diagnostics, completions, hovers and definitions.
servers
Package servers is a catalog of language servers: for each one, the command that starts it, the vim filetypes it serves, the files that mark a project root, its default initialization options and settings, and how to install it.
Package servers is a catalog of language servers: for each one, the command that starts it, the vim filetypes it serves, the files that mark a project root, its default initialization options and settings, and how to install it.
Package tags is CodeMirror's vocabulary of highlighting tags, the one @lezer/highlight defines: a closed set of tags a highlighter maps to styles, arranged so that a style for a general tag covers its subtags.
Package tags is CodeMirror's vocabulary of highlighting tags, the one @lezer/highlight defines: a closed set of tags a highlighter maps to styles, arranged so that a style for a general tag covers its subtags.

Jump to

Keyboard shortcuts

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