richeditor

package
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: Apache-2.0 Imports: 27 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.

Documentation

Overview

Package richeditor is a rich text editor after ProseMirror's architecture (NSH's RichEditor, nsh/docs/dev/rich-editor.md): a document whose structure a Schema defines, changes as invertible, mappable steps grouped into transactions, immutable states, commands and plugins. The kernel depends on no view and is tested on its own; View renders its states.

Positions count as ProseMirror's do: a text its UTF-16 code units, a leaf node one, a node with content its two boundaries.

The kernel is a port of ProseMirror's (MIT, © Marijn Haverbeke and others) and the extension layer follows Tiptap's (MIT, © Tiptap GmbH), whose structures, algorithms and names it keeps; see NOTICE.

Index

Constants

View Source
const DefaultPriority = 100

DefaultPriority is an extension's unless it gives one: higher runs first.

Variables

View Source
var (
	Undo = historyCommand(false)
	Redo = historyCommand(true)
)

Undo and Redo walk the history.

View Source
var (
	AddColumnBefore = tableCommand(func(_ *State, r *selectedRect, tr *Transaction) bool {
		addColumn(tr, r, r.Left)
		return true
	})
	AddColumnAfter = tableCommand(func(_ *State, r *selectedRect, tr *Transaction) bool {
		addColumn(tr, r, r.Right)
		return true
	})
	AddRowBefore = tableCommand(func(_ *State, r *selectedRect, tr *Transaction) bool {
		addRow(tr, r, r.Top)
		return true
	})
	AddRowAfter = tableCommand(func(_ *State, r *selectedRect, tr *Transaction) bool {
		addRow(tr, r, r.Bottom)
		return true
	})
	// DeleteColumn and DeleteRow refuse to delete every column or row.
	DeleteColumn = tableCommand(func(s *State, r *selectedRect, tr *Transaction) bool {
		if r.Left == 0 && r.Right == r.m.Width {
			return false
		}
		for i := r.Right - 1; ; i-- {
			removeColumn(tr, r, i)
			if i == r.Left {
				break
			}
			table := tr.Doc.Resolve(r.tableStart - 1).NodeAfter()
			if table == nil {
				return false
			}
			r = &selectedRect{r.Rect, r.tableStart, TableMapOf(table), table}
		}
		return true
	})
	DeleteRow = tableCommand(func(s *State, r *selectedRect, tr *Transaction) bool {
		if r.Top == 0 && r.Bottom == r.m.Height {
			return false
		}
		for i := r.Bottom - 1; ; i-- {
			removeRow(tr, r, i)
			if i == r.Top {
				break
			}
			table := tr.Doc.Resolve(r.tableStart - 1).NodeAfter()
			if table == nil {
				return false
			}
			r = &selectedRect{r.Rect, r.tableStart, TableMapOf(table), table}
		}
		return true
	})
)

AddColumnBefore and the commands after it edit the table at the selection, by Tiptap's names.

View Source
var (
	ToggleHeaderRow    = toggleHeader("row")
	ToggleHeaderColumn = toggleHeader("column")
	ToggleHeaderCell   = toggleHeader("cell")
)

ToggleHeaderRow, ToggleHeaderColumn and ToggleHeaderCell turn cells to header cells and back.

View Source
var EmptySlice = &Slice{Content: emptyFragment}

EmptySlice holds nothing.

View Source
var EmptyStepMap = &StepMap{}

EmptyStepMap moves nothing.

Functions

func BaseKeymap

func BaseKeymap() map[string]Command

BaseKeymap is what a press of Enter and the deleting keys do anywhere.

func CanJoin

func CanJoin(doc *Node, pos int) bool

CanJoin says the nodes around pos can join.

func CanSplit

func CanSplit(doc *Node, pos, depth int, typesAfter []NodeTypeAttrs) bool

CanSplit says pos can split depth levels, each new level's types or the same when nil.

func Characters

func Characters(s *State, nodes bool) int

Characters counts a state's characters.

func ColumnWidths

func ColumnWidths(table *Node) []float64

ColumnWidths are a table's widths by column, 0 for none.

func CreateParagraphNear

func CreateParagraphNear(s *State, dispatch func(*Transaction)) bool

CreateParagraphNear makes a paragraph beside a selected block.

func DeleteCellSelection

func DeleteCellSelection(s *State, dispatch func(*Transaction)) bool

DeleteCellSelection empties the selected cells.

func DeleteSelection

func DeleteSelection(s *State, dispatch func(*Transaction)) bool

DeleteSelection deletes a selection that holds something.

func DeleteTable

func DeleteTable(s *State, dispatch func(*Transaction)) bool

DeleteTable deletes the table at the selection.

func DocJSONString

func DocJSONString(n *Node) string

DocJSONString writes a document as JSON.

func DragSource

func DragSource(s *State, pos int) (from, to int, ok bool)

DragSource is what a handle at pos carries, from to to: the siblings the selection covers when pos is in a selection over several, else the block at pos, a defining parent standing for its first child, as a list item for its paragraph. ok is false where there is no block.

func ExitCode

func ExitCode(s *State, dispatch func(*Transaction)) bool

ExitCode leaves a code block to the block after it.

func FindParentNode

func FindParentNode(s *State, pred func(*Node) bool) int

FindParentNode is the position before the nearest ancestor of the selection pred accepts, -1 for none.

func GapCursorValid

func GapCursorValid(r *ResolvedPos) bool

GapCursorValid says a gap cursor may stand at pos: between closed blocks, in a parent whose default content there is a textblock, unless its spec's Extra["allowGapCursor"] says otherwise.

func GoToNextCellOrAddRow

func GoToNextCellOrAddRow(s *State, dispatch func(*Transaction)) bool

GoToNextCellOrAddRow is Tab: past the last cell a new row.

func InsertCells

func InsertCells(s *State, dispatch func(*Transaction), tableStart int, rect Rect, cells *CellArea)

InsertCells puts cells into the table starting at tableStart with their top left at rect's, growing the table and splitting the cells crossing the area's edges, and selects them.

func InsertPoint

func InsertPoint(doc *Node, pos int, typ *NodeType) int

InsertPoint is where a node of typ fits at or near pos, -1 for nowhere.

func IsActive

func IsActive(s *State, name string, attrs Attrs) bool

IsActive says the node or mark of name, with attrs, is at the selection.

func IsAllowedURI

func IsAllowedURI(href string, protocols []string) bool

IsAllowedURI is Tiptap's check of a link's address.

func IsMarkActive

func IsMarkActive(s *State, t *MarkType, attrs Attrs) bool

IsMarkActive says the selection is in a mark of t with attrs.

func IsNodeActive

func IsNodeActive(s *State, t *NodeType, attrs Attrs) bool

IsNodeActive says the selection is in a node of t with attrs.

func JoinBackward

func JoinBackward(s *State, dispatch func(*Transaction)) bool

JoinBackward joins the textblock at a cursor's start with what is before.

func JoinForward

func JoinForward(s *State, dispatch func(*Transaction)) bool

JoinForward joins the textblock at a cursor's end with what is after.

func JoinPoint

func JoinPoint(doc *Node, pos, dir int) int

JoinPoint is the nearest place around pos, going dir, that can join, -1 for none.

func Lift

func Lift(s *State, dispatch func(*Transaction)) bool

Lift lifts the selected block out of its parent.

func LiftEmptyBlock

func LiftEmptyBlock(s *State, dispatch func(*Transaction)) bool

LiftEmptyBlock lifts an empty block out of its parent.

func LiftTarget

func LiftTarget(r *NodeRange) int

LiftTarget is the depth a range can lift to, -1 for none.

func MarkRange

func MarkRange(r *ResolvedPos, t *MarkType) (from, to int, ok bool)

MarkRange is the range of the mark of t around pos, its marks' run.

func MergeBindings

func MergeBindings(maps ...map[string]Command) map[string]Command

MergeBindings joins keymaps, a key's commands running in the given order.

func MergeCells

func MergeCells(s *State, dispatch func(*Transaction)) bool

MergeCells merges the selected cells, their contents joined.

func NewlineInCode

func NewlineInCode(s *State, dispatch func(*Transaction)) bool

NewlineInCode inserts a line break in a code block.

func NodeJSON

func NodeJSON(n *Node) map[string]any

NodeJSON is a node in ProseMirror's JSON shape, which Tiptap's documents have too.

func PlainText

func PlainText(doc *Node) string

PlainText is a document's text, a blank line between its blocks, a table's rows as lines of tab-separated cells.

func RedoDepth

func RedoDepth(s *State) int

RedoDepth is the steps Redo can take.

func SelectAll

func SelectAll(s *State, dispatch func(*Transaction)) bool

SelectAll selects the document.

func SelectNodeBackward

func SelectNodeBackward(s *State, dispatch func(*Transaction)) bool

SelectNodeBackward selects the node before a cursor at a textblock's start.

func SelectNodeForward

func SelectNodeForward(s *State, dispatch func(*Transaction)) bool

SelectNodeForward selects the node after a cursor at a textblock's end.

func SelectParentNode

func SelectParentNode(s *State, dispatch func(*Transaction)) bool

SelectParentNode selects the block around the selection.

func SelectionPosNext

func SelectionPosNext(r *ResolvedPos, dir int) int

SelectionPosNext is the caret of the next textblock going dir.

func SliceToText

func SliceToText(s *Slice) string

SliceToText is what a slice copies as.

func SplitBlock

func SplitBlock(s *State, dispatch func(*Transaction)) bool

SplitBlock splits the textblock at the selection.

func SplitCell

func SplitCell(s *State, dispatch func(*Transaction)) bool

SplitCell splits a merged cell into cells of one slot.

func UndoDepth

func UndoDepth(s *State) int

UndoDepth and RedoDepth are the steps there are.

func UndoInputRule

func UndoInputRule(s *State, dispatch func(*Transaction)) bool

UndoInputRule undoes the rule that just ran, leaving the typed text.

func Words

func Words(s *State) int

Words counts a state's words.

func WriteHTML

func WriteHTML(n *Node) string

WriteHTML writes a node as Tiptap's HTML.

func WriteMarkdown

func WriteMarkdown(doc *Node) string

WriteMarkdown writes a document as Markdown: GFM's task items and pipe tables, and a table a pipe table cannot hold as its HTML on one line, which reads back as it was.

Types

type AddMarkStep

type AddMarkStep struct {
	From, To int
	Mark     *Mark
}

AddMarkStep adds Mark from From to To.

func (*AddMarkStep) Apply

func (s *AddMarkStep) Apply(doc *Node) (*Node, error)

func (*AddMarkStep) Invert

func (s *AddMarkStep) Invert(*Node) Step

func (*AddMarkStep) Map

func (s *AddMarkStep) Map(m Mappable) Step

func (*AddMarkStep) Merge

