editor

package
v1.0.1-0...-517973f Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2026 License: MPL-2.0 Imports: 54 Imported by: 1 module, 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 editor is Kvit's block editor as a unison widget: a Markdown note shown as a column of blocks (paragraphs, headings, list items, to-dos, quotes, code, dividers), edited in place with the inline formatting drawn and its Markdown markers shown only around the caret.

The note is a flat list of blocks (Doc), each holding its Markdown source. The caret and the selection are positions in that source. The Editor panel lays every block out with kvit-ui's text package, draws the rows in view, turns keys and pointer input into operations on the Doc, and describes each block to screen readers as an editable text.

Index

Constants

View Source
const DiffFenceLanguage = "diff"

DiffFenceLanguage is the language Kvit Works registers for diffs.

View Source
const MaxIndent = 4

MaxIndent is the deepest a list item nests.

Variables

View Source
var NoRange = TextRange{StartIndex: -1, EndIndex: -1}

NoRange is what SelectionRange answers when nothing is selected.

View Source
var TextColors = []struct{ Name, Value string }{
	{"Red", "#e05c5c"}, {"Orange", "#e0a04c"}, {"Green", "#58a866"},
	{"Blue", "#4a90d9"}, {"Purple", "#9068c8"}, {"Pink", "#d06ca8"},
}

TextColors are the colours the text colour menus offer: the name each shows and the value written into the note.

View Source
var ToolbarKinds = []KindChoice{
	{"Text", Paragraph}, {"Heading 1", Heading1}, {"Heading 2", Heading2}, {"Heading 3", Heading3},
	{"Heading 4", Heading4}, {"Bulleted List", Bullet}, {"Numbered List", Numbered}, {"To-do", Todo},
	{"Quote", Quote}, {"Code Block", Code}, {"Callout", Callout}, {"Divider", Divider},
}

ToolbarKinds are the kinds the toolbar's block type list offers, in its order.

Functions

func BlockMarkdown

func BlockMarkdown(b Block, number int) string

BlockMarkdown writes one block as Markdown. number is the list number for a numbered block. A block's attribute tag trails its last line, or a code fence's opening line, whose closing fence must stay bare to close it.

func BlockMenuCommands

func BlockMenuCommands() (lines []string, more map[string][]string)

BlockMenuCommands are the block menu's lines, in order, and for a line that opens a submenu, the submenu's lines under its label.

func EmptyTable

func EmptyTable(columns, rows int) string

EmptyTable builds an empty table of the given size, for the grid-picker insertion: at least one column, rows may be zero data rows.

func FenceLanguages

func FenceLanguages() []string

FenceLanguages are the registered fence languages, sorted.

func InsertTableColumn

func InsertTableColumn(markdown string, afterCol int) string

InsertTableColumn returns the Markdown with an empty column after afterCol: -1 puts it at the left.

func InsertTableRow

func InsertTableRow(markdown string, afterRow int) string

InsertTableRow returns the Markdown with an empty data row after afterRow: -1 puts it at the top, rowCount-1 or beyond appends.

func IsLoneURL

func IsLoneURL(s string) bool

IsLoneURL reports whether s is a bare URL with nothing around it.

func IsTableDelimiterRow

func IsTableDelimiterRow(line string) bool

IsTableDelimiterRow reports whether a line is a table delimiter row.

func ListNumber

func ListNumber(blocks []Block, i int) int

