sheet

package
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Sep 30, 2026 License: MIT Imports: 28 Imported by: 0

Documentation

Overview

Package sheet is the spreadsheet engine: cell storage, formula parsing and dependency-ordered recalculation. It has no knowledge of the terminal UI.

Index

Constants

View Source
const (
	MinChartW, MinChartH = 20, 8
	MaxChartW, MaxChartH = 240, 120
)

Chart size limits, in terminal cells.

View Source
const (
	MaxCols = formula.MaxCols
	MaxRows = formula.MaxRows
)

Worksheet bounds, matching Lotus 1-2-3 Release 2 (A..IV, 1..8192).

View Source
const (
	Empty  = value.Empty
	Number = value.Number
	Text   = value.Text
	Bool   = value.Bool
	Error  = value.Error
)

Kinds of values.

View Source
const (
	FmtAuto       = value.FmtAuto
	FmtText       = value.FmtText
	FmtNumber     = value.FmtNumber
	FmtPercent    = value.FmtPercent
	FmtScientific = value.FmtScientific
	FmtAccounting = value.FmtAccounting
	FmtFinancial  = value.FmtFinancial
	FmtCurrency   = value.FmtCurrency
	FmtDate       = value.FmtDate
	FmtTime       = value.FmtTime
	FmtDateTime   = value.FmtDateTime
	FmtDuration   = value.FmtDuration
	FmtCustom     = value.FmtCustom
	FmtSize       = value.FmtSize

	// MaxDecimals caps Increase decimal places.
	MaxDecimals = value.MaxDecimals
)

Number formats.

View Source
const DefaultMaxCells = 10_000_000

DefaultMaxCells is the max-cells setting's default: about 200 MB of numbers at 20 bytes each (store.go).

View Source
const DefaultWidth = 10

DefaultWidth is the initial column width: nine characters plus padding.

View Source
const FileExt = ".012"

FileExt is the extension of the native worksheet format.

View Source
const MacroAPI = 1

MacroAPI is the version of the scripting API macros are written for. A file records it with each macro, so a later build that changes the API can tell old scripts from new ones.

View Source
const MaxFrozen = 50

MaxFrozen caps frozen rows and columns, as Sheets' View > Freeze does in practice: more than a screenful can't stay on screen anyway.

View Source
const MaxNote = 4096

MaxNote caps a note's length in bytes, so a file or a paste can't make one without bound.

View Source
const MaxRowHeight = 50

MaxRowHeight caps a row's height in lines.

View Source
const MaxStepBytes = 1 << 30

MaxStepBytes is the most undo history one change may hold without asking: the UI asks before a change its UndoCost puts over it, and runs it WithoutUndo if told to go on. Plain cells cost about 20 B each, so only millions of formulas or of distinct long texts come near it.

View Source
const MaxUndo = 100

MaxUndo is how many steps of undo history a workbook keeps, at most; MaxUndoBytes also bounds it.

View Source
const MaxUndoBytes = 256 << 20

MaxUndoBytes caps the memory the undo history's before-images hold, as estimated by step.size. When a new step takes the history past it, the oldest steps are dropped first; the newest step is always kept, however large, so any single change can be undone (a step past MaxStepBytes asks first). 256 MB holds a step clearing a full max-cells sheet of numbers, about 195 MB, and MaxUndo steps rewriting a whole column of 8192 take 16 MB (see docs/contributing/limits.md).

View Source
const NumColors = int(numColors)

NumColors is how many colors there are, ColorNone included, for tables indexed by Color.

Variables

View Source
var (
	// ErrMergeOne is why a single cell can't be merged.
	ErrMergeOne = errors.New("Select more than one cell to merge")
	// ErrMergeMany is why merging a whole column's rows is refused.
	ErrMergeMany = fmt.Errorf("That would make more than %d merged cells", maxMerges)
	// ErrSortMerged is why a range holding merged cells isn't sorted.
	ErrSortMerged = errors.New("Can't sort a range with merged cells; unmerge them first")
)
View Source
var (
	// OnBegin, when set, is called as a recalculation ("recalc") or a
	// pivot table refresh ("pivot") begins; OnRecalc or OnPivot as it
	// ends. They pair up like parentheses: a recalculation holds the
	// pivot refreshes it causes, which follow its own evaluation.
	OnBegin func(trace any, op string)
	// OnRecalc, when set, is called after every recalculation of any
	// workbook.
	OnRecalc func(trace any, i RecalcInfo)
)

The engine knows nothing of logging; cmd/012 points these hooks at telemetry. They run on the goroutine that changed the workbook and must be cheap. trace is the workbook's (see SetTrace), handed back so the engine's work is timed as spans nested in whatever the workbook's owner has open: a command, an import, a macro run.

View Source
var (
	ErrPushedOff  = errors.New("There's data at the edge of the sheet that would be pushed off")
	ErrPasteEdge  = errors.New("The paste doesn't fit: it would go past the edge of the sheet")
	ErrFillTooBig = errors.New("That would write more cells than max-cells allows (see File > Settings)")
)

Errors returned by operations that would lose data or don't fit.

View Source
var (
	// ErrOutputEdit is what typing into a sent output's cell says.
	ErrOutputEdit = errors.New("That cell shows a notebook cell's output: change the cell, or freeze the region to edit its values")
	// ErrNoRegion is returned for a region the workbook doesn't hold:
	// deleted, unlinked, undone, or on a sheet deleted.
	ErrNoRegion = errors.New("There's no region by that name")
)

Errors of regions.

View Source
var (
	// Pending is shown while an answer is on its way.
	Pending = functions.Pending
	// ErrNoRemote means JEV functions can't run: there is no API key.
	ErrNoRemote = functions.ErrNoRemote
	// ErrRemote is a question the model couldn't answer.
	ErrRemote = functions.ErrRemote
)
View Source
var (
	// ErrSourceEdit is what typing into a source's tab says.
	ErrSourceEdit = errors.New("A linked source is read-only: its rows are the file's")
	// ErrNoSource is returned for a source the workbook doesn't hold.
	ErrNoSource = errors.New("There's no linked source by that name")
)

Errors of sources.

View Source
var (
	ErrNoTable      = errors.New("There's no table by that name")
	ErrTableOverlap = errors.New("A table can't overlap another table, a region or a pivot table")
)

Errors of tables.

View Source
var (
	ErrDiv0  = value.ErrDiv0
	ErrValue = value.ErrValue
	ErrName  = value.ErrName
	ErrNA    = value.ErrNA
	ErrNum   = value.ErrNum
	ErrRef   = value.ErrRef // also circular references
)

Error values, using Google Sheets codes.

View Source
var ChartTypes = func() []ChartType {
	out := make([]ChartType, len(chartTypeNames))
	for i := range out {
		out[i] = ChartType(i)
	}
	return out
}()

ChartTypes lists the types in the order the chart editor offers them.

View Source
var ErrLinkedEdit = errors.New("That cell shows part of a linked file: unlink it (Data > Linked file > Unlink) to edit it")

ErrLinkedEdit is what typing into a linked file's cell says.

View Source
var (
	// ErrPivotEdit is what editing a pivot table's results says, as
	// Sheets refuses to.
	ErrPivotEdit = errors.New("Pivot table results can't be edited: change the pivot with Data > Edit pivot table")
)

Errors of pivot tables.

View Source
var ErrSpillEdit = errors.New("That cell holds part of an array result: edit the formula it spills from")

ErrSpillEdit is what typing into a spilled cell says: its value belongs to the formula that spilled it.

View Source
var ErrWhole = errors.New("this change does more than set cells: it can only be accepted whole")

ErrWhole is returned when part of a proposal that must be made whole is picked.

View Source
var OnLive func(trace any, i LiveInfo)

OnLive, when set, is called after every op applied, like OnRecalc (see OnBegin, whose op is "live").

View Source
var OnPivot func(trace any, i PivotInfo)

OnPivot, when set, is called after every pivot recomputation, like OnRecalc (see OnBegin).

Functions

func CanonicalArg added in v0.3.0

func CanonicalArg(arg string, loc *locale.Locale) string

CanonicalArg is the argument of a rule or filter condition typed in loc as it's stored: a number or date in en-US's form, a formula (after =) in its syntax, text as typed.

func CanonicalEntry added in v0.3.0

func CanonicalEntry(typed string, loc *locale.Locale) string

CanonicalEntry is an entry typed in loc as the cell stores it: numbers, dates and times in en-US's form, formulas with its separators, text as typed, behind a ' when it would read as something else stored (1.5, typed as text in fr-FR).

func CleanNote added in v0.2.0

func CleanNote(text string) string

CleanNote tidies a note as SetNote stores it: control characters other than line breaks dropped, trailing space trimmed, at most MaxNote bytes.

func ColName

func ColName(c int) string

ColName converts a zero-based column index to letters: 0 -> A, 26 -> AA.

func CondArg added in v0.3.0

func CondArg(op CondOp, typed string, loc *locale.Locale) string

CondArg is a condition's value typed in loc as it's kept: as typed for a condition on text, as CanonicalArg for the rest.

func DefaultLocale added in v0.3.0

func DefaultLocale() *locale.Locale

DefaultLocale is the locale of workbooks that don't name one.

func EntryValue added in v0.3.0

func EntryValue(input string) (Value, Format)

EntryValue is the value and the format an entry implies ("$5", a date), as typing it into a cell would store them, for a source whose rows arrive as text. Formulas stay text, as a data file's should.

func EscapeColumn added in v0.3.0

func EscapeColumn(name string) string

EscapeColumn writes a table column's name as a structured reference holds it, with ' before each of [ ] # and '.

func FitWidth added in v0.5.0

func FitWidth(text string) int

FitWidth is how wide fitting a table (LoadFitWidths) makes a column for text: its characters and a space either side, capped.

func FormatNumber

func FormatNumber(v float64, width int) string

FormatNumber formats a number in the General format within width columns, for use outside the grid (e.g. the status line).

func FormatPattern

func FormatPattern(v float64, pat string) string

FormatPattern renders v with a number format pattern, as TEXT() does.

func FormatText

func FormatText(v Value, f Format) string

FormatText renders v under f with no width limit, e.g. for TEXT() or copying out of the grid.

func FormatTextIn added in v0.3.0

func FormatTextIn(v Value, f Format, loc *locale.Locale) string

FormatTextIn is FormatText as shown in loc, e.g. for a CSV file written in loc.

func FormatValue

func FormatValue(v Value, width int) string

FormatValue renders v in width columns with one column of padding, the way the grid shows it in Automatic format: numbers right-aligned, booleans and errors centered. Text is not handled here because it can overflow into neighboring cells.

func IsFormulaEntry

func IsFormulaEntry(input string) bool

IsFormulaEntry reports whether input is written as a formula: it starts with "=", or with "+" or "-" followed by something that isn't a plain number (as Sheets accepts "+A1").

func IsPending

func IsPending(v Value) bool

IsPending reports whether v is waiting for a remote answer.

func IsPeriod added in v0.3.0

func IsPeriod(arg string) bool

IsPeriod reports whether a date rule's value names a period (or a day relative to today) rather than a date.

func LocalArg added in v0.3.0

func LocalArg(arg string, loc *locale.Locale) string

LocalArg is the inverse of CanonicalArg, for editing an argument again.

func LocalCondArg added in v0.3.0

func LocalCondArg(op CondOp, arg string, loc *locale.Locale) string

LocalCondArg is the inverse of CondArg, for editing a value again.

func LocalEntry added in v0.3.0

func LocalEntry(input string, loc *locale.Locale) string

LocalEntry is the inverse of CanonicalEntry: a cell's entry as typed in loc, as the formula bar shows it and editing starts from.

func LocalizeError added in v0.3.0

func LocalizeError(err error, loc *locale.Locale) error

LocalizeError writes a formula's parse error, alone or wrapped, as the formula was typed in loc: "Expected ; or ) in ROUND" in de-DE.

func MaxCells

func MaxCells() int

MaxCells returns the cell budget.

func ParseCol

func ParseCol(s string) (int, bool)

ParseCol converts column letters (case-insensitive) to a zero-based index.

func ParseNumber

func ParseNumber(s string) (float64, bool)

ParseNumber recognizes numbers the way Google Sheets does on entry.

func Periods added in v0.3.0

func Periods() []string

Periods lists the words a date rule takes, in the order the rules editor's hint gives them.

func PivotCols added in v0.6.0

func PivotCols(p Pivot) []int

PivotCols are the source columns a pivot reads, for a source to stream no others.

func Qualified

func Qualified(sheet string, r Rect) string

Qualified writes r on sheet as a formula would: Sheet2!A1:B3.

func QuoteSheet

func QuoteSheet(name string) string

QuoteSheet writes a sheet name as a formula needs it, e.g. 'Q3 plan'.

func RangesText added in v0.2.0

func RangesText(rs []Rect) string

RangesText writes ranges as ParseRanges reads them.

func SetDefaultLocale added in v0.3.0

func SetDefaultLocale(l *locale.Locale)

SetDefaultLocale sets the locale of workbooks that don't name one of their own; nil is en-US.

func SetMaxCells

func SetMaxCells(n int)

SetMaxCells sets the cell budget; n < 1 restores the default.

func ShiftEntry

func ShiftEntry(input string, dc, dr int) (string, error)

ShiftEntry returns an entry as if it were typed in one cell and copied dc columns and dr rows away: a formula's relative references move and $absolute ones stay, as in a paste. Other entries come back unchanged. A macro recorded with relative references replays formulas this way.

func SplitSheet

func SplitSheet(s string) (sheet, rest string)

SplitSheet splits a reference such as "'Q3 plan'!B2" into the sheet name, unquoted, and the rest.

func ValidMacroName

func ValidMacroName(name string) error

ValidMacroName reports why name can't name a macro, or nil.

func ValidName

func ValidName(name string) error

ValidName checks that name can be a named range, following Sheets' rules: letters, digits, _ and ., starting with a letter or _, and not something a formula would read as a cell or a boolean.

func ValidRegionName added in v0.3.0

func ValidRegionName(name string) error

ValidRegionName checks that name can name a region: a nushell variable's name of letters, digits and _, not starting with a digit, as a notebook cell's name is.

func ValidSheetName

func ValidSheetName(name string) error

ValidSheetName checks a name for a sheet, following Excel's rules (a superset of what Sheets accepts is fine to read, but names written by 012 must open in Excel too).

func ValidTableName added in v0.3.0

func ValidTableName(name string) error

ValidTableName checks that name can name a table: a named range's rules, except that only a name Excel reads as a cell is refused, so Table1 is one; and not starting with nu., which regions' names use.

Types

type Addr

type Addr = formula.Addr

Addr identifies a cell by zero-based column and row.

func ParseAddr

func ParseAddr(s string) (Addr, bool)

ParseAddr parses an A1-style reference, ignoring absolute markers.

type Align

type Align uint8

Align is a cell's horizontal alignment.

const (
	AlignAuto   Align = iota // numbers right, text left, booleans and errors centered
	AlignLeft                //
	AlignCenter              //
	AlignRight               //
	// AlignFill is only returned by Display: the text spans the cell
	// exactly and isn't padded (Accounting's $ at the left edge).
	AlignFill
)

func Display

func Display(v Value, f Format, width int) (string, Align)

Display renders v under format f for a cell width columns wide, as the grid shows it: the text without padding, and where it goes. Numbers go right, text left, booleans and errors center. A formatted number that doesn't fit in width-1 columns becomes a run of #, as in Sheets; Automatic first drops decimals and falls back to scientific notation. Accounting returns AlignFill: exactly width columns, $ at the left.

func DisplayIn added in v0.3.0

func DisplayIn(v Value, f Format, width int, loc *locale.Locale) (string, Align)

DisplayIn is Display as shown in loc: its separators, currency and date order (see Format.CodeIn).

func ParseAlign

func ParseAlign(s string) (Align, bool)

ParseAlign is the inverse of Align.String.

func (Align) String

func (a Align) String() string

String returns the alignment's name as stored in files.

type AskKind added in v0.6.0

type AskKind uint8

AskKind is what a SourceQuestion asks.

const (
	// AskCell asks a cell's value: At, on the source's tab.
	AskCell AskKind = iota
	// AskRange asks the values of a range, R, as an array: read whole,
	// so no bigger than the host's budget.
	AskRange
	// AskCall asks what a function computes, Call, its ranges named by
	// their sources' names.
	AskCall
	// AskPivot asks a pivot table's groups over the source, Pivot.
	AskPivot
)

type Blocked added in v0.5.0

type Blocked struct {
	Author int
	Label  string
}

Blocked is a later step that keeps an author's step from being undone or redone: whose it is, and what it did.

type BorderKind added in v0.3.0

type BorderKind uint8

BorderKind is which edges of a range Format > Borders sets.