func (s *AddMarkStep) Merge(other Step) Step

func (*AddMarkStep) StepMap

func (s *AddMarkStep) StepMap() *StepMap

type AllSelection

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

AllSelection selects the whole document.

func NewAllSelection

func NewAllSelection(doc *Node) *AllSelection

NewAllSelection selects doc.

func (*AllSelection) Anchor

func (s *AllSelection) Anchor() int

func (*AllSelection) AnchorPos

func (s *AllSelection) AnchorPos() *ResolvedPos

func (*AllSelection) Bookmark

func (s *AllSelection) Bookmark() Bookmark

func (*AllSelection) Content

func (s *AllSelection) Content() *Slice

func (*AllSelection) Empty

func (s *AllSelection) Empty() bool

func (*AllSelection) Eq

func (s *AllSelection) Eq(o Selection) bool

func (*AllSelection) From

func (s *AllSelection) From() int

func (*AllSelection) FromPos

func (s *AllSelection) FromPos() *ResolvedPos

func (*AllSelection) Head

func (s *AllSelection) Head() int

func (*AllSelection) HeadPos

func (s *AllSelection) HeadPos() *ResolvedPos

func (*AllSelection) Map

func (s *AllSelection) Map(doc *Node, _ Mappable) Selection

func (*AllSelection) Ranges

func (s *AllSelection) Ranges() []SelectionRange

func (*AllSelection) Replace

func (s *AllSelection) Replace(tr *Transaction, content *Slice)

func (*AllSelection) ReplaceWith

func (s *AllSelection) ReplaceWith(tr *Transaction, node *Node)

func (*AllSelection) To

func (s *AllSelection) To() int

func (*AllSelection) ToPos

func (s *AllSelection) ToPos() *ResolvedPos

type AttrSpec

type AttrSpec struct {
	Name       string
	Default    any
	HasDefault bool
	// Validate refuses a value, for documents that come from outside.
	Validate func(any) error
}

AttrSpec is an attribute: required unless it has a default.

type AttrStep

type AttrStep struct {
	Pos   int
	Attr  string
	Value any
}

AttrStep sets an attribute of the node at Pos.

func (*AttrStep) Apply

func (s *AttrStep) Apply(doc *Node) (*Node, error)

func (*AttrStep) Invert

func (s *AttrStep) Invert(doc *Node) Step

func (*AttrStep) Map

func (s *AttrStep) Map(m Mappable) Step

func (*AttrStep) Merge

func (s *AttrStep) Merge(Step) Step

func (*AttrStep) StepMap

func (s *AttrStep) StepMap() *StepMap

type Attrs

type Attrs = map[string]any

Attrs are a node's or mark's attributes: JSON's values, numbers as float64, never changed once made.

type Bookmark

type Bookmark interface {
	Map(m Mappable) Bookmark
	Resolve(doc *Node) Selection
}

Bookmark is a selection without a document.

type Built

type Built struct {
	Schema   *Schema
	Plugins  []*Plugin
	Commands map[string]CommandFactory
}

Built is what a list of extensions makes.

func Build

func Build(exts ...Extension) (*Built, error)

Build resolves extensions, refusing duplicate names: the schema in their order by priority, and the runtime in Tiptap's, the list reversed then by priority, so an app's extension after the kit binds before it, under one keymap merging every extension's bindings.

type CellArea

type CellArea struct {
	Width, Height int
	Rows          []*Fragment
}

CellArea is a rectangle of pasted cells, a fragment of cells per row.

func ClipCells

func ClipCells(a *CellArea, width, height int) *CellArea

ClipCells repeats or cuts an area to a width and height.

func PastedCells

func PastedCells(slice *Slice) *CellArea

PastedCells is the cells slice holds, nil unless it is a table's rows or cells.

type CellRect

type CellRect struct {
	Pos  int
	Rect Rect
}

CellRect is a cell's offset and rectangle.

type CellSelection

type CellSelection struct {
	AnchorCell, HeadCell *ResolvedPos
	// contains filtered or unexported fields
}

CellSelection selects a rectangle of cells: Replace fills the first and empties the others.

func ColSelection

func ColSelection(anchor, head *ResolvedPos) *CellSelection

ColSelection selects the columns from anchor's to head's.

func NewCellSelection

func NewCellSelection(anchor, head *ResolvedPos) *CellSelection

NewCellSelection selects the cells between two positions before cells.

func RowSelection

func RowSelection(anchor, head *ResolvedPos) *CellSelection

RowSelection selects the rows from anchor's to head's.

func (*CellSelection) Anchor

func (s *CellSelection) Anchor() int

func (*CellSelection) AnchorPos

func (s *CellSelection) AnchorPos() *ResolvedPos

func (*CellSelection) Bookmark

func (s *CellSelection) Bookmark() Bookmark

func (*CellSelection) Content

func (s *CellSelection) Content() *Slice

Content is the rectangle as rows.

func (*CellSelection) Empty

func (s *CellSelection) Empty() bool

func (*CellSelection) Eq

func (s *CellSelection) Eq(o Selection) bool

func (*CellSelection) From

func (s *CellSelection) From() int

func (*CellSelection) FromPos

func (s *CellSelection) FromPos() *ResolvedPos

func (*CellSelection) Head

func (s *CellSelection) Head() int

func (*CellSelection) HeadPos

func (s *CellSelection) HeadPos() *ResolvedPos

func (*CellSelection) IsColSelection

func (s *CellSelection) IsColSelection() bool

IsColSelection says the selection covers whole columns.

func (*CellSelection) IsRowSelection

func (s *CellSelection) IsRowSelection() bool

IsRowSelection says the selection covers whole rows.

func (*CellSelection) Map

func (s *CellSelection) Map(doc *Node, m Mappable) Selection

func (*CellSelection) Ranges

func (s *CellSelection) Ranges() []SelectionRange

func (*CellSelection) Replace

func (s *CellSelection) Replace(tr *Transaction, content *Slice)

func (*CellSelection) ReplaceWith

func (s *CellSelection) ReplaceWith(tr *Transaction, node *Node)

func (*CellSelection) To

func (s *CellSelection) To() int

func (*CellSelection) ToPos

func (s *CellSelection) ToPos() *ResolvedPos

type CharacterCountOptions

type CharacterCountOptions struct {
	// Limit is the most characters, none when 0.
	Limit int
	// CountNodes counts every position rather than text.
	CountNodes bool
}

CharacterCountOptions tune CharacterCount.

type Classes

type Classes struct {
	Content                                          string
	Nodes, Marks                                     map[string]string
	Placeholder, Caret, Selection, Composition       string
	GapCursor, DropCursor                            string
	SelectedNode, SelectedCell                       string
	SelectionHandle                                  string
	ListMarker, TaskCheckbox                         string
	TableResizeHandle, TableGrip, TableDropIndicator string
}

Classes are Tailwind classes of the parts, by Styles' names, each under its part's style.

type Command

type Command func(s *State, dispatch func(*Transaction)) bool

Command is an edit over a state: it says whether it applies, and with a dispatch makes the change. With a nil dispatch it only checks.

func Chain

func Chain(cmds ...Command) Command

Chain runs commands one after another, each on the state the one before left, and dispatches their changes as one transaction, as Tiptap's chain does: it says whether every one applied. Without a dispatch each checks on the state the ones before would leave.

func ChainCommands

func ChainCommands(cmds ...Command) Command

ChainCommands is ProseMirror's chainCommands: the first command that applies runs.

func ExitSuggestion

func ExitSuggestion(key string) Command

ExitSuggestion dismisses the Suggestion keyed key.

func GoToNextCell

func GoToNextCell(dir int) Command

GoToNextCell moves to the next cell, or the previous when dir is negative.

func InsertHardBreak

func InsertHardBreak(t *NodeType) Command

InsertHardBreak replaces the selection with a node of t.

func InsertMention

func InsertMention(t *NodeType, key string, attrs Attrs) Command

InsertMention replaces the active query with a mention and a space after it, one already there taken in.

func InsertTable

func InsertTable(rows, cols int, withHeader bool) Command

InsertTable inserts a table of rows and cols, a header row with withHeader, its first cell selected.

func LiftListItem

func LiftListItem(itemType *NodeType) Command

LiftListItem lifts the selected list items out of their list.

func MoveBlocks

func MoveBlocks(from, to, target int) Command

MoveBlocks moves the blocks from from to to to target, a position between blocks outside them whose parent takes them, as one transaction that selects what moved.

func MoveTableColumn

func MoveTableColumn(from, to, tablePos int) Command

MoveTableColumn moves a column, as MoveTableRow a row.

func MoveTableRow

func MoveTableRow(from, to, tablePos int) Command

MoveTableRow moves row from to the place of row to; table is the position before a table, the selection's when negative. The moved rows end up selected.

func SetBlockType

func SetBlockType(t *NodeType, attrs Attrs) Command

SetBlockType sets the selected textblocks to t.

func SetCellSelection

func SetCellSelection(anchor, head int) Command

SetCellSelection selects from the cell at anchor to the one at head.

func SetColumnWidth

func SetColumnWidth(col int, width float64, tablePos int) Command

SetColumnWidth sets col's width on every cell covering it, 0 for none.

func SetLink(t *MarkType, href string, protocols []string) Command

SetLink links the selection.

func SetMark

func SetMark(t *MarkType, attrs Attrs) Command

SetMark marks the selection, or the stored marks at a cursor.

func SetRowHeight

func SetRowHeight(row int, height float64, tablePos int) Command

SetRowHeight sets row's height, 0 for none.

func ShiftArrow

func ShiftArrow(axis string, dir int) Command

ShiftArrow extends a cell selection, starting one from a text selection at a cell's edge.

func SinkListItem

func SinkListItem(itemType *NodeType) Command

SinkListItem nests the selected list items in the item before them.

func SplitListItem

func SplitListItem(itemType *NodeType, itemAttrs Attrs) Command

SplitListItem splits the list item at the selection; an empty one leaves the list or lifts.

func ToggleBlockType

func ToggleBlockType(t *NodeType, attrs Attrs) Command

ToggleBlockType sets the textblock to t, or back to paragraph-like default when it is t.

func ToggleList

func ToggleList(t, item *NodeType) Command

ToggleList wraps the selection in a list of t, lifts it out, or turns the list it is in into one of t.

func ToggleMark

func ToggleMark(t *MarkType, attrs Attrs) Command

ToggleMark toggles a mark over the selection, or in the stored marks at a cursor.

func ToggleWrap

func ToggleWrap(t *NodeType, attrs Attrs) Command

ToggleWrap wraps the selection in t, or lifts it out.

func UnsetMark

func UnsetMark(t *MarkType) Command

UnsetMark removes t from the selection, the run around a cursor too.

func UpdateAttributes