ListNumber is the number a numbered block shows: the first number of its run (the Start of the run's first item, 1 when it has none), counted on over the numbered siblings directly above it at the same depth. Deeper items in between do not break the run, so a nested list restarts.

func LooksLikeTableStart

func LooksLikeTableStart(headerLine, delimiterLine string) bool

LooksLikeTableStart reports whether the two-line pair begins a pipe table: the header holds a pipe (so a lone --- never masquerades as a one-column table) and the delimiter has the same column count.

func NormalizeEmbedURL

func NormalizeEmbedURL(input string) string

NormalizeEmbedURL is normalizeEmbedURL for the application: what typed text an embed Edit URL… dialog writes.

func PasteOpensAFence

func PasteOpensAFence(text string) bool

PasteOpensAFence reports whether pasted text opens a code fence, in which case the plain text is the structure source even when the clipboard also holds HTML.

func PlainText

func PlainText(src string) string

PlainText is a block's inline Markdown as it is drawn: the markers of its formatted spans left out.

func RegisterFenceLanguage

func RegisterFenceLanguage(lang string, def FenceLanguage) bool

RegisterFenceLanguage adds a fence language, for every editor in the program. Programs register their languages as they start, before any block is drawn. It reports false, and changes nothing, for a language the editor draws itself or one already registered, so one part of a program cannot take over another's fence.

func RemoveTableColumn

func RemoveTableColumn(markdown string, col int) string

RemoveTableColumn returns the Markdown without column col, never removing the last column.

func RemoveTableRow

func RemoveTableRow(markdown string, row int) string

RemoveTableRow returns the Markdown without data row row.

func ResetFenceLanguages

func ResetFenceLanguages()

ResetFenceLanguages forgets every registered language. Tests use it to start from a known state; a program never calls it.

func SavePastedPicture

func SavePastedPicture(dir, folder, slug string) (string, bool)

SavePastedPicture writes the picture on the clipboard into dir/folder as "<slug>-<yyyyMMdd-HHmmss>.png", with "-1", "-2" and so on added when that name is taken, and answers the path from dir, which is what the image block names. It reports false when the clipboard holds no picture or dir is "", which leaves a paste to take the clipboard's text instead. Kvit Works' message box passes its project's .kvit/pasted folder, "assets" and "message".

Under WSL a picture copied in Windows is not on unison's clipboard, so Windows' clipboard is asked last. Found there, the paste is done before the text is read, which is also the read that crashes WSLg's compositor while it is still fetching the picture from Windows.

func Serialize

func Serialize(blocks []Block) string

Serialize writes the whole note. Blocks are separated by a blank line, except consecutive list items, which form one Markdown list.

func SerializeTable

func SerializeTable(t PipeTable) string

SerializeTable writes a grid in canonical form: unpadded, one space around each cell. Cells are trimmed on the way out because they are trimmed on the way in; writing an untrimmed value would parse back to something else.

func SetTableAlignment

func SetTableAlignment(markdown string, col int, align TableAlign) string

SetTableAlignment returns the Markdown with a column's alignment set.

func SetTableCell

func SetTableCell(markdown string, row, col int, value string) string

SetTableCell returns the Markdown with one cell set; row -1 addresses the header. A newline in the value rides as <br>, a pipe escaped. Out of range or invalid Markdown comes back unchanged.

func SortTableColumn

func SortTableColumn(markdown string, col int, ascending bool) string

SortTableColumn returns the Markdown with data rows sorted by a column's text, ascending or not, as one step. A column that parses as numbers on both sides sorts numerically (10 after 3); otherwise case-insensitively. The sort is stable.

func SpanColor

func SpanColor(c palette.Color, opacity float32) unison.Color

SpanColor is a theme colour at an opacity from 0 to 1, as a span is painted in: a wash is usually a faint one, an outline an opaque one.

func StorePicture

func StorePicture(dir, folder, slug string, data []byte, at time.Time) (string, error)

StorePicture writes picture bytes into dir/folder as SavePastedPicture names them, re-encoded as PNG, and answers the path from dir.

func Summarize

func Summarize(body string) (snippet string, words int, text string)

Summarize is what a note list shows of a note and what search reads: the start of its text as drawn, up to 120 characters, its word count, and its whole text as drawn, one block to a line. Dividers count for nothing.

func TableAlignmentName

func TableAlignmentName(a TableAlign) string

TableAlignmentName is the alignment's name in menus and tests.

func TableCellCount

func TableCellCount(line string) int

TableCellCount is how many cells a row splits into, by parse's own rule.

func TableCellValue

func TableCellValue(markdown string, row, col int) string

TableCellValue reads one cell; row -1 is the header row, "" when outside.

Types

type Block

type Block struct {
	ID      int64
	Kind    Kind
	Indent  int
	Text    string
	Checked bool
	Lang    string
	// Title is a callout's title.
	Title string
	// Attrs is the block's presentation (alignment, a divider's style and so
	// on) as Kvit stores it: the inside of a "<!--kvit ...-->" comment at the
	// end of the block's Markdown, space-separated key=value tokens and bare
	// flags in key order. The editor keeps it so a note saves unchanged.
	Attrs string
	// Start is the number written on a numbered item that begins a list,
	// so a list that does not begin at 1 shows the numbers written: one
	// that a table or a paragraph interrupts goes on at 2, as Markdown
	// numbers it. Only the first item of a run of numbered siblings uses
	// it, and 0 is 1.
	Start int
}

Block is one block of a note.

func NewBlock

func NewBlock(kind Kind, text string) Block

NewBlock is a block of a kind holding text, with an identity of its own.

func ParseMarkdown

func ParseMarkdown(src string) []Block

ParseMarkdown reads a note into blocks. It covers the block syntax the editor edits; anything else becomes a Raw block holding its lines.

func (*Block) Attr

func (b *Block) Attr(key string) (string, bool)

Attr is one of a block's presentation attributes: the value of key=value in its payload, "" for a bare flag, and whether it is there at all.

type Compact

type Compact struct {
	unison.Panel
	// Editor edits the box's document. The box owns its OnChange.
	Editor *Editor
	// OnSubmit runs on Enter, or Ctrl+Enter, with the document as Markdown:
	// handed over rather than left to be fetched, because sending is
	// usually followed by clearing the box.
	OnSubmit func(markdown string)
	// OnEdited runs after every change to the document, for a host saving
	// a draft; Markdown walks the whole document, so debounce it.
	OnEdited func()
	// OnGrew runs after the box grew taller while the caret was in it, on
	// the next pass of the event loop, so the host can keep the box's foot,
	// and the send control beside it, on screen.
	OnGrew func()
	// OnCaretInside runs when the caret comes into the box or leaves it,
	// for a host that draws the box's frame in the focus colour.
	OnCaretInside func(inside bool)
	// contains filtered or unexported fields
}

Compact is the editor sized like a field.

func NewCompact

func NewCompact(ui *kvitui.UI, o CompactOptions) *Compact

NewCompact makes an empty box: one empty paragraph.

func (*Compact) CapHeight

func (c *Compact) CapHeight() float32

CapHeight is the tallest the box's text grows before it scrolls, without the margins.

func (*Compact) CaretInside

func (c *Compact) CaretInside() bool

CaretInside reports whether the caret is in the box, which is what a host asks rather than whether the box has the focus.

func (*Compact) Clear

func (c *Compact) Clear()

Clear empties the box to one empty paragraph, which is a change a host storing a draft is told of.

func (*Compact) ContentHeight

func (c *Compact) ContentHeight() float32

ContentHeight is how tall the box's rows are, without the margins.

func (*Compact) Empty

func (c *Compact) Empty() bool

Empty reports whether the box holds nothing: no blocks, or one block with no text. A picture on its own is not nothing.

func (*Compact) Focus

func (c *Compact) Focus()

Focus puts the caret back in the row it was last in, or at the end of the last row when that row is a picture, where nothing can be typed.

func (*Compact) FocusBlock

func (c *Compact) FocusBlock(i int, atEnd bool)

FocusBlock puts the caret in row i, at its end or its start.

func (*Compact) LineUnit

func (c *Compact) LineUnit() float32

LineUnit is one line of body text, in pixels, which MaximumLines counts.

func (*Compact) Markdown

func (c *Compact) Markdown() string

Markdown is the box's document as Markdown.

func (*Compact) ReturnSubmits

func (c *Compact) ReturnSubmits() bool

ReturnSubmits reports whether Enter sends.

func (*Compact) RowCount

func (c *Compact) RowCount() int

RowCount is how many blocks the box's document has.

func (*Compact) SetMarkdown

func (c *Compact) SetMarkdown(md string)

SetMarkdown replaces the document, dropping the selection and the undo history, since an undo across the change would bring the old document back. A document that ends in a picture gets an empty paragraph under it. A caret that was in the box is put at the end of the new document, as a reader who was typing when a quotation or a stored draft arrived is still typing there.

func (*Compact) SetMaximumLines

func (c *Compact) SetMaximumLines(n int)

SetMaximumLines sets how many lines of body text tall the box grows before it scrolls; 12 when n is below 1.

func (*Compact) SetReturnSubmits

func (c *Compact) SetReturnSubmits(on bool)

SetReturnSubmits makes Enter send (true) or gives it back to the editor, where it makes the next block.

type CompactOptions

type CompactOptions struct {
	// MaximumLines is how many lines of body text tall the box grows before
	// it scrolls; 12 when 0.
	MaximumLines int
	// Margin is the space between the box's edges and its text, in design
	// pixels. Kvit Works draws the box's frame and padding itself and uses 0.
	Margin float32
	// Placeholder is what an empty paragraph says the box is for.
	Placeholder string
	// EnterMakesBlocks gives Enter back to the editor, where it makes the
	// next block, as a capture box wants. Enter sends when it is false.
	EnterMakesBlocks bool
	// ShowPictureLine shows an image block's Markdown line under the picture
	// while the caret is in it. Kvit Works leaves it off: the path is a file
	// the box named itself, and a click on the picture then opens it rather
	// than moving the caret.
	ShowPictureLine bool
	// Pictures are the folders the box's pictures are looked up in: for
	// Kvit Works, Base is the folder pasted pictures are written under.
	Pictures PictureFolders
	// PasteImage, when set, writes a picture on the clipboard where the box
	// keeps its pictures and answers the path the image block names
	// (SavePastedPicture). Nil refuses a pasted picture, which is the answer
	// while there is no project to put it in.
	PasteImage func() (stored string, ok bool)
	// OpenPicture, when set, is asked to show a picture a press landed on.
	OpenPicture func(path, alt string)
}

CompactOptions say how a Compact is made. The zero value is Kvit Works' message box without pictures.

type Completion

type Completion struct {
	Label, Detail string
	Insert        string
}

Completion is one choice of the list: what it shows, and what goes between the brackets when it is chosen.

type DecorationEntry

type DecorationEntry struct {
	ID, Owner string
	// Block is the block a container follows, or the block a margin item
	// is beside.
	Block int
	// Line is a margin item's line within its block, counted from 0.
	Line  int
	Panel unison.Paneler
}

DecorationEntry is one container or margin item, as ContainersAfter and MarginItemsForBlock list them.

type DecorationPanel

type DecorationPanel interface {
	SetDecorationBlock(block int)
}

DecorationPanel is what the panel of a container or a margin item may implement to be told which block it is drawn beside: the block a container follows, the block a margin item sits by.

type Decorations

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

Decorations is one editor's decorations. Every entry has an owner, the name of the program part that made it, so RemoveAll takes back one part's entries and leaves another's; and an id, which later moves and removals name and which it keeps across a move.

func (*Decorations) Active

func (d *Decorations) Active() bool

Active reports whether anything is registered at all.

func (*Decorations) AddContainer

func (d *Decorations) AddContainer(owner string, afterBlock int, panel unison.Paneler) string

AddContainer draws panel after block afterBlock, as wide as the rows and as tall as the panel's preferred height at that width, pushing the blocks below it down. Two containers after one block are stacked in the order they were added. A block the document does not have draws nothing until the container is moved to one it has. A nil panel registers nothing and returns "".

func (*Decorations) AddMarginItem

func (d *Decorations) AddMarginItem(owner string, block, line int, panel unison.Paneler) string

AddMarginItem draws panel in the margin column beside line line of block block, as wide as the column and as tall as the line. Lines are counted from 0 within the block's drawn text; a line past its last one is beside the last, and a block with no text of its own has one line, its whole row, and a line below 0 is line 0. The item shows only while the column is reserved.

func (*Decorations) AddSpan

func (d *Decorations) AddSpan(owner string, block, start, length int, style SpanStyle, color unison.Color) string

AddSpan marks length characters of block block's display text from start, painted in color through the channels style names. A run past the end of the text is cut at its end, and a block with no text of its own shows nothing. A table drawn as its grid counts in its Markdown, which is its display text, and shows the run over the characters its cells draw from that part of it. An empty style, a colour with no opacity or a length below 1 registers nothing and returns "".

func (*Decorations) BlockGeometry

func (d *Decorations) BlockGeometry(block int) geom.Rect

BlockGeometry is block's row, with the containers drawn after it.

func (*Decorations) Clear

func (d *Decorations) Clear()

Clear takes back every entry.

func (*Decorations) ContainerCount

func (d *Decorations) ContainerCount() int

ContainerCount, MarginItemCount and SpanCount count the entries.

func (*Decorations) ContainerGeometry

func (d *Decorations) ContainerGeometry(id string) geom.Rect

ContainerGeometry is where a container is drawn.

func (*Decorations) ContainersAfter

func (d *Decorations) ContainersAfter(block int) []DecorationEntry

ContainersAfter lists the containers after block, in the order they were added, which is the order they are stacked in.

func (*Decorations) HasSpans

func (d *Decorations) HasSpans() bool

HasSpans reports whether any run of characters is marked.

func (*Decorations) LineGeometry

func (d *Decorations) LineGeometry(block, line int) geom.Rect

LineGeometry is visual line line of block's drawn text: the line's top and height, across the text's width. A line past the last is the last; a block with no text of its own answers its whole row.

func (*Decorations) MarginColumnEms

func (d *Decorations) MarginColumnEms() float32

MarginColumnEms is the margin column's width in the reading font's size.

func (*Decorations) MarginColumnReserved

func (d *Decorations) MarginColumnReserved() bool

MarginColumnReserved reports whether the margin column is reserved.

func (*Decorations) MarginColumnWidth

func (d *Decorations) MarginColumnWidth() float32

MarginColumnWidth is the margin column's width in pixels, 0 while it is not reserved.

func (*Decorations) MarginItemCount

func (d *Decorations) MarginItemCount() int

func (*Decorations) MarginItemsForBlock

func (d *Decorations) MarginItemsForBlock(block int) []DecorationEntry

MarginItemsForBlock lists the margin items beside block, in the order they were added.

func (*Decorations) OnChange

func (d *Decorations) OnChange(f func())

OnChange adds f to what runs after every change Revision counts.

func (*Decorations) Relayout

func (d *Decorations) Relayout()

Relayout measures the containers again. A container's height is read at every layout and when the editor draws, so this is only for a host that needs the new geometry before the next frame.

func (*Decorations) RemoveAll

func (d *Decorations) RemoveAll(owner string)

RemoveAll takes back every entry owner made.

func (*Decorations) RemoveContainer

func (d *Decorations) RemoveContainer(id string) bool

RemoveContainer takes a container and its panel out of the editor.

func (*Decorations) RemoveMarginItem

func (d *Decorations) RemoveMarginItem(id string) bool

RemoveMarginItem takes a margin item and its panel out of the editor.

func (*Decorations) RemoveSpan

func (d *Decorations) RemoveSpan(id string) bool

RemoveSpan unmarks a span's characters.

func (*Decorations) Revision

func (d *Decorations) Revision() int

Revision is bumped whenever any entry is added, moved, restyled or removed, or the margin column is reserved or given up.

func (*Decorations) SetContainerBlock

func (d *Decorations) SetContainerBlock(id string, afterBlock int) bool

SetContainerBlock moves a container to after another block.

func (*Decorations) SetMarginColumnReserved

func (d *Decorations) SetMarginColumnReserved(reserved bool)

SetMarginColumnReserved reserves the column at the right of the rows that margin items are drawn in, or gives it up. A program reserves it once, when it starts, rather than with its first item, so the text never moves sideways under the reader when one appears.

func (*Decorations) SetMarginItemPosition

func (d *Decorations) SetMarginItemPosition(id string, block, line int) bool

SetMarginItemPosition moves a margin item beside another block or line.

func (*Decorations) SetSpanRange

func (d *Decorations) SetSpanRange(id string, block, start, length int) bool

SetSpanRange moves a span. Its length may go to 0, which is what a mark whose words were just deleted is until it is placed again.

func (*Decorations) SetSpanStyle

func (d *Decorations) SetSpanStyle(id string, style SpanStyle, color unison.Color) bool

SetSpanStyle repaints a span.

func (*Decorations) SpanCount

func (d *Decorations) SpanCount() int

func (*Decorations) SpanRects

func (d *Decorations) SpanRects(id string) []geom.Rect

SpanRects is where a span is painted: one rectangle for each line it crosses. It is empty for a span on no text.

func (*Decorations) SpansForBlock

func (d *Decorations) SpansForBlock(block int) []SpanEntry

SpansForBlock lists the spans marking block, in the order they were added, which is the order they are painted in.

type DiagramMath

type DiagramMath interface {
	// Size is tex typeset beside text of textSize pixels, and false when it
	// does not typeset.
	Size(tex string, textSize float32) (diagram.Size, bool)
	// Draw typesets tex beside text of textSize pixels with its top left at
	// origin, in colour c, and reports false when it does not typeset.
	Draw(gc *unison.Canvas, tex string, textSize float32, origin geom.Point, c unison.Color) bool
}

DiagramMath typesets the $$…$$ labels of Mermaid diagrams. The editor works without one, and then draws such a label as its source.

type Doc

type Doc struct {
	Blocks []Block
	Path   string
	Dirty  bool

	// The caret and the selection anchor. When Anchor is in another block
	// than Caret, the selection spans blocks.
	Caret  Pos
	Anchor Pos
	// Focused is false when no block has the caret (block selection, or
	// nothing clicked yet).
	Focused bool

	// Now is the clock, replaceable in tests.
	Now func() time.Time
	// ReadOnly refuses every change: the caret moves and text can be
	// selected and copied, but nothing is edited. A note in a vault that
	// cannot be written, in the trash or in a backup is read-only.
	ReadOnly bool
	// contains filtered or unexported fields
}

func NewDoc

func NewDoc(blocks []Block) *Doc

func (*Doc) ApplyTypedConversion

func (d *Doc) ApplyTypedConversion() bool

ApplyTypedConversion runs after typing. It is a separate undo step, so one Ctrl+Z brings back the literal "# ".

func (*Doc) AsCode

func (d *Doc) AsCode(id int64)

AsCode is a rendered diagram's "As code" control: the block is shown as its source in a code block tagged `plain`, which no later open or paste examines again. It is one undo step.

func (*Doc) Backspace

func (d *Doc) Backspace()

Backspace at a caret with no selection. At the start of a block, in this order: a list item, to-do or quote outdents, then becomes a paragraph; an empty block is deleted; a non-empty one merges into the block above.

func (*Doc) Begin

func (d *Doc) Begin() DocState

Begin and Commit bracket a gesture that changes the document several times but must undo as one step (a drag that reorders blocks live).

func (*Doc) Block

func (d *Doc) Block(id int64) *Block

func (*Doc) CaretBlock

func (d *Doc) CaretBlock() *Block

func (*Doc) Commit

func (d *Doc) Commit(kind string, before DocState)

func (*Doc) Convert

func (d *Doc) Convert(id int64, k Kind)

Convert changes a block's kind, keeping its text.

func (*Doc) CopiedText

func (d *Doc) CopiedText() (text string, markdown bool)

CopiedText is what copying the text selection puts on the clipboard, and whether that is Markdown. Across blocks it is Markdown, as RangeMarkdown writes it. Inside one block it is plain text: the characters drawn between the selection's ends, without the block's fence, prefix or number and without the markers of its inline spans, since none of them was on the screen to select; inside one cell of a table, the characters the cell draws. Selected code comes back as it stands, a link as its words, and an inline formula, which is drawn as a picture, as its TeX between $ signs. It is "" when nothing is selected.

func (*Doc) CrossBlock

func (d *Doc) CrossBlock() bool

func (*Doc) CurrentColor

func (d *Doc) CurrentColor() string

CurrentColor is the text colour of the colour span holding the selection, "" for none.

func (*Doc) DeleteBlocks

func (d *Doc) DeleteBlocks(ids []int64)

func (*Doc) DeleteForward

func (d *Doc) DeleteForward()

DeleteForward at a caret with no selection: at the end of a block it pulls the next block's text in.

func (*Doc) DeleteSelection

func (d *Doc) DeleteSelection()

func (*Doc) DeleteWordBack

func (d *Doc) DeleteWordBack()

DeleteWordBack deletes what Ctrl+Shift+Left would select: back to the start of the word before the caret, with the spaces and punctuation between. With a selection, or at the start of a block, it is Backspace.

func (*Doc) DeleteWordForward

func (d *Doc) DeleteWordForward()

DeleteWordForward deletes what Ctrl+Shift+Right would select. With a selection, or at the end of a block, it is Delete.

func (*Doc) DisplayPosition

func (d *Doc) DisplayPosition(i, mdPos int) int

DisplayPosition is the display offset that Markdown offset mdPos of block i stands for: the reverse of MarkdownPosition. An offset inside a hidden marker goes to the nearest edge of the text the marker wraps.

func (*Doc) DisplayText

func (d *Doc) DisplayText(i int) string

DisplayText is block i's text as a reader sees it with every marker hidden, which is what display offsets count in.

func (*Doc) Duplicate

func (d *Doc) Duplicate(ids []int64) []int64

func (*Doc) Edit

func (d *Doc) Edit(kind string, fn func())

Edit runs fn as one undoable step. Consecutive typing in one block merges into one step while the keystrokes are under 500 ms apart and each adds fewer than 20 characters.

func (*Doc) Enter

func (d *Doc) Enter()

Enter splits the block at the caret. On an empty list item or quote it turns the block into a paragraph instead (leaving the list). In a code block it starts a new line with the current line's indentation.

func (*Doc) HasSelection

func (d *Doc) HasSelection() bool

func (*Doc) Indent

func (d *Doc) Indent(ids []int64, delta int)

func (*Doc) Index

func (d *Doc) Index(id int64) int

func (*Doc) InsertMarkdownAt

func (d *Doc) InsertMarkdownAt(index int, markdown string) int

InsertMarkdownAt inserts parsed Markdown blocks at index, as one undo step, returning how many were inserted.

func (*Doc) InsertPlainTextAt

func (d *Doc) InsertPlainTextAt(index int, text string) int

InsertPlainTextAt inserts each line of text as a paragraph at index, as one undo step, returning how many were inserted. Each line is stripped to its display text, as a plain-text paste strips it.

func (*Doc) InsertText

func (d *Doc) InsertText(text string)

InsertText types text at the caret, replacing any selection. Pasted text with blank lines becomes blocks.

func (*Doc) JoinLines

func (d *Doc) JoinLines(ids []int64)

JoinLines replaces the line breaks inside each block with spaces, as one undo step: the block menu's "Remove line breaks".

func (*Doc) LeaveBlock

func (d *Doc) LeaveBlock()

LeaveBlock is Ctrl+Enter in a code block: a paragraph below it.

func (*Doc) MarkdownPosition

func (d *Doc) MarkdownPosition(i, displayPos int) int

MarkdownPosition is the offset in block i's Markdown that display offset displayPos stands for. displayPos is clamped to the display text first; a position at or past its end is the end of the Markdown, after any closing marker. Display offset 0 of "**bold**" is Markdown offset 2, where its first visible character is. An index the document does not hold answers 0.

func (*Doc) Move

func (d *Doc) Move(ids []int64, dir int) bool

Move shifts the given blocks up (-1) or down (+1) as a group.

func (*Doc) MoveBlocksTo

func (d *Doc) MoveBlocksTo(indexes []int, targetGap int) bool

MoveBlocksTo moves the blocks at sorted indexes to the gap before targetGap, as one undo step, preserving their order. targetGap counts in the list before the move. A gap inside a contiguous dragged run moves nothing.

func (*Doc) MoveTo

func (d *Doc) MoveTo(id int64, to int)

MoveTo puts one block at index `to` without recording undo; a drag calls it on every step and records a single step when it ends.

func (*Doc) Paste

func (d *Doc) Paste(text string, plain bool)

Paste inserts pasted text at the caret, replacing any selection, as InsertText does, with the rules for text arriving from outside the note:

  • Into a text block, Markdown with blank lines becomes blocks, and so do several lines opening a code fence, so the fence is read as one. Several flat lines become a paragraph each, spliced at the caret as pasteLines describes. A plain-text paste does the same split, with inline formatting stripped from each line.
  • Into a code block, the block's text after the paste goes through the step a fence takes when a note is opened (textdiagram.Ingest): a character diagram in an untagged or `text` block is tagged `diagram`, and a diagram is straightened, in the same undo step as the paste. Typing into the block never does this, since retagging a block while someone types in it would change it under them.
func (d *Doc) PasteLink(url string) bool

PasteLink replaces a single-block text selection with a link whose label is the selected text and whose address is url, which is what pasting a lone URL over words does. It reports whether there was such a selection.

func (*Doc) RangeMarkdown

func (d *Doc) RangeMarkdown() string

RangeMarkdown is the selection as Markdown: a whole block written with its prefix, fence or number, and a partly selected block as a fragment whose inline markers are balanced, so a sweep starting inside a bold phrase comes back as "**phrase**" rather than "phrase**". Two whole list items are one line apart and everything else a blank line apart. It is "" when nothing is selected.

func (*Doc) Redo

func (d *Doc) Redo() bool

func (*Doc) Seal

func (d *Doc) Seal()

Seal ends typing merge, so the next keystroke starts a new undo step (a click elsewhere or a caret move does this).

func (*Doc) SelRange

func (d *Doc) SelRange() (Pos, Pos)

SelRange returns the selection in document order.

func (*Doc) SelectedMarkdown

func (d *Doc) SelectedMarkdown() string

SelectedMarkdown is what Copy puts on the clipboard: the partial first and last blocks as their source text, whole blocks between them as Markdown.

func (*Doc) SelectionIn

func (d *Doc) SelectionIn(i int) (int, int, bool)

SelectionIn returns the part of the selection inside block i, as source offsets, and whether any of it is there.

func (*Doc) SelectionRange

func (d *Doc) SelectionRange() TextRange

SelectionRange is the text selection as block indexes and Markdown offsets, NoRange when there is none.

func (*Doc) SelectionStats

func (d *Doc) SelectionStats() (Stats, bool)

SelectionStats counts the selected text, and reports false when nothing is selected.

func (*Doc) SetAttr

func (d *Doc) SetAttr(ids []int64, key, value string)

SetAttr sets one presentation attribute of blocks, "" removing it, as one undo step: the alignment a menu chooses, a divider's style.

func (*Doc) SetCaret

func (d *Doc) SetCaret(id int64, off int)

SetCaret puts the caret in a block with no selection.

func (*Doc) SetCodeLanguage

func (d *Doc) SetCodeLanguage(id int64, lang string)

SetCodeLanguage gives a code block a language from the language menu, as one undo step. The block's text goes through textdiagram.Ingest with the new language: choosing "Text diagram" straightens the drawing, and choosing plain text for a block holding a diagram tags it `diagram` again. "Plain code" (`plain`) is the language that keeps a block from being tagged.

func (*Doc) SetColor

func (d *Doc) SetColor(value string)

SetColor gives the selected text a colour, written as <span style="color:VALUE">…</span>. Inside a colour span it changes that span's colour, and an empty value takes the span away, keeping its text.

func (*Doc) Stats

func (d *Doc) Stats() Stats

Stats counts the whole note: a paragraph is a block with a word in it.

func (*Doc) ToggleFormat

func (d *Doc) ToggleFormat(marker string)

ToggleFormat is Ctrl+B and friends: wrap the selection in the marker, or unwrap it when the selection is exactly a span of that marker. With no selection it inserts an empty pair with the caret between them.

func (*Doc) ToggleTodo

func (d *Doc) ToggleTodo(id int64)

func (*Doc) Undo

func (d *Doc) Undo() bool

func (*Doc) UndoSteps

func (d *Doc) UndoSteps() int

UndoSteps is how many steps Undo can take back.

func (*Doc) Words

func (d *Doc) Words() (words, chars int)

type DocState

type DocState struct {
	Blocks []Block
	Caret  Pos
	Anchor Pos
}

DocState is what undo restores: every block, and where the caret was.

type Document

type Document struct {
	unison.Panel
	// Editor draws the document. Its Doc is read-only; a host may set its
	// OnChange, FollowLink, CopyRich and the other callbacks a note sets.
	Editor *Editor
	// OnViewMoved runs after the reader scrolls a document that scrolls
	// itself, for a host that remembers where they were.
	OnViewMoved func()
	// contains filtered or unexported fields
}

Document is a read-only document drawn by the editor.

func NewDocument

func NewDocument(ui *kvitui.UI, o DocumentOptions) *Document

NewDocument makes an empty read-only document.

func (*Document) BlockCount

func (d *Document) BlockCount() int

BlockCount is how many blocks the document has.

func (*Document) BlockMarkdown

func (d *Document) BlockMarkdown(i int) string

BlockMarkdown is one block written as Markdown, "" for an index the document does not hold.

func (*Document) BlockRect

func (d *Document) BlockRect(i int) geom.Rect

BlockRect is where block i is drawn, with the containers after it; empty for an index the document does not hold.

func (*Document) CharRect

func (d *Document) CharRect(i, off int) geom.Rect

CharRect is where a caret before Markdown offset off of block i would be drawn: beside the character, one line tall.

func (*Document) ClearSelection

func (d *Document) ClearSelection()

ClearSelection drops the selection.

func (*Document) CopiedText

func (d *Document) CopiedText() (text string, markdown bool)

CopiedText is what CopySelection puts on the clipboard, and whether that is Markdown: across blocks the selection as SelectedMarkdown gives it, and inside one block the characters drawn, in plain text, as Doc.CopiedText describes. "" when nothing is selected.

func (*Document) CopySelection

func (d *Document) CopySelection() bool

CopySelection puts the selection on the clipboard as CopiedText gives it: Markdown with HTML beside it when the editor's CopyRich is set, or plain text alone. It reports false when nothing was selected.

func (*Document) Decorations

func (d *Document) Decorations() *Decorations

Decorations is the document's own decorations: washes over the words a comment is on, marks beside blocks.

func (*Document) HasSelection

func (d *Document) HasSelection() bool

HasSelection reports whether anything is selected.

func (*Document) Markdown

func (d *Document) Markdown() string

Markdown is the document as it was last set.

func (*Document) PictureSpots

func (d *Document) PictureSpots() []PictureSpot

PictureSpots are the document's pictures and where they are drawn, for a host that lays a button over each.

func (*Document) Region

func (d *Document) Region() *kvitui.Region

Region is the region a document that scrolls itself scrolls in, nil for one as tall as its document.

func (*Document) RestoreViewPosition

func (d *Document) RestoreViewPosition(p ViewPosition)

RestoreViewPosition puts the view back where ViewPosition found it. The offset is kept within the block's height, in case the block is shorter than it was. It does nothing for a document that does not scroll itself or a block it does not hold.

func (*Document) RevealSpan

func (d *Document) RevealSpan(id string, margin float32) bool

RevealSpan brings a span of the document's decorations into view, margin pixels below the top of the view, and reports false for a document that does not scroll itself or a span it does not have.

func (*Document) Scrolls

func (d *Document) Scrolls() bool

Scrolls reports whether the document scrolls itself.

func (*Document) SelectAll

func (d *Document) SelectAll() bool

SelectAll selects the whole document as text, and reports false when there is nothing to select.

func (*Document) SelectedMarkdown

func (d *Document) SelectedMarkdown() string

SelectedMarkdown is the selection as Markdown that stands on its own (Doc.RangeMarkdown), "" when nothing is selected.

func (*Document) SelectedRange

func (d *Document) SelectedRange() TextRange

SelectedRange is the selection as block indexes and Markdown offsets, NoRange when nothing is selected.

func (*Document) SetMarkdown

func (d *Document) SetMarkdown(md string)

SetMarkdown replaces the document, dropping any selection.

func (*Document) SpanRects

func (d *Document) SpanRects(id string) []geom.Rect

SpanRects is where a span of the document's decorations is painted, one rectangle for each line it crosses.

func (*Document) ViewPosition

func (d *Document) ViewPosition() ViewPosition

ViewPosition is the block at the top of the view and how far into it the view starts; Block is -1 for a document that does not scroll itself or has no blocks.

type DocumentOptions

type DocumentOptions struct {
	// Scrolls makes the document scroll itself inside the height the caller
	// gives it, rather than be as tall as its document.
	Scrolls bool
	// Margin is the space between the document's edges and its text, in
	// design pixels. Kvit Works' surfaces use 0, since each is inside a pane
	// with margins of its own.
	Margin float32
	// BlockSpacing is the space between blocks in design pixels; 0 keeps the
	// reader's paragraph spacing.
	BlockSpacing int
	// TightRows makes each row as tall as its text, without the room the
	// note keeps for the gutter's buttons; ListSpacing is then the space
	// between two items of a list, in design pixels (Embedding.TightRows).
	TightRows   bool
	ListSpacing int
	// FitTables, TextWidth and ScrollTables are the embedding's options of
	// the same names: columns sized as a browser sizes them, text kept to a
	// width in design pixels while tables and code blocks use the document's
	// whole width, and a table too wide for its room scrolled sideways.
	FitTables    bool
	TextWidth    float32
	ScrollTables bool
	// Pictures are the folders the document's pictures are looked up in.
	Pictures PictureFolders
	// OpenPicture, when set, is asked to show a picture a press landed on, in
	// place of the editor's own full-size view.
	OpenPicture func(path, alt string)
}

DocumentOptions say how a Document is made.

type Editor

type Editor struct {
	unison.Panel

	// Doc is the note being edited.
	Doc *Doc
	// OnChange runs after anything a status line would show has changed:
	// the note, the caret, the selection or the block selection.
	OnChange func()
	// Placeholder is shown in an empty paragraph.
	Placeholder string
	// PickImage, when set, is asked for a picture for a new image block:
	// the application shows a file dialog and writes the block's line.
	PickImage func(block int64)
	// LoadImage loads the picture an image block names, by the path as
	// written; nil draws every picture as a card naming it.
	LoadImage func(path string) (unison.Drawable, error)
	// RunQuery, when set, answers a query block's spec, and OpenNote opens a
	// note one of its rows names.
	RunQuery func(body string) query.Answer
	OpenNote func(path string)

	// Printing lays the note out for pages: no gutter, no side margins, and
	// none of the controls a reader presses on screen.
	Printing bool
	// LineNumbers numbers the lines of code blocks (View, Code line numbers).
	LineNumbers bool
	// FormatBar shows the formatting bar over a text selection.
	FormatBar bool
	// CompleteLink, when set, is what typing after "[[" offers: the notes,
	// or after a "#", a note's headings, for what is typed.
	CompleteLink func(query string) []Completion

	// CopyRich, when set, puts Markdown on the clipboard with its HTML, and
	// PasteRich reads HTML off the clipboard as Markdown, reporting false
	// when there is none worth reading.
	CopyRich  func(markdown string)
	PasteRich func() (string, bool)
	// PasteImage, when set, saves a clipboard picture into the vault and
	// reports the stored path. Nil keeps image data from being pasted,
	// leaving the text path to run instead.
	PasteImage func() (string, bool)
	// SaveDroppedImage, when set, copies an image file dropped from another
	// application into the vault's picture folder and reports the stored
	// path. Nil keeps the file path as written.
	SaveDroppedImage func(sourcePath string) (stored string, ok bool)
	// BlocksHTML, when set, writes blocks as HTML for the block menu's
	// Copy as, HTML.
	BlocksHTML func(blocks []Block, indexes []int) string
	// FollowLink, when set, follows a link a press landed on.
	FollowLink func(LinkRef)
	// OnLink, when set, opens the link dialog, as Ctrl+K does.
	OnLink func()
	// OnEditEmbed, when set, edits an embed block's address, as the block
	// menu's Edit URL… does.
	OnEditEmbed func(id int64, current string)
	// OnExport, when set, exports blocks, as the block menu's Export does.
	OnExport func(ids []int64)

	// LoadPreview, when set, is asked to read a web page for its embed card,
	// and answers through SetPreview; OpenURL opens an address.
	LoadPreview func(address string)
	OpenURL     func(address string)

	// RemotePolicy, when set, gates remote pictures and pages: nothing remote
	// loads until its origin is approved (opening a note is not consent).
	// Nil draws every remote picture as not loaded.
	RemotePolicy RemotePolicy
	// Centered keeps the text to a column in the middle, as focus mode does,
	// when the reader has set no width of their own.
	Centered bool
	// Typewriter, when set to the region the editor scrolls in, keeps the
	// caret's line in the middle of the view and fades the other blocks
	// (typewriter mode).
	Typewriter *kvitui.Region

	// DiagramMath, when set, typesets the $$…$$ labels of Mermaid diagrams
	// (diagram.go); without it they are drawn as their source.
	DiagramMath DiagramMath
	// EquationNumbers numbers the display equations at their right (View,
	// Equation numbers).
	EquationNumbers bool
	// SaveDiagramPNG, when set, is given a diagram's PNG by its PNG
	// control; without it a file dialog asks where to write it.
	SaveDiagramPNG func(png []byte)
	// OnStatus, when set, shows a short message about what was just done,
	// such as where a diagram was saved.
	OnStatus func(message string)
	// contains filtered or unexported fields
}

Editor is the block editor. Put it in a kvitui.Region to scroll it; it takes the width it is given and is as tall as its note.

func New

func New(ui *kvitui.UI, doc *Doc) *Editor

New returns an editor showing doc.

func (*Editor) AcceptTag

func (e *Editor) AcceptTag()

AcceptTag takes the highlighted offered label, or the typed text.

func (*Editor) AddCardLabel

func (e *Editor) AddCardLabel(id int64, col, index int, name string)

AddCardLabel adds a label to a card, as the chip row's + tag does. A leading hash comes off (the stored form does not carry it); empty and duplicate labels are ignored.

func (*Editor) Align

func (e *Editor) Align(value string)

Align sets the alignment of the caret's block or the selected blocks: "left", "center" or "right".

func (*Editor) Alignment

func (e *Editor) Alignment() string

Alignment is the caret's block's alignment: "left", "center" or "right".

func (*Editor) ApplyCardDetails

func (e *Editor) ApplyCardDetails(id int64, col, index int, labels []string, due string) bool

ApplyCardDetails writes the details dialog's fields: the labels and the due date. A due value the stored form cannot hold is refused: it returns false and writes nothing, so an invalid date never comes back as title text with the due date cleared.

func (*Editor) BeginTagEdit

func (e *Editor) BeginTagEdit(i, col, index int)

BeginTagEdit opens the label field in a card's chip row.

func (*Editor) BlockAtY

func (e *Editor) BlockAtY(y float32) (block int, offset float32)

BlockAtY is the block being read at height y of the editor, and how far below that block's top y is: the block whose row, with the containers after it, holds y. The space between two rows belongs to the one below, which is the one being read when the top of a view falls there. It is -1 for an empty document.

func (*Editor) BlockRect

func (e *Editor) BlockRect(i int) geom.Rect

BlockRect is block i's row with the containers drawn after it, which is the space the block takes in the document; empty for an index the document does not hold.

func (*Editor) BlockTop

func (e *Editor) BlockTop(i int) float32

BlockTop is the top of block i's row; 0 for an index the document does not hold.

func (*Editor) BoardChipRects

func (e *Editor) BoardChipRects(i, col, index int) (words []string, rects []geom.Rect)

BoardChipRects are a card's label and due chips, in the editor, for tests: each chip's words and rectangle.

func (*Editor) BoardLabels

func (e *Editor) BoardLabels(id int64) []string

BoardLabels are the labels used anywhere on a board, in first-use order.

func (*Editor) BoardPart

func (e *Editor) BoardPart(i int, part string, col, index int) geom.Rect

BoardPart is where a part of a task board is, in the editor: "column N" parts ("fold", "name", "left", "right", "add", "close", "addcard"), a card's "box" or "card", "addtag" or "adddue" on the hovered card, "addcolumn", or a filter chip by its words.

func (*Editor) BoardText

func (e *Editor) BoardText(i int) string

BoardText is a task board's cards as text, for tests: each column's name and its cards shown, "[x]" for a finished one.

func (*Editor) CardDetailsState

func (e *Editor) CardDetailsState(id int64, col, index int) (labels, due string, ok bool)

CardDetailsState reads the card-details dialog's fields: the labels as typed and the due date.

func (*Editor) CardGhost

func (e *Editor) CardGhost() (block int64, at, hot geom.Point, ok bool)

CardGhost reports the dragged card drawn under the pointer, for tests: its block, the pointer in editor coordinates, and the press offset inside the card in board coordinates.

func (*Editor) CaretLineColumn

func (e *Editor) CaretLineColumn() (line, col int)

CaretLineColumn is the caret's 1-based line and column within its block's display text: the line breaks are the display text's own newlines, as the status bar shows them.

func (*Editor) CaretRect

func (e *Editor) CaretRect() (geom.Rect, bool)

CaretRect is the caret's rectangle in the editor's coordinates, and false when no block holds the caret.

func (*Editor) CharRect

func (e *Editor) CharRect(i, off int) geom.Rect

CharRect is where a caret before Markdown offset off of block i is drawn: its x, and the top and height of its line. It is what places something beside a character, such as the actions offered at the end of a selection. In a table drawn as its grid, an offset in a cell's text answers where that character is in the cell. A block that draws no text answers its row; an index the document does not hold answers an empty rectangle.

func (*Editor) ClearDue

func (e *Editor) ClearDue()

ClearDue clears a card's due date through the picker.

func (*Editor) ClearFocus

func (e *Editor) ClearFocus()

ClearFocus takes the caret out of every block, as a press outside the note does.

func (*Editor) ClearPictures

func (e *Editor) ClearPictures()

ClearPictures drops every cached picture, so a policy set after the first layout is read.

func (*Editor) ClearSelection

func (e *Editor) ClearSelection()

ClearSelection drops the text selection and the block selection, and leaves the caret where it is.

func (*Editor) CloseLightbox

func (e *Editor) CloseLightbox()

CloseLightbox closes the full-size picture.

func (*Editor) ColorItems

func (e *Editor) ColorItems() []kvitui.MenuItem

ColorItems are the text colour menu's lines: each colour, and Remove color when the selection has one.

func (*Editor) CommitTag

func (e *Editor) CommitTag(name string)

CommitTag adds a label through the chip row's field.

func (*Editor) ContentHeight

func (e *Editor) ContentHeight() float32

ContentHeight is the height of the rows, from the top of the first to the bottom of the last with the containers after it, without the margins.

func (*Editor) CopiedText

func (e *Editor) CopiedText() (text string, markdown bool)

CopiedText is what copying the editor's selection puts on the clipboard, and whether that is Markdown: blocks selected whole as SelectionMarkdown writes them, and a text selection as Doc.CopiedText gives it.

func (*Editor) Decorations

func (e *Editor) Decorations() *Decorations

Decorations is the editor's decoration registry, made on first use.

func (*Editor) DrawPage

func (e *Editor) DrawPage(gc *unison.Canvas, p Page)

DrawPage draws one page's part of the note with its top at the canvas's origin.

func (*Editor) DuePickerOpen

func (e *Editor) DuePickerOpen() (col, index, year, month int, selected string, ok bool)

DuePickerOpen reports the picker's card, visible month and day, for tests.

func (*Editor) Embed

func (e *Editor) Embed(emb Embedding)

Embed lays the editor out and has it answer as emb says. The editor keeps a copy; calling Embed again replaces it.

func (*Editor) Embedded

func (e *Editor) Embedded() (Embedding, bool)

Embedded is the embedding the editor was given, and false for the note editor.

func (*Editor) FocusBlock

func (e *Editor) FocusBlock(i, off int)

FocusBlock puts the caret in block i at a source offset and gives the editor the keyboard focus. Focusing a table shows its Markdown: the grid is for the pointer, which makes a cell live.

func (*Editor) ForgetPicture

func (e *Editor) ForgetPicture(path string)

ForgetPicture drops a cached picture so an approval reloads it.

func (*Editor) Format

func (e *Editor) Format(marker string)

Format wraps the selection in an inline marker, or unwraps it.

func (*Editor) FormatBarButtons

func (e *Editor) FormatBarButtons() []*unison.Panel

FormatBarButtons are the formatting bar's buttons while it is shown, for tests.

func (*Editor) GoToAnchor

func (e *Editor) GoToAnchor(anchor string) bool

GoToAnchor puts the caret at the heading a "#anchor" names, and reports whether there is one.

func (*Editor) GoToHeading

func (e *Editor) GoToHeading(heading string) bool

GoToHeading puts the caret at the heading a heading's text names, as [[note#Heading]] does, and reports whether there is one.

func (*Editor) HasSelection

func (e *Editor) HasSelection() bool

HasSelection reports whether the editor has text or whole blocks selected: what a host offering actions on a selection asks.

func (*Editor) HasTableSelection

func (e *Editor) HasTableSelection() bool

HasTableSelection reports whether a swept rectangle of more than one cell is selected.

func (*Editor) Headings

func (e *Editor) Headings() (levels []int, texts, anchors []string)

Headings are the note's headings for the link dialog's heading list: each one's level, text and the anchor a link reaches it by.

func (*Editor) IndexesOf

func (e *Editor) IndexesOf(ids []int64) []int

IndexesOf are blocks' places in the note, in order.

func (*Editor) InsertItems

func (e *Editor) InsertItems() []kvitui.MenuItem

InsertItems are the toolbar's Insert menu: each kind of the block type list, then the kinds that start with content of their own.

func (*Editor) InsertTable

func (e *Editor) InsertTable(cols, rows int)

InsertTable adds an empty table of cols columns and rows data rows below the caret's block, and makes its first cell live.

func (*Editor) Lightbox

func (e *Editor) Lightbox() (path, alt string, open bool)

Lightbox reports the open full-size picture, if any.

func (*Editor) LinkAtCaret

func (e *Editor) LinkAtCaret() (id int64, start, end int, text, address string, ok bool)

LinkAtCaret is the Markdown link, text(address), the caret is in: its block, its range in the block's source, its text and its address.

func (*Editor) MathMenuState

func (e *Editor) MathMenuState() (open bool, query string, names []string, sel int)

MathMenuState is the command menu's state for tests: whether it is open, its query, the names it lists (the completion rows, or in browse mode the highlighted category's entries), and the highlighted one's index.

