core

package
v0.3.2 Latest Latest
Warning

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

Go to latest
Published: Aug 19, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Index

Constants

View Source
const (
	LineEndingNameLF     = "lf"
	LineEndingNameCRLF   = "crlf"
	LineEndingNameNative = "native"
)

Line-ending option value names, as used in config, completion, and status

View Source
const (
	// SlabInitSize is the capacity of a Slab's first backing array
	SlabInitSize = 256

	// SlabMaxSize is the largest Slab will allocate for any later backing array
	SlabMaxSize = 4096
)
View Source
const (
	// BinarySampleSize is how much of a file LooksBinary inspects; callers can
	// read just this much before deciding whether to load the rest
	BinarySampleSize = 1024
)
View Source
const DefaultCommentToken = "#"

DefaultCommentToken is used for line comments when no token is configured

View Source
const (
	DefaultRopeLeafChars = 1024
)
View Source
const MaxIndent = 16

MaxIndent is the maximum spaces per indent level

View Source
const MaxPlaintextScan = 10000

Variables

View Source
var (
	ErrChangeSetLengthMismatch = errors.New("change set length mismatch")
	ErrChangeOutOfRange        = errors.New("change out of range")
	ErrChangeOrder             = errors.New("change order invalid")
)
View Source
var (
	ErrRopeIndexOutOfRange = errors.New("rope index out of range")
	ErrRopeLineOutOfRange  = errors.New("rope line out of range")
)
View Source
var (
	ErrEmptySelection       = errors.New("empty selection")
	ErrPrimaryIndexNotFound = errors.New("primary index not found")
	ErrLastRangeRemoval     = errors.New("last range removal")
	ErrRangeIndexNotFound   = errors.New("range index not found")
)
View Source
var (
	ErrPairNotFound = errors.New(
		"surround pair not found around all cursors",
	)
	ErrSurroundCursorOverlap = errors.New(
		"cursors overlap for a single surround pair",
	)
	ErrRangeExceedsText      = errors.New("cursor range exceeds text length")
	ErrCursorOnAmbiguousPair = errors.New("cursor on ambiguous surround pair")
)
View Source
var (
	// ErrBinaryFile is returned by LoadText when a file's content looks binary
	ErrBinaryFile = errors.New("binary file")
)
View Source
var ErrInvalidLineEnding = errors.New("invalid line ending")

Functions

func BracketPairs added in v0.3.0

func BracketPairs() [][2]rune

BracketPairs returns every pair GetPair recognizes, open then close

func CharIsLineEnding

func CharIsLineEnding(ch rune) bool

CharIsLineEnding reports whether ch terminates a line

func CharIsPunctuation

func CharIsPunctuation(ch rune) bool

CharIsPunctuation reports whether ch is punctuation or a symbol

func CharIsWhitespace

func CharIsWhitespace(ch rune) bool

CharIsWhitespace reports whether ch is a space or tab

func CharIsWord

func CharIsWord(ch rune) bool

CharIsWord reports whether ch may appear inside a word

func CreateBlockCommentTransaction

func CreateBlockCommentTransaction(
	doc Rope, commented bool, commentChanges []CommentChange,
) (Transaction, []Range, error)

CreateBlockCommentTransaction builds the transaction and updated ranges for a block comment toggle operation

func EnsureGraphemeBoundaryNext

func EnsureGraphemeBoundaryNext(doc Rope, charIdx int) int

EnsureGraphemeBoundaryNext snaps charIdx to the next grapheme boundary if it is not already on one

func EnsureGraphemeBoundaryPrev

func EnsureGraphemeBoundaryPrev(doc Rope, charIdx int) int

EnsureGraphemeBoundaryPrev snaps charIdx to the previous grapheme boundary if it is not already on one

func FindMatchingBracket

func FindMatchingBracket(doc Rope, cursorPos int) (int, bool)

FindMatchingBracket returns the position of the bracket matching the one at cursorPos, scanning at most MaxPlaintextScan characters. Returns (pos, true) on success, (0, false) if not found or not on a bracket

func GetCommentToken

func GetCommentToken(text Rope, tokens []string, lineNum int) (string, bool)

GetCommentToken returns the longest token matching the start of the non-whitespace content on the given line

func GetSurroundPos

func GetSurroundPos(doc Rope, sel Selection, skip int) ([]int, error)

GetSurroundPos returns flat pairs of [open, close] positions for every range in sel, auto-detecting the nearest pair. skip controls how many pairs to step over

func GetSurroundPosFor