func UpdateAttributes(t *NodeType, attrs Attrs) Command

UpdateAttributes sets attrs on the blocks of t in the selection.

func WrapIn

func WrapIn(t *NodeType, attrs Attrs) Command

WrapIn wraps the selected blocks in t.

func WrapInList

func WrapInList(listType *NodeType, attrs Attrs) Command

WrapInList wraps the selected blocks in a list of listType.

type CommandFactory

type CommandFactory func(args Attrs) Command

CommandFactory makes a named command from its arguments.

type ContentMatch

type ContentMatch struct {
	ValidEnd bool
	// contains filtered or unexported fields
}

ContentMatch is a state of the automaton a content expression compiles to, ProseMirror's: the node types it may go on with, and whether the content may end here.

func (*ContentMatch) Edge

func (m *ContentMatch) Edge(n int) (*NodeType, *ContentMatch)

Edge is its nth edge.

func (*ContentMatch) EdgeCount

func (m *ContentMatch) EdgeCount() int

EdgeCount and Edge list the types it goes on with.

func (*ContentMatch) FillBefore

func (m *ContentMatch) FillBefore(after *Fragment, toEnd bool, start int) *Fragment

FillBefore is what must go before after, from index start, for it to fit here, ending in a valid end with toEnd; nil when nothing can.

func (*ContentMatch) FindWrapping

func (m *ContentMatch) FindWrapping(target *NodeType) []*NodeType

FindWrapping is the types to wrap a node of target in to fit here, an empty list for none needed; nil when none can.

func (*ContentMatch) MatchFragment

func (m *ContentMatch) MatchFragment(frag *Fragment, start, end int) *ContentMatch

MatchFragment is the state after frag's children from start to end (the end of frag when negative), nil when one does not fit.

func (*ContentMatch) MatchType

func (m *ContentMatch) MatchType(t *NodeType) *ContentMatch

MatchType is the state after a node of t, nil when t does not fit.

type Decoration

type Decoration struct {
	From, To int
	Class    string
	Node     bool
	Widget   func(cx *core.Scope) core.Node
	Side     int
	Key      string
}

Decoration styles a range without changing the document: Class on the range's text, or with Node on the block at From. With Widget it is a view in the text at From instead, taking no position: Side below zero puts it before a cursor there, else after, and Key, when set, keeps its view while the decoration stays.

type Extension

type Extension struct {
	Name     string
	Priority int
	Nodes    []NodeSpec
	Marks    []MarkSpec
	Global   []GlobalAttrs
	Keys     func(s *Schema) map[string]Command
	Rules    func(s *Schema) []InputRule
	Plugins  func(s *Schema) []*Plugin
	Commands func(s *Schema) map[string]CommandFactory
}

Extension contributes to an editor in one unit, as Tiptap's do: to the schema, the keys, the rules, the plugins and the named commands.

func CharacterCount

func CharacterCount(o CharacterCountOptions) Extension

CharacterCount refuses changes that grow past the limit, a document over it already may shrink, and trims what is pasted to what fits.

func Link(o LinkOptions) Extension

Link is the link mark with autolinking, opening on Mod-click and linking a selection when a URL is pasted over it, not growing as text is typed after it.

func Mention

func Mention(o MentionOptions) Extension

Mention is an inline node showing @name with its one position, and the Suggestion that finds it. Id identifies who, so nothing goes by the text.

func StarterKit

func StarterKit(o StarterOptions) []Extension

StarterKit is a rich text editor's usual types with their commands, keys and rules, by Tiptap's names.

func TableKit

func TableKit(o TableOptions) Extension

TableKit is tables with their commands and keys, outside StarterKit.

type FoundLink struct {
	Start, End int
	Href       string
}

FoundLink is a link in text: its byte range and address.

func FindLinks(text string) []FoundLink

FindLinks detects URLs, host names and e-mail addresses in text, leaving trailing punctuation and unbalanced closing brackets out, as linkify does.

type Fragment

type Fragment struct {
	Content []*Node
	Size    int
}

Fragment is a node's children.

func EmptyFragment

func EmptyFragment() *Fragment

EmptyFragment holds nothing.

func FragmentFrom

func FragmentFrom(nodes ...*Node) *Fragment

FragmentFrom makes a fragment of nodes, joining text with equal marks.

func (*Fragment) AddToEnd

func (f *Fragment) AddToEnd(node *Node) *Fragment

AddToEnd is the fragment before node.

func (*Fragment) AddToStart

func (f *Fragment) AddToStart(node *Node) *Fragment

AddToStart is the fragment after node.

func (*Fragment) Append

func (f *Fragment) Append(o *Fragment) *Fragment

Append is the fragment followed by other.

func (*Fragment) Child

func (f *Fragment) Child(i int) *Node

Child is its child i.

func (*Fragment) ChildCount

func (f *Fragment) ChildCount() int

func (*Fragment) Cut

func (f *Fragment) Cut(from, to int) *Fragment

Cut is the fragment from from to to; to past its end when negative.

func (*Fragment) CutByIndex

func (f *Fragment) CutByIndex(from, to int) *Fragment

CutByIndex is its children from from to to.

func (*Fragment) Descendants

func (f *Fragment) Descendants(fn func(*Node, int, *Node, int) bool)

Descendants calls fn on every node inside.

func (*Fragment) Eq

func (f *Fragment) Eq(o *Fragment) bool

Eq says two fragments are equal.

func (*Fragment) FirstChild

func (f *Fragment) FirstChild() *Node

func (*Fragment) LastChild

func (f *Fragment) LastChild() *Node

func (*Fragment) MaybeChild

func (f *Fragment) MaybeChild(i int) *Node

MaybeChild is its child i, nil past the end.

func (*Fragment) NodesBetween

func (f *Fragment) NodesBetween(from, to int, fn func(*Node, int, *Node, int) bool, start int, parent *Node)

NodesBetween calls fn on the nodes between from and to.

func (*Fragment) ReplaceChild

func (f *Fragment) ReplaceChild(i int, node *Node) *Fragment

ReplaceChild is the fragment with child i replaced.

func (*Fragment) String

func (f *Fragment) String() string

func (*Fragment) TextBetween

func (f *Fragment) TextBetween(from, to int, blockSep, leafText string) string

TextBetween is its text from from to to.

type GapCursor

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

GapCursor is a cursor at a position no text selection can hold.

func NewGapCursor

func NewGapCursor(pos *ResolvedPos) *GapCursor

NewGapCursor is a gap cursor at pos, which GapCursorValid accepts.

func (*GapCursor) Anchor

func (s *GapCursor) Anchor() int

func (*GapCursor) AnchorPos

func (s *GapCursor) AnchorPos() *ResolvedPos

func (*GapCursor) Bookmark

func (s *GapCursor) Bookmark() Bookmark

func (*GapCursor) Content

func (s *GapCursor) Content() *Slice

func (*GapCursor) Empty

func (s *GapCursor) Empty() bool

func (*GapCursor) Eq

func (s *GapCursor) Eq(o Selection) bool

func (*GapCursor) From

func (s *GapCursor) From() int

func (*GapCursor) FromPos

func (s *GapCursor) FromPos() *ResolvedPos

func (*GapCursor) Head

func (s *GapCursor) Head() int

func (*GapCursor) HeadPos

func (s *GapCursor) HeadPos() *ResolvedPos

func (*GapCursor) Map

func (s *GapCursor) Map(doc *Node, m Mappable) Selection

func (*GapCursor) Ranges

func (s *GapCursor) Ranges() []SelectionRange

func (*GapCursor) Replace

func (s *GapCursor) Replace(tr *Transaction, content *Slice)

func (*GapCursor) ReplaceWith

func (s *GapCursor) ReplaceWith(tr *Transaction, node *Node)

func (*GapCursor) To

func (s *GapCursor) To() int

func (*GapCursor) ToPos

func (s *GapCursor) ToPos() *ResolvedPos

type Geometry

type Geometry interface {
	// CoordsAtPos is the caret's box at pos in the content box, the box
	// that scrolls.
	CoordsAtPos(pos int) (Rect2, bool)
	// PosAtCoords is the position nearest a point of the content box.
	PosAtCoords(x, y float64) (int, bool)
	// SelectionRect is the box over the selection's lines.
	SelectionRect() (Rect2, bool)
}

Geometry answers where positions are, from the last view mounted.

type GlobalAttrs

type GlobalAttrs struct {
	Types []string
	Attrs []AttrSpec
}

GlobalAttrs add attributes to other types.

type HistoryOptions

type HistoryOptions struct {
	// Depth is the most undo steps kept, 100 when 0.
	Depth int
	// NewGroupDelay is the pause that starts a new undo step, 500 ms
	// when 0.
	NewGroupDelay time.Duration
}

HistoryOptions tune the history.

type HistoryState

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

HistoryState is the history plugin's field.

type InputRule

type InputRule struct {
	Match   *regexp.Regexp
	Handler func(s *State, match []string, start, end int) *Transaction
	// NoUndo keeps Backspace from undoing it.
	NoUndo bool
}

InputRule changes text as it is typed: Match, ending in $, is tried on the text before the cursor, and Handler gives the transaction of what it does, nil for nothing. Match is the groups' text, by index, "" for one unmatched.

func MarkInputRule

func MarkInputRule(re *regexp.Regexp, t *MarkType, attrs func(match []string) Attrs) InputRule

MarkInputRule marks the last group, deleting what is around it in the match: "**bold**".

func TextInputRule

func TextInputRule(re *regexp.Regexp, text string) InputRule

TextInputRule replaces what matched with text.

func TextblockTypeInputRule

func TextblockTypeInputRule(re *regexp.Regexp, t *NodeType, attrs func(match []string) Attrs) InputRule

TextblockTypeInputRule turns the textblock into t: "# " a heading.

func WrappingInputRule

func WrappingInputRule(re *regexp.Regexp, t *NodeType, attrs func(match []string) Attrs, joinPredicate func(match []string, n *Node) bool) InputRule

WrappingInputRule wraps the textblock in t: "> " a quote, "- " a list.

type LinkOptions

type LinkOptions struct {
	// NoAutolink keeps URLs typed from becoming links, and NoOpenOnClick
	// presses from opening them.
	NoAutolink, NoOpenOnClick bool
	// Open opens a link pressed with Mod, or in a read-only editor.
	Open func(href string)
	// Protocols are allowed beside http, https, ftp, mailto and tel.
	Protocols []string
}

LinkOptions tune Link.

type MapResult

type MapResult struct {
	Pos int
	// contains filtered or unexported fields
}

MapResult is a position mapped: where it went and what became of the content around it.

func (MapResult) Deleted

func (m MapResult) Deleted() bool

Deleted says the token on the side it was mapped with is gone.

func (MapResult) DeletedAcross

func (m MapResult) DeletedAcross() bool