func (*Editor) MenuEntries

func (e *Editor) MenuEntries() ([]string, int)

MenuEntries are the names of the / menu's entries, in order, and the index of the highlighted one; nil and -1 when the menu is closed.

func (*Editor) MenuOpen

func (e *Editor) MenuOpen() bool

MenuOpen reports whether the / menu is open.

func (*Editor) MoveTagHighlight

func (e *Editor) MoveTagHighlight(delta int)

MoveTagHighlight moves the highlighted offered label.

func (*Editor) OpenCardDetails

func (e *Editor) OpenCardDetails(i, col, index int)

OpenCardDetails opens the card-details dialog: the labels, the due date the storage grammar is strict about, moving to another column, and deleting the card.

func (*Editor) OpenDuePicker

func (e *Editor) OpenDuePicker(i, col, index int)

OpenDuePicker opens the calendar for a card's due date, on its month when it has one and on this month otherwise.

func (*Editor) OpenLightbox

func (e *Editor) OpenLightbox(path, alt string)

OpenLightbox opens a picture full-size, as a click on a resolved image does.

func (*Editor) Paginate

func (e *Editor) Paginate(width, height float32) []Page

Paginate lays the note out at a width and cuts it into pages of a height.

func (*Editor) PartRect

func (e *Editor) PartRect(i int, part string) geom.Rect