const (
	BorderAll    BorderKind = iota // every edge of every cell
	BorderOuter                    // the range's outline
	BorderInner                    // the edges between its cells
	BorderTop                      // its top edge
	BorderBottom                   //
	BorderLeft                     //
	BorderRight                    //
	BorderNone                     // no edges: removes every line
)

func ParseBorderKind added in v0.3.0

func ParseBorderKind(s string) (BorderKind, bool)

ParseBorderKind is the inverse of BorderKind.String.

func (BorderKind) String added in v0.3.0

func (k BorderKind) String() string

String names the kind, as undo labels and macros write it.

type Borders added in v0.3.0

type Borders uint32

Borders are the lines on a cell's four edges, two bits each in the low byte, and their colors, four bits each above: ColorNone draws in the ink of the text (see Color and theme.CellBorder).

func BordersOf added in v0.3.0

func BordersOf(top, bottom, left, right Line) Borders

BordersOf is the borders with these lines.

func (Borders) Bottom added in v0.3.0

func (b Borders) Bottom() Line

func (Borders) Color added in v0.3.0

func (b Borders) Color(e Edge) Color

Color is the color of edge e's line.

func (Borders) IsZero added in v0.3.0

func (b Borders) IsZero() bool

IsZero reports whether no edge has a line.

func (Borders) Left added in v0.3.0

func (b Borders) Left() Line

func (Borders) Line added in v0.3.0

func (b Borders) Line(e Edge) Line

Line is the line on edge e.

func (Borders) Right added in v0.3.0

func (b Borders) Right() Line

func (Borders) Stroke added in v0.3.0

func (b Borders) Stroke(e Edge) Stroke

Stroke is edge e's line and color.

func (Borders) Top added in v0.3.0

func (b Borders) Top() Line

func (Borders) With added in v0.3.0

func (b Borders) With(e Edge, l Line) Borders

With is b with edge e drawn with l, in the color it had; no line has no color.

func (Borders) WithColor added in v0.3.0

func (b Borders) WithColor(e Edge, c Color) Borders

WithColor is b with edge e's line in color c.

func (Borders) WithStroke added in v0.3.0

func (b Borders) WithStroke(e Edge, st Stroke) Borders

WithStroke is b with edge e drawn as st.

type Cell

type Cell struct {
	// Input is the entry exactly as typed: text, a number such as "$1,200"
	// or "12%", or a formula starting with "=". Empty for a blank cell
	// that only has formatting.
	Input string
	Value Value

	// Format and Style are plain values, so copying a Cell copies its
	// formatting. They survive clearing the contents, as in Sheets.
	// Style is kept at the end, with the flags, where it fits in what
	// alignment would otherwise pad, so a Cell stays 256 bytes.
	Format Format

	// Note is the cell's note, as Sheets' Insert > Note: text shown when
	// the cell is active or hovered. Like formatting, it survives clearing
	// the contents, and it moves and copies with the cell.
	Note string

	Style Style
	// contains filtered or unexported fields
}

Cell holds what the user typed, what it evaluates to, and how it is formatted. A cell may have formatting but no contents (Sheets lets you format blank cells before typing); such a cell counts as blank everywhere contents matter.

func (*Cell) Blank

func (c *Cell) Blank() bool

Blank reports whether the cell has no contents (it may still have formatting).

func (*Cell) IsFormula

func (c *Cell) IsFormula() bool

IsFormula reports whether the cell holds a formula.

func (*Cell) Spilled added in v0.2.0

func (c *Cell) Spilled() bool

Spilled reports whether the cell shows part of an array another cell's formula computed (see SpillAnchor).

type Change

type Change struct {
	Label string
	Focus Rect
	Sheet *Sheet
	// Tabs is set when the step added, deleted, renamed or moved sheets;
	// Focus means nothing then.
	Tabs bool
	// Macros is set when the step changed nothing but the macros; Focus
	// means nothing then either.
	Macros bool
}

Change describes an undo step: what it did, in lower case for use in a sentence ("clear B3:B5"), the sheet it happened on and the range it affected there.

type Chart

type Chart struct {
	Type ChartType
	Data Rect
	// ByRow puts each series in a row instead of a column, like Sheets'
	// "Switch rows / columns".
	ByRow bool
	// Header takes series names from the first row of the data (the first
	// column when ByRow).
	Header bool
	// Labels takes category labels from the first column of the data (the
	// first row when ByRow).
	Labels bool
	Title  string
	At     Addr // the cell under the top-left corner
	W, H   int  // size in terminal cells
	// ChartOptions are the stacking, axis and legend settings of Sheets'
	// Customize tab; see chartopts.go.
	ChartOptions
}

Chart is a chart floating over the grid.

func ParseChart added in v0.3.0

func ParseChart(line string) (Chart, error)

ParseChart reads a chart written by JSON.

func (Chart) JSON added in v0.3.0

func (c Chart) JSON() string

JSON is the chart as a line of the file.

type ChartData

type ChartData struct {
	Categories []string
	Series     []ChartSeries
	Format     Format
}

ChartData is what a chart draws: category labels and series of the same length, and the number format of the values, for axis labels.

type ChartFate

type ChartFate struct {
	Name     string // the chart's title, or Chart 1, Chart 2 by position
	Was, Now Rect   // the range it drew, and draws
	// Removed is set when the range no longer fits the new data: it
	// holds nothing now, or it was a whole table and the new sheet's
	// table there has other series.
	Removed bool
}

ChartFate says what replacing a sheet did to one of its charts.

type ChartLegend added in v0.2.0

type ChartLegend int

ChartLegend is where a chart's legend goes.

const (
	LegendBottom ChartLegend = iota // under the plot, centered
	LegendRight                     // a column right of the plot
	LegendNone                      // no legend
)

func ParseChartLegend added in v0.2.0

func ParseChartLegend(s string) (ChartLegend, bool)

ParseChartLegend parses a position as String writes it.

func (ChartLegend) String added in v0.2.0

func (l ChartLegend) String() string

String is the position as files store it.

type ChartOptions added in v0.2.0

type ChartOptions struct {
	// Stack stacks the series of column, bar and area charts.
	Stack ChartStack
	// Trend draws a linear trend line through each series of a scatter
	// chart.
	Trend bool
	// Min and Max fix the ends of the value axis when HasMin and HasMax
	// are set; otherwise the axis fits the data.
	Min, Max       float64
	HasMin, HasMax bool
	// Log puts the value axis on a logarithmic scale, leaving out values
	// that aren't positive.
	Log bool
	// NoGrid hides the gridlines.
	NoGrid bool
	// Legend is where the legend goes.
	Legend ChartLegend
}

ChartOptions are a chart's settings beyond its type and data, as in the Customize tab of Sheets' chart editor. The zero value is Sheets' default: not stacked, no trend line, an automatic linear value axis with gridlines, and the legend at the bottom. Every field is a plain value, so charts stay comparable with ==.

type ChartSeries

type ChartSeries struct {
	Name   string
	Values []float64
}

ChartSeries is one named run of values. Blank and non-numeric cells are NaN, drawn as gaps.

type ChartStack added in v0.2.0

type ChartStack int

ChartStack is how the series of a chart pile up.

const (
	StackNone    ChartStack = iota // side by side
	StackNormal                    // on top of each other
	StackPercent                   // on top of each other, as shares of 100%
)

func ParseChartStack added in v0.2.0

func ParseChartStack(s string) (ChartStack, bool)

ParseChartStack parses a stacking as String writes it.

func (ChartStack) String added in v0.2.0

func (s ChartStack) String() string

String is the stacking as files store it, "" for none.

func (ChartStack) Title added in v0.2.0

func (s ChartStack) Title() string

Title is the stacking as the chart editor shows it.

type ChartType

type ChartType int

ChartType is how a chart draws its series. Adding one takes a constant here and its name in chartTypeNames; the chart editor, the file format and ChartTypes follow from the table, and internal/chart draws it.

const (
	ChartColumn  ChartType = iota // vertical bars, one group per category
	ChartBar                      // horizontal bars
	ChartLine                     // one line per series
	ChartPie                      // the first series as slices of a whole
	ChartArea                     // lines filled down to the axis
	ChartScatter                  // points at X, Y: the first series is X
)

func ParseChartType

func ParseChartType(s string) (ChartType, bool)

ParseChartType parses a type name as String writes it.

func (ChartType) Stackable added in v0.2.0

func (t ChartType) Stackable() bool

Stackable reports whether charts of type t can stack their series.

func (ChartType) String

func (t ChartType) String() string

func (ChartType) Title

func (t ChartType) Title() string

Title is the type's name as the chart editor shows it, e.g. "Column".

type Clip

type Clip struct {
	Range Rect // the range copied
	Src   Rect // Range trimmed to its cells when whole lines
	// contains filtered or unexported fields
}

Clip is a copied range: snapshots of its cells, and of the formatting they show, taken at copy time.

func (*Clip) MoveRange

func (c *Clip) MoveRange(to Addr) Rect

MoveRange is the range cutting c moves when pasted at to: the whole lines copied when to starts a line, else the copied cells.

func (*Clip) Size

func (c *Clip) Size() (cols, rows int)

Size returns the clip's width and height in cells.

func (*Clip) TextIn added in v0.3.0

func (c *Clip) TextIn(loc *locale.Locale) [][]string

TextIn returns the clip's values as General shows them in loc, row by row, for the system clipboard. Blank rows and columns past the last value are left off, so copying whole columns gives their data; a block of more than MaxCells cells, blanks between values included, is too big for text, and TextIn returns nil.

type Color added in v0.2.0

type Color uint8

Color is one of the named colors rules draw with. Each is an ANSI color slot, so the terminal's palette or the color scheme applies: the UI maps them to theme roles, never to fixed RGB.

const (
	ColorNone Color = iota
	ColorRed
	ColorYellow
	ColorGreen
	ColorCyan
	ColorBlue
	ColorMagenta
)

func Colors added in v0.2.0

func Colors() []Color

Colors lists the named colors, ColorNone first, in the order the rules editor offers them.

func ParseColor added in v0.2.0

func ParseColor(s string) (Color, bool)

ParseColor is the inverse of Color.String, ignoring case.

func (Color) String added in v0.2.0

func (c Color) String() string

String names the color as files store it; "" for none.

func (Color) Title added in v0.2.0

func (c Color) Title() string

Title names the color for people, e.g. "Green", or "None".

type CondFormat added in v0.2.0

type CondFormat struct {
	Ranges []Rect
	// Op is the test of a single-color rule and Args its values, as
	// typed: "100", "=B2" (a formula, relative to the first range's
	// top-left cell as a copied formula would be), a date, or for
	// RuleFormula the formula, e.g. "=$C2>100".
	Op    RuleOp
	Args  [2]string
	Style RuleStyle
	// Scale, when set, makes the rule a color scale of 2 or 3 points,
	// lowest first, and Op, Args and Style mean nothing. A data bar's
	// and an icon set's points are kept here too (condbars.go).
	Scale []ScalePoint
	// Bar, when set, makes the rule a data bar in that color, from its
	// first point to its second.
	Bar Color
	// Icons, when set, makes the rule an icon set, one icon more than
	// its points, which are the thresholds of the icons after the first.
	Icons IconSet
	// Reverse gives the icons the other way round, the lowest icon to
	// the highest values.
	Reverse bool
	// BarOnly shows a data bar or icon without the cell's value.
	BarOnly bool
}

CondFormat is a conditional format rule.

func ParseCondFormat added in v0.2.0

func ParseCondFormat(line string) (CondFormat, error)

ParseCondFormat reads a rule written by JSON, checking it.

func (CondFormat) Check added in v0.2.0

func (f CondFormat) Check() error

Check reports why a rule can't be used, in words for the rules editor.

func (CondFormat) IsBar added in v0.3.0

func (f CondFormat) IsBar() bool

IsBar reports whether the rule is a data bar.

func (CondFormat) IsIcons added in v0.3.0

func (f CondFormat) IsIcons() bool

IsIcons reports whether the rule is an icon set.

func (CondFormat) IsScale added in v0.2.0

func (f CondFormat) IsScale() bool

IsScale reports whether the rule is a color scale.

func (CondFormat) JSON added in v0.2.0

func (f CondFormat) JSON() string

JSON writes the rule as a line of the file, e.g. {"ranges":"B2:B20","condition":"gt","values":["100"],"fill":"green"}.

func (CondFormat) Summary added in v0.2.0

func (f CondFormat) Summary() string

Summary describes the rule in a few words, e.g. "Greater than 100".

type CondOp

type CondOp uint8

CondOp is one of Sheets' filter conditions.

const (
	CondNone CondOp = iota
	CondEmpty
	CondNotEmpty
	CondContains
	CondNotContains
	CondStartsWith
	CondEndsWith
	CondExactly
	CondGreater
	CondGreaterEq
	CondLess
	CondLessEq
	CondEqual
	CondNotEqual
)

func CondOps

func CondOps() []CondOp

CondOps lists the conditions in the order Sheets' menu shows them.

func ParseCondOp

func ParseCondOp(s string) (CondOp, bool)

ParseCondOp is the inverse of CondOp.String.

func (CondOp) OnText added in v0.3.0

func (op CondOp) OnText() bool

OnText reports whether the condition tests the text a cell shows (contains, starts with ...), which is in the locale's rendering, so its value is kept as typed rather than read as a number or date.

func (CondOp) String

func (op CondOp) String() string

String names the condition as stored in files.

func (CondOp) TakesArg

func (op CondOp) TakesArg() bool

TakesArg reports whether the condition compares with a value.

func (CondOp) Title

func (op CondOp) Title() string

Title names the condition for people, e.g. "Greater than".

type Condition

type Condition struct {
	Op  CondOp
	Arg string // the value compared with, as typed; unused by CondEmpty and CondNotEmpty
}

Condition is a test on a cell, e.g. "greater than 100".

func (Condition) Matches

func (c Condition) Matches(v Value, shown string) bool

Matches reports whether a cell with value v, shown as shown, meets the condition, as the filter tests it.

func (Condition) Test added in v0.6.0

func (c Condition) Test() func(v Value, shown string) bool