DeletedAcross says tokens on both sides are gone.

func (MapResult) DeletedAfter

func (m MapResult) DeletedAfter() bool

func (MapResult) DeletedBefore

func (m MapResult) DeletedBefore() bool

DeletedBefore and DeletedAfter say the token before or after it is gone.

type Mappable

type Mappable interface {
	Map(pos, assoc int) int
	MapResult(pos, assoc int) MapResult
}

Mappable maps positions through changes.

type Mapping

type Mapping struct {
	Maps     []*StepMap
	From, To int
	// contains filtered or unexported fields
}

Mapping is a run of maps, some mirroring others, so what one deleted the other's undoing brings back.

func NewMapping

func NewMapping(maps ...*StepMap) *Mapping

NewMapping makes a mapping of maps.

func (*Mapping) AppendMap

func (m *Mapping) AppendMap(sm *StepMap, mirrors int)

AppendMap adds a map, mirroring map mirrors when it is not negative.

func (*Mapping) AppendMapping

func (m *Mapping) AppendMapping(o *Mapping)

AppendMapping adds another mapping's maps.

func (*Mapping) AppendMappingInverted

func (m *Mapping) AppendMappingInverted(o *Mapping)

AppendMappingInverted adds another mapping's maps inverted, last first.

func (*Mapping) GetMirror

func (m *Mapping) GetMirror(n int) int

GetMirror is the map mirroring n, -1 for none.

func (*Mapping) Invert

func (m *Mapping) Invert() *Mapping

Invert is the mapping back.

func (*Mapping) Map

func (m *Mapping) Map(pos, assoc int) int

Map maps pos.

func (*Mapping) MapResult

func (m *Mapping) MapResult(pos, assoc int) MapResult

MapResult maps pos and reports what happened.

func (*Mapping) Slice

func (m *Mapping) Slice(from, to int) *Mapping

Slice is the maps from from to to.

type Mark

type Mark struct {
	Type  *MarkType
	Attrs Attrs
}

Mark is a mark on inline content.

func (*Mark) AddToSet

func (m *Mark) AddToSet(set []*Mark) []*Mark

AddToSet is set with the mark, in rank order, without what it excludes; set itself when a mark there excludes it.

func (*Mark) Eq

func (m *Mark) Eq(o *Mark) bool

Eq says two marks are of one type with equal attributes.

func (*Mark) IsInSet

func (m *Mark) IsInSet(set []*Mark) bool

IsInSet says set holds the mark.

func (*Mark) RemoveFromSet

func (m *Mark) RemoveFromSet(set []*Mark) []*Mark

RemoveFromSet is set without the mark.

type MarkSpec

type MarkSpec struct {
	Name  string
	Attrs []AttrSpec
	// NotInclusive keeps text typed at its end out of it.
	NotInclusive bool
	// Excludes are the marks it cannot coexist with, space separated: its
	// own type when "", every one with "_", none with "none".
	Excludes string
	Group    string
	// RenderText is unused by marks' kernel; Extra is as NodeSpec's.
	Extra map[string]any
}

MarkSpec is a type of mark.

type MarkType

type MarkType struct {
	Name   string
	Schema *Schema
	Spec   MarkSpec
	Rank   int
	// contains filtered or unexported fields
}

MarkType is a type of a schema's marks.

func (*MarkType) Create

func (t *MarkType) Create(attrs Attrs) *Mark

Create makes a mark of the type.

func (*MarkType) Excludes

func (t *MarkType) Excludes(other *MarkType) bool

Excludes says marks of the type exclude marks of other.

func (*MarkType) IsInSet

func (t *MarkType) IsInSet(set []*Mark) *Mark

IsInSet is the mark of the type in set, nil for none.

func (*MarkType) RemoveFromSet

func (t *MarkType) RemoveFromSet(set []*Mark) []*Mark

RemoveFromSet is set without marks of the type.

type MentionOptions

type MentionOptions struct {
	Suggestion SuggestionOptions
}

MentionOptions tune Mention.

type Node

type Node struct {
	Type    *NodeType
	Attrs   Attrs
	Content *Fragment
	Marks   []*Mark
	Text    string
	// contains filtered or unexported fields
}

Node is a node of a document, never changed once made; a text node holds Text and the others Content.

func DocFromJSONString

func DocFromJSONString(s *Schema, text string) (*Node, error)

DocFromJSONString reads a document from JSON and checks it.

func NodeFromJSON

func NodeFromJSON(s *Schema, v map[string]any) (*Node, error)

NodeFromJSON reads a node of s, checking only what it needs to.

func ParseHTML

func ParseHTML(s *Schema, source string) (*Node, error)

ParseHTML reads HTML into a document of the starter's names, what the schema does not have dropped to its text.

func ParseMarkdown

func ParseMarkdown(s *Schema, source string) (*Node, error)

ParseMarkdown reads CommonMark and GFM into a document of the starter's names, keeping what the schema has: task items as taskItem, pipe tables as tables, the first row header cells.

func (*Node) AttrNum

func (n *Node) AttrNum(name string) float64

Attr reads an attribute as a number, 0 when it is none.

func (*Node) AttrStr

func (n *Node) AttrStr(name string) string

AttrStr reads an attribute as a string.

func (*Node) CanAppend

func (n *Node) CanAppend(o *Node) bool

CanAppend says other's content can follow the node's.

func (*Node) CanReplace

func (n *Node) CanReplace(from, to int, replacement *Fragment, start, end int) bool

CanReplace says replacing children from to to with replacement, from start to end of it, keeps the node valid.

func (*Node) CanReplaceWith

func (n *Node) CanReplaceWith(from, to int, t *NodeType, marks []*Mark) bool

CanReplaceWith says a node of t in place of children from to to keeps the node valid.

func (*Node) Check

func (n *Node) Check() error

Check says the node and all inside fit the schema.

func (*Node) Child

func (n *Node) Child(i int) *Node

func (*Node) ChildCount

func (n *Node) ChildCount() int

func (*Node) Copy

func (n *Node) Copy(content *Fragment) *Node

Copy is the node with other content.

func (*Node) Cut

func (n *Node) Cut(from, to int) *Node

Cut is the node from from to to.

func (*Node) Descendants

func (n *Node) Descendants(f func(node *Node, pos int, parent *Node, index int) bool)

Descendants calls f on every node inside.

func (*Node) Eq

func (n *Node) Eq(o *Node) bool

Eq says two nodes are equal, whole.

func (*Node) FirstChild

func (n *Node) FirstChild() *Node

func (*Node) HasMarkup

func (n *Node) HasMarkup(t *NodeType, attrs Attrs, marks []*Mark) bool

HasMarkup says the node has that markup.

func (*Node) InlineContent

func (n *Node) InlineContent() bool

func (*Node) IsAtom

func (n *Node) IsAtom() bool

func (*Node) IsBlock

func (n *Node) IsBlock() bool

func (*Node) IsInline

func (n *Node) IsInline() bool

func (*Node) IsLeaf

func (n *Node) IsLeaf() bool

func (*Node) IsText

func (n *Node) IsText() bool

func (*Node) IsTextblock

func (n *Node) IsTextblock() bool

func (*Node) LastChild

func (n *Node) LastChild() *Node

func (*Node) Mark

func (n *Node) Mark(marks []*Mark) *Node

Mark is the node with other marks.

func (*Node) MaybeChild

func (n *Node) MaybeChild(i int) *Node

func (*Node) NodeAt

func (n *Node) NodeAt(pos int) *Node

NodeAt is the node at pos, nil for none.

func (*Node) NodeSize

func (n *Node) NodeSize() int

NodeSize is the positions it takes.

func (*Node) NodesBetween

func (n *Node) NodesBetween(from, to int, f func(node *Node, pos int, parent *Node, index int) bool, start int)

NodesBetween calls f on the nodes from from to to, depth first, skipping a node's children when it returns false.

func (*Node) RangeHasMark

func (n *Node) RangeHasMark(from, to int, m *MarkType) bool

RangeHasMark says a node from from to to has a mark of m.

func (*Node) Replace

func (n *Node) Replace(from, to int, slice *Slice) (*Node, error)

Replace is the node with from to to replaced by slice.

func (*Node) Resolve

func (n *Node) Resolve(pos int) *ResolvedPos

Resolve resolves pos, which must be in the document.

func (*Node) SameMarkup

func (n *Node) SameMarkup(o *Node) bool

SameMarkup says two nodes differ at most in content.

func (*Node) Slice

func (n *Node) Slice(from, to int, includeParents bool) *Slice

Slice is the document from from to to, open as far as the two share no parent, or to their deepest shared depth with includeParents.

func (*Node) String

func (n *Node) String() string

func (*Node) TextBetween

func (n *Node) TextBetween(from, to int, blockSep, leafText string) string

TextBetween is the text from from to to, blocks joined by blockSep and leaves as leafText or their LeafText.

func (*Node) TextContent

func (n *Node) TextContent() string

TextContent is its text.

func (*Node) WithText

func (n *Node) WithText(text string) *Node

WithText is a text node with other text.

type NodeProps

type NodeProps struct {
	// Node is the node now, and Pos where it is.
	Node func() *Node
	Pos  func() int
	// Selected says a node selection holds it.
	Selected func() bool
	// Content is the editor's rendering of the node's content, editable
	// where the view places it; nil for a leaf.
	Content core.Node
	Editor  *Session
	// SetAttrs changes attributes as a transaction, undoable as any other.
	SetAttrs func(attrs Attrs)
}

NodeProps is what a node view follows.

type NodeRange

type NodeRange struct {
	From, To *ResolvedPos
	Depth    int
}

NodeRange is a flat range of a node's children.

func (*NodeRange) End

func (n *NodeRange) End() int

func (*NodeRange) EndIndex

func (n *NodeRange) EndIndex() int

func (*NodeRange) Parent

func (n *NodeRange) Parent() *Node

func (*NodeRange) Start

func (n *NodeRange) Start() int

func (*NodeRange) StartIndex

func (n *NodeRange) StartIndex() int

type NodeSelection

type NodeSelection struct {
	Node *Node
	// contains filtered or unexported fields
}

NodeSelection selects one node.

func NewNodeSelection

func NewNodeSelection(pos *ResolvedPos) *NodeSelection

NewNodeSelection selects the node after pos.

func NodeSelectionAt

func NodeSelectionAt(doc *Node, from int) *NodeSelection

NodeSelectionAt selects the node at from.

func (*NodeSelection) Anchor

func (s *NodeSelection) Anchor() int

func (*NodeSelection) AnchorPos

func (s *NodeSelection) AnchorPos() *ResolvedPos

func (*NodeSelection) Bookmark

func (s *NodeSelection) Bookmark() Bookmark

func (*NodeSelection) Content

func (s *NodeSelection) Content() *Slice

func (*NodeSelection) Empty