PartRect is one of block i's controls in the editor's coordinates: the gutter's "menu" and "handle" (shown while the pointer is on the row), a to-do's "check" box, a code block's "copy" button, and a card's "load" button and "open" title, and a table's "cell" (or "cell:<row>:<col>" for another data cell), "header" (or "header:<col>" for another header column), "grip", and "addrow"/"addcol" (the + Row / + Column buttons under a live cell), and a code block's "codebar" (its horizontal scrollbar, when a long line runs past the panel).

func (*Editor) PerformAccessibilityAction

func (e *Editor) PerformAccessibilityAction(req accessibility.ActionRequest) bool

PerformAccessibilityAction carries out a screen reader's request on a block or on one of a block's controls.

func (*Editor) PickDueDay

func (e *Editor) PickDueDay(day int)

PickDueDay writes the picker's day into the card and closes it.

func (*Editor) PictureSpots

func (e *Editor) PictureSpots() []PictureSpot

PictureSpots are the pictures the document's image blocks draw, in order, for a host that lays something over them.

func (*Editor) PreviewTitle

func (e *Editor) PreviewTitle(address string) string

PreviewTitle is the title an embed card shows from its page, "" before the page is read.

func (*Editor) Previews

func (e *Editor) Previews() map[string]Preview

Previews are the pages read so far for their cards, by address, for another editor drawing the same note, such as the one a PDF is drawn by.

