richtext

package
v0.1.5 Latest Latest
Warning

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

Go to latest
Published: Oct 22, 2026 License: MIT Imports: 28 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

Index

Constants

View Source
const Format transfer.Format = "application/x-golet-rich-text"

Format is the clipboard's format of attributed text copied from an Editor: its paragraphs, styles and runs as JSON, which other Golet apps paste whole, as Lexical and Slate copy a format of their own first.

View Source
const ObjectReplacement = ''

ObjectReplacement is the character an Attachment takes in a text.

View Source
const RTF transfer.Format = "text/rtf"

RTF is the format of Rich Text Format, which macOS apps (TextEdit, Notes, Pages) copy.

Variables

This section is empty.

Functions

func Editor

func Editor(c *ui.Context, doc *Document, options ...EditorOptions) ui.Element

Editor creates an editor of doc's attributed text, as NSTextView edits attributed text: bold, italic, underline, strikethrough, code, fonts, sizes and colors, links, headings, lists, tasks, quotations, blocks of code, alignment and attachments, with the shortcuts of word processors (⌘B, ⌘I, ⌘U, ⌘K, ⇧⌘7, ⇧⌘8, ⌘], …), undo of formats with the text, rich copy and paste, and input methods composing in the typing attributes. The app keeps doc from frame to frame:

doc := richtext.NewDocument(richtext.NewText("Hello"))
// In the view:
if richtext.Editor(c, doc).Fill().Changed() {
	app.save(doc.Text())
}

A toolbar formats the selection through doc (doc.ToggleBold, doc.SetHeading, …) and shows its formats with doc.Formatting. Changed reports the edits the user made in the editor, not those the app made through doc. It lays out and draws only the paragraphs in view, so a long document edits as a short one.

func EditorBase

func EditorBase(c *ui.Context, doc *Document, options ...EditorOptions) ui.Element

EditorBase creates an Editor without padding, background, border or corners, for an editor of the app's own look.

Types

type Attachment

type Attachment struct {
	// Image is drawn in the box, unless Draw draws it.
	Image ui.ImageSource
	// Width and Height are the size of the box in DIPs; zero takes the
	// image's size. A box wider than the editor is scaled down to fit.
	Width, Height float32
	// Name describes the attachment to assistive technology, and stands
	// for it in plain text: an image's alternative text, a file's name.
	Name string
	// URL is where the attachment comes from, as a file's or an image's,
	// which HTML and Markdown write for it.
	URL string
	// Draw draws the attachment in r, instead of Image, as an app's chip
	// for a mention or a file.
	Draw func(p *ui.Painter, r ui.Rect)
	// Data is the app's.
	Data any
}

Attachment is an object inside an Text, as an image in a note: one object replacement character (U+FFFC) whose Attributes hold it, which the editor lays out as a box of its size inside the line, on the baseline, and selects, copies and deletes as one character.

type Attributes

type Attributes struct {
	// Font is a family, as for Element.Font.
	Font string
	// Size is in DIPs.
	Size float32
	// Weight goes from 100 (thin) to 900 (black): 700 is bold.
	Weight        int
	Italic        bool
	Underline     bool
	Strikethrough bool
	// Color colors the text, Background highlights it.
	Color, Background ui.Color
	// Code shows inline code, in the editor's monospaced font. Typing at
	// its edges does not continue it.
	Code bool
	// Link is a URL the run links to. Typing at its edges does not
	// continue it, as in NSTextView.
	Link string
	// Tag is the app's own mark over the run, as a mention or a comment's
	// ID: typing at its edges does not continue it, and the app styles it
	// with EditorOptions.TagStyle.
	Tag string
	// Attachment is what an object replacement character (U+FFFC) shows:
	// an image, or a drawing of the app's, inside the line. Only that
	// character takes it.
	Attachment *Attachment
}

Attributes are the attributes of a run of an Text. What they leave zero takes the style of the editor showing the text (its font, size and color), and Italic, Underline, Strikethrough and Code only turn those on. They are comparable: runs with equal attributes are one.

func (Attributes) Bold

func (a Attributes) Bold() bool

Bold reports whether the run is bold: its weight is 600 or more.