func (s *NodeSelection) Empty() bool

func (*NodeSelection) Eq

func (s *NodeSelection) Eq(o Selection) bool

func (*NodeSelection) From

func (s *NodeSelection) From() int

func (*NodeSelection) FromPos

func (s *NodeSelection) FromPos() *ResolvedPos

func (*NodeSelection) Head

func (s *NodeSelection) Head() int

func (*NodeSelection) HeadPos

func (s *NodeSelection) HeadPos() *ResolvedPos

func (*NodeSelection) Map

func (s *NodeSelection) Map(doc *Node, m Mappable) Selection

func (*NodeSelection) Ranges

func (s *NodeSelection) Ranges() []SelectionRange

func (*NodeSelection) Replace

func (s *NodeSelection) Replace(tr *Transaction, content *Slice)

func (*NodeSelection) ReplaceWith

func (s *NodeSelection) ReplaceWith(tr *Transaction, node *Node)

func (*NodeSelection) To

func (s *NodeSelection) To() int

func (*NodeSelection) ToPos

func (s *NodeSelection) ToPos() *ResolvedPos

type NodeSpec

type NodeSpec struct {
	Name string
	// Content is its content expression ("paragraph+", "inline*",
	// "(heading | paragraph) block*"); a leaf without one.
	Content string
	// Marks are the marks allowed in it, space separated, "_" for every
	// one and "none" for none; unset, an inline container's take every one.
	Marks string
	// Group is the groups it belongs to, space separated.
	Group  string
	Inline bool
	// Atom has a node with content count as one unit from outside.
	Atom bool
	// NoSelect keeps node selections off it.
	NoSelect bool
	// Code has its content kept as code: marks and commands treat it so.
	Code bool
	// Defining keeps a node when its content is replaced, and its content
	// keeps it when pasted; Isolating stops edits at its boundaries.
	Defining, Isolating bool
	// Whitespace "pre" keeps its white space as it is.
	Whitespace string
	Attrs      []AttrSpec
	// LeafText is what a leaf is as text.
	LeafText func(n *Node) string
	// RenderText is what the view shows for an inline leaf, one position
	// however long, a mention's @name.
	RenderText func(n *Node) string
	// Extra is what other parts read: a list's "listMarker", a table's
	// "tableRole".
	Extra map[string]any
}

NodeSpec is a type of node.

type NodeType

type NodeType struct {
	Name          string
	Schema        *Schema
	Spec          NodeSpec
	Groups        []string
	ContentMatch  *ContentMatch
	InlineContent bool
	// MarkSet is the marks allowed, nil for every one.
	MarkSet []*MarkType
	// contains filtered or unexported fields
}

NodeType is a type of a schema's nodes.

func (*NodeType) AllowsMarkType

func (t *NodeType) AllowsMarkType(m *MarkType) bool

AllowsMarkType says the type's content may hold marks of m.

func (*NodeType) AllowsMarks

func (t *NodeType) AllowsMarks(marks []*Mark) bool

AllowsMarks says it may hold all of marks.

func (*NodeType) Create

func (t *NodeType) Create(attrs Attrs, content *Fragment, marks []*Mark) *Node

Create makes a node without checking its content.

func (*NodeType) CreateAndFill

func (t *NodeType) CreateAndFill(attrs Attrs, content *Fragment, marks []*Mark) *Node

CreateAndFill makes a node filling what its content requires around content, nil when it cannot.

func (*NodeType) IsAtom

func (t *NodeType) IsAtom() bool

func (*NodeType) IsBlock

func (t *NodeType) IsBlock() bool

IsBlock, IsText, IsInline, IsLeaf, IsTextblock and IsAtom say what a type's nodes are.

func (*NodeType) IsInline

func (t *NodeType) IsInline() bool

func (*NodeType) IsLeaf

func (t *NodeType) IsLeaf() bool

func (*NodeType) IsText

func (t *NodeType) IsText() bool

func (*NodeType) IsTextblock

func (t *NodeType) IsTextblock() bool

func (*NodeType) ValidContent

func (t *NodeType) ValidContent(content *Fragment) bool

ValidContent says content fits the type.

type NodeTypeAttrs

type NodeTypeAttrs struct {
	Type  *NodeType
	Attrs Attrs
}

NodeTypeAttrs is a wrapper and its attributes.

func FindWrapping

func FindWrapping(r *NodeRange, typ *NodeType, attrs Attrs, innerRange *NodeRange) []NodeTypeAttrs

FindWrapping is the wrappers a range takes to sit in typ, nil for none.

type NodeView

type NodeView func(cx *core.Scope, props NodeProps) core.Node

NodeView renders a node type in place of the editor's: its element follows Node, and never changes the node but through SetAttrs. A block's is its block; an inline node's is a view in the text's lines, an attachment in place of what RenderText or LeafText calls it, which copy takes instead, and a press on it selects the node, atomically as it stays one position.

type Origin

type Origin uint8

Origin says where a transaction comes from.

const (
	OriginUser Origin = iota
	OriginInput
	OriginPaste
	OriginDrop
	OriginRemote
	OriginHistory
	OriginPlugin
	OriginAPI
)

type Plugin

type Plugin struct {
	// Key is unique in a state.
	Key string
	// Init and Apply are the plugin's field in the state.
	Init  func(s *State) any
	Apply func(tr *Transaction, value any, old, new *State) any
	// FilterTransaction refuses a transaction before it applies.
	FilterTransaction func(tr *Transaction, s *State) bool
	// AppendTransaction may add a transaction after others applied.
	AppendTransaction func(trs []*Transaction, old, new *State) *Transaction

	HandleKeyDown   func(v *Session, key string) bool
	HandleTextInput func(v *Session, from, to int, text string) bool
	HandlePaste     func(v *Session, slice *Slice) bool
	// TransformPasted changes what is pasted, and TransformPastedText the
	// text it comes from.
	TransformPasted     func(v *Session, slice *Slice) *Slice
	TransformPastedText func(v *Session, text string) string
	// HandleClick hears a press at pos, Clicks in a row, Mod held or not.
	HandleClick func(v *Session, pos, clicks int, mod bool) bool
	// Decorations are what the view draws without changing the document.
	Decorations func(s *State) []Decoration
}

Plugin is optional behavior over a state: a field in the state, hooks on transactions and hooks on the view's events, asked in plugin order, the first true consuming the event.

func FixTables

func FixTables() *Plugin

FixTables keeps the tables valid after every change.

func GapCursorPlugin

func GapCursorPlugin() *Plugin

GapCursorPlugin is prosemirror-gapcursor's plugin: arrows move into gaps, a press in one puts the cursor there, and the view draws it.

func History

func History(o HistoryOptions) *Plugin

History is the undo history: changes further apart than NewGroupDelay, or not adjacent, start a new step, an input method's commits group, and changes kept out of it or made by others map its steps.

func InputRules

func InputRules(rules []InputRule) *Plugin

InputRules runs rules on typed text.

func Keymap

func Keymap(key string, bindings map[string]Command) *Plugin

Keymap binds keys ("Mod-b", "Shift-Enter", "Backspace") to commands; a key's commands run until one applies. A binding with Shift spelled out goes before the shifted character's.

func Suggestion

func Suggestion(o SuggestionOptions) *Plugin

Suggestion follows a trigger and the query after it, for the app's list, which reads SuggestionStateOf and replaces the range.

func TableEditing

func TableEditing() *Plugin

TableEditing normalizes selections in tables: a selected cell, row or table becomes a cell selection, and a text selection across two cells of one table does.

type Rect

type Rect struct{ Left, Top, Right, Bottom int }

Rect is a rectangle of a table's map, its right and bottom past the end.

type Rect2

type Rect2 struct{ X, Y, Width, Height float64 }

Rect2 is a box in points.

type Ref

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

Ref is a View's methods.

func (*Ref) Blur

func (r *Ref) Blur()

Blur gives the keyboard back.

func (*Ref) Focus

func (r *Ref) Focus()

Focus takes the keyboard.

func (*Ref) PageBounds

func (r *Ref) PageBounds(pos int) core.Bounds

PageBounds is the caret's box at pos in the surface, for an Overlay the app places by the text, such as a mention's list.

func (*Ref) Session

func (r *Ref) Session() *Session

Session is the session it shows.

type RemoveMarkStep

type RemoveMarkStep struct {
	From, To int
	Mark     *Mark
}

RemoveMarkStep removes Mark from From to To.

func (*RemoveMarkStep) Apply

func (s *RemoveMarkStep) Apply(doc *Node) (*Node, error)

func (*RemoveMarkStep) Invert

func (s *RemoveMarkStep) Invert(*Node) Step

func (*RemoveMarkStep) Map

func (s *RemoveMarkStep) Map(m Mappable) Step

func (*RemoveMarkStep) Merge

func (s *RemoveMarkStep) Merge(other Step) Step

func (*RemoveMarkStep) StepMap

func (s *RemoveMarkStep) StepMap() *StepMap

type ReplaceAroundStep

type ReplaceAroundStep struct {
	From, To, GapFrom, GapTo int
	Slice                    *Slice
	Insert                   int
	Structure                bool
}

ReplaceAroundStep replaces From to To, keeping GapFrom to GapTo as the content at Insert of Slice.

func (*ReplaceAroundStep) Apply

func (s *ReplaceAroundStep) Apply(doc *Node) (*Node, error)

func (*ReplaceAroundStep) Invert

func (s *ReplaceAroundStep) Invert(doc *Node) Step

func (*ReplaceAroundStep) Map

func (s *ReplaceAroundStep) Map(m Mappable) Step

func (*ReplaceAroundStep) Merge

func (s *ReplaceAroundStep) Merge(Step) Step

func (*ReplaceAroundStep) StepMap

func (s *ReplaceAroundStep) StepMap() *StepMap

type ReplaceStep

type ReplaceStep struct {
	From, To  int
	Slice     *Slice
	Structure bool
}

ReplaceStep replaces From to To with Slice.

func (*ReplaceStep) Apply

func (s *ReplaceStep) Apply(doc *Node) (*Node, error)

func (*ReplaceStep) Invert

func (s *ReplaceStep) Invert(doc *Node) Step

func (*ReplaceStep) Map

func (s *ReplaceStep) Map(m Mappable) Step

func (*ReplaceStep) Merge

func (s *ReplaceStep) Merge(other Step) Step

func (*ReplaceStep) StepMap

func (s *ReplaceStep) StepMap() *StepMap

type ResolvedPos

type ResolvedPos struct {
	Pos          int
	Depth        int
	ParentOffset int
	// contains filtered or unexported fields
}

ResolvedPos is a position with what it is in.

func FindGapCursorFrom

func FindGapCursorFrom(r *ResolvedPos, dir int, mustMove bool) *ResolvedPos