func GetSurroundPosFor(
	doc Rope, sel Selection, ch rune, skip int,
) ([]int, error)

GetSurroundPosFor returns flat pairs of [open, close] positions for every range in sel, searching for the pair matching ch. skip controls how many pairs to step over

func HookDelete

func HookDelete(doc Rope, r Range, pairs AutoPairs) (Span, Range, bool)

HookDelete returns a Span and updated Range when backspace should erase an auto-inserted pair, or ok=false when no action is needed

func HookInsert

func HookInsert(
	doc Rope, r Range, ch rune, pairs AutoPairs,
) (Change, Range, bool)

HookInsert returns a Change and updated Range when ch should trigger an auto-pair action, or ok=false when no action is needed

func IsCloseBracket

func IsCloseBracket(ch rune) bool

IsCloseBracket reports whether ch is a closing bracket

func IsOpenBracket

func IsOpenBracket(ch rune) bool

IsOpenBracket reports whether ch is an opening bracket

func IsValidBracket

func IsValidBracket(ch rune) bool

IsValidBracket reports whether ch is either side of a bracket pair

func LineEndingNames

func LineEndingNames() []string

LineEndingNames returns the recognized line-ending option values, in display order

func LoadText

func LoadText(path string) ([]byte, error)

LoadText reads path, returning ErrBinaryFile without reading past the leading sample if the content looks binary, so a huge binary file is never fully loaded just to be rejected

func LooksBinary

func LooksBinary(data []byte) bool

LooksBinary reports whether data appears to be non-text content, biased toward false negatives: garbled binary is recoverable, a refused-open text file is not

func NextGraphemeBoundary

func NextGraphemeBoundary(doc Rope, charIdx int) int

NextGraphemeBoundary returns the char index one grapheme cluster after charIdx

func NthNextGraphemeBoundary

func NthNextGraphemeBoundary(doc Rope, step GraphemeStep) int

NthNextGraphemeBoundary returns the char index Count grapheme clusters after the step's start

func NthPrevGraphemeBoundary

func NthPrevGraphemeBoundary(doc Rope, step GraphemeStep) int

NthPrevGraphemeBoundary returns the char index Count grapheme clusters before the step's start

func PrevGraphemeBoundary

func PrevGraphemeBoundary(doc Rope, charIdx int) int

PrevGraphemeBoundary returns the char index one grapheme cluster before charIdx

func ReflowHardWrap

func ReflowHardWrap(text string, width int) string

ReflowHardWrap reformats text to fit within width columns by breaking at word boundaries. Existing line breaks are first collapsed into spaces and common quote, comment, and list prefixes are retained on wrapped rows

func TabWidthAt

func TabWidthAt(at TabStop) int

TabWidthAt returns the visual width of a tab character at the stop's column

Types

type Assoc

type Assoc int

Assoc controls which side of an edit a mapped position sticks to

const (
	AssocBefore Assoc = iota + 1
	AssocAfter
	AssocAfterWord
	AssocBeforeWord
	AssocBeforeSticky
	AssocAfterSticky
)

func (Assoc) Sticky

func (a Assoc) Sticky() bool

Sticky reports whether a position stays put across an insertion at it

type AutoPairs

type AutoPairs map[rune]Pair

AutoPairs holds the set of active bracket pairs, keyed by both opener and closer

func DefaultAutoPairs

func DefaultAutoPairs() AutoPairs

DefaultAutoPairs returns an AutoPairs with the standard bracket/quote pairs

func NewAutoPairs

func NewAutoPairs(pairs [][2]rune) AutoPairs

NewAutoPairs constructs AutoPairs from [open, close] pairs

func (AutoPairs) Get

func (a AutoPairs) Get(ch rune) (Pair, bool)

Get returns the Pair for ch, or false if ch is not a registered opener/closer

type BlockCommentToken

type BlockCommentToken struct {
	Start string
	End   string
}

BlockCommentToken holds the start and end delimiters for a block comment

func DefaultBlockCommentToken

func DefaultBlockCommentToken() BlockCommentToken

DefaultBlockCommentToken returns the fallback block comment delimiters

type BracketPair added in v0.2.0

type BracketPair struct {
	Open  rune
	Close rune
}

BracketPair is the open and close characters of a bracket pair

func GetPair

func GetPair(ch rune) BracketPair

GetPair returns the open and close characters for a bracket pair. If ch is not in any pair, both sides are ch

type Change

type Change struct {
	Span
	// contains filtered or unexported fields
}

Change describes a replacement over a character span

func DeleteChange