func (*Editor) ProvideAccessibility

func (e *Editor) ProvideAccessibility(b *unison.AccessibilityBuilder)

ProvideAccessibility describes the blocks in view, and the block with the caret wherever it is.

func (*Editor) QueryText

func (e *Editor) QueryText(i int) string

QueryText is a query block's answer as text, for tests: the error, or each row's cells.

func (*Editor) Refresh

func (e *Editor) Refresh()

Refresh redraws the editor after its Doc was changed from outside, and brings the caret into view.

func (*Editor) RefreshQueries

func (e *Editor) RefreshQueries()

RefreshQueries works the query blocks out again, after the vault changed.

func (*Editor) RemoveCardLabel

func (e *Editor) RemoveCardLabel(id int64, col, index int, name string)

RemoveCardLabel removes a label from a card, as its chip does.

func (*Editor) RemoveLinkAt

func (e *Editor) RemoveLinkAt(pos Pos) bool

RemoveLinkAt removes the link formatting at a position, keeping its text: "text(address)" becomes "text". Only a Markdown link is removable; a bare address is its own text and a wiki link keeps its brackets. It reports whether it removed one.

func (*Editor) ReplaceRange

func (e *Editor) ReplaceRange(id int64, start, end int, replacement string, caret int)

ReplaceRange replaces a range of a block's source, as one undo step, and puts the caret at an offset of the new text.