type Document

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

Document is what an Editor edits: a Text, its selection with the attributes typing gets there, and the history of undo, which the app keeps from frame to frame, as it keeps a TextBuffer. Its methods are safe from any goroutine: a toolbar, a menu or a timer formats and edits it while the editor shows it, and the editor follows what changed at its next frame (schedule changes from other goroutines with Window.Update, so that a frame comes).

Commands act on the selection as the editor's shortcuts do: on a range they change its runs or paragraphs, as one step of undo; on a caret, character formats change only the typing attributes, which the next typed text gets and the next move of the caret forgets, as ⌘B does in NSTextView.

func NewDocument

func NewDocument(text Text) *Document

NewDocument returns a document of text, its caret at the end.

func (*Document) BreakUndoCoalescing

func (d *Document) BreakUndoCoalescing()

BreakUndoCoalescing ends the step typing adds to, as at a save, so that what is typed next undoes on its own.

func (*Document) CanRedo

func (d *Document) CanRedo() bool

func (*Document) CanUndo

func (d *Document) CanUndo() bool

CanUndo and CanRedo report whether there is a step to undo or redo.

func (*Document) Edit

func (d *Document) Edit(fn func(e *Edit))

Edit changes the document with fn, as one step of undo, which undoing takes back whole with the selection before it:

doc.Edit(func(e *richtext.Edit) {
	e.ReplaceString(0, 0, "Dear Ann,\n", richtext.Attributes{})
	e.Format(0, 8, func(a *richtext.Attributes) { a.Italic = true })
})

func (*Document) Format

func (d *Document) Format(fn func(a *Attributes))

Format changes the attributes of the selection with fn, as one step of undo, or the typing attributes at a caret.

func (*Document) FormatParagraphs

func (d *Document) FormatParagraphs(fn func(p *ParagraphStyle))

FormatParagraphs changes the styles of the paragraphs selected with fn, as one step of undo.

func (*Document) Formatting

func (d *Document) Formatting() Formatting

Formatting returns the formats of the selection.

func (*Document) Indent

func (d *Document) Indent(levels int)

Indent indents the paragraphs selected by levels, or outdents them for a negative count, as Tab and Shift-Tab do in a list.

func (*Document) Insert

func (d *Document) Insert(text Text)

Insert replaces the selection with text, as a paste does.

func (*Document) InsertAttachment

func (d *Document) InsertAttachment(a *Attachment)

InsertAttachment replaces the selection with an attachment.

func (*Document) InsertText

func (d *Document) InsertText(s string)

InsertText replaces the selection with s, in the typing attributes, as typing does but as a step of undo of its own.

func (*Document) Redo

func (d *Document) Redo()

func (*Document) Selection

func (d *Document) Selection() (anchor, caret int)

Selection returns the selection: anchor is where it started, caret where it ends and the caret is, equal for a caret.

func (*Document) SetAlign

func (d *Document) SetAlign(a ui.Align)

SetAlign aligns the lines of the paragraphs selected.

func (*Document) SetHeading

func (d *Document) SetHeading(level int)

SetHeading makes the paragraphs selected headings of level, from 1, or body paragraphs for 0.

func (d *Document) SetLink(url string)

SetLink links the selection to url, or takes its link away for "". At a caret inside a link, it changes or takes away that link; elsewhere it inserts url, linked to itself.

func (*Document) SetSelection

func (d *Document) SetSelection(anchor, caret int)

SetSelection selects the runes between anchor and caret, or puts the caret at caret when they are equal; the editor scrolls it into view.

func (*Document) SetText

func (d *Document) SetText(text Text)

SetText replaces the text, as when the app opens another note: it is not a step of undo, and clears the history. The selection goes to the end.

func (*Document) SetTypingAttributes

func (d *Document) SetTypingAttributes(a Attributes)

SetTypingAttributes sets the attributes the next typed text gets, until the caret moves.

func (*Document) Text

func (d *Document) Text() Text

Text returns the text of the document, which later edits leave as it is.

func (*Document) ToggleBold

func (d *Document) ToggleBold()

ToggleBold makes the selection bold, or not when all of it is, as ⌘B does.