func DeleteChange(s Span) Change

DeleteChange removes the characters the span covers

func TextChange

func TextChange(s Span, text string) Change

TextChange replaces the characters the span covers with text

func (Change) Text

func (c Change) Text() string

Text returns replacement text, or empty string for a deletion

type ChangeSet

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

ChangeSet is an ordered set of edits over a document snapshot

func NewChangeSet

func NewChangeSet(doc Rope) ChangeSet

NewChangeSet returns an empty change set sized for doc

func NewChangeSetFromChanges

func NewChangeSetFromChanges(doc Rope, changes []Change) (ChangeSet, error)

NewChangeSetFromChanges builds a change set from non-overlapping changes, which must be ordered by position

func (ChangeSet) Apply

func (c ChangeSet) Apply(doc Rope) (Rope, error)

Apply runs the change set against doc, returning the resulting rope

func (ChangeSet) Changes

func (c ChangeSet) Changes() []Change

Changes returns the operations rebuilt as position-based edits

func (ChangeSet) Compose

func (c ChangeSet) Compose(other ChangeSet) ChangeSet

Compose combines two changesets: if c transforms docA→docB and other transforms docB→docC, the result transforms docA→docC

func (ChangeSet) Invert

func (c ChangeSet) Invert(original Rope) (ChangeSet, error)

Invert returns the change set undoing this one, given the document it was built against

func (ChangeSet) IsEmpty added in v0.3.2

func (c ChangeSet) IsEmpty() bool

IsEmpty reports whether the change set would leave a document unaltered

func (ChangeSet) Len

func (c ChangeSet) Len() int

Len is the document length the change set expects as input

func (ChangeSet) LenAfter

func (c ChangeSet) LenAfter() int

LenAfter is the document length the change set produces

func (ChangeSet) MapPos

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

MapPos rebases a position onto the resulting document; assoc decides which side of an insertion at pos it lands on

func (ChangeSet) MapRange

func (c ChangeSet) MapRange(r Range) (Range, error)

MapRange rebases both ends of a range onto the resulting document

func (ChangeSet) Operations

func (c ChangeSet) Operations() []Operation

Operations returns a copy of the operation sequence

type CharCategory

type CharCategory int

CharCategory classifies a character for reference word and motion behavior

const (
	CharCategoryWhitespace CharCategory = iota + 1
	CharCategoryEOL
	CharCategoryWord
	CharCategoryPunctuation
	CharCategoryUnknown
)

func CategorizeChar

func CategorizeChar(ch rune) CharCategory

CategorizeChar classifies ch for word-wise motion

type CommentChange

type CommentChange struct {
	Kind        CommentChangeKind
	Range       Range
	StartPos    int
	EndPos      int
	StartMargin bool
	EndMargin   bool
	StartToken  string
	EndToken    string
}

CommentChange describes the comment action for one selection range

func FindBlockComments

func FindBlockComments(
	tokens []BlockCommentToken, text Rope, sel Selection,
) (bool, []CommentChange, error)

FindBlockComments inspects each range in sel to determine whether it is already block-commented and returns the per-range actions

type CommentChangeKind

type CommentChangeKind int

CommentChangeKind identifies which variant a CommentChange represents

const (
	CommentChangeCommented CommentChangeKind = iota
	CommentChangeUncommented
	CommentChangeWhitespace
)

type Direction

type Direction int

Direction describes whether a range head is before or after its anchor

const (
	DirectionBackward Direction = iota + 1
	DirectionForward
)

type GraphemeStep added in v0.2.0

type GraphemeStep struct {
	From  int
	Count int
}

GraphemeStep is a starting char index and a count of grapheme clusters to move by

type History

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

History stores committed document revisions

func NewHistory

func NewHistory() History

NewHistory returns an empty history positioned at the root revision

func (*History) AtRoot

func (h *History) AtRoot() bool

AtRoot reports whether there is nothing left to undo

func (*History) CommitRevision

func (h *History) CommitRevision(tx Transaction, st State) error

CommitRevision records tx as a new revision branching from the current one, storing its inverse for undo

func (*History) CurrentRevision

func (h *History) CurrentRevision() int

CurrentRevision is the index of the revision in effect

func (*History) Earlier

func (h *History) Earlier(kind UndoKind) []Transaction

Earlier returns the transactions that walk back by kind, without applying them

func (*History) LastEditPos

func (h *History) LastEditPos() int

LastEditPos returns the char offset of the most recently committed change

func (*History) Later

func (h *History) Later(kind UndoKind) []Transaction