func (*Editor) RevealBlockRange

func (e *Editor) RevealBlockRange(id int64, start int)

RevealBlockRange scrolls the view to a range of a block's source.

func (*Editor) RowRect

func (e *Editor) RowRect(i int) geom.Rect

RowRect is block i's whole row, gutter included, in the editor's coordinates.

func (*Editor) SelectedBlocks

func (e *Editor) SelectedBlocks() []int64

SelectedBlocks are the ids of the blocks selected as whole blocks, in document order.

func (*Editor) SelectionMarkdown

func (e *Editor) SelectionMarkdown() string

SelectionMarkdown is the editor's selection as Markdown that stands on its own (RangeMarkdown), "" when nothing is selected.

func (*Editor) SelectionRange

func (e *Editor) SelectionRange() TextRange

SelectionRange is the editor's selection as block indexes and Markdown offsets: the text selection, or for blocks selected whole, the run from the start of the first to the end of the last; NoRange when nothing is selected.

func (*Editor) SetBlockSelection

func (e *Editor) SetBlockSelection(ids []int64)

SetBlockSelection selects whole blocks by id, as a handle click does, for callers (such as the find bar's tests) that do not go through the pointer.

func (*Editor) SetCardDue

func (e *Editor) SetCardDue(id int64, col, index int, day string)

SetCardDue sets a card's due date, as its date chip and the picker do. An invalid value clears it: the stored form only holds ISO days.

func (*Editor) SetColor

func (e *Editor) SetColor(value string)

SetColor colours the selected text; "" takes the colour away.

func (*Editor) SetDoc

func (e *Editor) SetDoc(doc *Doc)

SetDoc replaces the note being edited.

func (*Editor) SetEmbedSize

func (e *Editor) SetEmbedSize(ids []int64, width, height int)

SetEmbedSize gives embed blocks a configured width and height in px, kept in their width= and height= attributes: 0 clears to the default full-width card.

func (*Editor) SetEmbedURL

func (e *Editor) SetEmbedURL(id int64, url string) bool

SetEmbedURL rewrites an embed block's address, keeping its alt text, as one undo step (the block menu's Edit URL…).