FindGapCursorFrom is the first gap from pos going dir, moving off pos when mustMove; nil for none.

func (*ResolvedPos) After

func (r *ResolvedPos) After(d int) int

After is the position after it.

func (*ResolvedPos) Before

func (r *ResolvedPos) Before(d int) int

Before is the position before its ancestor at depth d.

func (*ResolvedPos) BlockRange

func (r *ResolvedPos) BlockRange(other *ResolvedPos, pred func(*Node) bool) *NodeRange

BlockRange is the flat range of blocks around from here to other, nil for none.

func (*ResolvedPos) Doc

func (r *ResolvedPos) Doc() *Node

Doc is the document.

func (*ResolvedPos) End

func (r *ResolvedPos) End(d int) int

End is where it ends.

func (*ResolvedPos) Index

func (r *ResolvedPos) Index(d int) int

Index is the child of its ancestor at depth d it points into.

func (*ResolvedPos) IndexAfter

func (r *ResolvedPos) IndexAfter(d int) int

IndexAfter is the index after it at depth d.

func (*ResolvedPos) MarksAcross

func (r *ResolvedPos) MarksAcross(end *ResolvedPos) []*Mark

MarksAcross are the marks after it that also go on to end.

func (*ResolvedPos) MarksHere

func (r *ResolvedPos) MarksHere() []*Mark

MarksHere are the marks typed text would take here.

func (*ResolvedPos) Node

func (r *ResolvedPos) Node(d int) *Node

Node is its ancestor at depth d; a negative d counts from its own.

func (*ResolvedPos) NodeAfter

func (r *ResolvedPos) NodeAfter() *Node

NodeAfter is the node after it, a text's rest, nil for none.

func (*ResolvedPos) NodeBefore

func (r *ResolvedPos) NodeBefore() *Node

NodeBefore is the node before it, a text's start, nil for none.

func (*ResolvedPos) Parent

func (r *ResolvedPos) Parent() *Node

Parent is the node it is directly in.

func (*ResolvedPos) PosAtIndex

func (r *ResolvedPos) PosAtIndex(index, d int) int

PosAtIndex is the position of child index of its ancestor at depth d.

func (*ResolvedPos) SameParent

func (r *ResolvedPos) SameParent(o *ResolvedPos) bool

SameParent says two positions are in one node.

func (*ResolvedPos) SharedDepth

func (r *ResolvedPos) SharedDepth(pos int) int

SharedDepth is the deepest ancestor holding pos too.

func (*ResolvedPos) Start

func (r *ResolvedPos) Start(d int) int

Start is where the content of its ancestor at depth d starts.

func (*ResolvedPos) TextOffset

func (r *ResolvedPos) TextOffset() int

TextOffset is how far into a text node it is.

type Schema

type Schema struct {
	Spec    SchemaSpec
	Nodes   map[string]*NodeType
	Marks   map[string]*MarkType
	TopNode *NodeType
	// contains filtered or unexported fields
}

Schema is a document's node and mark types.

func NewSchema

func NewSchema(spec SchemaSpec) (*Schema, error)

NewSchema makes a schema, refusing what cannot make one: a content expression that does not read or requires a type no document can fill.

func (*Schema) DefaultBlock

func (s *Schema) DefaultBlock() *NodeType

DefaultBlock is the first block type in the top node's content.

func (*Schema) Mark

func (s *Schema) Mark(name string, attrs Attrs) *Mark

Mark makes a mark of type name.

func (*Schema) Node

func (s *Schema) Node(name string, attrs Attrs, children ...*Node) *Node

Node makes a node of type name, panicking on an unknown one; attributes fill with their defaults. The schema's content rules are Check's.

func (*Schema) Text

func (s *Schema) Text(text string, marks ...*Mark) *Node

Text makes a text node, never empty.

type SchemaSpec

type SchemaSpec struct {
	Nodes   []NodeSpec
	Marks   []MarkSpec
	TopNode string
}

SchemaSpec is a schema's types in order: the first block type is the default one, and TopNode, "doc" when "", the document's.

type Selection

type Selection interface {
	Anchor() int
	Head() int
	From() int
	To() int
	FromPos() *ResolvedPos
	ToPos() *ResolvedPos
	HeadPos() *ResolvedPos
	AnchorPos() *ResolvedPos
	Ranges() []SelectionRange
	Empty() bool
	Eq(Selection) bool
	Map(doc *Node, m Mappable) Selection
	Content() *Slice
	Replace(tr *Transaction, content *Slice)
	ReplaceWith(tr *Transaction, node *Node)
	Bookmark() Bookmark
}

Selection is what is selected: text, a node, everything or a table's cells. Each kind maps through changes, gives its content as a Slice, replaces it, and has a bookmark that maps without a document.

func SelectionAtEnd

func SelectionAtEnd(doc *Node) Selection

SelectionAtEnd is the last selection in doc.

func SelectionAtStart

func SelectionAtStart(doc *Node) Selection

SelectionAtStart is the first selection in doc.

func SelectionFindFrom

func SelectionFindFrom(pos *ResolvedPos, dir int, textOnly bool) Selection

SelectionFindFrom is the first valid selection from pos going dir, a text one with textOnly; nil for none.

func SelectionFindFromOrNear

func SelectionFindFromOrNear(pos *ResolvedPos, dir int) Selection

SelectionFindFromOrNear is the selection from pos going dir, else near.

func SelectionNear

func SelectionNear(pos *ResolvedPos, bias int) Selection

SelectionNear is a valid selection near pos, bias the side looked at first.

func TextSelectionAt

func TextSelectionAt(doc *Node, anchor, head int) Selection

TextSelectionAt selects from anchor to head.

func TextSelectionBetween

func TextSelectionBetween(anchor, head *ResolvedPos, bias int) Selection

TextSelectionBetween is the text selection nearest the two positions.

type SelectionRange

type SelectionRange struct{ From, To *ResolvedPos }

SelectionRange is a range a selection covers.

type Session

type Session struct {

	// DispatchTransaction, when set, takes every transaction in place of
	// Dispatch's applying it, the app committing with UpdateState.
	DispatchTransaction func(tr *Transaction)
	// contains filtered or unexported fields
}

Session is the one live editor a view and the app share, on the engine goroutine as the reactive graph is: it holds the state, applies transactions, runs commands and tells its subscribers.

func NewSession

func NewSession(c SessionConfig) (*Session, error)

NewSession makes a session.

func (*Session) Apply

func (v *Session) Apply(tr *Transaction) error

Apply applies tr at once, dropping one that fails: the document stays as it was.

func (*Session) Blur

func (v *Session) Blur()

Blur asks its views to give the keyboard back.

func (*Session) Can

func (v *Session) Can(c Command) bool

Can says a command would apply.

func (*Session) CanNamed

func (v *Session) CanNamed(name string, args Attrs) bool

CanNamed says a named command would apply.

func (*Session) Command

func (v *Session) Command(name string, args Attrs) Command

Command is the named command with args, nil for an unknown name.

func (*Session) CoordsAtPos

func (v *Session) CoordsAtPos(pos int) (Rect2, bool)

CoordsAtPos is the caret's box at pos in the view's content box, false with no view; it panics on a position outside the document, as Resolve.

func (*Session) Copy

func (v *Session) Copy() (text, html string)

Copy is the selection as text and HTML, as it goes to the clipboard.

func (*Session) Cut

func (v *Session) Cut() (text, html string)

Cut copies and deletes the selection.

func (*Session) Dispatch

func (v *Session) Dispatch(tr *Transaction)

Dispatch applies tr, or hands it to DispatchTransaction.

func (*Session) DragBlock

func (v *Session) DragBlock(pos int, x, y float64) bool

DragBlock starts a handle's drag at a point of the surface: it selects the block at pos, a table too, and carries it, or the siblings a selection over several covers when pos is in it, and says whether it did. DragTo moves the drop cursor, and EndDrag drops them there, as one undo step.

func (*Session) DragTo

func (v *Session) DragTo(x, y float64)

DragTo moves a handle's drag to a point of the surface.

func (*Session) Editable

func (v *Session) Editable() bool

Editable says the user can change the document.

func (*Session) EndDrag

func (v *Session) EndDrag() bool

EndDrag drops what a handle carries where its drop cursor is, and says whether the blocks moved.

func (*Session) Focus

func (v *Session) Focus()

Focus and Blur are requests to the views showing it.

func (*Session) HTML

func (v *Session) HTML() string

func (*Session) HandleKey

func (v *Session) HandleKey(name string) bool

HandleKey offers a key, by its name ("Mod-b", "Shift-Enter"), to the plugins, the first taking it.

func (*Session) IsActive

func (v *Session) IsActive(name string, attrs Attrs) bool

IsActive says the node or mark of name is at the selection.

func (*Session) JSON

func (v *Session) JSON() string

func (*Session) Markdown

func (v *Session) Markdown() string

Markdown, JSON, HTML and Text are the document in those forms.

func (*Session) MoveChar

func (v *Session) MoveChar(dir int, extend bool)

MoveChar moves the head a grapheme by dir, extending with extend.

func (*Session) MoveWord

func (v *Session) MoveWord(dir int, extend bool)

MoveWord moves the head a word by dir.

func (*Session) OpenGap

func (v *Session) OpenGap() bool

OpenGap fills a gap cursor with the textblock its place takes, and puts a text cursor in it, for an input method to compose there; it says whether it did.

func (*Session) PageCoordsAtPos

func (v *Session) PageCoordsAtPos(pos int) (Rect2, bool)

PageCoordsAtPos is CoordsAtPos in the surface's points, for what the app places outside the editor, such as a block's handle.

func (*Session) Paste

func (v *Session) Paste(text, html string)

Paste pastes text, HTML when html is not empty, as the plugins allow.

func (*Session) PosAtCoords

func (v *Session) PosAtCoords(x, y float64) (int, bool)

PosAtCoords is the position nearest a point of the content box.

func (*Session) PosAtPageCoords

func (v *Session) PosAtPageCoords(x, y float64) (int, bool)

PosAtPageCoords is PosAtCoords from a point of the surface.

func (*Session) Run

func (v *Session) Run(c Command) bool

Run runs a command, and says whether it applied.

func (*Session) RunNamed

func (v *Session) RunNamed(name string, args Attrs) bool

RunNamed runs a named command.

func (*Session) SelectionRect

func (v *Session) SelectionRect() (Rect2, bool)

SelectionRect is the box over the selection's lines.

func (*Session) SetContent

func (v *Session) SetContent(doc *Node)

SetContent replaces the document, kept out of the history.

func (*Session) SetEditable

func (v *Session) SetEditable(on bool)

SetEditable sets whether the user can change the document.

func (*Session) State

func (v *Session) State() *State

State is the state now.

func (*Session) Subscribe