Later returns the transactions that walk forward by kind, without applying them

func (*History) Redo

func (h *History) Redo() (Transaction, bool)

Redo steps forward one revision, returning the transaction to apply

func (*History) Undo

func (h *History) Undo() (Transaction, bool)

Undo steps back one revision, returning the transaction to apply

type IndentStyle

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

IndentStyle describes whether indentation uses tabs or spaces

func AutoDetect

func AutoDetect(doc Rope) (IndentStyle, bool)

AutoDetect attempts to detect the indentation style used in doc. Returns the detected style and true, or false if confidence is too low

func ParseIndentStyle

func ParseIndentStyle(s string) IndentStyle

ParseIndentStyle creates an IndentStyle from an indent string such as " " (four spaces) or "\t"

func Spaces

func Spaces(n uint8) IndentStyle

Spaces returns an IndentStyle that uses n space characters per level

func Tabs

func Tabs() IndentStyle

Tabs returns an IndentStyle that uses tab characters

func (IndentStyle) AsStr

func (i IndentStyle) AsStr() string

AsStr returns the string for one indent level

func (IndentStyle) IndentWidth

func (i IndentStyle) IndentWidth(tabWidth int) int

IndentWidth returns the number of columns one indent level occupies

func (IndentStyle) IsTabs

func (i IndentStyle) IsTabs() bool

IsTabs reports whether this style uses tab characters

func (IndentStyle) Width

func (i IndentStyle) Width() uint8

Width returns the number of spaces per indent level (0 for tabs)

type LineEnding

type LineEnding string

LineEnding is the actual line-ending byte sequence for a document

const (
	LineEndingLF   LineEnding = "\n"
	LineEndingCRLF LineEnding = "\r\n"
)

func AutoDetectLineEndingString

func AutoDetectLineEndingString(s string) (LineEnding, bool)

AutoDetectLineEndingString infers the ending from the first terminator found, giving up after 100 ambiguous ones

func GetLineEndingOfString

func GetLineEndingOfString(s string) (LineEnding, bool)

GetLineEndingOfString reports the ending that s itself terminates with

func LineEndingFromChar

func LineEndingFromChar(ch rune) (LineEnding, bool)

LineEndingFromChar reports whether ch terminates a line, normalizing every single-character terminator to LF

func NativeLineEnding

func NativeLineEnding() LineEnding

NativeLineEnding is the platform's default line ending

func ParseLineEnding

func ParseLineEnding(value string) (LineEnding, error)

ParseLineEnding parses a "lf", "crlf", or "native" option value

func (*LineEnding) UnmarshalText

func (l *LineEnding) UnmarshalText(text []byte) error

UnmarshalText parses a line ending name, resolving native to the platform default

type LinePos added in v0.2.0

type LinePos struct {
	Line int
	Pos  int
}

LinePos addresses a point inside a line by 0-based line index and the absolute character offset of the point, not a column

type Movement

type Movement int

Movement controls whether a motion extends the selection or moves it

const (
	MovementMove Movement = iota + 1
	MovementExtend
)

type Operation

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

Operation is one piece of a change set

func (Operation) Kind

func (o Operation) Kind() OperationKind

Kind reports whether the operation retains, deletes, or inserts

func (Operation) LenChars

func (o Operation) LenChars() int

LenChars is the character count the operation inserts or spans

func (Operation) Text

func (o Operation) Text() string

Text is the inserted text, empty for retain and delete

type OperationKind

type OperationKind int

OperationKind identifies the operation variant

const (
	OperationRetain OperationKind = iota + 1
	OperationDelete
	OperationInsert
)

type Pair

type Pair struct {
	Open  rune
	Close rune
}

Pair describes one opener/closer bracket pair

func (Pair) Same

func (p Pair) Same() bool

Same reports whether the pair's open and close characters are identical

func (Pair) ShouldClose

func (p Pair) ShouldClose(doc Rope, r Range) bool

ShouldClose reports whether typing this pair's close character at range should insert the closing character rather than skip past an existing one

type Position added in v0.1.6

type Position struct {
	Line   int
	Column int
}

Position is a 1-based line and column document address, the way a person names a location. Distinct from geom.Point, a screen cell

type Range

type Range struct {
	Anchor int
	Head   int
}

Range is a selection span with an immovable anchor and movable head

func FindNthClosestPairsPos

func FindNthClosestPairsPos(doc Rope, r Range, skip int) (Range, error)

FindNthClosestPairsPos finds the nth-nearest surrounding bracket pair around r (plaintext only). The returned Range keeps the source range's direction