func (*Document) ToggleChecked

func (d *Document) ToggleChecked(i int)

ToggleChecked checks the task holding rune i, or unchecks it.

func (*Document) ToggleCode

func (d *Document) ToggleCode()

func (*Document) ToggleCodeBlock

func (d *Document) ToggleCodeBlock()

func (*Document) ToggleItalic

func (d *Document) ToggleItalic()

ToggleItalic, ToggleUnderline, ToggleStrikethrough and ToggleCode turn those formats on for the selection, or off when all of it has them.

func (*Document) ToggleList

func (d *Document) ToggleList(kind ListKind)

ToggleList makes the paragraphs selected items of a list of kind, or takes them out of it when all of them are.

func (*Document) ToggleQuote

func (d *Document) ToggleQuote()

ToggleQuote and ToggleCodeBlock make the paragraphs selected a quotation or a block of code, or not when all of them are.

func (*Document) ToggleStrikethrough

func (d *Document) ToggleStrikethrough()

func (*Document) ToggleUnderline

func (d *Document) ToggleUnderline()

func (*Document) TypingAttributes

func (d *Document) TypingAttributes() Attributes

TypingAttributes returns the attributes typing gets at the caret: those a command set at the caret, else those of the character before it (after it at the start of a paragraph), or of the first selected character, without a link, code or tag at their edges, as NSTextView derives them.

func (*Document) Undo

func (d *Document) Undo()

Undo takes back the last step of undo, and Redo the last step undone, restoring the text, its attributes and the selection.

func (*Document) Version

func (d *Document) Version() uint64

Version counts the changes of the document's text.

type Edit

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

Edit changes a document as one step of undo, in Document.Edit. Offsets are into the text as the edit's changes so far left it, and the selection follows them.

func (*Edit) Format

func (e *Edit) Format(start, end int, fn func(a *Attributes))

Format changes the attributes of the runes from start to end.

func (*Edit) FormatParagraphs

func (e *Edit) FormatParagraphs(start, end int, fn func(p *ParagraphStyle))

FormatParagraphs changes the styles of the paragraphs from the one holding start to the one holding end (see Text.FormatParagraphs).

func (*Edit) Replace

func (e *Edit) Replace(start, end int, text Text)

Replace replaces the runes from start to end with text.

func (*Edit) ReplaceString

func (e *Edit) ReplaceString(start, end int, s string, a Attributes)

ReplaceString replaces the runes from start to end with s, which takes attributes a.

func (*Edit) Select

func (e *Edit) Select(anchor, caret int)

Select selects the runes between anchor and caret.

func (*Edit) Selection

func (e *Edit) Selection() (anchor, caret int)

Selection returns the selection as the edit's changes so far moved it.

func (*Edit) Text

func (e *Edit) Text() Text

Text returns the text as the edit's changes so far left it.

type EditorOptions

type EditorOptions struct {
	// Label names the editor to assistive technology; "Rich text" when
	// empty.
	Label string
	// Placeholder shows while the text is empty.
	Placeholder string
	// Font is the text's: its zero fields take the theme's font and size.
	Font ui.Font
	// ReadOnly shows the text without letting the user change it: it is
	// selected and copied, and its links and tasks are clicked.
	ReadOnly bool
	// NoMarkdown turns off the Markdown shortcuts: "# " at the start of a
	// paragraph making a heading, **bold** making bold, and the others.
	NoMarkdown bool
	// OnLink opens the URL of a link clicked, instead of the system,
	// which opens only those ui.SafeToOpen allows.
	OnLink func(url string)
	// OnLinkCommand runs for ⌘K (Ctrl+K), as an app asks for the URL of a
	// link in a popover and sets it with Document.SetLink. Without it,
	// ⌘K links a selected URL to itself.
	OnLinkCommand func()
	// TagStyle styles the runs that carry a Tag, as an app shows mentions
	// or comments.
	TagStyle func(tag string, s *ui.Span)
	// Theme sets how the text looks: colors, code, headings, lists and
	// quotations. What it leaves zero, and all of it when nil, takes the
	// window theme's DefaultTheme.
	Theme *Theme
}