func (v *Session) Subscribe(f func(s *State, trs []*Transaction)) func()

Subscribe calls f after every change, and the returned function stops it.

func (*Session) Text

func (v *Session) Text() string

func (*Session) TypeText

func (v *Session) TypeText(text string, composition any)

TypeText types text as a user does: input rules first, then the stored marks, tagged with an input method's composition.

func (*Session) UpdateState

func (v *Session) UpdateState(s *State)

UpdateState replaces the state.

type SessionConfig

type SessionConfig struct {
	Extensions []Extension
	Schema     *Schema
	Plugins    []*Plugin
	Doc        *Node
	Markdown   string
	JSON       string
	HTML       string
	// ReadOnly keeps the user from changing it.
	ReadOnly bool
}

SessionConfig makes a Session: Extensions make its schema and plugins, or Schema and Plugins give them. Content is a Markdown text, unless Doc gives the document or JSON Tiptap's.

type Slice

type Slice struct {
	Content            *Fragment
	OpenStart, OpenEnd int
}

Slice is a piece of a document: content with OpenStart and OpenEnd levels open on each side.

func MaxOpen

func MaxOpen(f *Fragment, openIsolating bool) *Slice

MaxOpen is the most-open slice of fragment.

func NewSlice

func NewSlice(content *Fragment, openStart, openEnd int) *Slice

NewSlice makes a slice.

func SliceFromText

func SliceFromText(s *Schema, text string, r *ResolvedPos) *Slice

SliceFromText is pasted text as a slice: lines of the default block, a paragraph per run, in code as the text it is.

func (*Slice) Eq

func (s *Slice) Eq(o *Slice) bool

Eq says two slices are equal.

func (*Slice) InsertAt

func (s *Slice) InsertAt(pos int, f *Fragment) *Slice

InsertAt is the slice with fragment inserted at pos, nil when it fails.

func (*Slice) RemoveBetween

func (s *Slice) RemoveBetween(from, to int) (*Slice, error)

RemoveBetween is the slice without from to to.

func (*Slice) Size

func (s *Slice) Size() int

Size is the positions it adds.

type StarterOptions

type StarterOptions struct {
	// Levels are the headings' levels, 1 to 6 when nil.
	Levels                                              []int
	History                                             HistoryOptions
	NoHistory, NoTrailingNode, NoTaskList, NoTypography bool
	NoGapCursor                                         bool
	Link                                                LinkOptions
}

StarterOptions leave parts of StarterKit out, or tune them.

type State

type State struct {
	Schema      *Schema
	Doc         *Node
	Selection   Selection
	StoredMarks []*Mark
	Plugins     []*Plugin
	// Revision counts the transactions applied.
	Revision int
	// contains filtered or unexported fields
}

State is an editor's state, never changed once made: Apply returns a new one, which is what history and the view's updates rely on.

func NewState

func NewState(c StateConfig) (*State, error)

NewState makes a state, refusing two plugins with one key.

func (*State) Apply

func (s *State) Apply(tr *Transaction) (*State, error)

Apply applies tr, the new state alone.

func (*State) ApplyTransaction

func (s *State) ApplyTransaction(root *Transaction) (*State, []*Transaction, error)

ApplyTransaction applies tr and what plugins append to it, atomically: the new state, and every transaction applied. A filtered transaction leaves the state.

func (*State) PluginState

func (s *State) PluginState(key string) any

PluginState is plugin key's field.

func (*State) Reconfigure

func (s *State) Reconfigure(plugins []*Plugin) (*State, error)

Reconfigure is the state with other plugins, whose fields start again unless a plugin stays.

func (*State) Tr

func (s *State) Tr() *Transaction

Tr starts a transaction.

type StateConfig

type StateConfig struct {
	Schema      *Schema
	Doc         *Node
	Selection   Selection
	StoredMarks []*Mark
	Plugins     []*Plugin
}

StateConfig makes a state: Doc, or an empty document of Schema.

type StateError

type StateError struct{ Msg string }

StateError says a transaction could not apply.

func (*StateError) Error

func (e *StateError) Error() string

type Step

type Step interface {
	Apply(doc *Node) (*Node, error)
	StepMap() *StepMap
	Invert(doc *Node) Step
	// Map is the step over another change, nil when that deleted it.
	Map(m Mappable) Step
	// Merge joins the step with the next, nil when it cannot.
	Merge(other Step) Step
}

Step is one change of a document: it applies or fails, maps positions, inverts against the document it applied to and maps over other changes.

func ReplaceStepFit

func ReplaceStepFit(doc *Node, from, to int, slice *Slice) Step

ReplaceStepFit fits slice into from to to of doc: the step that inserts it, closing and wrapping nodes as needed, nil when it has no place there or nothing changes.

type StepMap

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

StepMap is how a step moves positions: triples of a start, an old size and a new size.

func (*StepMap) ForEach

func (m *StepMap) ForEach(f func(oldStart, oldEnd, newStart, newEnd int))

ForEach calls f with each changed range: old start and end, new start and end.

func (*StepMap) Invert

func (m *StepMap) Invert() *StepMap

Invert is the map back.

func (*StepMap) Map

func (m *StepMap) Map(pos, assoc int) int

Map maps pos.

func (*StepMap) MapResult

func (m *StepMap) MapResult(pos, assoc int) MapResult

MapResult maps pos, assoc saying which side it sticks to.

type Styles

type Styles struct {
	// Content is the box that scrolls, whose padding is the text's.
	Content core.Style
	// Nodes style blocks by type name, then "type[attr=value]"; Marks
	// inline text by mark name, as "mention" does its leaves.
	Nodes, Marks map[string]core.Style
	// Placeholder is the text of an empty document; Caret the caret, 2
	// points wide unless it gives a width; Selection behind selected text;
	// Composition what an input method composes; GapCursor the cursor
	// between blocks, 20 by 2 points unless it gives a size; DropCursor
	// the line where blocks a handle drags will land, 2 points tall.
	Placeholder, Caret, Selection, Composition, GapCursor, DropCursor core.Style
	// SelectedNode goes on the block a node selection holds, and SelectedCell
	// on the box in each selected cell.
	SelectedNode, SelectedCell core.Style
	// SelectionHandle is the knobs at a touch selection's ends.
	SelectionHandle core.Style
	// ListMarker is the marker a list's item shows; TaskCheckbox a task
	// item's box, whose Selected state is its check.
	ListMarker, TaskCheckbox core.Style
	// TableResizeHandle is the line of a column or row being resized;
	// TableGrip a table's grip over a column or beside a row;
	// TableDropIndicator the line where one dragged will land.
	TableResizeHandle, TableGrip, TableDropIndicator core.Style
}

Styles are the styles of the editor's parts, which supply its whole look.

type SuggestionOptions

type SuggestionOptions struct {
	// Key names it among an editor's, "suggestion" when "".
	Key string
	// Char is what starts it, "@" when "".
	Char string
	// AllowSpaces lets a query hold spaces.
	AllowSpaces bool
	// AllowedPrefixes are what may go before Char, " " and a line's start
	// when nil.
	AllowedPrefixes []string
	// Allow says a match may become active.
	Allow func(s *State, from, to int) bool
	// Class goes on the active range.
	Class string
	// CaptureKeys are taken while it is active, for the app's list.
	CaptureKeys []string
	// OnKey hears keys while it is active, and those it returns true for
	// are taken.
	OnKey func(key string) bool
}

SuggestionOptions tune a Suggestion.

type SuggestionState

type SuggestionState struct {
	Active   bool
	From, To int
	Query    string
	// Text is the trigger and the query.
	Text string

	// LastKey and KeyCount say what was captured, for an app reading them
	// after the fact.
	LastKey  string
	KeyCount int
	// contains filtered or unexported fields
}

SuggestionState is what a Suggestion's plugin holds.

func SuggestionStateOf

func SuggestionStateOf(s *State, key string) *SuggestionState

SuggestionStateOf is the state of the Suggestion keyed key.

type TableMap

type TableMap struct {
	Width, Height int
	Map           []int
	// contains filtered or unexported fields
}

TableMap is a table's grid, each slot the cell covering it as an offset from the table's start.

func TableMapOf

func TableMapOf(table *Node) *TableMap

TableMapOf is table's map, cached by node.

func (*TableMap) Cells

func (m *TableMap) Cells() []CellRect

Cells are each cell's offset with its rectangle, row by row.

func (*TableMap) CellsInRect

func (m *TableMap) CellsInRect(rect Rect) []int

CellsInRect are the cells whose top left is in rect.

func (*TableMap) ColCount

func (m *TableMap) ColCount(pos int) int

ColCount is the column the cell at pos starts in.

func (*TableMap) FindCell

func (m *TableMap) FindCell(pos int) Rect

FindCell is the rectangle of the cell at offset pos.

func (*TableMap) NextCell

func (m *TableMap) NextCell(pos int, axis string, dir int) int

NextCell is the cell next to the one at pos on axis ("horiz" or "vert"), -1 for none.

func (*TableMap) PositionAt

func (m *TableMap) PositionAt(row, col int, table *Node) int

PositionAt is where a cell at row and col of the table would go.

func (*TableMap) RectBetween

func (m *TableMap) RectBetween(a, b int) Rect

RectBetween is the rectangle around the cells at a and b, grown over the cells it cuts.

type TableOptions

type TableOptions struct {
	CellMinWidth float64
	// NotResizable keeps tables from resizing by their handles.
	NotResizable, LastColumnNotResizable bool
}

Table are a table's Tiptap options.

type TextSelection

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

TextSelection is a caret or range in inline content.

func NewTextSelection

func NewTextSelection(anchor, head *ResolvedPos) *TextSelection

NewTextSelection selects from anchor to head, which sit in inline content; head is anchor when nil.

func (*TextSelection) Anchor

func (s *TextSelection) Anchor() int

func (*TextSelection) AnchorPos

func (s *TextSelection) AnchorPos() *ResolvedPos

func (*TextSelection) Bookmark

func (s *TextSelection) Bookmark() Bookmark

func (*TextSelection) Content

func (s *TextSelection) Content() *Slice

func (*TextSelection) Cursor

func (s *TextSelection) Cursor() *ResolvedPos

Cursor is the empty selection at the head, nil unless it is one.

func (*TextSelection) Empty

func (s *TextSelection) Empty() bool

func (*TextSelection) Eq

func (s *TextSelection) Eq(o Selection) bool

func (*TextSelection) From

func (s *TextSelection) From() int

func (*TextSelection) FromPos

func (s *TextSelection) FromPos() *ResolvedPos

func (*TextSelection) Head

func (s *TextSelection) Head() int

func (*TextSelection) HeadPos

func (s *TextSelection) HeadPos() *ResolvedPos

func (*TextSelection) Map

func (s *TextSelection) Map(doc *Node, m Mappable) Selection