func FindNthPairsPos

func FindNthPairsPos(doc Rope, ch rune, r Range, n int) (Range, error)

FindNthPairsPos finds the nth surrounding pair for character ch around r (plaintext only). ch may be either opening or closing

func MoveNextLongWordEnd

func MoveNextLongWordEnd(doc Rope, r Range, count int) Range

MoveNextLongWordEnd moves count WORDS forward to the end of the next WORD

func MoveNextLongWordStart

func MoveNextLongWordStart(doc Rope, r Range, count int) Range

MoveNextLongWordStart moves count WORDS forward to the start of the next WORD

func MoveNextSubWordEnd

func MoveNextSubWordEnd(doc Rope, r Range, count int) Range

MoveNextSubWordEnd moves count sub-words forward to the end of the next sub-word

func MoveNextSubWordStart

func MoveNextSubWordStart(doc Rope, r Range, count int) Range

MoveNextSubWordStart moves count sub-words forward to the start of the next sub-word

func MoveNextWordEnd

func MoveNextWordEnd(doc Rope, r Range, count int) Range

MoveNextWordEnd moves count words forward to the end of the next word

func MoveNextWordStart

func MoveNextWordStart(doc Rope, r Range, count int) Range

MoveNextWordStart moves count words forward to the start of the next word

func MovePrevLongWordEnd

func MovePrevLongWordEnd(doc Rope, r Range, count int) Range

MovePrevLongWordEnd moves count WORDS backward to the end of the previous WORD

func MovePrevLongWordStart

func MovePrevLongWordStart(doc Rope, r Range, count int) Range

MovePrevLongWordStart moves count WORDS backward to the start of the previous WORD

func MovePrevSubWordEnd

func MovePrevSubWordEnd(doc Rope, r Range, count int) Range

MovePrevSubWordEnd moves count sub-words backward to the end of the previous sub-word

func MovePrevSubWordStart

func MovePrevSubWordStart(doc Rope, r Range, count int) Range

MovePrevSubWordStart moves count sub-words backward to the start of the previous sub-word

func MovePrevWordEnd

func MovePrevWordEnd(doc Rope, r Range, count int) Range

MovePrevWordEnd moves count words backward to the end of the previous word

func MovePrevWordStart

func MovePrevWordStart(doc Rope, r Range, count int) Range

MovePrevWordStart moves count words backward to the start of the previous word

func PointRange

func PointRange(head int) Range

PointRange returns an empty range at head

func TextObjectParagraph

func TextObjectParagraph(
	doc Rope, r Range, kind TextObjectKind, count int,
) Range

TextObjectParagraph selects the paragraph containing the cursor. A paragraph is a contiguous sequence of non-empty lines around=TextObjectAround includes the trailing empty lines

func TextObjectWord

func TextObjectWord(doc Rope, r Range, kind TextObjectKind, long bool) Range

TextObjectWord selects the word under or adjacent to the cursor long=true uses long-word (WORD) semantics: only whitespace is a boundary around=TextObjectAround includes trailing (or leading) whitespace

func (Range) Contains

func (r Range) Contains(pos int) bool

Contains reports whether pos falls inside this range

func (Range) ContainsRange

func (r Range) ContainsRange(q Range) bool

ContainsRange reports whether q falls entirely inside this range

func (Range) Cursor

func (r Range) Cursor(doc Rope) int

Cursor returns the char index of the block-cursor position. For a forward range the cursor sits one grapheme before the head; for backward or empty ranges it is the head itself

func (Range) CursorLine

func (r Range) CursorLine(doc Rope) (int, error)

CursorLine returns the line number that the block cursor is on

func (Range) Direction

func (r Range) Direction() Direction

Direction reports which side of the range the head sits on

func (Range) Extend

func (r Range) Extend(s Span) Range

Extend grows the range to also cover the span, keeping its direction

func (Range) Flip

func (r Range) Flip() Range

Flip swaps anchor and head, reversing direction

func (Range) Fragment

func (r Range) Fragment(doc Rope) (string, error)

Fragment returns the text covered by this range as a string

func (Range) From

func (r Range) From() int

From is the lower of anchor and head

func (Range) GraphemeAligned

func (r Range) GraphemeAligned(doc Rope) Range

GraphemeAligned snaps both ends of the range to grapheme cluster boundaries

func (Range) IsEmpty added in v0.3.2

func (r Range) IsEmpty() bool

IsEmpty reports whether anchor and head coincide

func (Range) IsSingleGrapheme