EditorOptions configure an Editor.

type FormatState

type FormatState uint8

FormatState is whether a format holds for a selection: all of it, none, or some of it, as a toolbar's button shows it.

const (
	FormatOff FormatState = iota
	FormatOn
	FormatMixed
)

type Formatting

type Formatting struct {
	// Attributes are those of the first rune selected, or the typing
	// attributes at a caret.
	Attributes                                   Attributes
	Bold, Italic, Underline, Strikethrough, Code FormatState
	// Link is the link all of the selection is in, "" when none is.
	Link string
	// Paragraph is the style of the first paragraph selected, and
	// ParagraphsMixed whether others differ from it.
	Paragraph       ParagraphStyle
	ParagraphsMixed bool
}

Formatting describes the formats of a document's selection, as a toolbar and a Format menu show them: of the runes selected, or of the typing attributes at a caret.

type HeadingStyle

type HeadingStyle struct {
	// Size is their size in ems, and Weight their weight: 700.
	Size   float32
	Weight int
	// Color colors them, the Text color by default.
	Color ui.Color
	// Top is the room above them in ems of their size, unless they start
	// the text: 0.6. Bottom is that below them in ems of the text: 0.25.
	Top, Bottom float32
}

HeadingStyle is how headings of one level look.

type ListKind

type ListKind uint8

ListKind is what a paragraph is an item of.

const (
	NoList ListKind = iota
	// Bullets is an unordered list.
	Bullets
	// Numbers is an ordered list, numbered from 1 among the items of one
	// level next to each other.
	Numbers
	// Tasks is a checklist, whose items are Checked or not.
	Tasks
)

type Paragraph

type Paragraph struct {
	Style ParagraphStyle
	Runs  []Run
}

Paragraph is a paragraph of an Text: its style and its runs, without its newline.

type ParagraphStyle

type ParagraphStyle struct {
	// Heading is the level of a heading, from 1, or 0 for a body
	// paragraph.
	Heading int      `json:"heading,omitempty"`
	List    ListKind `json:"list,omitempty"`
	// Checked marks a task done.
	Checked bool `json:"checked,omitempty"`
	// Indent is how many levels the paragraph is indented: the level of a
	// list's item, from 0.
	Indent int `json:"indent,omitempty"`
	// Align aligns its lines: Start (the default), Center or End.
	Align ui.Align `json:"align,omitempty"`
	// Quote and CodeBlock show the paragraph as a quotation, or as code in
	// the monospaced font, its spaces kept.
	Quote     bool `json:"quote,omitempty"`
	CodeBlock bool `json:"codeBlock,omitempty"`
}

ParagraphStyle is the style of a paragraph of an Text: what it is (a heading, an item of a list, a quote, a block of code) and how its lines align. Lists are flat, as in Quill and Automerge: an item's Indent is its level, and items next to each other make a list.

type Run

type Run struct {
	Text       string
	Attributes Attributes
}

Run is a run of text with its attributes.

type Text

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

Text is text whose runs have attributes of their own, in paragraphs that have a style of their own: what an Editor edits, as Foundation's AttributedString is what SwiftUI's TextEditor edits. It is a value: methods return a new text and leave the one they are called on as it was, sharing what did not change with it, so that keeping a version (for undo, to save it later, to compare) costs a pointer, and a version can be read from any goroutine while others are made. The zero value is the empty text.

Offsets count runes, newlines included, as Element.TextSelection does. Paragraphs end at newlines; the style of a paragraph and the attributes of its newline belong to it, as in word processors, so that an empty paragraph remembers the attributes typing gets there. Runs are kept as long as they can be: neighbors with the same attributes are one run.

func NewText

func NewText(s string) Text

NewText returns s as an Text, without attributes.

func ParseHTML

func ParseHTML(s string) Text

ParseHTML returns the attributed text of an HTML document or fragment, as a paste from a browser, mail or a word processor brings: paragraphs, headings, lists, task lists, quotations, blocks of code, alignment, bold, italic, underline, strikethrough, code and links. Fonts, sizes and colors are left out, as in Notes, so that what is pasted takes the editor's.

func ParseMarkdown