Test compiles the condition, for what filters rows outside a sheet (a linked source's view): see test.

type Criteria

type Criteria struct {
	Hidden []string
	Cond   Condition
}

Criteria is what one column of a filter lets through: its displayed value must not be one of Hidden (Sheets' "Filter by values", unchecked values; "" stands for blanks) and must meet Cond ("Filter by condition").

func ParseCriteria added in v0.3.0

func ParseCriteria(line string) (Criteria, error)

ParseCriteria reads criteria written by JSON.

func (Criteria) IsZero

func (c Criteria) IsZero() bool

IsZero reports whether the criteria let every row through.

func (Criteria) JSON added in v0.3.0

func (cr Criteria) JSON() string

JSON is the criteria as a filter column's are written in the file: the values hidden, and a condition and its value.

type DropDisplay added in v0.3.0

type DropDisplay uint8

DropDisplay is how a dropdown's cells show that they have one.

const (
	DropArrow DropDisplay = iota // ▾ at the cell's right
	DropChip                     // the value on a chip, with its ▾, as Sheets draws them
	DropPlain                    // the value alone; Alt+Down still opens the list

)

func DropDisplays added in v0.3.0

func DropDisplays() []DropDisplay

DropDisplays lists the displays in the order the rules editor offers them.

func ParseDropDisplay added in v0.3.0

func ParseDropDisplay(s string) (DropDisplay, bool)

ParseDropDisplay is the inverse of DropDisplay.String.

func (DropDisplay) String added in v0.3.0

func (d DropDisplay) String() string

func (DropDisplay) Title added in v0.3.0

func (d DropDisplay) Title() string

Title names the display for people, e.g. "Chip".

type Edge added in v0.3.0

type Edge uint8

Edge is one of a cell's edges.

const (
	EdgeTop Edge = iota
	EdgeBottom
	EdgeLeft
	EdgeRight
)

type Filter

type Filter struct {
	Range Rect
	Cols  map[int]Criteria // by column; a column without criteria hides nothing
}

A filter hides the rows of a range whose values don't meet criteria set per column, as Sheets' Data > Create a filter. Rows are hidden, never deleted: formulas still see them (SUM over a filtered range includes hidden rows, as in Sheets). The range's first row holds the headers and is never hidden. Criteria are re-applied whenever values change.

type FilterValue

type FilterValue struct {
	Text  string // as en-US shows it, as filters keep it; "" for blanks
	Label string // as the sheet's locale shows it, for the list
	Count int
	Shown bool
}

FilterValue is one entry of a filter's values list: a value as shown, how many rows have it, and whether it is checked (shown).

type FindOptions

type FindOptions struct {
	MatchCase  bool
	WholeCell  bool  // the whole cell must match, not just part of it
	Regex      bool  // the query is a regular expression; replacements may use $1
	InFormulas bool  // search formula text instead of formula results
	Within     *Rect // limit the search to a range; nil searches the sheet
}

FindOptions mirror Google Sheets' Find and replace dialog.

type Format

type Format = value.Format

Format is a cell's number format.

func ParseValue

func ParseValue(s string) (float64, Format, bool)

ParseValue recognizes everything Sheets turns into a number on entry: numbers, currency, percentages, dates and times, with the format Sheets applies.

func Preset

func Preset(k FormatKind) Format

Preset returns kind with Sheets' default decimals: two for the number kinds.

type FormatKind

type FormatKind = value.FormatKind

FormatKind is a number format from Sheets' Format > Number menu.

func ParseFormatKind

func ParseFormatKind(s string) (FormatKind, bool)

ParseFormatKind is the inverse of FormatKind.String.

type FuncDef

type FuncDef = functions.FuncDef

FuncDef describes a spreadsheet function.

func Funcs

func Funcs() []*FuncDef

Funcs returns every function, sorted by name.

func LookupFunc

func LookupFunc(name string) (*FuncDef, bool)

LookupFunc finds a function by name or alias; callers pass upper case.

type IconSet added in v0.3.0

type IconSet uint8

IconSet is a set of icons, drawn in a terminal's own glyphs so they read without color: arrows, circles filling up, symbols and bars rising. Each set comes in the sizes Excel has it in.

const (
	IconsNone IconSet = iota
	IconsArrows
	IconsCircles
	IconsSymbols
	IconsRating
)

func IconSets added in v0.3.0

func IconSets() []IconSet

IconSets lists the sets in the order the rules editor offers them.

func ParseIconSet added in v0.3.0

func ParseIconSet(s string) (IconSet, bool)

ParseIconSet is the inverse of IconSet.String.

func (IconSet) Glyphs added in v0.3.0

func (i IconSet) Glyphs(n int) []string

Glyphs are the set's n icons, lowest first.

func (IconSet) IconColor added in v0.3.0

func (i IconSet) IconColor(k, n int) Color

IconColor is the color icon k of n draws in: the lowest red, the highest green and those between yellow, as Excel colors arrows and symbols, or blue for every bar of a rating.

func (IconSet) Sizes added in v0.3.0

func (i IconSet) Sizes() []int

Sizes are how many icons the set comes with.

func (IconSet) String added in v0.3.0

func (i IconSet) String() string

func (IconSet) Title added in v0.3.0

func (i IconSet) Title() string

Title names the set for people, e.g. "Arrows".

type ImportResult

type ImportResult struct {
	Sheets  []*Sheet          // the sheets added, in tab order
	Renamed map[string]string // imported names changed to fit, old to new
	Names   int               // named ranges left out, their names taken
}

ImportResult says what an import into a workbook did.

type InvalidEntry added in v0.2.0

type InvalidEntry struct {
	Addr   Addr
	Help   string // what the rule wants, e.g. "Input must be a number between 1 and 10"
	Reject bool   // the rule refuses it; otherwise it may be kept, marked invalid
}

InvalidEntry is an entry a cell's validation doesn't accept.

func (*InvalidEntry) Error added in v0.2.0

func (e *InvalidEntry) Error() string

type Kind

type Kind = value.Kind

Kind is the type of a computed cell value.

type Line added in v0.3.0

type Line uint8

Line is how an edge is drawn.

const (
	LineNone Line = iota
	LineThin
	LineThick
	LineDouble
)

func Heavier added in v0.3.0

func Heavier(a, b Line) Line

Heavier is the line drawn where two edges meet: double over thick over thin.

func ParseLine added in v0.3.0

func ParseLine(s string) (Line, bool)

ParseLine is the inverse of Line.String.

func (Line) String added in v0.3.0

func (l Line) String() string

String returns the line's name as stored in files.

type Link struct {
	Target
	Kind LinkKind
	Name string // see LinkKind
}

Link is a precedent or dependent: where it is, and how it's linked.

func (Link) OnGrid added in v0.3.0

func (l Link) OnGrid() bool

OnGrid reports whether the link is cells of a sheet's grid rather than a notebook cell.

type LinkKind added in v0.3.0

type LinkKind uint8

LinkKind is how a traced cell is linked to the one traced.

const (
	// LinkRef is a reference or range the formula writes out, or a
	// formula reading the cell through one.
	LinkRef LinkKind = iota
	// LinkName is a named range the formula uses: Link.Name is its name.
	LinkName
	// LinkRegion is a region's table the formula names, nu.sales:
	// Link.Name is how the formula names it.
	LinkRegion
	// LinkSpill is the array formula whose values the cell shows, among
	// precedents, or the cells a formula spills into, among dependents.
	LinkSpill
	// LinkFile is the linked file a region's cells come from: Link.Name
	// is its path, and Target the region's cells.
	LinkFile
	// LinkTable is a table's cells a formula reads by a structured
	// reference or the table's name alone: Link.Name is the reference as
	// written, Sales[Amount].
	LinkTable
	// LinkOutput is the notebook cell whose output a region shows:
	// Link.Name is the cell's name, Target.Sheet the notebook tab and
	// Target.Range.From.Row the cell's index there.
	LinkOutput
)

type LinkSource added in v0.3.0

type LinkSource struct {
	// Path is the file, as the UI resolves it: relative to the
	// workbook's folder when it can be (see RebaseLinks).
	Path string
	// Format is the name of the file's format ("CSV", "NUON"), or "" to
	// tell it by the extension.
	Format string
	// Table is a SQLite table to read, or Query a query to run.
	Table, Query string
	// Window keeps the last Window rows under the header, dropping older
	// ones, as tail -f does; 0 keeps every row, up to max-cells.
	Window int
	// Paged links the file as a source (source.go): read in place, a
	// window of rows at a time, on a tab of its own, rather than into
	// cells. Order is how its tab sorts and filters the rows, nil for
	// the source's own order; it is replaced whole, never changed.
	Paged bool
	Order *SourceOrder
}

LinkSource is what a linked file reads, as the file keeps it.

type LinkedRegion added in v0.3.0

type LinkedRegion struct {
	// Name names the region: in LiveOps, in formulas (nu.name) and to
	// commands ($name).
	Name   string
	Sheet  *Sheet
	Anchor Addr
	// Area is the cells it covers, the anchor alone while it has none.
	Area   Rect
	Source LinkSource
	// Rows counts the data rows it shows, under the header; Dropped the
	// older rows the window let go.
	Rows, Dropped int
	// Updated is when the file was last read, zero until it is.
	Updated time.Time
	// Err says why the file can't be read, or its rows can't be shown,
	// "" when all is well; Note says what was left out.
	Err, Note string
	// Paused is set while the region isn't following its file.
	Paused bool
	// Stale is set when its cells may no longer be the file's: the file
	// is to be read again, whole.
	Stale bool
}

LinkedRegion is a linked file as the UI shows it: where it is, what it reads, and how the reading goes.

type LiveCell added in v0.3.0

type LiveCell struct {
	V Value
	F Format
}

LiveCell is a value as a source gave it, with its format (a date's, a file size's), Automatic for none.

type LiveInfo added in v0.3.0

type LiveInfo struct {
	Rows     int // rows the op brought
	Cells    int // cells that changed
	Reset    bool
	Duration time.Duration // writing the cells and recalculating what reads them
}

LiveInfo describes one op applied, for telemetry. It holds counts only, never contents.

type LiveOp added in v0.3.0

type LiveOp struct {
	// Region is the region's name (Region.Name).
	Region string
	// At is when the source changed.
	At time.Time
	// Reset has Rows replace every row under the header; otherwise they
	// follow the last.
	Reset bool
	// Header is the table's first row, when it is new or changed: the
	// source's column names.
	Header LiveRow
	// Rows are data rows, under the header.
	Rows []LiveRow
	// Err says why the source can't be read, "" when it can. An op with
	// an error changes no rows: the region keeps what it shows.
	Err string
	// Note says what the source left out, if anything.
	Note string
}

LiveOp is one change a source makes to its region.

type LiveRow added in v0.3.0

type LiveRow []LiveCell

LiveRow is a row of a region's table, from its first column.

type Look added in v0.2.0

type Look struct {
	// Styled is set when a single-color rule applies, with its Style.
	Styled bool
	Style  RuleStyle
	// Scaled is set when a color scale colors the cell, Pos of the way
	// (0 to 1) from From to To.
	Scaled   bool
	From, To Color
	Pos      float64
	// Bar is set when a data bar draws across the cell, BarLen of the
	// way (0 to 1), in BarColor.
	Bar      bool
	BarColor Color
	BarLen   float64
	// Icon, when set, is the icon an icon set draws at the cell's left,
	// in IconColor.
	Icon      string
	IconColor Color
	// ValueHidden is set when a data bar or icon shows without the
	// cell's value.
	ValueHidden bool

	Checkbox bool // a checkbox, checked when Checked
	Checked  bool
	Dropdown bool        // offers a list to pick from
	Display  DropDisplay // how it shows that it does
	Invalid  bool        // holds what its validation rule doesn't accept
}

Look is how a sheet's rules draw a cell: a conditional format's style or place on a color scale, and what its validation rule shows (a checkbox, a dropdown's marker, an invalid entry's mark).

type Macro

type Macro struct {
	Name   string
	Key    string // the shortcut's digit, "0" to "9", or "" for none
	Source string // the Starlark script
	API    int    // the scripting API it was written for, MacroAPI or older
}

Macro is a saved macro.

type MergeKind added in v0.3.0

type MergeKind uint8

MergeKind is how Format > Merge cells joins a range.

const (
	MergeAll          MergeKind = iota // the whole range, one cell
	MergeHorizontally                  // each row of it
	MergeVertically                    // each column of it
)

type Name

type Name struct {
	Name  string // as the user spelled it; formulas match it in any case
	Sheet *Sheet // the sheet the range is on
	Range Rect
	// Lost is set when every cell of the range was deleted: formulas using
	// the name show #REF!, as in Sheets. Range is then zero.
	Lost bool
}

Name is a named range. Names belong to the workbook, as in Sheets, and each points at a range on one of its sheets.

func (Name) Gone

func (n Name) Gone() bool

Gone reports whether the name no longer points at cells: its cells or its sheet were deleted.

func (Name) Ref

func (n Name) Ref() string

Ref is what the name stands for, e.g. "B2:B20", or "#REF!" when gone. In a workbook of several sheets it names the sheet: "Sales!B2:B20".

type Node

type Node = formula.Node

Node is a parsed formula expression.

func Parse

func Parse(src string) (Node, error)

Parse parses a formula with this engine's functions. src may start with "="; error positions are relative to src.

type Op added in v0.5.0

type Op struct {
	Seq    uint64 // its place in the order, from 1
	Author int
	Kind   OpKind
	Change
}

Op is one operation in the order the workbook ran it: a step made, undone or redone, by its author, with what the step says of itself.

type OpKind added in v0.5.0

type OpKind int

OpKind is what an operation did to the history.

const (
	OpDo   OpKind = iota // a step made
	OpUndo               // a step undone
	OpRedo               // a step redone
)

type ParseError

type ParseError = formula.ParseError

ParseError describes a formula that could not be parsed.

type Pivot

type Pivot struct {
	// Source names the sheet the data is on. Like a reference written
	// with a sheet name, it follows renames, and while no sheet has the
	// name the pivot shows #REF!.
	Source string
	// Range is the data on the source sheet; its first row holds the
	// headers, which name the fields.
	Range   Rect
	Rows    []PivotGroup
	Columns []PivotGroup
	Values  []PivotValue
	Filters []PivotFilter
	// RowTotals adds a Grand Total row, and a subtotal row after each
	// outer group when there are several row groups. ColumnTotals adds a
	// Grand Total column when there are column groups, and a subtotal
	// column after each outer group when there are several.
	RowTotals, ColumnTotals bool
	// Lost is set when the source range was deleted.
	Lost bool
}

A pivot table summarizes a range of another sheet, as Sheets' Insert > Pivot table: rows grouped by the values of some columns (Rows), spread across others (Columns), with values summarized per group (Values), and rows left out by Filters. It lives on a sheet of its own, starting at A1. The engine owns its results: they are derived cells, recomputed whenever the source's cells change, never saved (the file keeps the definition) and never edited by hand. A sheet has at most one pivot.

func FrequencyPivot

func FrequencyPivot(src *Sheet, r Rect, col int) Pivot

FrequencyPivot is a frequency table of column col of r: each distinct value with how many rows have it and their share, most frequent first, as VisiData's Shift+F. It is a pivot like any other; it counts rows rather than values, so blanks are counted too.

func NewPivot

func NewPivot(src *Sheet, r Rect) Pivot

NewPivot starts a pivot over r on src with nothing chosen yet and both grand totals on, as Sheets' new pivot tables.

func ParsePivot added in v0.3.0

func ParsePivot(line string) (Pivot, error)

ParsePivot reads a pivot table's definition written by JSON.

func (Pivot) JSON added in v0.3.0

func (p Pivot) JSON() string

JSON is the pivot table's definition as a line of the file.

type PivotFilter

type PivotFilter struct {
	Col      int
	Criteria Criteria
}

PivotFilter leaves out the source rows whose value in Col doesn't meet Criteria, as a filter's column does.

type PivotGroup

type PivotGroup struct {
	Col  int  // column on the source sheet
	Desc bool // Z to A, or largest first
	// SortBy orders the groups by their label (0) or by the grand total
	// of Values[SortBy-1].
	SortBy int
}

PivotGroup is a column of the source whose distinct values become rows or columns of the pivot.

type PivotGroups added in v0.6.0

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

PivotGroups is a pivot table's source rows gathered into groups, as GatherPivot leaves them for the layout.

func GatherPivot added in v0.6.0

func GatherPivot(p Pivot, shape SourceShape, scan func(each func(row int, vals []LiveCell) bool) error) (*PivotGroups, error)

GatherPivot gathers a pivot's groups from a linked source of shape shape, whose rows scan streams: it calls its argument with each row (counting from 0, under the header) and its values by column (those PivotCols names, the rest blank), stopping when told. It touches no workbook, so it runs in the background.

func (*PivotGroups) Records added in v0.6.0

func (g *PivotGroups) Records() int

Records counts the source rows the groups summarize.

type PivotInfo

type PivotInfo struct {
	Records  int // source rows summarized
	Groups   int // groups of the row fields
	Cells    int // cells of the results
	Failed   bool
	Duration time.Duration
}

PivotInfo describes one pivot recomputation, for telemetry. It holds counts only, never contents.

type PivotValue

type PivotValue struct {
	Col       int
	Summarize Summarize
	ShowAs    ShowAs
	Name      string // the header; "" for Sheets' "SUM of Sales"
}

PivotValue is a column of the source summarized per group.

type PointKind added in v0.2.0

type PointKind uint8

PointKind is how a color scale point is placed.

const (
	PointMin        PointKind = iota // the lowest value
	PointMax                         // the highest value
	PointNumber                      // a number
	PointPercent                     // a percentage of the way from lowest to highest
	PointPercentile                  // a percentile of the values

)

func ParsePointKind added in v0.2.0

func ParsePointKind(s string) (PointKind, bool)

ParsePointKind is the inverse of PointKind.String.

func PointKinds added in v0.2.0

func PointKinds() []PointKind

PointKinds lists the kinds in the order the rules editor offers them.

func (PointKind) String added in v0.2.0

func (k PointKind) String() string

func (PointKind) TakesValue added in v0.2.0

func (k PointKind) TakesValue() bool

TakesValue reports whether the point needs a value.

func (PointKind) Title added in v0.2.0

func (k PointKind) Title() string

Title names the kind for people, e.g. "Percentile".

type Proposal added in v0.6.0

type Proposal struct {
	Label string
	// Cells are the cells whose contents, format or note the change
	// sets, by sheet in the copy's order, then row and column.
	Cells []Proposed
	// Other says what the change does besides setting cells, one
	// phrase each ("inserts or deletes rows or columns on Sheet1"); a
	// proposal with any is made whole only.
	Other []string
	// Sheets are the sheets, by name, whose lines, charts, rules,
	// filters or pivot the change changes; Book is set when it changes
	// the sheet list, the settings, the names or the macros.
	Sheets []string
	Book   bool
	// Remote is set when a formula it enters asks a hosted model (JEV),
	// which reaches the network once the change is made.
	Remote bool
	// contains filtered or unexported fields
}

Proposal is a change made on a copy of a workbook.

func Propose added in v0.6.0

func Propose(w *Workbook, label string, fn func(*Workbook) error) (*Proposal, error)

Propose makes fn, labelled label, on a copy of w and says what it changed. w isn't changed; fn may be run again on it when the proposal is applied whole.

func (*Proposal) Apply added in v0.6.0

func (p *Proposal) Apply(w *Workbook, pick func(i int) bool) error

Apply makes the proposal on w as one step, in the name of w's author: the cells pick keeps (nil keeps them all), or the whole change run again on w when it does more than set cells.

func (*Proposal) Empty added in v0.6.0

func (p *Proposal) Empty() bool

Empty reports whether the proposal changes nothing.

func (*Proposal) Result added in v0.6.0

func (p *Proposal) Result() *Workbook

Result is the copy with the change made, to read what it would look like. It must not be changed.

func (*Proposal) Whole added in v0.6.0

func (p *Proposal) Whole() bool

Whole reports whether the proposal can only be made whole.

type Proposed added in v0.6.0

type Proposed struct {
	Sheet    string
	At       Addr
	Was, Now string
	Look     bool
}

Proposed is a cell a proposal sets: its sheet, where, its input before and after ("" for blank), and whether its format, style or note change too.

type Protection added in v0.2.0

type Protection struct {
	Range Rect   // the whole grid when Sheet is set
	Sheet bool   // the whole sheet is protected
	Desc  string // what the user wrote to describe it, may be ""
}

Protection is a protected range, or the whole sheet.

func (Protection) Label added in v0.2.0

func (p Protection) Label() string

Label names the protection as the UI shows it: its description, or its range, or "the sheet".

type RecalcInfo

type RecalcInfo struct {
	Full      bool // every formula, as after loading
	Evaluated int  // cells marked dirty and recomputed
	Cells     int  // cells stored on every sheet, including formatting-only ones
	Volatile  int  // volatile formulas on every sheet, recomputed every time
	Circular  bool
	// Duration includes the pivot tables the recalculation refreshed,
	// and the recalculation of what reads their results.
	Duration time.Duration
}

RecalcInfo describes one recalculation, for telemetry. It holds counts only, never contents.

type Rect

type Rect = formula.Rect

Rect is an inclusive rectangular range of cells.

func NewRect

func NewRect(a, b Addr) Rect

NewRect returns the normalized rectangle spanning a and b.

func ParseRange

func ParseRange(s string) (Rect, bool)

ParseRange parses "A1", "A1:B3" or 1-2-3 style "A1..B3".

func ParseRanges added in v0.2.0

func ParseRanges(s string) ([]Rect, bool)

ParseRanges reads ranges written as "A1:A9,C1:C9" (spaces or commas between), as the rules editor takes them.

type Region added in v0.3.0

type Region struct {
	// Name identifies the region in the workbook, ignoring case: a
	// linked file's is made from the file's name, a sent output's is its
	// cell's. Notebook cells read linked files as $name.
	Name string
	// At is the table's first cell.
	At Addr
	// File is the file a linked file follows; zero for a sent output.
	File LinkSource
	// Output is set on a notebook cell's output sent to the sheet: the
	// output of the cell of the region's name.
	Output bool
}

Region is a region's definition.

func (Region) FormulaName added in v0.3.0

func (r Region) FormulaName() string

FormulaName is how formulas name the region: nu.sales.

func (Region) Linked added in v0.3.0

func (r Region) Linked() bool

Linked reports whether the region is a linked file, not a source.

type RemoteAnswer

type RemoteAnswer = functions.RemoteAnswer

The questions and answers are the function library's (functions/remote.go); the engine's API names them too.

type RemoteCall

type RemoteCall = functions.RemoteCall

The questions and answers are the function library's (functions/remote.go); the engine's API names them too.

type RemoteSource

type RemoteSource = functions.RemoteSource

The questions and answers are the function library's (functions/remote.go); the engine's API names them too.

type RuleOp added in v0.2.0

type RuleOp uint8

RuleOp is a test on a cell's value, as Sheets' conditional formatting and data validation offer them. Conditional formats use them all; validation uses the comparisons (and RuleNone for "any date").

const (
	RuleNone RuleOp = iota
	RuleEmpty
	RuleNotEmpty
	RuleContains
	RuleNotContains
	RuleStartsWith
	RuleEndsWith
	RuleExactly
	RuleDateIs
	RuleDateBefore
	RuleDateAfter
	RuleGreater
	RuleGreaterEq
	RuleLess
	RuleLessEq
	RuleEqual
	RuleNotEqual
	RuleBetween
	RuleNotBetween
	RuleFormula
	// The tests of a cell against the others in the rule's ranges, as
	// Excel's top 10, above average and duplicate values rules (see
	// condrank.go).
	RuleTop
	RuleBottom
	RuleTopPercent
	RuleBottomPercent
	RuleAboveAverage
	RuleBelowAverage
	RuleDuplicate
	RuleUnique
)

func CompareOps added in v0.2.0

func CompareOps() []RuleOp

CompareOps are the comparisons data validation offers for numbers, dates and text lengths.

func CondFormatOps added in v0.2.0

func CondFormatOps() []RuleOp

CondFormatOps lists the tests a single-color conditional format may use, in the order Sheets' menu shows them.

func ParseRuleOp added in v0.2.0

func ParseRuleOp(s string) (RuleOp, bool)

ParseRuleOp is the inverse of RuleOp.String.

func (RuleOp) Args added in v0.2.0

func (op RuleOp) Args() int

Args is how many values the test compares with: 0, 1, or 2 for between.

func (RuleOp) OnText added in v0.3.0

func (op RuleOp) OnText() bool

OnText reports whether the test is on the text a cell shows, in the locale's rendering, so its value is kept as typed (see CondOp.OnText).

func (RuleOp) Ranks added in v0.3.0

func (op RuleOp) Ranks() bool

Ranks reports whether the test compares a cell with the rest of the rule's cells (top values, above average, duplicates) rather than with values of its own.

func (RuleOp) String added in v0.2.0

func (op RuleOp) String() string

String names the test as files store it.

func (RuleOp) Title added in v0.2.0

func (op RuleOp) Title() string

Title names the test for people, e.g. "Greater than".

type RuleStyle added in v0.2.0

type RuleStyle struct {
	Text, Fill                             Color
	Bold, Italic, Underline, Strikethrough bool
}

RuleStyle is what a conditional format rule does to the cells it matches: a text color, a fill, and text styles added to the cell's own.

func (RuleStyle) IsZero added in v0.2.0

func (s RuleStyle) IsZero() bool

IsZero reports whether the style changes nothing.

type ScalePoint added in v0.2.0

type ScalePoint struct {
	Kind  PointKind
	Value string // the number, percent or percentile; unused by min and max
	Color Color
}

ScalePoint is a point of a color scale: where it is among the values, and its color.

func (ScalePoint) String added in v0.2.0

func (p ScalePoint) String() string

pointText writes a point as the rules editor shows it, e.g. "Min" or "Percentile 50".

type Segment added in v0.3.0

type Segment struct {
	Text string
	// Value marks a value a part computed, written in its place.
	Value bool
	// Next marks the part computed next.
	Next bool
}

Segment is a piece of the formula Steps shows.

type Sheet

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

Sheet is a sparse worksheet, one of a Workbook's sheets.

func New

func New() *Sheet

New returns an empty worksheet, the only sheet of a new workbook.

func Read

func Read(r io.Reader) (*Sheet, error)

Read loads a file written by Write, of this or an earlier version, and returns the sheet that was shown when it was saved.

func ReadTraced

func ReadTraced(r io.Reader, trace any) (*Sheet, error)

ReadTraced is Read giving the workbook trace (see SetTrace) before it recalculates, so that recalculation nests in the caller's span.

func (*Sheet) AddChart

func (s *Sheet) AddChart(c Chart) int

AddChart adds a chart on top of the others and returns its index.

func (*Sheet) AddCondFormat added in v0.2.0

func (s *Sheet) AddCondFormat(f CondFormat) error

AddCondFormat adds a rule after the others, as one undo step.

func (*Sheet) AddLinked added in v0.3.0

func (s *Sheet) AddLinked(a Addr, src LinkSource) (string, error)

AddLinked makes a linked file at a reading src, named after the file, as one undo step, and returns its name. It starts empty and stale: the UI reads the file and sends its rows.

func (*Sheet) AddRegion added in v0.3.0

func (s *Sheet) AddRegion(r Region) error

AddRegion adds a region to the sheet as one undo step. It starts empty and stale: the UI sends its rows.

func (*Sheet) AddValidation added in v0.2.0

func (s *Sheet) AddValidation(v Validation) error

AddValidation adds a rule, taking its cells from the rules they had, as one undo step.

func (*Sheet) Addrs

func (s *Sheet) Addrs() []Addr

Addrs returns every non-blank cell in row-major order.

func (*Sheet) AdjustDecimals

func (s *Sheet) AdjustDecimals(r Rect, delta int)

AdjustDecimals shows delta more (or fewer) decimal places in every non-blank number cell of r, starting from what each cell shows now.

func (*Sheet) Batch

func (s *Sheet) Batch(c Change, fn func() error) error

Batch runs fn as a single undo step: everything it changes is undone together, and formulas are recalculated once at the end. Batches nest; inner ones join the outermost.

func (*Sheet) Book

func (s *Sheet) Book() *Workbook

Book returns the workbook the sheet belongs to.

func (*Sheet) BorderedIn added in v0.3.0

func (s *Sheet) BorderedIn(r Rect) []Addr

BorderedIn returns the blank cells of r whose own formatting draws borders, in no particular order, at the cost of the cells that wrap or draw borders.

func (*Sheet) CanRedo

func (s *Sheet) CanRedo() bool

func (*Sheet) CanUndo

func (s *Sheet) CanUndo() bool

func (*Sheet) Cell

func (s *Sheet) Cell(a Addr) *Cell

Cell returns the cell at a, or nil if it has neither contents nor formatting. Use Blank to test for contents.

func (*Sheet) CellFormat

func (s *Sheet) CellFormat(a Addr) Format

CellFormat returns the number format the cell at a has, its own or its row's or column's, without the one a formula infers.

func (*Sheet) CellStyle

func (s *Sheet) CellStyle(a Addr) Style

CellStyle returns the text style the cell at a shows: its own, or its row's or column's.

func (*Sheet) ChartData

func (s *Sheet) ChartData(c Chart) ChartData

ChartData reads a chart's cells. Series names and labels are the cells' text as displayed.

func (*Sheet) Charts

func (s *Sheet) Charts() []Chart

Charts returns the sheet's charts, bottom first.

func (*Sheet) CheckEntry added in v0.2.0

func (s *Sheet) CheckEntry(a Addr, input string) *InvalidEntry

CheckEntry reports whether the cell at a would accept input: nil when it has no rule or input meets it (blanks always do), or an *InvalidEntry. A formula is checked by the value it computes.

func (*Sheet) CheckboxInput added in v0.3.0

func (s *Sheet) CheckboxInput(a Addr, on bool) string

CheckboxInput is what checking (on) or unchecking the checkbox at a enters: TRUE or FALSE, or its rule's own values.

func (*Sheet) ClearCondFormats added in v0.2.0

func (s *Sheet) ClearCondFormats(cr Rect)

ClearCondFormats takes the cells of cr out of every rule, removing rules left with no cells, as Sheets' "Clear formatting rules" for a selection.

func (*Sheet) ClearFormatting

func (s *Sheet) ClearFormatting(r Rect)

ClearFormatting resets the format and style of every cell in r, as Sheets' Format > Clear formatting.

func (*Sheet) ClearHistory

func (s *Sheet) ClearHistory()

func (*Sheet) ClearNotes added in v0.2.0

func (s *Sheet) ClearNotes(r Rect) int

ClearNotes deletes the notes in r as one undo step and returns how many there were.

func (*Sheet) ClearValidations added in v0.2.0

func (s *Sheet) ClearValidations(cr Rect)

ClearValidations takes the cells of cr out of every rule, as Sheets' "Remove rule" does for a selection.

func (*Sheet) ColFormats

func (s *Sheet) ColFormats() map[int]Format

ColFormats and RowFormats return the columns and rows that have a format or style of their own, by index.

func (*Sheet) ColStyles

func (s *Sheet) ColStyles() map[int]Style

ColStyles and RowStyles are the same for text styles.

func (*Sheet) ColWidth

func (s *Sheet) ColWidth(c int) int

ColWidth returns the display width of column c.

func (*Sheet) ColsWidth added in v0.3.0

func (s *Sheet) ColsWidth(from, to int) int

ColsWidth is the width of columns from..to together, at the cost of the columns with a width of their own.

func (*Sheet) ColumnFiltered

func (s *Sheet) ColumnFiltered(col int) bool

ColumnFiltered reports whether the filter has criteria for column col.

func (*Sheet) CondFormats added in v0.2.0

func (s *Sheet) CondFormats() []CondFormat

CondFormats returns the sheet's conditional format rules, in the order they're tried.

func (*Sheet) Copy

func (s *Sheet) Copy(r Rect) *Clip

Copy snapshots the cells in r, and what formatting they show, for pasting. Whole columns or rows are trimmed to the cells they hold, keeping their line formats.

func (*Sheet) CreateFilter

func (s *Sheet) CreateFilter(r Rect)

CreateFilter puts a filter on r, whose first row is the header row.

func (*Sheet) CreateTable added in v0.3.0

func (s *Sheet) CreateTable(name string, r Rect) error

CreateTable makes a table named name of r, whose first row names its columns, with its header styled and no bands, as one undo step. Blank or repeated names in the header row are replaced with ones of their own (Column2, Amount2), in the cells too; a range of one row gains an empty row of data.

func (*Sheet) Decimal

func (s *Sheet) Decimal() bool

Decimal and SetDecimal on a sheet are its workbook's.

func (*Sheet) DefineName

func (s *Sheet) DefineName(name string, r Rect) error

func (*Sheet) DeleteChart

func (s *Sheet) DeleteChart(i int)

DeleteChart removes chart i.

func (*Sheet) DeleteCols

func (s *Sheet) DeleteCols(at, n int)

DeleteCols deletes n columns starting at column at.

func (*Sheet) DeleteCondFormat added in v0.2.0

func (s *Sheet) DeleteCondFormat(i int)

DeleteCondFormat removes rule i.

func (*Sheet) DeleteName

func (s *Sheet) DeleteName(name string) error

func (*Sheet) DeleteRegion added in v0.3.0

func (s *Sheet) DeleteRegion(name string) error

DeleteRegion removes a region and its cells, as one undo step.

func (*Sheet) DeleteRows

func (s *Sheet) DeleteRows(at, n int)

DeleteRows deletes n rows starting at row at. References to deleted cells become #REF!; ranges that lose some of their rows shrink.

func (*Sheet) DeleteValidation added in v0.2.0

func (s *Sheet) DeleteValidation(i int)

DeleteValidation removes rule i.

func (s *Sheet) DependentLinks(a Addr, max int) (links []Link, more bool)

DependentLinks returns the formulas that read the cell at a directly: through a reference, a range, a named range or a region's name. When the formula at a spills, the cells it spills into come first, and the formulas reading any of them count too. Formulas on this sheet come in row-major order, then those on other sheets in tab order. With max > 0 at most max formulas are found, and more reports that there were others: a cell read by a million formulas costs what max does.

func (*Sheet) Dependents

func (s *Sheet) Dependents(a Addr) []Target

Dependents returns the formula cells that read a directly; see DependentLinks.

func (*Sheet) Discard added in v0.3.0

func (s *Sheet) Discard() bool

Discard takes back the workbook's last change; see Workbook.Discard.

func (*Sheet) DisplayFormat

func (s *Sheet) DisplayFormat(a Addr) Format

DisplayFormat returns the format the cell at a is shown with: its own, its row's or column's, or for Automatic, the one inferred from its formula (=DATE() shows a date, =SUM(B2:B4) of currency shows currency).

func (*Sheet) DropdownItems added in v0.2.0

func (s *Sheet) DropdownItems(a Addr) []string

DropdownItems lists what a dropdown cell offers: the rule's items, or the distinct values shown in its range, in order, blanks left out.

func (*Sheet) Edge

func (s *Sheet) Edge(a Addr, dc, dr int) Addr

Edge returns where a data-edge jump (Ctrl+arrow in Excel, End+arrow in 1-2-3) from a in direction (dc, dr) lands. Inside a block of filled cells it stops at the block's last cell; from a blank cell, or at the end of a block, it goes to the next filled cell. With nothing filled ahead it stops at the edge of the worksheet. Rows the filter hides are skipped. Blank stretches are jumped over through the index of filled cells, so a jump costs what the block it walks holds, not the empty rows past it.

func (*Sheet) EdgeAbove added in v0.3.0

func (s *Sheet) EdgeAbove(a Addr) Line

EdgeAbove is the line on the edge between the cell at a and the one above it: the heavier of their facing lines.

func (*Sheet) EdgeLeft added in v0.3.0

func (s *Sheet) EdgeLeft(a Addr) Line

EdgeLeft is the line on the edge between the cell at a and the one to its left.

func (*Sheet) EditName

func (s *Sheet) EditName(old, name string, r Rect) error

func (*Sheet) EraseRange

func (s *Sheet) EraseRange(r Rect)

EraseRange clears the contents of every cell in r, keeping their formatting and notes as Sheets' Delete does.

func (*Sheet) EvaluateSteps added in v0.3.0

func (s *Sheet) EvaluateSteps(a Addr) *Steps

EvaluateSteps starts evaluating the formula at a step by step, or returns nil when a holds no formula.

func (*Sheet) ExplainError

func (s *Sheet) ExplainError(a Addr) string

ExplainError says why the cell at a shows an error, for the context line: where the error starts and what went wrong, e.g. "Division by zero in B3/0", or "From B5: division by zero in B3/0" when it comes from another cell. It is empty for cells without errors.

func (*Sheet) FillDown

func (s *Sheet) FillDown(r Rect) (Rect, error)

FillDown copies the top row of r into the rest of it, adjusting references (Ctrl+D). A single-row range fills from the row above. When the top rows of r start a series and the rest is blank (1, 2 and then empty cells), it continues the series instead, as dragging the fill handle would.

func (*Sheet) FillEntry

func (s *Sheet) FillEntry(r Rect, origin Addr, input string) error

FillEntry stores input in every cell of r as if it had been typed at origin and copied to each cell, adjusting references (Ctrl+Enter).

func (*Sheet) FillRight

func (s *Sheet) FillRight(r Rect) (Rect, error)

FillRight copies the left column of r into the rest of it (Ctrl+R). A single-column range fills from the column to the left. Like FillDown, it continues a series started in the leftmost columns.

func (*Sheet) FillSeries

func (s *Sheet) FillSeries(src, dst Rect) (Rect, error)

FillSeries extends src over dst, which contains it and reaches past it along one axis: down or up, right or left. Each column (or row) of src is continued on its own. It returns the range filled, as one undo step.

func (*Sheet) Filled added in v0.3.0

func (s *Sheet) Filled(a Addr) bool

Filled reports whether the cell at a has contents: !Cell(a).Blank(), without making the cell.

func (*Sheet) FilledBounds

func (s *Sheet) FilledBounds(r Rect) (Rect, bool)

FilledBounds returns the smallest range holding every non-blank cell of r, and false if there is none.

func (*Sheet) Filter

func (s *Sheet) Filter() *Filter

Filter returns a copy of the sheet's filter, or nil if it has none.

func (*Sheet) FilterColumn

func (s *Sheet) FilterColumn(col int, cr Criteria)

FilterColumn sets the criteria for column col of the filter.

func (*Sheet) FilterRange

func (s *Sheet) FilterRange() (Rect, bool)

FilterRange returns the filter's range, and false if there is no filter.

func (*Sheet) FilterValues

func (s *Sheet) FilterValues(col int) []FilterValue

FilterValues lists the distinct values in column col of the filter's data rows, among the rows the other columns' criteria let through, as Sheets' "Filter by values" does. Numbers come first in numeric order, then text alphabetically, then blanks.

func (*Sheet) Find

func (s *Sheet) Find(query string, o FindOptions) ([]Addr, error)

Find returns the cells matching query in reading order: row by row, left to right.

func (*Sheet) FreezeRegion added in v0.3.0

func (s *Sheet) FreezeRegion(name string) error

FreezeRegion turns a region's table into plain values, each in the format it showed, and removes the region, as one undo step.

func (*Sheet) Frozen

func (s *Sheet) Frozen() (rows, cols int)

Frozen returns how many rows and columns are frozen at the top and left.

func (*Sheet) Grow added in v0.3.0

func (s *Sheet) Grow(r Rect) Rect

Grow returns r grown to hold every merge it overlaps, as a selection in Sheets takes in the merged cells it touches.

func (*Sheet) GuessChart

func (s *Sheet) GuessChart(r Rect) Chart

GuessChart sets up a chart over r the way Sheets does: series down columns, a header row when the first row is text over numbers, and category labels when the first column is text.

func (*Sheet) HasLinked added in v0.3.0

func (s *Sheet) HasLinked() bool

HasLinked reports whether the sheet holds a linked file.

func (*Sheet) HasRegions added in v0.3.0

func (s *Sheet) HasRegions() bool

HasRegions reports whether the sheet has regions, so what draws it can skip looking for them.

func (*Sheet) HasRules added in v0.2.0

func (s *Sheet) HasRules() bool

HasRules reports whether the sheet has conditional formats or data validation, so drawing can skip asking for looks when it has none.

func (*Sheet) HasSpills added in v0.2.0

func (s *Sheet) HasSpills() bool

HasSpills reports whether a formula on the sheet spills or would, or a region shows a table (whose cells are spilled cells too), so what draws the sheet can skip looking for spilled cells.

func (*Sheet) HasTables added in v0.3.0

func (s *Sheet) HasTables() bool

HasTables reports whether the sheet has tables, so what draws it can skip looking for them.

func (*Sheet) Heights added in v0.3.0

func (s *Sheet) Heights() map[int]int

Heights returns the rows that have a height set by hand.

func (*Sheet) Hidden

func (s *Sheet) Hidden() bool

Hidden reports whether the sheet is hidden.

func (*Sheet) HiddenRows

func (s *Sheet) HiddenRows() int

HiddenRows returns how many rows the filter hides.

func (*Sheet) InPivot

func (s *Sheet) InPivot(r Rect) bool

InPivot reports whether r overlaps the pivot table's results, which can't be edited.

func (*Sheet) InRegion added in v0.3.0

func (s *Sheet) InRegion(r Rect) (Addr, Region, bool)

InRegion returns a cell of r a region covers, and the region.

func (*Sheet) InSpill added in v0.2.0

func (s *Sheet) InSpill(r Rect) (Addr, bool)

InSpill returns a spilled cell in r whose anchor isn't in r, which an edit of r can't change: editing spilled cells is refused, while clearing or replacing the anchor with its spill is fine.

func (*Sheet) InsertCols

func (s *Sheet) InsertCols(at, n int) error

InsertCols inserts n blank columns before column at.

func (*Sheet) InsertRows

func (s *Sheet) InsertRows(at, n int) error

InsertRows inserts n blank rows before row at, shifting the rows below down and adjusting every reference to them.

func (*Sheet) InvalidIn added in v0.3.0

func (s *Sheet) InvalidIn(r Rect) []*InvalidEntry

InvalidIn lists the cells in r whose contents fail their validation, in reading order: blanks never do. A cell's rule decides whether its entry is refused (Reject) or kept and marked. The cost is the cells stored where r meets a rule's ranges.

func (*Sheet) IsNotebook added in v0.3.0

func (s *Sheet) IsNotebook() bool

IsNotebook reports whether the sheet is a notebook tab.

func (*Sheet) IsSource added in v0.6.0

func (s *Sheet) IsSource() bool

IsSource reports whether the sheet is a linked source's tab.

func (*Sheet) Len

func (s *Sheet) Len() int

Len returns the number of non-blank cells.

func (s *Sheet) Link(a Addr) string

Link returns the address a cell links to: its text when that is a URL (http, https or mailto), or the target of a HYPERLINK formula. It is empty for other cells.

func (*Sheet) LinkedAt added in v0.3.0

func (s *Sheet) LinkedAt(a Addr) (LinkedRegion, bool)

LinkedAt returns the linked file covering the cell at a.

func (*Sheet) LinkedRegions added in v0.3.0

func (s *Sheet) LinkedRegions() []LinkedRegion

LinkedRegions returns the sheet's linked files, in the order they were made.

func (*Sheet) Live

func (s *Sheet) Live() bool

Live reports whether the sheet is in its workbook, i.e. not deleted.

func (*Sheet) Load

func (s *Sheet) Load(a Addr, input string, f Format, st Style) error

Load stores an entry at a with its number format and style, without recalculating or recording undo. With an Automatic format the entry implies one as if typed ("$5" is currency, "9/26/2026" a date). A formula that fails to parse is rejected with a *ParseError and nothing is stored. Call RecalcAll when every cell is in.

func (*Sheet) LoadColWidth

func (s *Sheet) LoadColWidth(c, w int)

LoadColWidth sets column c's width, as a loader does: without recording undo or recalculating.

func (*Sheet) LoadCondFormats added in v0.2.0

func (s *Sheet) LoadCondFormats(fs []CondFormat) (skipped int)

LoadCondFormats adds rules as a loader does: without recording undo. Rules that don't check are left out and counted.

func (*Sheet) LoadFilter

func (s *Sheet) LoadFilter(f *Filter)

LoadFilter puts filter f on the sheet (nil removes it), as a loader does: without recording undo. Its criteria apply once values are computed, as they do whenever values change.

func (*Sheet) LoadFitWidths added in v0.3.0

func (s *Sheet) LoadFitWidths()

LoadFitWidths widens each column of the used range whose width isn't set to its widest text among the first rows (a header and a sample below it), capped, as a table a region shows is fitted: what an importer does for a format that keeps no widths of its own (CSV, JSON). Without recording undo.

func (*Sheet) LoadFrozen

func (s *Sheet) LoadFrozen(rows, cols int)

LoadFrozen freezes the first rows rows and cols columns, as a loader does: without recording undo. SetFrozen is the undoable way.

func (*Sheet) LoadLineFormat

func (s *Sheet) LoadLineFormat(row bool, n int, f Format, st Style)

LoadLineFormat gives a whole column (row false) or row a format and style, as an importer does, without recording undo or touching its cells; column -1 is the whole sheet.

func (*Sheet) LoadMerge added in v0.3.0

func (s *Sheet) LoadMerge(r Rect)

LoadMerge adds a merge as a loader does, without recording undo; one cell or one overlapping another is left out.

func (*Sheet) LoadNote added in v0.2.0

func (s *Sheet) LoadNote(a Addr, text string)

LoadNote sets a note as a loader does: without recording undo.

func (*Sheet) LoadProtection added in v0.2.0

func (s *Sheet) LoadProtection(p Protection)

LoadProtection adds a protection as a loader does: without recording undo.

func (*Sheet) LoadRowHeight added in v0.3.0

func (s *Sheet) LoadRowHeight(row, h int)

LoadRowHeight sets a row's height as an importer does, without recording undo.

func (*Sheet) LoadTable added in v0.3.0

func (s *Sheet) LoadTable(t Table) error

LoadTable adds t to the sheet as a loader does, without recording undo, its cells loaded. Columns t doesn't name, or names in a number other than its range's width, are named from its header row, and the names are made unique. Its range isn't checked against what else the sheet holds: edits since it was made (a region sent over it, a table moved onto another) may overlap them, and the file opens as it was saved.

func (*Sheet) LoadValidations added in v0.2.0

func (s *Sheet) LoadValidations(vs []Validation) (skipped int)

LoadValidations adds rules as a loader does: without recording undo. Rules that don't check are left out and counted.

func (*Sheet) LocalText added in v0.3.0

func (s *Sheet) LocalText(a Addr) string

LocalText is the cell's value as its format displays it in the sheet's locale, with no width limit: what text conditions test.

func (*Sheet) Locale added in v0.3.0

func (s *Sheet) Locale() *locale.Locale

Locale is the sheet's workbook's.

func (*Sheet) Look added in v0.2.0

func (s *Sheet) Look(a Addr) Look

Look returns how the sheet's rules draw the cell at a.

func (*Sheet) LookupName

func (s *Sheet) LookupName(name string) (Name, bool)

func (*Sheet) MakeNotebook added in v0.3.0

func (s *Sheet) MakeNotebook()

MakeNotebook turns an empty sheet into a notebook tab, without an undo step, as 012 nu does with a new file's sheet.

func (*Sheet) Merge added in v0.3.0

func (s *Sheet) Merge(r Rect, k MergeKind) error

Merge joins r into merged cells as k says, as one undo step: each keeps its top-left cell's contents and clears the rest, keeping their formatting and notes. Merges it overlaps are replaced.

func (*Sheet) MergeAcross added in v0.3.0

func (s *Sheet) MergeAcross(rows bool, n int) (Rect, bool)

MergeAcross returns a merge the line after the first n rows (or columns) would cut through, as freezing them would, and whether there is one.

func (*Sheet) MergeAt added in v0.3.0

func (s *Sheet) MergeAt(a Addr) (Rect, bool)

MergeAt returns the merged range holding a, and false when a isn't merged.

func (*Sheet) MergeLoses added in v0.3.0

func (s *Sheet) MergeLoses(r Rect, k MergeKind) (Addr, bool)

MergeLoses returns the first cell merging r with k would clear: one with contents that isn't the top-left of its merge. Sheets warns that only the top-left value is kept.

func (*Sheet) Merges added in v0.3.0

func (s *Sheet) Merges() []Rect

Merges returns the merged ranges, in the order they were made.

func (*Sheet) MergesIn added in v0.3.0

func (s *Sheet) MergesIn(r Rect) []Rect

MergesIn returns the merges that overlap r.

func (*Sheet) Move

func (s *Sheet) Move(src Rect, to Addr) (Rect, error)

Move moves the cells in src so its top-left corner lands on to, as cut and paste does in Sheets, with the formatting they show; whole columns or rows take their line formats along. Formulas anywhere that referred to the moved cells follow them; references to cells the move overwrote become #REF!. It returns the destination range.

func (*Sheet) MoveCondFormat added in v0.2.0

func (s *Sheet) MoveCondFormat(i, to int)

MoveCondFormat moves rule i to position to, changing which rule wins where several apply.

func (*Sheet) MoveTo

func (s *Sheet) MoveTo(dst *Sheet, src Rect, to Addr) (Rect, error)

MoveTo moves the cells in src to sheet dst, src's top-left corner landing on to, as cutting on one sheet and pasting on another does in Sheets. Formulas anywhere that read the moved cells follow them to dst, naming its sheet where they need to; the moved formulas keep reading what they read, naming this sheet for cells that stayed behind. References to cells the move overwrote become #REF!.

func (*Sheet) Name

func (s *Sheet) Name() string

Name returns the sheet's name.

func (*Sheet) NameUsers

func (s *Sheet) NameUsers(name string) int

func (*Sheet) NamedSheets

func (s *Sheet) NamedSheets(a Addr) []string

NamedSheets returns the sheet names the formula at a names, as written and without repeats (in any case), or nil for anything else. Names of sheets that don't exist are included: exporters check them.

func (*Sheet) NamedTables added in v0.3.0

func (s *Sheet) NamedTables(a Addr) []string

NamedTables returns the tables the formula at a reads by structured references, as written and without repeats (in any case), or nil for anything else. Exporters check that they write them.

func (*Sheet) Names

func (s *Sheet) Names() []Name

func (*Sheet) NextFilledCol

func (s *Sheet) NextFilledCol(row, col, dir, limit int) (int, bool)

NextFilledCol returns the nearest column of row, from col on in direction dir (1 or -1) and no further than limit, whose cell has contents, looking only at the columns that hold any.

func (*Sheet) NextShownRow

func (s *Sheet) NextShownRow(r, d int) (int, bool)

NextShownRow returns the first row from r+d on (d is 1 or -1) that the filter doesn't hide, jumping over the hidden blank rows at the end of its range at once, and false past the edge of the sheet.

func (*Sheet) Note added in v0.2.0

func (s *Sheet) Note(a Addr) string

Note returns the note on the cell at a, or "".

func (*Sheet) NotebookCells added in v0.3.0

func (s *Sheet) NotebookCells() []notebook.Cell

NotebookCells returns a notebook tab's cells.

func (*Sheet) NotesIn added in v0.2.0

func (s *Sheet) NotesIn(r Rect) []Addr

NotesIn returns the cells in r that have notes, in row-major order. It walks the cells the sheet holds, not r's addresses.

func (*Sheet) Paste

func (s *Sheet) Paste(c *Clip, dst Rect, values bool) (Rect, error)

Paste writes the clip into dst and returns the range written. Formulas shift their relative references by the distance pasted, as in Sheets; with values set, only the computed values are pasted, keeping the destination's formatting. Otherwise each cell shows the formatting its source showed (see clipfmt.go). Like Sheets, a destination that is an exact multiple of the clip's size is tiled; otherwise the clip is pasted once at dst's top-left corner.

func (*Sheet) Pivot

func (s *Sheet) Pivot() (Pivot, bool)

Pivot returns a copy of the sheet's pivot table, and false if it has none.

func (*Sheet) PivotError

func (s *Sheet) PivotError() string

PivotError says why the pivot shows #REF!, or "" when it doesn't.

func (*Sheet) PivotRange

func (s *Sheet) PivotRange() (Rect, bool)

PivotRange returns the cells the pivot's results cover, from A1 (at least A1, even while it shows nothing), and false without a pivot.

func (*Sheet) PivotSource

func (s *Sheet) PivotSource() *Sheet

PivotSource returns the sheet the pivot reads, or nil when no sheet has its name.

func (s *Sheet) PrecedentLinks(a Addr) []Link

PrecedentLinks returns what the cell at a comes from. For a formula, the cells and ranges it reads in the order it mentions them, named ranges and regions as their cells, with repeats dropped and references to sheets that don't exist left out. For a cell an array spilled into, the formula that spilled it; for a region's cell, the linked file or notebook cell the region shows.

func (*Sheet) Precedents

func (s *Sheet) Precedents(a Addr) []Target

Precedents returns the cells and ranges the formula at a reads, in the order the formula mentions them; see PrecedentLinks.

func (*Sheet) Protect added in v0.2.0

func (s *Sheet) Protect(p Protection)

Protect adds a protected range, or protects the whole sheet, as one undo step. Protecting the sheet again replaces its description.

func (*Sheet) Protecting added in v0.2.0

func (s *Sheet) Protecting(r Rect) (Protection, bool)

Protecting returns the first protection r overlaps.

func (*Sheet) Protections added in v0.2.0

func (s *Sheet) Protections() []Protection

Protections returns the sheet's protected ranges, in the order added.

func (*Sheet) RangeStats

func (s *Sheet) RangeStats(r Rect) Stats

RangeStats computes Stats over r. The result is kept until a cell or value changes. A selection over a large, well-filled sheet is summed from the cells' statistics index (see rangeStats), so changing it costs a block per column plus the rows at its ends, not a read of every cell.

func (*Sheet) Reactive added in v0.3.0

func (s *Sheet) Reactive() bool

Reactive reports whether the notebook runs the cells reading a cell again whenever it runs.

func (*Sheet) Reads added in v0.3.0

func (s *Sheet) Reads(u Addr, t *Sheet, r Rect) bool

Reads reports whether the formula at u, on s, reads any cell of r on t directly: through a reference, a range, a named range or a region's name. It costs the formula's references, so asking it of every cell on screen is cheap.

func (*Sheet) RecalcAll

func (s *Sheet) RecalcAll()

RecalcAll recomputes every formula in the workbook. Loaders call it once the sheets are built, so it also starts a fresh undo history: loading isn't undoable.

func (*Sheet) RecalcVolatile

func (s *Sheet) RecalcVolatile()

RecalcVolatile recomputes volatile formulas and their dependents on every sheet, e.g. after remote answers arrive. It doesn't touch the undo history.

func (*Sheet) Redo

func (s *Sheet) Redo() (Change, bool)

func (*Sheet) Region

func (s *Sheet) Region(a Addr) Rect

Region returns the block of data around a, as Sheets picks the range to sort or filter when a single cell is selected: filled cells connected to a (diagonals count), and anything touching their bounding box, until nothing more touches it. A blank cell with no filled neighbors is a region of its own.

func (*Sheet) RegionAt added in v0.3.0

func (s *Sheet) RegionAt(a Addr) (Region, bool)

RegionAt returns the region covering the cell at a.

func (*Sheet) RegionTable added in v0.3.0

func (s *Sheet) RegionTable(name string) (Rect, bool)

RegionTable returns the cells of a region's table, header row included, when it has one.

func (*Sheet) Regions added in v0.3.0

func (s *Sheet) Regions() []Region

Regions returns the sheet's regions in the order they were made.

func (*Sheet) RemoteCalls

func (s *Sheet) RemoteCalls(a Addr) []RemoteCall

RemoteCalls returns the questions the formula at a asks, with their current inputs, so the UI can show details or re-ask them.

func (*Sheet) RemoveFilter

func (s *Sheet) RemoveFilter()

RemoveFilter removes the filter, showing every row again.

func (*Sheet) Replace

func (s *Sheet) Replace(a Addr, query, repl string, o FindOptions) (bool, error)

Replace replaces matches of query in the cell at a and reports whether the cell changed. Formula cells are only changed when searching within formulas, as in Sheets. A replacement that turns a formula invalid is returned as an error and leaves the cell unchanged.

func (*Sheet) ReplaceAll

func (s *Sheet) ReplaceAll(query, repl string, o FindOptions) (int, error)

ReplaceAll replaces every match and returns how many cells changed. It stops at the first cell whose replacement is an invalid formula.

func (*Sheet) RowFormats

func (s *Sheet) RowFormats() map[int]Format

func (*Sheet) RowHeight added in v0.3.0

func (s *Sheet) RowHeight(row int) (int, bool)

RowHeight returns the height set for row by hand, in lines, and false when it has none and fits its contents.

func (*Sheet) RowHidden

func (s *Sheet) RowHidden(r int) bool

RowHidden reports whether the filter hides row r.

func (*Sheet) RowStyles

func (s *Sheet) RowStyles() map[int]Style

func (*Sheet) RuleAbove added in v0.3.0

func (s *Sheet) RuleAbove(row int) bool

RuleAbove reports whether a border lies on the edge above row: the top of one of its cells or the bottom of one in the row before, or a column's, row's or the sheet's format drawing either.

func (*Sheet) Seal

func (s *Sheet) Seal()

func (*Sheet) Set

func (s *Sheet) Set(a Addr, input string) error

Set stores an entry at a and recalculates affected cells. An empty input erases the contents but keeps the cell's formatting. A formula that fails to parse is rejected with a *ParseError and the sheet is left unchanged. A pivot table's results can't be set: that's ErrPivotEdit.

func (*Sheet) SetBorderStroke added in v0.3.0

func (s *Sheet) SetBorderStroke(r Rect, k BorderKind, st Stroke)

SetBorderStroke is SetBorders with lines of a color. An outline of whole columns or rows draws the sheet's first and last edges too.

func (*Sheet) SetBorders added in v0.3.0

func (s *Sheet) SetBorders(r Rect, k BorderKind, l Line)

SetBorders draws the edges k names in r with line l, or removes every line of r for BorderNone, as one undo step. Neighbors outside r lose the lines on the edges they share with the ones set.

func (*Sheet) SetChart

func (s *Sheet) SetChart(i int, c Chart, label string)

SetChart replaces chart i, as one undo step described by label, e.g. "move chart".

func (*Sheet) SetColWidth

func (s *Sheet) SetColWidth(c, w int)

SetColWidth sets column c's width; w <= 0 resets it to the default.

func (*Sheet) SetCondFormat added in v0.2.0

func (s *Sheet) SetCondFormat(i int, f CondFormat) error

SetCondFormat replaces rule i, as one undo step.

func (*Sheet) SetDecimal

func (s *Sheet) SetDecimal(on bool)

func (*Sheet) SetFormat

func (s *Sheet) SetFormat(r Rect, f Format)

SetFormat gives every cell in r the number format f, including blank cells, which keep it for when something is typed. Whole columns and rows keep it as their line's format rather than on each cell.

func (*Sheet) SetFrozen

func (s *Sheet) SetFrozen(rows, cols int)

SetFrozen freezes the first rows rows and cols columns (0 unfreezes).

func (*Sheet) SetNote added in v0.2.0

func (s *Sheet) SetNote(a Addr, text string) error

SetNote sets the note on the cell at a as one undo step; an empty note deletes it. A pivot table's results can't take notes: ErrPivotEdit; nor can the cells an array spills into: ErrSpillEdit.

func (*Sheet) SetNotebookCells added in v0.3.0

func (s *Sheet) SetNotebookCells(label string, cells []notebook.Cell)

SetNotebookCells replaces a notebook tab's cells as one undo step described by label ("add cell"). Cells without an ID are given one.

func (*Sheet) SetPivot

func (s *Sheet) SetPivot(p Pivot, label string) error

SetPivot replaces the sheet's pivot definition as one undo step, labelled label ("edit pivot table" when empty).

func (*Sheet) SetReactive added in v0.3.0

func (s *Sheet) SetReactive(on bool)

SetReactive turns the notebook's reactive setting on or off, as one undo step.

func (*Sheet) SetRemote

func (s *Sheet) SetRemote(r RemoteSource)

SetRemote on a sheet is its workbook's.

func (*Sheet) SetRowHeight added in v0.3.0

func (s *Sheet) SetRowHeight(from, to, h int)

SetRowHeight sets rows from..to to h lines, as one undo step; h 0 has them fit their contents again, as Sheets' Fit to data. Heights are kept row by row, so a range of more than materializeLimit rows (whole columns) stops at the last row holding a cell.

func (*Sheet) SetStyle

func (s *Sheet) SetStyle(r Rect, fn func(*Style))

SetStyle changes the text style of every cell in r with fn, e.g. to turn on bold while keeping italics. Callers wanting a specific undo label ("bold B2:B5") wrap it in Batch.

func (*Sheet) SetValidation added in v0.2.0

func (s *Sheet) SetValidation(i int, v Validation) error

SetValidation replaces rule i, as one undo step.

func (*Sheet) Shaped added in v0.3.0

func (s *Sheet) Shaped() bool

Shaped reports whether any row may be other than one line of text under the one above: something wraps or draws borders, a row has a height of its own, or cells are merged. The grid lays out a sheet that isn't shaped a line per row without asking more.

func (*Sheet) SheetFormat

func (s *Sheet) SheetFormat() (Format, Style)

SheetFormat returns the format and style of the whole sheet, which every cell without its own, its row's or its column's shows.

func (*Sheet) ShownText

func (s *Sheet) ShownText(a Addr) string

ShownText is the cell's value as its format displays it, with no width limit: what filters and the values list compare.

func (*Sheet) SortRange

func (s *Sheet) SortRange(r Rect, keys []SortKey)

SortRange sorts the rows of r by keys, first key first, as Sheets' Data > Sort range does (r excludes any header row). The sort is stable, so rows that tie keep their order. Only the cells inside r move. Formulas move with their rows and their relative references shift by the distance moved, as if copied there; references to the sorted cells from elsewhere are left alone. The whole sort is one undo step.

Only rows holding cells are sorted: rows whose keys are all blank go last in their order, as blank rows do, so the cost is the rows with data, however tall r is.

func (*Sheet) Source added in v0.6.0

func (s *Sheet) Source() (SourceInfo, bool)

Source returns the linked source the sheet is the tab of.

func (*Sheet) SpillAnchor added in v0.2.0

func (s *Sheet) SpillAnchor(a Addr) (Addr, bool)

SpillAnchor returns the cell whose array result the cell at a shows, when a is a spilled cell (not the anchor itself).

func (*Sheet) SpillArea added in v0.2.0

func (s *Sheet) SpillArea(a Addr) (Rect, bool)

SpillArea returns the cells the formula at a spills into, the anchor first, when it spills.

func (*Sheet) StateID

func (s *Sheet) StateID() int

func (*Sheet) StrokeAbove added in v0.3.0

func (s *Sheet) StrokeAbove(a Addr) Stroke

StrokeAbove is EdgeAbove with its color: the heavier line's, or the cell's own where the lines are as heavy.

func (*Sheet) StrokeLeft added in v0.3.0

func (s *Sheet) StrokeLeft(a Addr) Stroke

StrokeLeft is EdgeLeft with its color.

func (*Sheet) TableAt added in v0.3.0

func (s *Sheet) TableAt(a Addr) (Table, bool)

TableAt returns the table holding the cell at a.

func (*Sheet) TableLook added in v0.3.0

func (s *Sheet) TableLook(a Addr) (header, band bool)

TableLook says how the cell at a draws as part of a table: in the header row's style, or on a band (every other data row), when its table has them.

func (*Sheet) Tables added in v0.3.0

func (s *Sheet) Tables() []Table

Tables returns the sheet's tables, in the order they were made.

func (*Sheet) Undo

func (s *Sheet) Undo() (Change, bool)

func (*Sheet) UndoCost added in v0.3.0

func (s *Sheet) UndoCost(r Rect) int64

UndoCost estimates the undo history a change to every cell of r would hold: a slot a cell, the rich cells in r whole, and r's share of the sheet's strings. The UI asks it before every command that edits, so it costs the fewer of r's cells and the sheet's rich cells.

func (*Sheet) Unload

func (s *Sheet) Unload(a Addr)

Unload removes a cell a loader stored, as an importer does with a row that doesn't fit whole.

func (*Sheet) Unmerge added in v0.3.0

func (s *Sheet) Unmerge(r Rect) int

Unmerge splits the merges overlapping r back into cells, as one undo step, and returns how many there were.

func (*Sheet) Unprotect added in v0.2.0

func (s *Sheet) Unprotect(i int)

Unprotect removes protection i (in Protections' order).

func (*Sheet) UnprotectRange added in v0.2.0

func (s *Sheet) UnprotectRange(r Rect) int

UnprotectRange removes every protection r overlaps, the sheet's included, as one undo step, and returns how many there were.

func (*Sheet) UsedRange

func (s *Sheet) UsedRange() (Rect, bool)

UsedRange returns the smallest range from A1 covering every non-blank cell, and false if the sheet is empty.

func (*Sheet) Validation added in v0.2.0

func (s *Sheet) Validation(a Addr) (Validation, bool)

Validation returns the rule of the cell at a, if it has one.

func (*Sheet) Validations added in v0.2.0

func (s *Sheet) Validations() []Validation

Validations returns the sheet's validation rules.

func (*Sheet) Value

func (s *Sheet) Value(a Addr) Value

Value returns the computed value at a.

func (*Sheet) Version added in v0.3.0

func (s *Sheet) Version() uint64

Version changes whenever anything the grid draws may have: cells, their values and formats, widths, heights and merges.

func (*Sheet) Widths

func (s *Sheet) Widths() map[int]int

Widths returns the columns that have a non-default width.

func (*Sheet) WrappedIn added in v0.3.0

func (s *Sheet) WrappedIn(row int) []int

WrappedIn returns the columns of row whose cells wrap text they hold, outside merged cells, in no particular order.

func (*Sheet) Write

func (s *Sheet) Write(w io.Writer) error

Write saves the workbook the sheet belongs to; see Workbook.Write.

type ShowAs

type ShowAs uint8

ShowAs is how a summarized value shows: as itself, or as a share of a total, as Sheets' "Show as".

const (
	ShowValue ShowAs = iota
	ShowPctRow
	ShowPctColumn
	ShowPctTotal
)

func ParseShowAs

func ParseShowAs(name string) (ShowAs, bool)

ParseShowAs is the inverse of ShowAs.String.

func ShowAsList

func ShowAsList() []ShowAs

ShowAsList lists the choices in Sheets' order.

func (ShowAs) String

func (s ShowAs) String() string

func (ShowAs) Title

func (s ShowAs) Title() string

type SortKey

type SortKey struct {
	Col  int
	Desc bool // Z to A
}

SortKey is one column to sort by.

type SourceAnswer added in v0.6.0

type SourceAnswer struct {
	V     Value
	A     *functions.Array
	Why   string
	Pivot *PivotGroups
}

SourceAnswer is what a SourceQuestion is answered: a value, an array of them, or a pivot table's groups; for an error that needs one, why.

type SourceFilter added in v0.6.0

type SourceFilter struct {
	Col  int
	Cond Condition
}

SourceFilter is a condition a source's view shows the rows meeting, on a column.

type SourceHost added in v0.6.0

type SourceHost interface {
	// Answer returns the answer to q, or false while it isn't known,
	// queuing q to be worked out.
	Answer(q SourceQuestion) (SourceAnswer, bool)
}

SourceHost answers the questions of a workbook's formulas and pivot tables about its linked sources.

type SourceInfo added in v0.6.0

type SourceInfo struct {
	// Name names it in formulas (sales[amount], nu.sales) and in the
	// SourceHost's questions.
	Name   string
	Sheet  *Sheet
	Source LinkSource
	Shape  SourceShape
	// Known is set once its host has opened it; Err says why it can't.
	Known bool
	Err   string
}

SourceInfo is a linked source as the UI shows it.

type SourceOrder added in v0.6.0

type SourceOrder struct {
	Sort   []SourceSort
	Filter []SourceFilter
}

SourceOrder is how a source's tab sorts and filters the rows it shows. Formulas read the source in its own order, every row, as they read a sheet whatever its filter hides.

func (*SourceOrder) IsZero added in v0.6.0

func (o *SourceOrder) IsZero() bool

IsZero reports whether the order is the source's own, every row.

type SourceQuestion added in v0.6.0

type SourceQuestion struct {
	Kind   AskKind
	Source string
	At     Addr
	R      Rect
	Call   functions.StreamCall
	Pivot  Pivot
}

SourceQuestion is one question about a linked source. Source is the source's name, the one whose file changing makes the answer stale; a call may read others too, named in its arguments.

func (SourceQuestion) Key added in v0.6.0

func (q SourceQuestion) Key() string

Key identifies the question by its content.

func (SourceQuestion) Sources added in v0.6.0

func (q SourceQuestion) Sources() []string

Sources names every source the question reads.

type SourceShape added in v0.6.0

type SourceShape struct {
	Cols    []string
	Formats []Format
	Numeric []bool
	Rows    int
}

SourceShape is what a source is, as its host finds on opening it: its columns' names, the formats their types show in, which hold numbers, and how many rows it has under the header.

type SourceSort added in v0.6.0

type SourceSort struct {
	Col  int
	Desc bool
}

SourceSort is a column a source's view is sorted by.

type Stats

type Stats struct {
	Sum         float64
	Count, Nums int
}

Stats summarizes the values in r, as shown in the status line for a selection. Count is non-blank cells, Nums is numeric cells.

type Steps added in v0.3.0

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

Steps is a formula evaluated one part at a time, as Excel's Evaluate Formula: the part computed next is marked in the formula, computing it puts its value in its place, and a reference to another formula can be stepped into. The values come from one evaluation by the function library with each part recorded where it stands (functions.EvalParts), so they are what the formula computes, context and all, and a branch IF didn't take is never computed. References are read as the formula reads them: the cell's value.

func (*Steps) CanStepIn added in v0.3.0

func (st *Steps) CanStepIn() bool

CanStepIn reports whether the next part is a reference to a formula's cell, which Into steps into.

func (*Steps) Cell added in v0.3.0

func (st *Steps) Cell() (*Sheet, Addr)

Cell is the formula's cell.

func (*Steps) Done added in v0.3.0

func (st *Steps) Done() bool

Done reports whether every part is computed.

func (*Steps) Into added in v0.3.0

func (st *Steps) Into() *Steps

Into starts stepping through the formula the next part refers to, when it is a reference to a formula's cell; nil otherwise.

func (*Steps) Next added in v0.3.0

func (st *Steps) Next() (expr, value string, ok bool)

Next is the part computed next, as written, and its value as the formula would write it; ok is false once done.

func (*Steps) Progress added in v0.3.0

func (st *Steps) Progress() (done, total int)

Progress is how many parts are computed, of how many.

func (*Steps) Restart added in v0.3.0

func (st *Steps) Restart()

Restart goes back to the formula as written.

func (*Steps) Result added in v0.3.0

func (st *Steps) Result() string

Result is the formula's value, an array it spills written whole.

func (*Steps) Step added in v0.3.0

func (st *Steps) Step()

Step computes the next part.

func (*Steps) Text added in v0.3.0

func (st *Steps) Text() []Segment

Text is the formula as it stands: "=" and its text, with the parts computed so far as their values and the next part marked, or once every part is computed, the formula's value.

type Stroke added in v0.3.0

type Stroke struct {
	Line  Line
	Color Color
}

Stroke is a line and its color.

type Style

type Style struct {
	Bold, Italic, Underline, Strikethrough bool
	Align                                  Align
	Wrap                                   Wrap
	VAlign                                 VAlign

	Borders Borders // see borders.go
	// contains filtered or unexported fields
}

Style is a cell's text style, with its wrapping, alignment and borders. It is a plain value so cells can be copied freely, twelve bytes, which the end of a Cell has room for (see Cell).

func (Style) IsZero

func (s Style) IsZero() bool

IsZero reports whether s is the default style.

type Summarize

type Summarize uint8

Summarize is how a pivot value summarizes a group's cells, as Sheets' "Summarize by". Each is one entry of summaries.

const (
	SumBy Summarize = iota
	CountABy
	CountBy
	CountUniqueBy
	AverageBy
	MaxBy
	MinBy
	// CountRowsBy counts rows, blank or not. Sheets has no such choice;
	// frequency tables use it so blank values are counted.
	CountRowsBy
)

func ParseSummarize

func ParseSummarize(name string) (Summarize, bool)

ParseSummarize is the inverse of Summarize.String.

func Summaries

func Summaries() []Summarize

Summaries lists the choices of "Summarize by", in Sheets' order.

func (Summarize) Desc

func (f Summarize) Desc() string

func (Summarize) String

func (f Summarize) String() string

func (Summarize) Title

func (f Summarize) Title() string

type Table added in v0.3.0

type Table struct {
	Name  string // as the user spelled it; formulas match it in any case
	Range Rect   // header row included
	// Cols are the columns' names, left to right: the header row's text
	// as last settled, never blank and never the same twice.
	Cols []string
	// Banded shades every other data row; Header styles the header row.
	Banded, Header bool
}

Table is a table on a sheet.

func (Table) Col added in v0.3.0

func (t Table) Col(name string) int

Col returns the index of the column named name, ignoring case, or -1.

func (Table) Data added in v0.3.0

func (t Table) Data() Rect

Data is the table's data rows, below the header row.

type TableInfo added in v0.3.0

type TableInfo struct {
	Name  string
	Sheet *Sheet
	// Range is its cells, header row included, when Shown.
	Range Rect

	Cols []string
	// Region is set on a region's table, which its source names and
	// shapes: the commands that change tables leave it alone.
	Region bool
	// contains filtered or unexported fields
}

TableInfo is a table as formulas find it: a table's, or a region's.

func (TableInfo) Shown added in v0.3.0

func (t TableInfo) Shown() bool

Shown reports whether the table has cells: a region's may have none yet.

type Target

type Target struct {
	Sheet *Sheet
	Range Rect
}

Target is a traced cell or range and the sheet it is on.

type VAlign added in v0.3.0

type VAlign uint8

VAlign is where a cell's text sits in a row taller than it, as Sheets' Format > Alignment's top, middle and bottom.

const (
	VAlignAuto   VAlign = iota // the bottom, as in Sheets; the middle of a merged cell
	VAlignTop                  //
	VAlignMiddle               //
	VAlignBottom               //
)

func ParseVAlign added in v0.3.0

func ParseVAlign(s string) (VAlign, bool)

ParseVAlign is the inverse of VAlign.String.

func (VAlign) Offset added in v0.3.0

func (v VAlign) Offset(k, n int, merged bool) int

Offset is the line, of n a row has, where the first of k lines of text starts: the top, the middle or the bottom, the bottom for VAlignAuto unless merged is set, which centers it.

func (VAlign) String added in v0.3.0

func (v VAlign) String() string

String returns the vertical alignment's name as stored in files.

type ValidKind added in v0.2.0

type ValidKind uint8

ValidKind is what a validation rule checks.

const (
	ValidList     ValidKind = iota // one of Items, picked from a dropdown
	ValidRange                     // one of the values of Source, picked from a dropdown
	ValidCheckbox                  // TRUE or FALSE, drawn as a checkbox
	ValidNumber                    // a number meeting Op
	ValidDate                      // a date meeting Op; any date with RuleNone
	ValidLength                    // text whose length meets Op
	ValidFormula                   // anything for which the formula Args[0] is TRUE

)

func ParseValidKind added in v0.2.0

func ParseValidKind(s string) (ValidKind, bool)

ParseValidKind is the inverse of ValidKind.String.

func ValidKinds added in v0.2.0

func ValidKinds() []ValidKind

ValidKinds lists the kinds in the order the rules editor offers them.

func (ValidKind) Compares added in v0.2.0

func (k ValidKind) Compares() bool

Compares reports whether the kind compares with Op and Args.

func (ValidKind) Dropdown added in v0.2.0

func (k ValidKind) Dropdown() bool

Dropdown reports whether cells of the kind offer a list to pick from.

func (ValidKind) String added in v0.2.0

func (k ValidKind) String() string

func (ValidKind) Title added in v0.2.0

func (k ValidKind) Title() string

Title names the kind for people, e.g. "Dropdown (from a range)".

type Validation added in v0.2.0

type Validation struct {
	Ranges []Rect
	Kind   ValidKind
	// Op compares numbers, dates or lengths with Args, as typed; RuleNone
	// with ValidDate accepts any date. With ValidFormula, Args[0] is the
	// formula, relative to the first range's top-left cell.
	Op    RuleOp
	Args  [2]string
	Items []string // ValidList's items
	// Source is ValidRange's range, e.g. "A2:A9" or "Lists!A1:A20".
	Source string
	// Reject refuses an invalid entry; otherwise it's kept and marked.
	Reject bool
	// Help replaces the rule's own help text, shown on the context line.
	Help string
	// Display is how a dropdown's cells show it (validstyle.go). A
	// checkbox's Items, when it has any, are its checked and unchecked
	// values.
	Display DropDisplay
}

Validation is a data validation rule.

func ParseValidation added in v0.2.0

func ParseValidation(line string) (Validation, error)

ParseValidation reads a rule written by JSON, checking it.

func (Validation) Check added in v0.2.0

func (v Validation) Check() error

Check reports why a rule can't be used, in words for the rules editor.

func (Validation) CheckboxValues added in v0.3.0

func (v Validation) CheckboxValues() (checked, unchecked string, custom bool)

CheckboxValues are what a checkbox rule's cells hold checked and unchecked: TRUE and FALSE, or its own values (Items), the unchecked one "" for a blank cell.

func (Validation) HelpText added in v0.2.0

func (v Validation) HelpText() string

HelpText is what the context line says about a cell under the rule: the rule's own help text, or Sheets' message for its criteria.

func (Validation) JSON added in v0.2.0

func (v Validation) JSON() string

JSON writes the rule as a line of the file, e.g. {"ranges":"D2:D20","criteria":"list","items":["Yes","No"]}.

func (Validation) SourceRange added in v0.2.0

func (v Validation) SourceRange() (string, Rect, bool)

SourceRange is ValidRange's source: its sheet as written ("" for the rule's own) and range.

func (Validation) Summary added in v0.2.0

func (v Validation) Summary() string

Summary describes the rule in a few words, e.g. "Number between 1 and 10".

type Value

type Value = value.Value

Value is the computed contents of a cell.

type Workbook

type Workbook struct {

	// Circular is set when the last recalculation found a cycle.
	Circular bool
	// contains filtered or unexported fields
}

A Workbook is an ordered list of sheets, as a Google Sheets spreadsheet: each sheet has its own cells, column widths, frozen panes, filter and charts, while named ranges, the undo history and recalculation are shared, so a formula on one sheet can read another (=Sheet2!A1, ='Q3 plan'!B2:C9) and one undo step can span sheets.

Formulas refer to other sheets by name. Renaming a sheet rewrites the formulas that name it; deleting one leaves them as written, showing #REF! ("Unresolved sheet name"), until a sheet of that name exists again, as in Sheets.

func NewBook

func NewBook() *Workbook

NewBook returns a workbook with one empty sheet, Sheet1.

func ReadBook

func ReadBook(r io.Reader) (*Workbook, error)

ReadBook loads a workbook written by Write, of this or an earlier version.

func (*Workbook) Active

func (w *Workbook) Active() int

Active returns the index of the sheet last shown, as saved in the file.

func (*Workbook) AddNotebook added in v0.3.0

func (w *Workbook) AddNotebook(name string, after *Sheet) (*Sheet, error)

AddNotebook adds a notebook tab named name ("" for Notebook, then Notebook 2 and so on) after the sheet after, as one undo step.

func (*Workbook) AddSheet

func (w *Workbook) AddSheet(name string, at int) (*Sheet, error)

AddSheet inserts a new, empty sheet at index at (clamped to the ends), as one undo step. An empty name picks the next SheetN.

func (*Workbook) AddSource added in v0.6.0

func (w *Workbook) AddSource(name string, src LinkSource, after *Sheet) (*Sheet, error)

AddSource adds a tab linking src as a source named name (a free name made from the file's when ""), after the sheet after, as one undo step. The tab and the table share the name. Its host opens it.

func (*Workbook) Adopt added in v0.6.0

func (w *Workbook) Adopt(author int)

Adopt makes the steps of nobody in particular (author 0), made while one person edited alone, the author's: a session sharing its workbook from then on keeps its person's earlier steps theirs to undo.

func (*Workbook) ApplyLive added in v0.3.0

func (w *Workbook) ApplyLive(op LiveOp) error

ApplyLive applies op to its region: its rows are written, a window drops the oldest, and what reads the cells that changed recalculates. It returns ErrNoRegion for a region the workbook doesn't hold.

func (*Workbook) Author added in v0.5.0

func (w *Workbook) Author() int

Author is who makes the steps that follow (SetAuthor).

func (*Workbook) Batch

func (w *Workbook) Batch(c Change, fn func() error) error

Batch runs fn as a single undo step across sheets, as Sheet.Batch; the step is shown on c.Sheet when undone.

func (*Workbook) Begin

func (w *Workbook) Begin(c Change) (end func())

Begin opens an undo step that stays open until the returned function is called, for changes made over several calls that undo together, such as a macro run. Changes in between join it as in a Batch, and Undo and Redo do nothing while it is open. Call Settle to see the values of formulas changed so far.

func (*Workbook) CanRedo

func (w *Workbook) CanRedo() bool

func (*Workbook) CanUndo

func (w *Workbook) CanUndo() bool

CanUndo and CanRedo report whether there is a step to undo or redo: with the history shared, one of the current author's.

func (*Workbook) Checkpoint added in v0.5.0

func (w *Workbook) Checkpoint() int

Checkpoint marks where the history stands, for UndoTo.

func (*Workbook) ClearHistory

func (w *Workbook) ClearHistory()

ClearHistory forgets all undo and redo steps.

func (*Workbook) CreatePivot

func (w *Workbook) CreatePivot(src *Sheet, r Rect, name string, p Pivot) (*Sheet, error)

CreatePivot adds a sheet named name ("" for the next Pivot Table N) right after src, holding p over r on src, as one undo step.

func (*Workbook) Decimal

func (w *Workbook) Decimal() bool

Decimal reports whether the workbook computes in decimal.

func (*Workbook) DefaultSummarize

func (w *Workbook) DefaultSummarize(p Pivot, col int) Summarize

DefaultSummarize is how a new value summarizes column col, as in Sheets: SUM when the column holds a number, COUNTA otherwise.

func (*Workbook) DefineName

func (w *Workbook) DefineName(name string, s *Sheet, r Rect) error

DefineName names the range r on sheet s, as one undo step.

func (*Workbook) DeleteMacro

func (w *Workbook) DeleteMacro(name string) bool

DeleteMacro removes the named macro as an undo step, reporting whether there was one.

func (*Workbook) DeleteName

func (w *Workbook) DeleteName(name string) error

DeleteName removes a named range, as one undo step. Formulas that use it show #NAME? until it is defined again.

func (*Workbook) DeleteSheet

func (w *Workbook) DeleteSheet(s *Sheet) error

DeleteSheet removes s, as one undo step. Formulas on other sheets that refer to it show #REF! until it's restored or another sheet takes its name. The last sheet can't be deleted.

func (*Workbook) Discard added in v0.3.0

func (w *Workbook) Discard() bool

Discard takes back the last change and forgets it, so redo can't bring it back: a paste or fill refused after the fact. It reports whether there was a change to take back.

func (*Workbook) DuplicateSheet

func (w *Workbook) DuplicateSheet(s *Sheet) (*Sheet, error)

DuplicateSheet copies s, cells, widths, heights, frozen panes, filter, merges, tables and charts, to a new sheet right after it named "Copy of ...", as Sheets' Duplicate; each table copied takes a name of its own (Sales_2). Formulas are copied as written, so references without a sheet name read the copy's own cells.

func (*Workbook) EditName

func (w *Workbook) EditName(old, name string, s *Sheet, r Rect) error

EditName renames the named range old and points it at r on sheet s, as one undo step. Formulas that use it are rewritten to the new name, as in Sheets.

func (*Workbook) EndStep added in v0.5.0

func (w *Workbook) EndStep()

EndStep closes the step left open (Begin) by a participant who is gone, as if they had ended it: what it did stays, one step.

func (*Workbook) FieldName

func (w *Workbook) FieldName(p Pivot, col int) string

FieldName is the header of column col in the pivot's source, or "Column B" when the header is blank.

func (*Workbook) FreeCellName added in v0.3.0

func (w *Workbook) FreeCellName(base string) string

FreeCellName is a name like base that no cell and no region of the workbook has: base, then base_2 and so on; cell1 and on for "".

func (*Workbook) HiddenSheets

func (w *Workbook) HiddenSheets() []*Sheet

HiddenSheets returns the hidden sheets, in tab order.

func (*Workbook) HideSheet

func (w *Workbook) HideSheet(s *Sheet) error

HideSheet hides s, as one undo step. The last visible sheet can't be hidden.

func (*Workbook) HistoryBytes

func (w *Workbook) HistoryBytes() int64

HistoryBytes estimates the memory the undo steps hold.

func (*Workbook) InStep added in v0.5.0

func (w *Workbook) InStep() (bool, int)

InStep reports whether a step is open (Begin, a macro running), and whose it is.

func (*Workbook) Index

func (w *Workbook) Index(s *Sheet) int

Index returns s's position in tab order, or -1 if it was deleted.

func (*Workbook) InsertBook

func (w *Workbook) InsertBook(src *Workbook, at int, label string) (ImportResult, error)

InsertBook moves the sheets of src, an imported workbook, into w at index at (clamped to the ends; the UI puts them after the sheet shown), with src's named ranges, as one undo step labelled label. A sheet whose name w already has gets a number ("Sales 2"), and src's formulas follow the new name; a named range whose name w already has is left out. src is used up.

func (*Workbook) LastOp added in v0.5.0

func (w *Workbook) LastOp() uint64

LastOp is the latest operation's sequence number, 0 before any.

func (*Workbook) Len

func (w *Workbook) Len() int

Len returns the number of sheets.

func (*Workbook) LinkedRegion added in v0.3.0

func (w *Workbook) LinkedRegion(name string) (LinkedRegion, bool)

LinkedRegion returns the linked file name names.

func (*Workbook) LinkedRegions added in v0.3.0

func (w *Workbook) LinkedRegions() []LinkedRegion

LinkedRegions returns every live sheet's linked files, sheet by sheet.

func (*Workbook) LoadNotes added in v0.3.0

func (w *Workbook) LoadNotes() []string

LoadNotes say what opening the file changed that the user should know, such as notebook sheets converted.

func (*Workbook) Locale added in v0.3.0

func (w *Workbook) Locale() *locale.Locale

Locale is the workbook's locale: its own, or the default.

func (*Workbook) LocaleTag added in v0.3.0

func (w *Workbook) LocaleTag() string

LocaleTag is the tag of the locale the workbook names, or "" when it follows the default.

func (*Workbook) Lookup

func (w *Workbook) Lookup(name string) *Sheet

Lookup finds a sheet by name, ignoring case.

func (*Workbook) LookupName

func (w *Workbook) LookupName(name string) (Name, bool)

LookupName finds a named range, ignoring case.

func (*Workbook) LookupSource added in v0.6.0

func (w *Workbook) LookupSource(name string) (SourceInfo, bool)

LookupSource finds a linked source by name, ignoring case.

func (*Workbook) LookupTable added in v0.3.0

func (w *Workbook) LookupTable(name string) (TableInfo, bool)

LookupTable finds a table formulas can read by name, ignoring case.

func (*Workbook) Macro

func (w *Workbook) Macro(name string) (Macro, bool)

Macro finds a macro by name, ignoring case.

func (*Workbook) MacroForKey

func (w *Workbook) MacroForKey(key string) (Macro, bool)

MacroForKey finds the macro a shortcut digit runs.

func (*Workbook) MacroOrigin

func (w *Workbook) MacroOrigin() string

MacroOrigin identifies the computer the workbook's macros were made or trusted on, as saved in the file; "" when unknown. The UI compares it with its own to decide whether to ask before running a macro from a file made elsewhere.

func (*Workbook) Macros

func (w *Workbook) Macros() []Macro

Macros returns the saved macros in the order they were added.

func (*Workbook) MoveSheet

func (w *Workbook) MoveSheet(s *Sheet, to int)

MoveSheet moves s to index to in tab order, as one undo step.

func (*Workbook) NameUsers

func (w *Workbook) NameUsers(name string) int

NameUsers returns how many formulas mention the name.

func (*Workbook) Names

func (w *Workbook) Names() []Name

Names returns the named ranges, sorted by name.

func (*Workbook) NewCellID added in v0.3.0

func (w *Workbook) NewCellID() int

NewCellID is an ID no cell of the workbook has had.

func (*Workbook) NextPivotName

func (w *Workbook) NextPivotName() string

NextPivotName is the name Sheets gives a new pivot sheet: Pivot Table 1, then 2 and so on.

func (*Workbook) NextTableName added in v0.3.0

func (w *Workbook) NextTableName() string

NextTableName is a name no table has yet: Table1, Table2 ...

func (*Workbook) Notebook added in v0.3.0

func (w *Workbook) Notebook() *Sheet

Notebook is the workbook's first notebook tab, or nil.

func (*Workbook) OpsSince added in v0.5.0

func (w *Workbook) OpsSince(seq uint64) ([]Op, uint64)

OpsSince is the operations after seq, the last opLogSize at most, and the sequence number of the latest.

func (*Workbook) Output added in v0.3.0

func (w *Workbook) Output(id int) *notebook.Output

Output is what the cell with the ID id left when it last ran, or nil.

func (*Workbook) OutputCaps added in v0.3.0

func (w *Workbook) OutputCaps() notebook.Caps

OutputCaps are how much of the outputs a file keeps.

func (*Workbook) OutputsChanged added in v0.3.0

func (w *Workbook) OutputsChanged() int

OutputsChanged counts changes to outputs, for the modified flag.

func (*Workbook) PauseLinked added in v0.3.0

func (w *Workbook) PauseLinked(name string, paused bool)

PauseLinked stops a linked file following its file, or has it follow again. It isn't an edit: what follows the file reads it.

func (*Workbook) PivotFilterValues

func (w *Workbook) PivotFilterValues(p Pivot, col int) []FilterValue

PivotFilterValues lists the distinct values of column col of the pivot's source, among the rows its other filters let through, as a filter's values list does.

func (w *Workbook) RebaseLinks(fn func(string) string)

RebaseLinks rewrites the path of every linked file with fn, as the UI does when the workbook is saved in another folder, in the undo history too, so undo puts back regions reading the same files. It isn't an edit: the regions read the same files.

func (*Workbook) RecalcAll

func (w *Workbook) RecalcAll()

RecalcAll recomputes every formula and clears the undo history.

func (*Workbook) RecalcAnswered

func (w *Workbook) RecalcAnswered(calls []RemoteCall)

RecalcAnswered recomputes the formulas that were waiting for the answers to calls, and what depends on them, on every sheet: with thousands of JEV cells, an answer costs the cells that asked it, not all of them. It doesn't touch the undo history.

func (*Workbook) RecalcSourced added in v0.6.0

func (w *Workbook) RecalcSourced(keys []string)

RecalcSourced recomputes the formulas and pivot tables that were waiting for the answers to the questions with keys, and what depends on them. It doesn't touch the undo history.

func (*Workbook) Redo

func (w *Workbook) Redo() (Change, bool)

Redo reapplies the last undone step and describes it.

func (*Workbook) RedoBlocked added in v0.5.0

func (w *Workbook) RedoBlocked() (Blocked, bool)

RedoBlocked reports whether the current author's latest undo can't be redone, and the first step made since that's in the way.

func (*Workbook) Region added in v0.3.0

func (w *Workbook) Region(name string) (*Sheet, Region, bool)

Region finds a region by name, ignoring case, on any sheet.

func (*Workbook) ReloadLinked added in v0.3.0

func (w *Workbook) ReloadLinked(name string)

ReloadLinked marks a linked file stale, so the UI reads it again, whole.

func (*Workbook) RemoveTable added in v0.3.0

func (w *Workbook) RemoveTable(name string) error

RemoveTable removes a table, keeping its cells, as one undo step. Formulas that read it read the same cells by address instead, as Excel's Convert to range leaves them.

func (*Workbook) RenameRegion added in v0.3.0

func (w *Workbook) RenameRegion(old, name string) error

RenameRegion gives a sent output its cell's new name, as one undo step; it is sent again.

func (*Workbook) RenameSheet

func (w *Workbook) RenameSheet(s *Sheet, name string) error

RenameSheet renames s, as one undo step, rewriting every formula that refers to it by its old name.

func (*Workbook) RenameTable added in v0.3.0

func (w *Workbook) RenameTable(old, name string) error

RenameTable renames a table, as one undo step, and every formula that reads it with it.

func (*Workbook) ReplaceSheet

func (w *Workbook) ReplaceSheet(dst, s *Sheet, label string) ([]ChartFate, error)

ReplaceSheet puts s, the sheet of an imported workbook, in the place of dst, as one undo step labelled label: it takes dst's name and position, so formulas reading dst read it, and named ranges on dst move to it. dst's charts that fit s's data stay, drawing it, and the rest go (see keepCharts); it returns what became of each. dst's cells and the rest go; undo brings them back, charts too.

func (*Workbook) ResizeTable added in v0.3.0

func (w *Workbook) ResizeTable(name string, r Rect) error

ResizeTable points a table at r, as one undo step. Its columns take their names from r's first row.

func (*Workbook) SaveMacro

func (w *Workbook) SaveMacro(old string, mc Macro, label string) error

SaveMacro stores mc in place of the macro named old, or adds it when old is "", as one undo step labelled label. Names are unique ignoring case, and so are shortcuts.

func (*Workbook) Seal

func (w *Workbook) Seal()

Seal ends a run of column width changes, so the next one starts a new undo step. The UI calls it between user actions.

func (*Workbook) SetActive

func (w *Workbook) SetActive(s *Sheet)

SetActive records which sheet is shown, for the file. It isn't an edit.

func (*Workbook) SetAuthor added in v0.5.0

func (w *Workbook) SetAuthor(a int)

SetAuthor names who makes the steps that follow; 0 is nobody in particular, as in a workbook only one person edits.

func (*Workbook) SetDecimal

func (w *Workbook) SetDecimal(on bool)

SetDecimal turns decimal arithmetic on or off for every sheet, as one undo step, and recalculates every formula.

func (*Workbook) SetLinkSource added in v0.3.0

func (w *Workbook) SetLinkSource(name string, src LinkSource) error

SetLinkSource changes what a linked file reads (its window, say), as one undo step; it is read again.

func (*Workbook) SetLocale added in v0.3.0

func (w *Workbook) SetLocale(tag string) bool

SetLocale sets the workbook's locale by its tag, "" to follow the default, as one undo step. Values don't change, only how they're typed and shown. It reports false for a tag it doesn't know.

func (*Workbook) SetMacroOrigin

func (w *Workbook) SetMacroOrigin(origin string)

SetMacroOrigin records where the macros were made or trusted. It isn't an edit: it changes nothing a user sees, and is saved with the next save.

func (*Workbook) SetOutput added in v0.3.0

func (w *Workbook) SetOutput(id int, o *notebook.Output)

SetOutput keeps o as what the cell with the ID id left, nil for nothing, giving it a Seq of its own. It isn't an undo step.

func (*Workbook) SetOutputCaps added in v0.3.0

func (w *Workbook) SetOutputCaps(c notebook.Caps)

SetOutputCaps sets how much of the outputs a file keeps.

func (*Workbook) SetRemote

func (w *Workbook) SetRemote(r RemoteSource)

SetRemote sets what answers the workbook's JEV functions: nil when no API key is configured, and the functions then evaluate to ErrNoRemote. It recomputes them, so a loaded file's questions are asked.

func (*Workbook) SetSourceOrder added in v0.6.0

func (w *Workbook) SetSourceOrder(name string, o *SourceOrder) error

SetSourceOrder changes how a source's tab sorts and filters its rows, as one undo step; o nil shows the source's own order.

func (*Workbook) SetSourceShape added in v0.6.0

func (w *Workbook) SetSourceShape(name string, shape SourceShape, err string)

SetSourceShape records what the host found on opening a source, or why it couldn't (err), and recalculates what reads it. It isn't an edit: the file is what it is.

func (*Workbook) SetSources added in v0.6.0

func (w *Workbook) SetSources(h SourceHost)

SetSources sets what answers the workbook's questions about linked sources, nil for nothing (they then say so), and recomputes what reads them.

func (*Workbook) SetTableStyle added in v0.3.0

func (w *Workbook) SetTableStyle(name string, banded, header bool) error

SetTableStyle sets whether a table's data rows are banded and its header row styled, as one undo step.

func (*Workbook) SetTrace

func (w *Workbook) SetTrace(trace any)

SetTrace gives the workbook its owner's trace, opaque to the engine: a *telemetry.Trace from the program or import that holds the workbook, which only its goroutine uses, as with the workbook itself.

func (*Workbook) Settle

func (w *Workbook) Settle()

Settle recalculates what the open step has changed so far, so formulas read inside it (by a macro, or a command it runs) see current values. Outside a step there is nothing pending.

func (*Workbook) ShareHistory added in v0.5.0

func (w *Workbook) ShareHistory()

ShareHistory has undo and redo take back only each author's own steps, from now on.

func (*Workbook) Sheet

func (w *Workbook) Sheet(i int) *Sheet

Sheet returns the sheet at index i in tab order.

func (*Workbook) Sheets

func (w *Workbook) Sheets() []*Sheet

Sheets returns the sheets in tab order.

func (*Workbook) SourceChanged added in v0.6.0

func (w *Workbook) SourceChanged(name string)

SourceChanged recalculates what reads a source, whose file changed: the formulas that asked it something or name its table, and the pivot tables over it. Its host has forgotten its answers.

func (*Workbook) Sources added in v0.6.0

func (w *Workbook) Sources() []SourceInfo

Sources returns the workbook's linked sources, in the order of their tabs.

func (*Workbook) StaleOutputs added in v0.3.0

func (w *Workbook) StaleOutputs() []string

StaleOutputs names the outputs sent to sheets that are to be sent again: new, put back by undo, moved, or no longer blocked.

func (*Workbook) StateID

func (w *Workbook) StateID() int

StateID identifies the workbook's contents in its undo history: undoing back to a saved state returns the ID it had when saved, so the UI can tell whether there are unsaved changes.

func (*Workbook) Table added in v0.3.0

func (w *Workbook) Table(name string) (*Sheet, Table, bool)

Table finds a table by name, ignoring case, on any sheet. Regions' tables aren't among them: see TableInfo.

func (*Workbook) TableInfos added in v0.3.0

func (w *Workbook) TableInfos() []TableInfo

TableInfos returns every table formulas can read, sheet by sheet: each sheet's tables in the order they were made, then its regions'.

func (*Workbook) TableRange added in v0.3.0

func (w *Workbook) TableRange(ref string) (s *Sheet, r Rect, ok bool, err error)

TableRange finds the cells a structured reference written alone stands for (Sales[Amount], Sales[#All]), as a formula outside the table reads them, or with a table's name alone its whole table, header row included. ok is false when ref is neither; err says why one names no cells.

func (*Workbook) Try added in v0.3.0

func (w *Workbook) Try(fn func() error, takeBack func() bool) (bool, error)

Try runs fn, a change, so that it can be taken back whole: after fn and a recalculation, takeBack says whether to. Outside any step, fn's change is a step of its own and taking it back discards it, as Discard does; inside a step another change opened (a macro's run), what fn changed is put back within that step, which goes on. It reports whether fn's change stayed, and fn's error. A paste or fill checked against validation after the fact runs through it.

func (*Workbook) Undo

func (w *Workbook) Undo() (Change, bool)

Undo reverts the last step and describes it.

func (*Workbook) UndoBlocked added in v0.5.0

func (w *Workbook) UndoBlocked() (Blocked, bool)

UndoBlocked reports whether the current author's latest step can't be undone, and the first later step in the way.

func (*Workbook) UndoLabel

func (w *Workbook) UndoLabel() string

UndoLabel describes the step Undo would revert, e.g. "clear B3:B5", or "" when there is none.

func (*Workbook) UndoTo added in v0.5.0

func (w *Workbook) UndoTo(c int)

UndoTo undoes the current author's steps made after checkpoint c, as cancelling a dialog does, whatever others changed meanwhile; it stops at a step it can't undo.

func (*Workbook) UnhideSheet

func (w *Workbook) UnhideSheet(s *Sheet) error

UnhideSheet shows s again, as one undo step.

func (w *Workbook) Unlink(name string) error

Unlink turns a linked file into the values it shows, as ordinary cells, as one undo step: FreezeRegion.

func (*Workbook) UnsavedOutputs added in v0.3.0

func (w *Workbook) UnsavedOutputs() []string

UnsavedOutputs names the cells whose outputs a file written now would leave out, over the caps.

func (*Workbook) ValueTitle

func (w *Workbook) ValueTitle(p Pivot, v PivotValue) string

ValueTitle is the header of a value: its name, or Sheets' "SUM of Sales".

func (*Workbook) Version added in v0.5.0

func (w *Workbook) Version() uint64

Version changes whenever the workbook changes: a step made, undone or redone, a recalculation, rows arriving at a region.

func (*Workbook) Visible

func (w *Workbook) Visible() []*Sheet

Visible returns the sheets that aren't hidden, in tab order.

func (*Workbook) WithoutUndo added in v0.3.0

func (w *Workbook) WithoutUndo(fn func())

WithoutUndo runs fn, a change too large to undo (see MaxStepBytes), recording no before-images, and forgets the undo history, which could no longer be undone past it. Inside a Batch it runs fn as part of it.

func (*Workbook) Write

func (w *Workbook) Write(out io.Writer) error

Write saves the workbook as JSON, storing each cell's input as typed and its formatting. Cells go one per line in row-major order so diffs read naturally. It streams: cells are written as they are read from the store, through a buffer of its own, so writing costs about nothing on top of the workbook whatever its size.

type Wrap added in v0.3.0

type Wrap uint8

Wrap is what a cell's text does when it is wider than its column, as Sheets' Format > Wrapping.

const (
	WrapOverflow Wrap = iota // run on into blank neighbors, Sheets' default
	WrapOn                   // break into lines; the row grows to fit them
	WrapClip                 // cut at the cell's edge
)

func ParseWrap added in v0.3.0

func ParseWrap(s string) (Wrap, bool)

ParseWrap is the inverse of Wrap.String.

func (Wrap) String added in v0.3.0

func (w Wrap) String() string

String returns the wrapping's name as stored in files.

Jump to

Keyboard shortcuts

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