func (r Range) IsSingleGrapheme(doc Rope) bool

IsSingleGrapheme reports whether this range covers exactly one grapheme cluster

func (Range) Len

func (r Range) Len() int

Len is the character count the range covers

func (Range) LineSpan added in v0.2.0

func (r Range) LineSpan(text Rope) (Span, error)

LineSpan returns the inclusive line span the range touches. An empty range covers one line; a non-empty one excludes an end on a line start

func (Range) Merge

func (r Range) Merge(q Range) Range

Merge returns the range spanning both, backward only when both are

func (Range) MinWidth1

func (r Range) MinWidth1(doc Rope) Range

MinWidth1 ensures the range covers at least one grapheme by advancing the head forward if the range is empty

func (Range) MoveHorizontally

func (r Range) MoveHorizontally(
	doc Rope, dir Direction, count int, move Movement,
) Range

MoveHorizontally moves range by count grapheme clusters in dir

func (Range) MoveVertically

func (r Range) MoveVertically(
	doc Rope, dir Direction, count int, move Movement,
) Range

MoveVertically moves the cursor by count lines, keeping the column the caller last moved to horizontally

func (Range) Overlaps

func (r Range) Overlaps(q Range) bool

Overlaps reports whether the two ranges share any character

func (Range) PutCursor

func (r Range) PutCursor(doc Rope, charIdx int, extend bool) Range

PutCursor moves the block cursor to charIdx, optionally extending the selection anchor using 1-width block cursor semantics

func (Range) Slice

func (r Range) Slice(doc Rope) (Rope, error)

Slice returns the rope sub-range covered by this range

func (Range) Span added in v0.2.0

func (r Range) Span() Span

Span is the character interval the range covers, ignoring direction

func (Range) TextObjectPairSurround

func (r Range) TextObjectPairSurround(
	doc Rope, kind TextObjectKind, ch rune, count int,
) Range

TextObjectPairSurround selects the pair surrounding the cursor. ch, if non-zero, specifies which pair; zero uses the nearest pair. kind controls whether the delimiters themselves are included

func (Range) To

func (r Range) To() int

To is the higher of anchor and head

func (Range) WithDirection

func (r Range) WithDirection(dir Direction) Range

WithDirection flips the range only when it faces the other way

type Rope

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

Rope stores text as a balanced binary tree of string leaves

func NewRope

func NewRope(text string) Rope

NewRope returns a rope holding text

func (Rope) CharAt

func (r Rope) CharAt(pos int) (rune, error)

CharAt returns the character at pos

func (Rope) CharToLine

func (r Rope) CharToLine(pos int) (int, error)

CharToLine returns the line containing pos

func (Rope) Delete

func (r Rope) Delete(s Span) (Rope, error)

Delete returns a rope without the characters the span covers

func (Rope) FindNthChar

func (r Rope) FindNthChar(
	n int, match rune, pos int, dir Direction,
) (int, bool)

FindNthChar finds the position of the nth matching character, starting from pos in the given direction

func (Rope) ForEachSegment

func (r Rope) ForEachSegment(s Span, fn func(string))

ForEachSegment applies fn to each contiguous leaf substring the span covers, without copying

func (Rope) Insert

func (r Rope) Insert(pos int, text string) (Rope, error)

Insert returns a rope with text added at pos

func (Rope) LenChars

func (r Rope) LenChars() int

LenChars is the character count of the whole rope

func (Rope) LenLines

func (r Rope) LenLines() int

LenLines is the line count, counting a trailing ending as a new line

func (Rope) Line

func (r Rope) Line(line int) (Rope, error)

Line returns the line's text, including its ending

func (Rope) LineEndCharIndex

func (r Rope) LineEndCharIndex(line int) (int, error)

LineEndCharIndex returns the position after the line's last character, excluding its ending

func (Rope) LineToChar

func (r Rope) LineToChar(line int) (int, error)

LineToChar returns the position where the line starts

func (Rope) Position added in v0.1.6

func (r Rope) Position(char int) (Position, error)

Position returns the 1-based line and column of a character offset

func (Rope) Slice

func (r Rope) Slice(s Span) (Rope, error)

Slice returns the characters the span covers as a new rope

func (Rope) SliceString

func (r Rope) SliceString(s Span) (string, error)

SliceString returns the substring the span covers without constructing a new rope; faster than Slice(s).String()

func (Rope) String

func (r Rope) String() string

String returns the whole rope as text

type Selection

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

Selection is a non-empty ordered set of ranges with one primary range