func ParseMarkdown(s string) Text

ParseMarkdown returns the attributed text of Markdown, CommonMark with GitHub's extensions and footnotes, as Markdown writes it: headings, lists and task lists, quotations, blocks of code, bold, italic, strikethrough, code, links, images, and the HTML tags of these marks and of underlines, <u>. A list item's paragraphs after its first are indented under it; a table's rows are paragraphs of their cells apart by tabs, the header's bold. Math, which the editor does not show, stays as written: \[ is an escaped bracket, as everywhere but in math.

func ParseRTF

func ParseRTF(data []byte) Text

ParseRTF returns the attributed text of a document in Rich Text Format, as macOS apps (TextEdit, Pages) and WordPad copy it: paragraphs, their alignment and lists, bold, italic, underline, strikethrough and links. Fonts, sizes and colors are left out, as ParseHTML leaves them.

func TextOf

func TextOf(paragraphs ...Paragraph) Text

TextOf returns an Text of paragraphs. A newline in a run starts another paragraph of the same style.

ui.TextOf(
	ui.Paragraph{Style: ui.ParagraphStyle{Heading: 1}, Runs: []ui.Run{{Text: "Groceries"}}},
	ui.Paragraph{Style: ui.ParagraphStyle{List: ui.Tasks}, Runs: []ui.Run{{Text: "Milk"}}},
)

func (Text) Append

func (t Text) Append(s string, a Attributes) Text

Append returns the text followed by s with attributes a.

func (Text) AttributesAt

func (t Text) AttributesAt(i int) Attributes

AttributesAt returns the attributes of rune i, or those of the end of the text for its length.

func (Text) Delete

func (t Text) Delete(start, end int) Text

Delete returns the text without the runes from start to end.

func (Text) Equal

func (t Text) Equal(u Text) bool

Equal reports whether t and u hold the same text with the same attributes and paragraph styles.

func (Text) Format

func (t Text) Format(start, end int, fn func(a *Attributes)) Text

Format returns the text with fn changing the attributes of the runes from start to end, newlines included. fn cannot add or take away an attachment, which only an object replacement character has.

func (Text) FormatParagraphs

func (t Text) FormatParagraphs(start, end int, fn func(p *ParagraphStyle)) Text

FormatParagraphs returns the text with fn changing the styles of the paragraphs from the one holding start to the one holding end, but for a paragraph end only starts, after a selection of whole paragraphs.

func (Text) HTML

func (t Text) HTML() string

HTML returns t as HTML: paragraphs, headings, lists (task lists with check boxes), quotations and blocks of code, and runs in the tags and styles of their attributes, as browsers, mail and word processors paste it.

func (Text) Insert

func (t Text) Insert(i int, with Text) Text

Insert returns the text with with inserted at rune i.

func (Text) Len

func (t Text) Len() int

Len returns the number of runes of the text, newlines included.

func (Text) Markdown

func (t Text) Markdown() string

Markdown returns t as CommonMark with GitHub's extensions: headings, lists and task lists, quotations, fenced blocks of code, **bold**, *italic*, ~~strikethrough~~, `code`, links and images; underlines are HTML's <u>, which Markdown keeps. Body paragraphs are apart by a blank line, so that they stay paragraphs; alignment, fonts and colors have no Markdown and are left out.

func (Text) MarshalJSON

func (t Text) MarshalJSON() ([]byte, error)

MarshalJSON writes t as JSON, as the clipboard's Format holds it, to save it: paragraphs of a style each, of runs of text and attributes. Attachments keep their names, URLs and sizes; images and drawings are the app's to save.

func (Text) ParagraphCount

func (t Text) ParagraphCount() int

ParagraphCount returns the number of paragraphs: one more than the newlines.

func (Text) ParagraphRange

func (t Text) ParagraphRange(i int) (start, end int)

ParagraphRange returns where the paragraph holding rune i starts and ends, before its newline.

func (Text) ParagraphStyleAt

func (t Text) ParagraphStyleAt(i int) ParagraphStyle

ParagraphStyleAt returns the style of the paragraph holding rune i.

func (Text) Paragraphs

func (t Text) Paragraphs() iter.Seq2[int, Paragraph]

Paragraphs returns the paragraphs of the text, with the rune each starts at.

func (Text) PlainText

func (t Text) PlainText() string

PlainText returns t as plain text, its attachments left out.

func (Text) Replace

func (t Text) Replace(start, end int, with Text) Text

Replace returns the text with the runes from start to end replaced by with. Paragraphs joined or split take the style of the one their first rune comes from, as AppKit fixes paragraph styles: deleting the newline after a heading keeps the heading, and text put at the start of a paragraph brings its own paragraph's style.

func (Text) ReplaceString

func (t Text) ReplaceString(start, end int, s string, a Attributes) Text

ReplaceString returns the text with the runes from start to end replaced by s, which takes attributes a and, for the paragraphs it adds, the style of the paragraph holding start.

func (Text) Runs

func (t Text) Runs(start, end int) iter.Seq2[int, Run]

Runs returns the runs of the text from rune start to rune end, with the rune each starts at: the newline ending a paragraph is a run of its own, or ends the paragraph's last run when it has the same attributes.

func (Text) Same

func (t Text) Same(u Text) bool

Same reports whether t and u are the same version of a text, without comparing them: a text is the same as what it was copied from.

func (Text) Slice

func (t Text) Slice(start, end int) Text

Slice returns the runes from start to end with their attributes and the styles of their paragraphs.

func (Text) String

func (t Text) String() string

String returns the text without its attributes.

func (*Text) UnmarshalJSON

func (t *Text) UnmarshalJSON(b []byte) error

UnmarshalJSON reads what MarshalJSON wrote.

type Theme

type Theme struct {
	// Text colors text, Muted the placeholder, the text of tasks done and
	// the boxes of those to do, and Link links.
	Text, Muted, Link ui.Color
	// Caret colors the caret, and Selection is behind the text selected.
	Caret, Selection ui.Color

	// CodeFont is the family of code, the system's monospaced font when
	// empty, and CodeSize its size in ems: 0.92. Code colors code, within
	// text and in blocks, the Text color by default.
	CodeFont string
	CodeSize float32
	Code     ui.Color
	// CodeBackground is behind code within text, which it hugs with
	// rounded corners.
	CodeBackground ui.Color
	// CodeBlockBackground fills blocks of code, with corners of
	// CodeBlockRadius ems (0.3) and CodeBlockPadding ems of room inside:
	// 0.7 across, and 0.5 at their top and bottom.
	CodeBlockBackground ui.Color
	CodeBlockRadius     float32
	CodeBlockPadding    [2]float32

	// Headings are the styles of headings of levels 1 to 6.
	Headings [6]HeadingStyle

	// Indent is how far a level of a list or of indentation goes, in ems,
	// a list's markers in that room: 1.7.
	Indent float32
	// Marker colors the bullets and numbers of lists, the Text color by
	// default. Checkbox fills the boxes of tasks done, and Checkmark draws
	// their checks: white.
	Marker, Checkbox, Checkmark ui.Color
	// QuoteBar colors the bar along quotations, QuoteBarWidth DIPs wide
	// (3), and QuoteText their text, the Muted color by default.
	QuoteBar, QuoteText ui.Color
	QuoteBarWidth       float32

	// Padding is the room around the text of an Editor, in DIPs across
	// and down: the window theme's Space(3) and Space(2.5). An EditorBase
	// has none, its room the app's.
	Padding [2]float32
}

Theme is how the editor's text looks: its colors, the font of code, the styles of headings, and the room of lists, quotations and blocks of code. What it leaves zero takes the value of DefaultTheme for the window's theme, so that a theme sets only what it changes:

richtext.Editor(c, doc, richtext.EditorOptions{Theme: &richtext.Theme{Link: ui.Hex("#7c3aed")}})

Lengths in ems are times the editor's font size (EditorOptions.Font).

func DefaultTheme

func DefaultTheme(t *ui.Theme) *Theme

DefaultTheme returns the editor's theme in a window's theme: its text, muted, accent, selection and border colors, code tinted with its text color, and headings from 1.8 times the text down to 0.9.

Jump to

Keyboard shortcuts

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