func (*Editor) SetImageEffects

func (e *Editor) SetImageEffects(ids []int64, rounded int, shadow bool, border, color string, stretch bool)

SetImageEffects sets an image block's effects as one undo step: rounded with a radius (0 clears), shadow, border with an optional colour ("" clears), and stretch.

func (*Editor) SetMarks

func (e *Editor) SetMarks(marks []Mark)

SetMarks replaces the matches drawn; nil takes them all away.

func (*Editor) SetMathCommands

func (e *Editor) SetMathCommands(m *mathcmd.Model)

SetMathCommands gives the editor the command menu's list: the application makes it once, with the math engine's commands (mathcmd.New(mathtex.Commands)), shares it between editors, and saves its recently used commands.

func (*Editor) SetPreview

func (e *Editor) SetPreview(address string, p Preview)

SetPreview gives a page's card what the page says, once it is read.

func (*Editor) ShiftDueMonth

func (e *Editor) ShiftDueMonth(delta int)

ShiftDueMonth moves the picker's visible month.

func (*Editor) TableCell

func (e *Editor) TableCell() (id int64, row, col int, ok bool)

TableCell reports the live cell: its block id, row (-1 header, 0.. data) and column, or false when no cell is live.

func (*Editor) TableCellSelected

func (e *Editor) TableCellSelected(id int64, row, col int) bool

TableCellSelected reports whether cell row, col of block id is in the swept rectangle.

func (*Editor) TableCellText

func (e *Editor) TableCellText(id int64, row, col int) string

TableCellText reads one cell of block id's table, "" outside it.

func (*Editor) TablePickerOpen

func (e *Editor) TablePickerOpen() bool

TablePickerOpen reports whether the grid picker is open.

func (*Editor) TableSelection

func (e *Editor) TableSelection() (id int64, top, bottom, left, right int, ok bool)

TableSelection is the swept rectangle normalized: top, bottom, left and right, rows -1 for the header, 0.. for data rows. ok is false when no rectangle is selected.

func (*Editor) TagChoices

func (e *Editor) TagChoices(id int64, col, index int, query string) []string

TagChoices are the board's labels a card does not already carry, narrowed by what has been typed (case-insensitive, a leading hash ignored): the list under the chip row's field, there to reuse a label rather than retype it.

func (*Editor) TagEditOpen

func (e *Editor) TagEditOpen() (col, index int, query string, choices []string, ok bool)

TagEditOpen reports the tag field's card, query and choices, for tests.

func (*Editor) TextPoint

func (e *Editor) TextPoint(i, off int) geom.Point

TextPoint is the point in the middle of the line of block i where a caret before source offset off is drawn, just right of it, in the editor's coordinates.

func (*Editor) TurnInto

func (e *Editor) TurnInto(k Kind)

TurnInto changes the kind of the caret's block, or of every selected block.

func (*Editor) UI

func (e *Editor) UI() *kvitui.UI

UI is the interface the editor draws with.

func (*Editor) WikiMenuEntries

func (e *Editor) WikiMenuEntries() ([]string, int)

WikiMenuEntries are the completion list's labels and the highlighted one, for tests; nil when the list is closed.

type Embedding

type Embedding struct {
	// NoGutter takes away the strip left of each row with the block menu's
	// button and the drag handle, and its width with it, so the text starts
	// near the editor's left edge.
	NoGutter bool
	// Margin is the space between the editor's edges and its rows, in design
	// pixels, in place of the note's page margin of 20: above the first row,
	// below the last, and at either side. Nothing is added below the last
	// row for scrolling past the end, so the editor is exactly as tall as its
	// rows and margins.
	Margin float32
	// BlockSpacing is the space between two rows in design pixels; 0 keeps
	// the reader's paragraph spacing.
	BlockSpacing int
	// TightRows takes away the 4 design pixels each row keeps above and
	// below its text, inside its hover tint and selection, so that a row is
	// as tall as its text: BlockSpacing is then all the space between two
	// blocks, and ListSpacing all the space between two items of a list. It
	// is for a document read more than edited, such as a transcript.
	TightRows bool
	// ListSpacing, with TightRows, is the space between two items of a list
	// in design pixels, where BlockSpacing separates every other two rows. At
	// 0 an item's first line is under the last line of the item before it
	// as the lines of one paragraph are under each other.
	ListSpacing int
	// LineHeight is how far apart the lines of a block are, as a multiple of
	// the font's own line height, in place of the reader's line height; 0
	// keeps the reader's. It is for a box short of room, such as a message
	// being typed, whose lines the host wants closer than a document's.
	LineHeight float64
	// Ink, when set, is the colour of the ordinary text of every block but
	// the four headings, in place of the theme's TextPrimary: paragraphs,
	// list items, to-do items, table cells, callouts, inline formulas, and
	// a code block's text where it has no syntax colour. Headings keep
	// TextPrimary, and quotes, checked to-dos, links, syntax colours, list
	// markers and display equations keep their own colours. The ink is read
	// through the theme each time a block is laid out, so it follows a
	// change of theme. It is for a document drawn among interface text that
	// uses a softer colour for what is read, such as a conversation beside
	// a page.
	Ink kvitui.Ink
	// ReadOnlyLook draws no caret, no focus bar, no hover tint and no inline
	// markers around the caret. It does not refuse edits by itself: set
	// Doc.ReadOnly for that.
	ReadOnlyLook bool
	// HideImageLine never shows an image block's Markdown line, even with the
	// caret in it: the picture keeps the keyboard as a whole, Backspace or
	// Delete removes it, the arrows leave it, and nothing can be typed into
	// it.
	HideImageLine bool
	// ReturnPressed, when set, takes Enter from the editor: it is called
	// with the index of the caret's block instead of the block being split.
	// Enter still takes the highlighted entry of an open menu, writes a new
	// line in a code block, makes the next item of a list with text in it,
	// ends a list or a quote on an empty item, and replaces a selection that
	// crosses blocks; Shift+Enter still breaks the line; Ctrl+Enter is
	// reported from every block, a list and a code block included.
	ReturnPressed func(blockIndex int)
	// OpenPicture, when set, is asked to show a picture a press landed on,
	// in place of the editor's own full-size view drawn inside its panel.
	OpenPicture func(path, alt string)
	// CopyFragments makes Ctrl+C and Ctrl+X put the selection on the
	// clipboard as Doc.CopiedText gives it: across blocks as Markdown, with
	// a partly selected block as a fragment whose inline markers are
	// balanced, and inside one block as the characters drawn, in plain text.
	CopyFragments bool
	// FitTables sizes the columns of a table the reader has not dragged as a
	// browser's automatic table layout does (tablefit.go). When every column
	// fits on one line, each is as wide as its widest cell and the table is
	// as wide as its content, with no last column widened to fill the room.
	// When they do not, each column gets its longest word, path or link, and
	// the room left is shared out by how much more each column wants, the
	// small wants met in full first, so short columns such as names, numbers
	// and "95 ms" stay on one line while a column of sentences wraps. A
	// column the reader dragged keeps its width.
	FitTables bool
	// TextWidth is the width, in design pixels, the editor lays its text out
	// in, as if the editor were that wide, margins included: paragraphs,
	// lists, quotes, headings and every block but tables and code wrap there,
	// from the rows' usual left edge. Tables and code blocks start at the same
	// edge and may use the editor's whole width past it (wideblocks.go): a
	// table as wide as its columns, a code block as wide as its longest line
	// and scrolling past the editor's right margin. 0 lays every block out in
	// the editor's whole width.
	TextWidth float32
	// ScrollTables lets a table whose columns cannot be made narrow enough for
	// its room, each at least its longest word, keep those widths and scroll
	// sideways inside its block as a code block's long lines do: clipped, with
	// a scrollbar under it, moved by the horizontal wheel, Shift with the
	// wheel and the scrollbar, and brought round to a cell made live
	// (tablescroll.go). Without it such a table is squeezed into its room.
	ScrollTables bool
	// Laid, when set, runs each time the rows have been measured again,
	// for a host that places things over them. It may ask where things are,
	// and must not change the editor.
	Laid func()
}