func NewSelection

func NewSelection(ranges []Range, primaryIndex int) (Selection, error)

NewSelection returns a selection over ranges, sorted and merged, with the range at primaryIndex kept primary

func PointSelection

func PointSelection(pos int) Selection

PointSelection returns a selection of one empty range at pos

func SingleSelection

func SingleSelection(r Range) Selection

SingleSelection returns a selection of one range

func SplitLinesOfSelection

func SplitLinesOfSelection(text Rope, sel Selection) (Selection, error)

SplitLinesOfSelection returns a new selection where each range covers exactly one line within the original selection spans

func (Selection) Equal

func (s Selection) Equal(other Selection) bool

Equal reports whether two selections have identical ranges and the same primary index

func (Selection) IntoSingle

func (s Selection) IntoSingle() Selection

IntoSingle discards every range but the primary

func (Selection) LineRanges

func (s Selection) LineRanges(text Rope) ([]Span, error)

LineRanges returns the line span each range touches

func (Selection) Map

func (s Selection) Map(cs ChangeSet) (Selection, error)

Map rebases every range onto the document produced by cs

func (Selection) MergeConsecutiveRanges

func (s Selection) MergeConsecutiveRanges() Selection

MergeConsecutiveRanges joins only ranges that touch end to start, leaving separated ranges alone

func (Selection) MergeRanges

func (s Selection) MergeRanges() Selection

MergeRanges collapses every range into one spanning first to last

func (Selection) Primary

func (s Selection) Primary() Range

Primary is the range that cursor operations act on

func (Selection) PrimaryIndex

func (s Selection) PrimaryIndex() int

PrimaryIndex is the position of the primary range in Ranges

func (Selection) Push

func (s Selection) Push(r Range) Selection

Push adds r and makes it primary

func (Selection) Ranges

func (s Selection) Ranges() []Range

Ranges returns a copy of every range, in document order

func (Selection) Remove

func (s Selection) Remove(idx int) (Selection, error)

Remove drops the range at idx, erroring when it is the only one

func (Selection) Replace

func (s Selection) Replace(idx int, r Range) (Selection, error)

Replace swaps the range at idx for r

func (Selection) SetPrimaryIndex

func (s Selection) SetPrimaryIndex(idx int) (Selection, error)

SetPrimaryIndex makes the range at idx primary

func (Selection) Transform

func (s Selection) Transform(f func(Range) Range) Selection

Transform applies f to every range, then re-sorts and re-merges

type Slab added in v0.1.38

type Slab[T any] struct {
	// contains filtered or unexported fields
}

Slab batches values into contiguous backing arrays, handing out individually stable pointers to each one

func (*Slab[T]) Add added in v0.1.38

func (s *Slab[T]) Add(v T) *T

Add copies v into the slab and returns a pointer to its slot

type Source added in v0.2.0

type Source struct {
	Text string
	Lang string
}

Source is a document's text together with the language it is written in. Highlighting, parsing, and language detection operate on this pair

type Span added in v0.2.0

type Span struct {
	From int
	To   int
}

Span is a half-open interval of character offsets, [From, To)

func (Span) IsEmpty added in v0.3.2

func (s Span) IsEmpty() bool

IsEmpty reports whether the span covers no characters

func (Span) Len added in v0.2.0

func (s Span) Len() int

Len is the character count the span covers

type State

type State struct {
	Doc       Rope
	Selection Selection
}

State is the document and selection at a point before a transaction

type TabStop added in v0.2.0

type TabStop struct {
	Column   int
	TabWidth int
}

TabStop is a visual column and the tab width in effect there

type TextObjectKind

type TextObjectKind int

TextObjectKind controls whether a selection covers the delimiter or just the content inside it

const (
	TextObjectAround TextObjectKind = iota + 1
	TextObjectInside
)

type Transaction

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

Transaction is an undoable change unit with optional selection state

func NewTransaction

func NewTransaction(doc Rope) Transaction

NewTransaction returns an empty transaction sized for doc

func ToggleBlockComments

func ToggleBlockComments(
	doc Rope, sel Selection, tokens []BlockCommentToken,
) (Transaction, error)

ToggleBlockComments toggles block comments on all ranges in sel

func ToggleLineComments

func ToggleLineComments(
	doc Rope, sel Selection, token string,
) (Transaction, error)

ToggleLineComments builds a transaction that toggles line comments on every non-blank line in sel using token (DefaultCommentToken when empty)

func (Transaction) Apply

func (t Transaction) Apply(doc Rope) (Rope, error)