func (*TextSelection) Ranges

func (s *TextSelection) Ranges() []SelectionRange

func (*TextSelection) Replace

func (s *TextSelection) Replace(tr *Transaction, content *Slice)

func (*TextSelection) ReplaceWith

func (s *TextSelection) ReplaceWith(tr *Transaction, node *Node)

func (*TextSelection) To

func (s *TextSelection) To() int

func (*TextSelection) ToPos

func (s *TextSelection) ToPos() *ResolvedPos

type Transaction

type Transaction struct {
	Transform
	Time   time.Time
	Origin Origin
	// contains filtered or unexported fields
}

Transaction is one user action's changes: a Transform with the state's selection, stored marks, metadata and an origin.

func CloseHistory

func CloseHistory(tr *Transaction) *Transaction

CloseHistory has the next change start a new undo step.

func (*Transaction) AddMark

func (tr *Transaction) AddMark(from, to int, mark *Mark) *Transaction

func (*Transaction) AddStoredMark

func (tr *Transaction) AddStoredMark(m *Mark) *Transaction

AddStoredMark adds a mark to the ensured marks.

func (*Transaction) Delete

func (tr *Transaction) Delete(from, to int) *Transaction

func (*Transaction) DeleteRange

func (tr *Transaction) DeleteRange(from, to int) *Transaction

func (*Transaction) DeleteSelection

func (tr *Transaction) DeleteSelection() *Transaction

DeleteSelection deletes the selection.

func (*Transaction) EnsureMarks

func (tr *Transaction) EnsureMarks(marks []*Mark) *Transaction

EnsureMarks keeps marks as the stored marks unless the selection's place has them.

func (*Transaction) Insert

func (tr *Transaction) Insert(pos int, content ...*Node) *Transaction

func (*Transaction) InsertText

func (tr *Transaction) InsertText(text string, from, to int) *Transaction

InsertText inserts text from from to to, or over the selection when from is negative, with the marks there, and puts the cursor after it.

func (*Transaction) Join

func (tr *Transaction) Join(pos, depth int) *Transaction

func (*Transaction) Lift

func (tr *Transaction) Lift(r *NodeRange, target int) *Transaction

func (*Transaction) Meta

func (tr *Transaction) Meta(key any) any

Meta reads a value stored under key.

func (*Transaction) RemoveMark

func (tr *Transaction) RemoveMark(from, to int, mark *Mark, typ *MarkType) *Transaction

func (*Transaction) RemoveStoredMark

func (tr *Transaction) RemoveStoredMark(t *MarkType) *Transaction

RemoveStoredMark removes a mark type from the ensured marks.

func (*Transaction) Replace

func (tr *Transaction) Replace(from, to int, slice *Slice) *Transaction

func (*Transaction) ReplaceRange

func (tr *Transaction) ReplaceRange(from, to int, slice *Slice) *Transaction

func (*Transaction) ReplaceRangeWith

func (tr *Transaction) ReplaceRangeWith(from, to int, node *Node) *Transaction

func (*Transaction) ReplaceSelection

func (tr *Transaction) ReplaceSelection(slice *Slice) *Transaction

ReplaceSelection replaces the selection with slice.

func (*Transaction) ReplaceSelectionWith

func (tr *Transaction) ReplaceSelectionWith(node *Node, inheritMarks bool) *Transaction

ReplaceSelectionWith replaces the selection with node, which takes the marks there when inheritMarks.

func (*Transaction) ReplaceWith

func (tr *Transaction) ReplaceWith(from, to int, content ...*Node) *Transaction

func (*Transaction) ScrollIntoView

func (tr *Transaction) ScrollIntoView() *Transaction

ScrollIntoView has the view reveal the selection.

func (*Transaction) ScrolledIntoView

func (tr *Transaction) ScrolledIntoView() bool

ScrolledIntoView says the view should reveal the selection.

func (*Transaction) Selection

func (tr *Transaction) Selection() Selection

Selection is the transaction's selection, mapped through its steps.

func (*Transaction) SelectionSet

func (tr *Transaction) SelectionSet() bool

SelectionSet says the selection was set.

func (*Transaction) SetBlockType

func (tr *Transaction) SetBlockType(from, to int, typ *NodeType, attrs func(*Node) Attrs) *Transaction

func (*Transaction) SetMeta

func (tr *Transaction) SetMeta(key, value any) *Transaction

SetMeta stores a value under key.

func (*Transaction) SetNodeAttribute

func (tr *Transaction) SetNodeAttribute(pos int, attr string, value any) *Transaction

func (*Transaction) SetNodeMarkup

func (tr *Transaction) SetNodeMarkup(pos int, typ *NodeType, attrs Attrs, marks []*Mark) *Transaction

func (*Transaction) SetSelection

func (tr *Transaction) SetSelection(s Selection) *Transaction

SetSelection sets the selection, which drops the stored marks.

func (*Transaction) SetStoredMarks

func (tr *Transaction) SetStoredMarks(marks []*Mark) *Transaction

SetStoredMarks sets the marks the next typed text takes.

func (*Transaction) Split

func (tr *Transaction) Split(pos, depth int, typesAfter []NodeTypeAttrs) *Transaction

func (*Transaction) Step

func (tr *Transaction) Step(s Step) *Transaction

func (*Transaction) StoredMarks

func (tr *Transaction) StoredMarks() []*Mark

StoredMarks are the marks stored now: any step drops them.

func (*Transaction) Wrap

func (tr *Transaction) Wrap(r *NodeRange, wrappers []NodeTypeAttrs) *Transaction

type Transform

type Transform struct {
	Doc     *Node
	Steps   []Step
	Docs    []*Node
	Mapping *Mapping
	Err     error
}

Transform collects steps, the documents between them and their mapping. A step that fails leaves it unchanged and sets Err, after which it takes no more.

func NewTransform

func NewTransform(doc *Node) *Transform

NewTransform starts a transform of doc.

func (*Transform) AddMark

func (t *Transform) AddMark(from, to int, mark *Mark) *Transform

AddMark adds mark from from to to where it is allowed.

func (*Transform) Before

func (t *Transform) Before() *Node

Before is the document before the steps.

func (*Transform) ClearIncompatible

func (t *Transform) ClearIncompatible(pos int, typ *NodeType, match *ContentMatch) *Transform

ClearIncompatible drops what a node of t at pos could not hold.

func (*Transform) Delete

func (t *Transform) Delete(from, to int) *Transform

Delete deletes from to to.

func (*Transform) DeleteRange

func (t *Transform) DeleteRange(from, to int) *Transform

DeleteRange deletes from to to, growing it over nodes it covers whole.

func (*Transform) DocChanged

func (t *Transform) DocChanged() bool

DocChanged says a step ran.

func (*Transform) Insert

func (t *Transform) Insert(pos int, content ...*Node) *Transform

Insert inserts content at pos.

func (*Transform) Join

func (t *Transform) Join(pos, depth int) *Transform

Join joins the nodes depth levels around pos.

func (*Transform) Lift

func (t *Transform) Lift(r *NodeRange, target int) *Transform

Lift moves range up to target.

func (*Transform) RemoveMark

func (t *Transform) RemoveMark(from, to int, mark *Mark, typ *MarkType) *Transform

RemoveMark removes mark from from to to; with a nil mark every mark, and with a type its marks by it.

func (*Transform) Replace

func (t *Transform) Replace(from, to int, slice *Slice) *Transform

Replace fits slice into from to to.

func (*Transform) ReplaceRange

func (t *Transform) ReplaceRange(from, to int, slice *Slice) *Transform

ReplaceRange replaces from to to with slice, moving the range up and the slice open as what is selected and pasted suggest.

func (*Transform) ReplaceRangeWith

func (t *Transform) ReplaceRangeWith(from, to int, node *Node) *Transform

ReplaceRangeWith replaces from to to with node.

func (*Transform) ReplaceWith

func (t *Transform) ReplaceWith(from, to int, content ...*Node) *Transform

ReplaceWith replaces from to to with content.

func (*Transform) SetBlockType

func (t *Transform) SetBlockType(from, to int, typ *NodeType, attrs func(*Node) Attrs) *Transform

SetBlockType sets the textblocks from from to to to typ.

func (*Transform) SetNodeAttribute

func (t *Transform) SetNodeAttribute(pos int, attr string, value any) *Transform

SetNodeAttribute sets one attribute of the node at pos.

func (*Transform) SetNodeMarkup

func (t *Transform) SetNodeMarkup(pos int, typ *NodeType, attrs Attrs, marks []*Mark) *Transform

SetNodeMarkup changes the node at pos, keeping its content.

func (*Transform) Split

func (t *Transform) Split(pos, depth int, typesAfter []NodeTypeAttrs) *Transform

Split splits the node around pos, depth levels up, with typesAfter for the new nodes.

func (*Transform) Step

func (t *Transform) Step(s Step) *Transform

Step applies s.

func (*Transform) Wrap

func (t *Transform) Wrap(r *NodeRange, wrappers []NodeTypeAttrs) *Transform

Wrap wraps range in wrappers.

type View

type View struct {
	// Editor is the session it shows; without one it makes its own of
	// StarterKit and TableKit from Markdown.
	Editor   *Session
	Markdown string
	// Placeholder shows while the document is empty.
	Placeholder string
	// NodeViews render node types by name: a block's in place of its own,
	// an inline node's as a view in the line where the node stands.
	NodeViews map[string]NodeView
	// BubbleMenu is the app's content in an overlay over the selection's
	// lines, shown while it returns one.
	BubbleMenu func() core.Node
	// BubbleMenuPlacement is its side, above when 0, and BubbleMenuOffset
	// its gap.
	BubbleMenuPlacement core.Placement
	BubbleMenuOffset    core.Points
	// OnChange receives the revision after a change of the document,
	// and OnSelectionChange after a move of the selection: read them from
	// the session.
	OnChange          func(revision int)
	OnSelectionChange func(s Selection)
	// OnPasteFiles receives pasted files and images, which insert nothing.
	OnPasteFiles func(paths []string)
	OnFocus      func()
	OnBlur       func()
	AutoFocus    bool
	Label        string
	Classes      Classes
	Styles       Styles
	StylesFunc   func() Styles
	Class        string
	Style        core.Style
	StyleFunc    func() core.Style
	TestID       string
	// OnLayout and Tooltip are its view's, as a core.View's.
	OnLayout func(core.Bounds)
	Tooltip  core.Node
	Ref      *Ref
}

View is a rich text editor over a Session: the document's blocks in a scroll view, the app styling every part (Classes, Styles), with typing, input methods composing in the line, selections by press and drag, keys through the session's keymaps, and tables' handles while they can be edited.

func (View) Render

func (p View) Render(cx *core.Scope) core.Node

Render implements core.Node.

Jump to

Keyboard shortcuts

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