Embedding is how an editor drawn somewhere other than the note pane is laid out and what it does with the few keys and presses a host takes over. Pass it to Editor.Embed before the editor is first shown.

type FenceLanguage

type FenceLanguage struct {
	// Tone is how each line of a block in the language is drawn.
	Tone func(line string) FenceTone
}

FenceLanguage is what a program says about a fence language it adds.

func DiffFence

func DiffFence() FenceLanguage

DiffFence is the diff drawing Kvit Works registers under DiffFenceLanguage: a line starting with "+" is added, one starting with "-" removed, and every other line plain.

type FenceTone

type FenceTone int

FenceTone is how a line of a registered fence language is drawn.

const (
	// FencePlain draws the line as the rest of the code.
	FencePlain FenceTone = iota
	// FenceAdded draws it in the theme's success colour.
	FenceAdded
	// FenceRemoved draws it in the theme's danger colour.
	FenceRemoved
)

The tones a line takes.

func DiffTone

func DiffTone(line string) FenceTone

DiffTone is DiffFence's tone for one line.

type ImageRef

type ImageRef struct {
	Alt, Path, Caption string
	// Width is the width the picture is drawn at, 0 for its own.
	Width int
	// Media is a sound or a video rather than a picture.
	Media bool
	// Remote is an http or https address.
	Remote bool
}

ImageRef is what an image line says.

func ParseImageLine

func ParseImageLine(line string) (ImageRef, bool)

ParseImageLine reads an image line. It fails for anything that is not exactly one image expression naming a picture, a sound, a video, or a web address.

type Kind

type Kind int

Kind is what a block is: a paragraph, a heading, a list item and so on.

const (
	Paragraph Kind = iota
	Heading1
	Heading2
	Heading3
	Heading4
	Bullet
	Numbered
	Todo
	Quote
	Code
	Divider
	// Raw keeps Markdown the editor does not model (tables, display math,
	// front matter) verbatim, so a note survives a load and save unchanged.
	Raw
	// Image is a line holding only ![alt](picture), drawn as the picture.
	Image
	// Media is such a line naming a sound or a video.
	Media
	// Callout is a quote headed "[!type] Title": a tinted panel.
	Callout
	// Table is a pipe table, kept as written and drawn as a grid.
	Table
	// Math is a display equation, a "$$ … $$" fence: its text is the TeX
	// between the fences, typeset away from the caret (mathblock.go).
	Math
)

The block kinds.

func (Kind) HasInline

func (k Kind) HasInline() bool

HasInline reports whether the block's text is parsed as inline Markdown.

func (Kind) IsHeading

func (k Kind) IsHeading() bool

IsHeading reports whether the block is one of the four headings.

func (Kind) IsList

func (k Kind) IsList() bool

IsList reports whether a block of this kind takes the list rules: Enter continues it, Enter on an empty item leaves it, Backspace at the start outdents and then turns it into a paragraph.

func (Kind) IsText

func (k Kind) IsText() bool

IsText reports whether the block is edited as text at all.

func (Kind) String

func (k Kind) String() string

type KindChoice

type KindChoice struct {
	Name string
	Kind Kind
}

KindChoice is a kind of block by the name the toolbar gives it.

type LinkRef

type LinkRef struct {
	// Wiki is true for [[note]], [[note#heading|alias]] and [[#heading]];
	// Target is then what is between the brackets.
	Wiki bool
	// Target is a wiki link's inside, or a Markdown link's address: a web
	// address, a path, or "#heading".
	Target string
}

LinkRef is a link a press follows.

type Mark

type Mark struct {
	Block      int64
	Start, End int
	Current    bool
}

Mark is one match to draw, in rune offsets of a block's Markdown source.

type Page

type Page struct{ From, To float32 }

Page is one page's part of the note, from one y to another in the laid out note.

type PictureFolders

type PictureFolders struct {
	// Base is the folder a relative path is written against: the folder
	// the document is in, or for a transcript the session folder.
	Base string
	// Root is the folder a path is also looked up in when it is not beside
	// the document: a note in a subfolder names assets/a.png from the
	// project's top. For a file from a track's copy it is that copy, so the
	// pictures drawn are the copy's own.
	Root string
	// Site is the folder a path starting with "/" is looked up in, as a
	// website names a file at its root: static/ in a Hugo site. Root when
	// empty.
	Site string
}

PictureFolders are the folders a document's pictures are looked up in.

func (PictureFolders) Loader

func (f PictureFolders) Loader() func(stored string) (unison.Drawable, error)

Loader is what Editor.LoadImage takes for these folders: each picture found by Resolve, read once and kept while the file is unchanged, and a picture wider than the text column is ever drawn scaled down as it is read. A web address is refused; the editor draws it as a card.

func (PictureFolders) Resolve

func (f PictureFolders) Resolve(stored string) string

Resolve is the file a stored picture path names: beside the document, then from the top of Root, then as written, and a path starting with "/" from the site folder last, the first that is a file. A web address comes back as it is, and a path that names no file comes back "".

type PictureSpot

type PictureSpot struct {
	Block     int
	Path, Alt string
	Rect      geom.Rect
}

PictureSpot is a picture an image block draws, and where.

type PipeTable

type PipeTable struct {
	Valid      bool
	Headers    []string
	Alignments []TableAlign
	Rows       [][]string
}

Table is a pipe table read into cells.

func ParseTable

func ParseTable(markdown string) PipeTable

ParseTable reads pipe-table Markdown into a grid; Valid is false when it is not a table.

func (PipeTable) ColumnCount

func (t PipeTable) ColumnCount() int

ColumnCount is the header's width; RowCount counts data rows only.

func (PipeTable) RowCount

func (t PipeTable) RowCount() int

type Pos

type Pos struct {
	Block int64
	Off   int
}

Pos is a caret position: a block and a source rune offset in it.

type Preview

type Preview struct {
	Title, Description string
	// Image is the page's picture, or nil.
	Image unison.Drawable
	// Failed says why the page could not be read, "" when it was.
	Failed string
}

Preview is what a web page says about itself, for its card.

type RemotePolicy

type RemotePolicy interface {
	IsAllowed(url string) bool
	Allow(url string)
	CanRequest(url string) bool
	Refusal(url string) string
	Origin(url string) string
}

RemotePolicy gates remote pictures and pages: nothing remote loads until its origin is approved. The app implements it over its egress policy.

type SpanEntry

type SpanEntry struct {
	ID, Owner            string
	Block, Start, Length int
	Style                SpanStyle
	Color                unison.Color
}

SpanEntry is one marked run of characters, as SpansForBlock lists them. Start and Length are in the block's display text: its Markdown with every inline marker taken out (DisplayPosition).

type SpanRange

type SpanRange struct {
	Start, End, ContentStart, ContentEnd int
}

SpanRange is an inline span of a block's source, in rune offsets: its opening marker is [Start, ContentStart) and its closing marker [ContentEnd, End).

func Spans

func Spans(src string) []SpanRange

Spans are the inline spans of a block's source, as the editor reads them, for the find bar's mapping of what the reader sees to the source.

type SpanStyle

type SpanStyle int

SpanStyle is how a marked run of characters is painted. The two compose: a wash is behind the characters and an outline around them, one box for each line the run crosses.

const (
	SpanWash SpanStyle = 1 << iota
	SpanOutline
)

The span styles.

type Stats

type Stats struct {
	Words, Chars, CharsNoSpaces, Paragraphs, Blocks, ReadingMinutes int
}

Stats are counts of a note or a selection.

func StatsOfText

func StatsOfText(text string) Stats

StatsOfText counts text as the reader sees it: a paragraph, and a block, is a line with something on it.

type TableAlign

type TableAlign int

TableAlign is one column's alignment.

const (
	TableAlignNone TableAlign = iota
	TableAlignLeft
	TableAlignCenter
	TableAlignRight
)

func TableAlignmentFromName

func TableAlignmentFromName(name string) TableAlign

TableAlignmentFromName parses a menu name back; unknown names mean none.

type TextRange

type TextRange struct {
	StartIndex, StartPos, EndIndex, EndPos int
}

TextRange is a selection as block indexes and Markdown offsets, start before end. StartIndex and EndIndex are -1 when nothing is selected.

type ViewPosition

type ViewPosition struct {
	Block  int
	Offset float32
}

ViewPosition is where the reader of a document that scrolls itself is: the block at the top of the view and how far its top is above the view's top. A block is the same block however the rows above it were measured, which a distance from the top of the document is not.

Jump to

Keyboard shortcuts

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