Apply runs the transaction's changes against doc

func (Transaction) Changes

func (t Transaction) Changes() ChangeSet

Changes is the edit the transaction applies

func (Transaction) Compose

func (t Transaction) Compose(other Transaction) Transaction

Compose returns a transaction equivalent to applying this one then other, keeping other's selection

func (Transaction) Invert

func (t Transaction) Invert(original Rope) (Transaction, error)

Invert returns the transaction undoing this one, given the document it was built against. The result carries no selection

func (Transaction) Selection

func (t Transaction) Selection() *Selection

Selection is the selection to adopt afterwards, nil to keep the current

func (Transaction) WithChanges

func (t Transaction) WithChanges(cs ChangeSet) Transaction

WithChanges returns a copy carrying cs

func (Transaction) WithSelection

func (t Transaction) WithSelection(s Selection) Transaction

WithSelection returns a copy that adopts s once applied

type UndoKind

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

UndoKind selects how many steps history navigation travels

func UndoSteps

func UndoSteps(n int) UndoKind

UndoSteps counts revisions rather than elapsed time

type VisualMoveFormat

type VisualMoveFormat struct {
	ViewportWidth      int
	TabWidth           int
	MaxWrap            int
	MaxIndentRetain    int
	WrapIndicatorWidth int
}

VisualMoveFormat carries the display parameters needed to compute visual row positions when soft-wrap is active. A zero-value (ViewportWidth == 0) causes MoveVerticallyVisual to fall back to text-line movement

func (*VisualMoveFormat) ExtendVerticallyVisual

func (vf *VisualMoveFormat) ExtendVerticallyVisual(
	doc Rope, r Range, dir Direction, count int,
) Range

ExtendVerticallyVisual extends r up or down by count visual rows when soft-wrap is active. Falls back to text-line movement when soft-wrap is disabled

func (*VisualMoveFormat) MoveVerticallyVisual

func (vf *VisualMoveFormat) MoveVerticallyVisual(
	doc Rope, r Range, dir Direction, count int,
) Range

MoveVerticallyVisual moves r up or down by count visual rows when soft-wrap is active. Falls back to text-line movement when soft-wrap is disabled

func (*VisualMoveFormat) VisualRowOfOffset

func (vf *VisualMoveFormat) VisualRowOfOffset(args VisualRowOfOffsetArgs) int

VisualRowOfOffset returns the zero-based visual row within its text line on which the character at CharOff (relative to line start) is displayed

func (*VisualMoveFormat) VisualRowStarts

func (vf *VisualMoveFormat) VisualRowStarts(runes []rune) []int

VisualRowStarts returns the char offsets at which each soft-wrapped visual row after the first begins; empty if the line fits on one row. Wraps at word boundaries, breaking mid-word only past MaxWrap

func (*VisualMoveFormat) VisualRows

func (vf *VisualMoveFormat) VisualRows(doc Rope, line int) int

VisualRows returns the number of visual (soft-wrapped) rows the given text line occupies. It returns 1 when soft-wrap is inactive

func (*VisualMoveFormat) VisualScrollUp

func (vf *VisualMoveFormat) VisualScrollUp(
	args VisualScrollUpArgs,
) VisualScrollUpRes

VisualScrollUp moves upward from a visual row, clamped at the document start

type VisualRowOfOffsetArgs added in v0.2.0

type VisualRowOfOffsetArgs struct {
	Doc     Rope
	Line    int
	CharOff int
}

VisualRowOfOffsetArgs is a text line and a character offset within it

type VisualScrollUpArgs

type VisualScrollUpArgs struct {
	Doc  Rope
	Line int
	Row  int
	Up   int
}

VisualScrollUpArgs identifies a visual row and upward distance

type VisualScrollUpRes

type VisualScrollUpRes struct {
	Line int
	Row  int
}

VisualScrollUpRes identifies the resulting line and visual row

type WordMotionTarget

type WordMotionTarget int

WordMotionTarget identifies the destination of a word motion

const (
	WordMotionNextWordStart WordMotionTarget = iota + 1
	WordMotionNextWordEnd
	WordMotionPrevWordStart
	WordMotionPrevWordEnd
	WordMotionNextLongWordStart
	WordMotionNextLongWordEnd
	WordMotionPrevLongWordStart
	WordMotionPrevLongWordEnd
	WordMotionNextSubWordStart
	WordMotionNextSubWordEnd
	WordMotionPrevSubWordStart
	WordMotionPrevSubWordEnd
)

Jump to

Keyboard shortcuts

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