doc

package
v1.7.0 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2026 License: MIT Imports: 18 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package doc parses a markdown file into prose and fenced code blocks without losing a byte of the original, so output can be spliced back in.

Index

Constants

View Source
const (
	FnJSON   = "json"
	FnHeader = "header"
	FnStatus = "status"
)

Response functions, which read an http block's response.

View Source
const (
	Status   = "?"    // exit status
	StatusAs = "err?" // the same, spelled out
	Ran      = "ran?" // "true" if the block ran, else "false"
)

Block facts, which end in ? so they can't clash with shell variables.

View Source
const (
	ChoiceDropdown = "dropdown" // pick one from a list; the default
	ChoiceRadio    = "radio"    // pick one of a group of buttons
	ChoiceMulti    = "multi"    // check any number of boxes
)

The values of a choice's mode=.

View Source
const ChoiceLang = "choice"

ChoiceLang is the language of a choice, a block whose body lists options as task list items, the checked ones chosen:

```choice {#env mode=radio var=env}
- [ ] staging
- [x] prod
```

It never runs.

View Source
const DefaultHistory = 10

DefaultHistory is how many earlier runs a bare history attribute keeps when the front matter doesn't say.

View Source
const IncludeAttr = "<include"

IncludeAttr marks an include block:

```go {<include file=main.go from=10 to=20 number_on}
```

mdsh writes the selected lines into the block's body. The block never runs and has no name.

View Source
const LinesFit = "fit"

LinesFit is the lines= value that sizes a textbox to its text.

View Source
const RegionEnd = regionClose

RegionEnd is the line that closes an output region.

View Source
const TapeLang = "tape"

TapeLang is the language of a tape fence, which types the input for the tty block its for= names:

```tape {for=shell}
Type "exit"
Enter
```

It can be an include block too, to read the tape from a file.

View Source
const TextboxLang = "textbox"

TextboxLang is the language of a textbox, a block that holds text typed in an interactive view instead of code:

```textbox {#host lines=1 placeholder="Which host?" var=host}
db1.example.com
```

The body is the text. It never runs.

View Source
const VarPrefix = "MDSH_VAR_"

VarPrefix starts the name of the variable an input's var= binds.

Variables

View Source
var BlockAttrs = []AttrSpec{
	{Name: "#", Kind: AttrText, Default: "block-N", Help: "The block's name, for output, placeholders and --only"},
	{Name: "skip", Kind: AttrFlag, Default: "off", Help: "Don't run the block"},
	{Name: "run", Kind: AttrCond, Default: "run", Help: "Run only if the condition holds; once runs it only while it has no output"},
	{Name: "show", Kind: AttrCond, Default: "shown", Help: "Print the code only if the condition holds"},
	{Name: "show-output", Kind: AttrCond, Default: "shown", Help: "Print the output only if the condition holds"},
	{Name: "show-stderr", Kind: AttrCond, Bare: true, Default: "front matter show_stderr, else only when the block fails", Help: "Show stderr, or only if the condition holds"},
	{Name: "collapse", Kind: AttrCond, Bare: true, Default: "expanded", Help: "In mdsh-gui, open with the code folded to one line, or only if the condition holds"},
	{Name: "collapse-output", Kind: AttrCond, Bare: true, Default: "expanded", Help: "In mdsh-gui, open with the output folded to one line, or only if the condition holds"},
	{Name: "history", Kind: AttrNumber, Bare: true, Default: "off", Help: "Keep the outputs of this many earlier runs under the current one, newest first; bare keeps the front matter's history, else 10"},
	{Name: "nosave", Kind: AttrFlag, Default: "off", Help: "Saving keeps what the file holds: the block's output, or a textbox's text or a choice's picks, lives in the session only"},
	{Name: "links", Kind: AttrFlag, Default: "off", Help: "Make web addresses in the output clickable, in mdsh-gui and mdsh -i; History adds it to the commands typed there"},
	{Name: "secret", Kind: AttrFlag, Default: "off", Help: "The block's code and output hold a secret: mdsh-gui and mdsh -i mask them until you show them, copying still works, reports print them as (secret) unless --show-secrets, and as with nosave its output isn't saved to the file"},
	{Name: "env", Kind: AttrText, Default: "top-level env", Help: "Run in a named sub-env; a/b stacks b on a"},
	{Name: "share", Kind: AttrList, Default: "front matter env.share, else all", Help: "Exported variables a new sub-env gets from its parent, besides PATH, HOME, USER and the rest of the base set; empty for just the base set"},
	{Name: "on_error", Kind: AttrChoice, Values: []string{"stop", "continue"}, Default: "front matter on_error", Help: "Stop the run if this block fails, or go on"},
	{Name: "depends", Kind: AttrList, Default: "none", Help: "Blocks to run first, in order: each one that hasn't run this session is asked about"},
	{Name: "always", Kind: AttrFlag, Default: "off", Help: "As a dependency, run again each time a block that depends on it runs, even if it already ran this session"},
	{Name: "confirm", Kind: AttrText, Bare: true, Default: "off", Help: "Ask before running, with this question if given"},
	{Name: "timeout", Kind: AttrDuration, Default: "none", Help: "Kill the block's shell after this long; stops the run. A background block is killed alone"},
	{Name: "background", Kind: AttrFlag, Default: "off", Help: "Start the block and go on to the next; its output is kept apart, and the run waits for it at the end"},
	{Name: "tty", Kind: AttrFlag, Default: "off", Help: "Run on a terminal, for commands that need one; the session is saved as an asciinema cast, or a GIF with out=recording:<name>.gif"},
	{Name: "frame", Kind: AttrNumber, Default: "the last", Help: "With tty, or on a cast fence, the frame of the recording that still views show and the player opens at, counting from 1; mdsh-gui sets it where you leave the player"},
	{Name: "out", Kind: AttrChoice, Values: []string{"text", "markdown", "image", "image:", "screenshot", "screenshot:", "recording:"}, Default: "text", Help: "How output is inserted: fenced text, raw markdown, or an image saved beside the file"},
	{Name: "raw", Kind: AttrFlag, Default: "off", Help: "On an http block, save the response body as it came instead of pretty-printing JSON"},
	{Name: "embed", Kind: AttrChoice, Values: []string{"inline"}, Default: "off", Help: "With out=image or out=screenshot, write a data URI instead of a file"},
	{Name: IncludeAttr, Kind: AttrFlag, Include: true, Help: "Fill the block with lines from another file; it never runs"},
	{Name: "file", Kind: AttrText, Include: true, Help: "The file to include, relative to the document's folder; res://name is name in the document's assets folder"},
	{Name: "from", Kind: AttrNumber, Include: true, Default: "the first line", Help: "The first line to include, counting from 1"},
	{Name: "to", Kind: AttrNumber, Include: true, Default: "the last line", Help: "The last line to include"},
	{Name: "number_on", Kind: AttrFlag, Include: true, Default: "off", Help: "Show each included line's number in the file"},
	{Name: "lines", Kind: AttrNumber, Values: []string{LinesFit}, Inputs: []string{TextboxLang}, Default: "1", Help: "The most lines a textbox holds, 1 or less being one line; fit holds any number and sizes the box to the text"},
	{Name: "mode", Kind: AttrChoice, Values: []string{ChoiceDropdown, ChoiceRadio, ChoiceMulti}, Inputs: []string{ChoiceLang}, Default: ChoiceDropdown, Help: "Pick one from a dropdown or radio buttons, or check any number of boxes"},
	{Name: "placeholder", Kind: AttrText, Inputs: []string{TextboxLang, ChoiceLang}, Default: "none", Help: "What an empty textbox, or a dropdown with nothing chosen, shows in an interactive view"},
	{Name: "var", Kind: AttrText, Inputs: []string{TextboxLang, ChoiceLang}, Default: "none", Help: "Bind the text, or the checked options one per line, to $MDSH_VAR_<name> for blocks and conditions"},
}

BlockAttrs are the block attributes mdsh reads, in the order the spec lists them. Others are kept untouched.

View Source
var ErrDependsOrder = errors.New("a block would go above one it depends on")

ErrDependsOrder is what a move fails with, wrapped, when it would take a block above one its depends= names.

View Source
var ErrNoMove = errors.New("the block can't move further that way")

ErrNoMove is StepTarget's answer for a move up from the top or down from the bottom.

View Source
var ErrRenumber = errors.New("deleting the block would renumber the blocks after it")

ErrRenumber is returned by DeleteBlock when taking the block out would renumber a block after it whose block-N id something uses. Naming the blocks first (see NameBlocks) fixes it.

Functions

func CloseSections added in v1.3.0

func CloseSections(hs []Heading, end int)

CloseSections sets each heading's Span.End to the start of the next heading of the same or a higher level, or to end. The headings are in order and their Span.Start is set.

func EscapeValue

func EscapeValue(v string) string

EscapeValue quotes a value for the :"..." part of a placeholder.

func Expand

func Expand(text string, lookup Lookup) (string, error)

Expand replaces each placeholder in text with its value from lookup, ignoring any stored :"..." value. A placeholder lookup doesn't know is an error.

func GeneratedID added in v1.3.0

func GeneratedID(id string) bool

GeneratedID reports whether id is one NewBlockID makes.

func IsHistoryID added in v1.3.0

func IsHistoryID(id string) bool

IsHistoryID reports whether id is one the History pane gives the blocks it adds, history-N.

func NewBlockID added in v1.3.0

func NewBlockID() string

NewBlockID returns a new id for a block that has none: block-<uuidv7>. Unlike block-N, it doesn't change when blocks move.

func RegionStart

func RegionStart(id string) string

RegionStart returns the line that opens an output region for id.

func RegionStartAt added in v1.6.0

func RegionStartAt(id, at string) string

RegionStartAt returns the line that opens an output region for id stamped with at=, the time its block's run started.

func SetAttr added in v1.6.0

func SetAttr(info, key, value string) string

SetAttr returns info, a fence info string, with key set to value, replacing what key held, or with value empty, taken out:

SetAttr("go {<include file=a.go}", "to", "20")       // go {<include file=a.go to=20}
SetAttr("go {<include file=a.go to=20}", "to", "30") // go {<include file=a.go to=30}
SetAttr("go {<include file=a.go to=20}", "to", "")   // go {<include file=a.go}

A value with a space or a quote in it is quoted. Like SetFlag, it returns info unchanged when info has text after the language that isn't attributes.

func SetFlag added in v1.3.0

func SetFlag(info, key string, on bool) string

SetFlag returns info, a fence info string, with the bare attribute key added (on) or taken out, keeping the rest of it as it is:

SetFlag("sh {#a}", "collapse", true)     // sh {#a collapse}
SetFlag("sh {#a collapse}", "collapse", false) // sh {#a}

It returns info unchanged when key is already as asked, when key holds a value, such as a condition, which it leaves alone, or when info has text after the language that isn't attributes, as in sh foo.

func UnescapeValue

func UnescapeValue(v string) string

UnescapeValue reverses EscapeValue.

func ValidVar added in v1.3.0

func ValidVar(name string) bool

ValidVar reports whether name can follow VarPrefix in a variable.

Types

type AttrKind added in v1.2.0

type AttrKind string

AttrKind is what kind of value a block attribute takes.

const (
	AttrFlag     AttrKind = "flag"     // no value: skip, tty
	AttrText     AttrKind = "text"     // any text: env=, file=, a confirm question
	AttrCond     AttrKind = "cond"     // a condition: run=, show=
	AttrChoice   AttrKind = "choice"   // one of Values: out=, on_error=
	AttrDuration AttrKind = "duration" // a Go duration: timeout=30s
	AttrNumber   AttrKind = "number"   // a whole number: frame=, from=
	AttrList     AttrKind = "list"     // comma-separated names: share=
)

type AttrSpec added in v1.2.0

type AttrSpec struct {
	// Name is the attribute's key; "#" is the block id, written #id.
	Name string   `json:"name"`
	Kind AttrKind `json:"kind"`
	// Bare is true when a value is optional, as for confirm and
	// show-stderr. Flags are always bare.
	Bare bool `json:"bare,omitempty"`
	// Values are the choices for AttrChoice. A value ending in ":" may
	// be followed by a path, as in out=image:plots/sales.png. For
	// AttrNumber they are words allowed besides numbers, as lines=fit.
	Values []string `json:"values,omitempty"`
	// Default says what happens without the attribute.
	Default string `json:"default,omitempty"`
	// Help is one line on what the attribute does.
	Help string `json:"help"`
	// Include is true for the attributes of include blocks. Include
	// blocks take none of the others.
	Include bool `json:"include,omitempty"`
	// Inputs are the input block languages, textbox and choice, that
	// the attribute is for. Empty for the attributes of other blocks.
	Inputs []string `json:"inputs,omitempty"`
}

AttrSpec describes a block attribute, for tools that help write them, such as mdsh-gui's attribute form and completion.

func LookupAttr added in v1.2.0

func LookupAttr(name string) (AttrSpec, bool)

LookupAttr finds the spec for an attribute name.

func (AttrSpec) Check added in v1.2.0

func (s AttrSpec) Check(value string, set bool) error

Check reports whether value suits the attribute. set is false when the attribute is given bare, without =.

type Attrs

type Attrs map[string]string

Attrs are a block's Pandoc-style attributes. The block id is stored under "#". A bare key such as skip is stored with an empty value.

func ParseInfo

func ParseInfo(info string) (lang string, attrs Attrs)

ParseInfo splits a fence info string such as

sh {#build env=build share=GREETING skip}

into its language and attributes. The Pandoc form {.sh #build} is also accepted; its first class is the language.

func (Attrs) Has

func (a Attrs) Has(key string) bool

Has reports whether key was set, with or without a value.

func (Attrs) List

func (a Attrs) List(key string) []string

List splits a comma-separated value. It returns nil when key is unset, and an empty, non-nil slice when key is set to nothing.

type Block

type Block struct {
	ID    string
	Lang  string
	Attrs Attrs
	Body  string
	// Span covers the fence lines, including the closing fence's newline.
	Span Span
	// BodySpan covers the lines between the fences, as they are in Src.
	// It ends at Span.End when the fence is never closed.
	BodySpan Span
	// Fence is the opening fence's run of backticks or tildes, and Info
	// its info string.
	Fence, Info string
	// Output covers any output already attached to this block, starting
	// right after Span: the current output and, under it, the earlier
	// runs History holds. It is empty (Start == End == Span.End) when
	// there is none. CurrentOutput is the current output alone.
	Output Span
	// History holds the earlier runs' outputs kept under the current
	// output by history=N, newest first. See Entry.
	History []Entry
	// CurrentParts cover the current output's parts, the stdout fence
	// or region and the stderr fence, each from its opening line to its
	// end, prefixes included.
	CurrentParts []Span
	// CurrentAt is the current output's at=, when its run started, or
	// "" when it has none.
	CurrentAt string
	// Prefix is what starts each line of a block nested in block quotes or
	// list items, such as "> " or "   ". Output written after the block
	// starts each line with it. Empty at the top level.
	Prefix string
	// Lead is the part of the opening fence line that holds list markers
	// when the fence opens on the same line as its list item, such as
	// "- " or "> 1. ". Empty otherwise.
	Lead string
	// VarTaken says why an input's var= binds nothing: an earlier input
	// binds the same name and this one isn't a copy of it. Empty
	// otherwise.
	VarTaken string
	// MirrorOf is the id of the first input that binds this input's var=,
	// when this one is a copy of it: the same control, differing at most
	// in its value. Copies show one value, and setting one sets them all
	// (see SetText and SetChoice). Empty otherwise.
	MirrorOf string
	// contains filtered or unexported fields
}

Block is a fenced code block.

func (*Block) Choice added in v1.3.0

func (b *Block) Choice() Choice

Choice reads a choice's attributes and options. A nosave choice with a session value (see SetValue) has the options that value names checked, whatever the body says.

func (*Block) Cond

func (b *Block) Cond(attr string) (Cond, bool)

Cond returns the condition in a block attribute, and whether it is set. Parse has already checked that it is valid.

func (*Block) CurrentOutput added in v1.6.0

func (b *Block) CurrentOutput() Span

CurrentOutput covers block b's current output: Output without the earlier runs under it.

func (*Block) Depends added in v1.3.0

func (b *Block) Depends() []string

Depends returns the ids of the blocks b's depends= names, in order, or nil if it has none.

func (*Block) HasOutput

func (b *Block) HasOutput() bool

HasOutput reports whether output is already saved after b in the file.

func (*Block) HistoryCap added in v1.6.0

func (b *Block) HistoryCap(o Options) int

HistoryCap is how many earlier runs block b keeps: N for history=N, the front matter's history, else DefaultHistory, for a bare history, and 0 without it. Parse checks the value.

func (*Block) Include

func (b *Block) Include() (Include, error)

Include reads an include block's attributes.

func (*Block) IsChoice added in v1.3.0

func (b *Block) IsChoice() bool

IsChoice reports whether b is a choice.

func (*Block) IsHTTP added in v1.6.0

func (b *Block) IsHTTP() bool

IsHTTP reports whether b is an http block: a request mdsh makes itself, with checks on what comes back (see package httpblock).

func (*Block) IsInclude

func (b *Block) IsInclude() bool

IsInclude reports whether b is an include block.

func (*Block) IsInput added in v1.3.0

func (b *Block) IsInput() bool

IsInput reports whether b is a textbox or a choice: a block someone fills in, not one that runs.

func (*Block) IsTape

func (b *Block) IsTape() bool

IsTape reports whether b is a tape for another block.

func (*Block) IsTextbox added in v1.3.0

func (b *Block) IsTextbox() bool

IsTextbox reports whether b is a textbox.

func (*Block) Named added in v1.3.0

func (b *Block) Named() bool

Named reports whether b's id is written in its fence, rather than block-N from its place in the document.

func (*Block) NoSave added in v1.4.0

func (b *Block) NoSave() bool

NoSave reports whether b carries the nosave attribute, or secret, which implies it: its value lives in the session only. Write-back keeps what the file holds after a runnable block, in its output copies and placeholders, and in a textbox or choice, instead of the run's output or what was typed or picked. See SetValue and OutputNoSave.

func (*Block) OutputNoSave added in v1.4.0

func (b *Block) OutputNoSave() bool

OutputNoSave reports whether write-back keeps the output after b as the file has it: b is nosave, or an output fence attached to it is.

func (*Block) Request added in v1.6.0

func (b *Block) Request() (*httpblock.Request, error)

Request reads http block b's request, as written, placeholders and all.

func (*Block) SecretRef added in v1.6.0

func (b *Block) SecretRef(ref Ref, more []string) bool

SecretRef reports whether ref, read from http block b, holds a secret: a capture marked secret, a json() path such a capture reads, or a header() whose value the output masks (more is the front matter's mdsh.http.secret_headers). Write-back stores it bare.

func (*Block) SecretVar added in v1.6.0

func (b *Block) SecretVar(name string) bool

SecretVar reports whether name is one of http block b's captures marked secret: write-back stores a placeholder for it bare.

func (*Block) SessionValue added in v1.4.0

func (b *Block) SessionValue() (string, bool)

SessionValue is the value SetValue gave nosave input b this session, and whether it has one. Without one, b's value is its body.

func (*Block) Textbox added in v1.3.0

func (b *Block) Textbox() Textbox

Textbox reads a textbox's attributes and text: the session's value for a nosave textbox that has one (see SetValue), else its body.

func (*Block) Value added in v1.4.0

func (b *Block) Value() string

Value is what input b's var= holds, or would if it bound it.

func (*Block) Var added in v1.3.0

func (b *Block) Var() (name, value string, ok bool)

Var is the variable input b binds with var=, such as MDSH_VAR_host, and its value: a textbox's text, or the labels a choice has checked, one per line. ok is false when b binds none, the name isn't valid or an earlier input binds it, including one b is a copy of.

type Choice added in v1.3.0

type Choice struct {
	// Mode is ChoiceDropdown, ChoiceRadio or ChoiceMulti.
	Mode string
	// Options are the body's task list items, in order. Other lines are
	// left alone.
	Options []Option
	// Placeholder is what a dropdown shows while nothing is chosen.
	Placeholder string
}

Choice is what a choice block asks for.

type Cond

type Cond struct {
	Ref *Ref // nil for a constant
	// Once is run=once: run the block only if it has no output, saved
	// after it or from running earlier. The runner checks that; Eval
	// reports true.
	Once  bool
	Not   bool
	Op    string // "", "==" or "!="
	Value string // compared against, or the constant
	Text  string // as written
}

Cond is a condition such as

{{$DEBUG}}                    true unless empty, 0, false or no
!{{$DEBUG}}                   the opposite
{{#detect/env(OS)}}==Linux    string comparison; != also works
{{$?}}==0                     the most recent block's exit status
{{#build/?}}!=0               block build's exit status
{{#build/err?}}               the same; true when build failed
{{$ran?}}, {{#build/ran?}}    whether the block ran
{{#login/status}}==201        an http block's response status;
                              json($.path) and header(Name) too
true, false                   constants
once                          in run= only: the block has no output yet

func ParseCond

func ParseCond(s string) (Cond, error)

ParseCond parses a condition.

func (Cond) Eval

func (c Cond) Eval(lookup Lookup) bool

Eval reports whether c holds. An unknown ref reads as empty.

type Copy added in v1.2.0

type Copy struct {
	// For is the id of the block whose output it copies.
	For string
	// Stream is "stderr" for a copy of the stderr fence, else "".
	Stream string
	// Region is set for an output region, a copy of out=markdown or
	// image output.
	Region bool
	// Span covers the copy's lines, prefixes included.
	Span Span
	// Prefix and Lead are as for Block.
	Prefix, Lead string
	// NoSave is set for a copy fence marked nosave: write-back keeps
	// what it holds, whatever its block does.
	NoSave bool
}

Copy is a copy of a block's output somewhere else in the document: an output fence, or an output region, whose for= block isn't the one right above it.

type Document

type Document struct {
	Src []byte
	// Shebang is the #! line, without its newline. Empty if there is none.
	Shebang string
	// FrontMatter covers the front matter, including both --- lines.
	FrontMatter Span
	Options     Options
	// FrontMatterErr is why mdsh can't read the front matter, or nil.
	// The rest of the document parses as usual, with Options at their
	// defaults, so front ends can still show it; they show the error,
	// and run (see run.Session) refuses to run any block until the
	// front matter is fixed.
	FrontMatterErr error
	Blocks         []*Block
	// Placeholders are the env placeholders in the prose, in order.
	// Empty when the front matter turns them off.
	Placeholders []*Placeholder
	// Sections are the mdsh:if ... mdsh:end sections, in order of their
	// if lines. They may nest.
	Sections []*Section
	// Folds are the mdsh:collapse lines, in order.
	Folds []*Fold
	// Copies are the output fences and regions in the prose that aren't
	// right after the block they are for, in order. A run refills them.
	Copies []*Copy
	// Warnings are problems that don't stop the document running, such
	// as a copy for a block that doesn't exist.
	Warnings []string
}

Document is a parsed markdown file.

func Parse

func Parse(src []byte) (*Document, error)

Parse splits src into front matter and fenced blocks. Output fences and output regions written by mdsh are attached to the block they follow instead of being returned as blocks.

func (*Document) AppendBlock added in v1.1.0

func (d *Document) AppendBlock(info, body string) (*Block, error)

AppendBlock adds a fenced block holding body to the end of d, after a blank line, and returns it. info is the fence's info string: a language, such as sh, and any attributes. Earlier blocks keep their spans, so results for them stay valid. It fails if the end of d would swallow the block, such as an unclosed fence.

func (*Document) Block

func (d *Document) Block(id string) *Block

Block returns the block with the given id, or nil.

func (*Document) BlockText added in v1.1.0

func (d *Document) BlockText(b *Block) string

BlockText is b's source, opening fence to closing fence, without the list markers and block quote prefixes it is nested in. SetBlock takes it back.

func (*Document) BlocksIn added in v1.3.0

func (d *Document) BlocksIn(span Span) (from, to int)

BlocksIn is the blocks that start in span: d.Blocks[from:to].

func (*Document) Boundaries added in v1.3.0

func (d *Document) Boundaries() []int

Boundaries lists, in order, the byte offsets in Src where a block or a section can be moved to: the start of each top-level markdown block (a paragraph, heading, list, quote, table or fenced block), and the end of the file. Offsets inside a list, a block quote, front matter, or a block's attached output or an output copy are not boundaries.

func (*Document) CheckDependsMove added in v1.3.0

func (d *Document) CheckDependsMove(span Span, at int) error

CheckDependsMove fails if moving span to at, one of Boundaries, would take a block above one it depends on (see DependsLimits).

func (*Document) DeleteBlock added in v1.3.0

func (d *Document) DeleteBlock(b *Block) (warnings []string, err error)

DeleteBlock takes b's unit (see Unit) out of the document, the block with its attached output and its tape, and parses d again. The gap it leaves closes up to one blank line. It fails, leaving d as it was, if anything else in the document uses b's id, such as a depends=, a condition or a placeholder, since the file wouldn't parse without it. It returns the problems it leaves that don't stop the file parsing, such as an output copy of b somewhere else.

Every other *Block keeps its identity, with its spans moved to match, so results indexed by block can follow. Ids don't change: a delete that would renumber a block that is referred to or that has output fails with ErrRenumber.

func (*Document) DeleteBlockers added in v1.3.0

func (d *Document) DeleteBlockers(b *Block) []string

DeleteBlockers names what stops DeleteBlock deleting b: what else in the document uses its id, such as a depends= or a placeholder. It is nil when b can go, or when b isn't a top-level block.

func (*Document) Dep added in v1.3.0

func (d *Document) Dep(id string) *Block

Dep is the block id names in a depends=, or nil if no block can be depended on by that id: there is none, or it is an include, a tape or an input, which never runs. A depends= naming one is ignored.

func (*Document) DependsLimits added in v1.3.0

func (d *Document) DependsLimits(span Span) MoveLimits

DependsLimits works out span's MoveLimits. A depends= already out of order doesn't limit the move.

func (*Document) Fixes added in v1.4.0

func (d *Document) Fixes() []Fix

Fixes lists the fixes for d's warnings that have one: an output copy for a block that isn't there goes, and a depends= loses an id that names no block that runs, and a value in front matter that doesn't parse is quoted when a colon in it is why. A warning has at most one fix; the front matter's is for FrontMatterErr's text.

func (*Document) Headings added in v1.3.0

func (d *Document) Headings() []Heading

Headings lists the top-level headings, in order. Headings in a list, a block quote, the front matter, or a block's output aren't sections and are left out.

func (*Document) InfoSpan added in v1.3.0

func (d *Document) InfoSpan(b *Block) Span

InfoSpan is where b's info string, the part of its opening fence line after the backticks, is in d's source.

func (*Document) InputFor added in v1.4.0

func (d *Document) InputFor(name string) *Block

InputFor is the textbox or choice that binds variable name, such as MDSH_VAR_host, with var=, or nil when none does.

func (*Document) Label added in v1.3.0

func (d *Document) Label(b *Block) string

Label is how messages name b: its id, or "at line N" when mdsh made the id up, as block-N or block-<uuidv7>, since those tell a reader nothing. "block " + Label reads well either way.

func (*Document) MatchMirrors added in v1.4.0

func (d *Document) MatchMirrors() ([]byte, bool)

MatchMirrors returns d's source with every copy of an input set to the value of the first, and whether that changed anything: the fix for the warning Parse gives when copies differ.

func (*Document) Mirrors added in v1.4.0

func (d *Document) Mirrors(b *Block) []*Block

Mirrors is input b with every copy of it: the first input that binds its var= and those that mirror it, in order. It is just b when b has none.

func (*Document) MoveBlock added in v1.3.0

func (d *Document) MoveBlock(b *Block, at int) ([]int, error)

MoveBlock moves b's unit (see Unit) to at, one of Boundaries, and returns the new order of the blocks as MoveSpan does.

func (*Document) MoveSection added in v1.3.0

func (d *Document) MoveSection(start, at int) ([]int, error)

MoveSection moves the section of the heading at start (see Section), with everything in it, to at: the start of a heading of the same or a higher level, or the end of the file, so the section lands between sections at its own depth. It returns the blocks' new order, as MoveSpan does.

func (*Document) MoveSpan added in v1.3.0

func (d *Document) MoveSpan(span Span, at int) (order []int, err error)

MoveSpan moves the source at span to at, and parses d again. span starts at one of Boundaries and ends at one, or at the end of a line followed only by blank lines up to one; at is one of Boundaries. The moved text gets a blank line on each side, and the gap it leaves closes up to one blank line. Moving to where span already is changes nothing.

Every *Block keeps its identity, with its spans moved to match. order gives the blocks' new order: d.Blocks[j] was d.Blocks[order[j]], so results indexed by block can follow. Ids don't change, so name the blocks first (see NameBlocks): a move fails, leaving d as it was, if it would renumber a block that is referred to or that has output. It also fails if it would split an mdsh:if section, or take a block above one it depends on (see CheckDependsMove).

func (*Document) NameBlocks added in v1.3.0

func (d *Document) NameBlocks(want func(*Block) bool, newID func() string) ([]Rename, error)

NameBlocks writes an id from newID into the fence of each block that has none and that want picks, and carries what pointed at its block-N id over to the new one: its saved output, output copies, tapes, the placeholders and conditions that name it, and links to its files under <doc>.assets/. Every *Block in d keeps its identity, as with SetBlock. It returns the ids it replaced, in document order.

func (*Document) NewIndex added in v1.4.1

func (d *Document) NewIndex() *Index

NewIndex indexes d.

func (*Document) OrderProblems added in v1.3.0

func (d *Document) OrderProblems(runnable func(*Block) bool) []OrderProblem

OrderProblems lists what in d depends on block order and may be wrong:

  • a condition, placeholder or tape that reads a block below it, which hasn't run yet when it is read;
  • a condition or placeholder such as {{$?}} that reads the runnable block above it, naming that block, since a move changes which it is;
  • each runnable block or input inside an mdsh:if section, naming the sections, since a move can take it in or out of one;
  • each var= bound by more than one input, naming the one that wins.

Some of these are only facts, not mistakes, so show the problems a change added, with NewProblems. runnable says which blocks run.

func (*Document) Refs

func (d *Document) Refs() []Ref

Refs lists every variable the document's placeholders, conditions and sections refer to.

func (*Document) RenameBlock added in v1.3.0

func (d *Document) RenameBlock(b *Block, id string) error

RenameBlock gives b, a block whose id is written in its fence, the id id, and carries over what names it: its saved output and output copies (for=), tapes, placeholders, conditions and other blocks' depends=. Links to its files under <doc>.assets/ keep the old name, since the files keep it until the block runs again. Every *Block in d keeps its identity, as with NameBlocks.

func (*Document) Section added in v1.3.0

func (d *Document) Section(start int) (Span, int, error)

Section is the section of the heading that starts at start: from it to the next heading of the same or a higher level, or the end of the file. It also returns the heading's level.

func (*Document) SetBlock added in v1.1.0

func (d *Document) SetBlock(b *Block, text string) error

SetBlock replaces b, which must be one of d's blocks, with text, as BlockText gives it, and parses d again. The fence, attributes and id may change; output saved for b follows a new id. Every *Block in d keeps its identity, with its spans moved to match the new source, so results that point at them stay valid. It fails if text isn't one block of the same kind, or would rename other blocks.

func (*Document) SetBody added in v1.3.0

func (d *Document) SetBody(b *Block, body string) []byte

SetBody returns d's source with b's body replaced by body, which gets a newline at its end if it has none, unless it is empty. The fence gets longer if a line of body would close it, and each line starts with b's container prefix.

func (*Document) SetChecks added in v1.4.0

func (d *Document) SetChecks(b *Block, checked []bool) bool

SetChecks sets the picks of nosave choice b, and of every copy of it, for this session, as SetChoice does in the source: one bool per option. It reports false when b isn't a nosave choice.

func (*Document) SetChoice added in v1.3.0

func (d *Document) SetChoice(b *Block, checked []bool) []byte

SetChoice returns d's source with choice b's options checked as checked says, one bool per option, and those of every copy of it. Options past its end are unchecked.

func (*Document) SetSource added in v1.2.0

func (d *Document) SetSource(src []byte) error

SetSource replaces d's source with src and parses it again, as when the whole file is edited at once. A block whose info string and body are unchanged keeps its identity, wherever it moved, with its spans moved to match src, so results that point at it stay valid. Edited and new blocks are new *Blocks, and blocks no longer in src are dropped. A nosave input's session value (see SetValue) is kept by id, so what was typed survives an edit elsewhere in the file. If src doesn't parse, d is left as it was.

func (*Document) SetText added in v1.4.0

func (d *Document) SetText(b *Block, text string) []byte

SetText returns d's source with textbox b's text replaced by text, and that of every copy of it.

func (*Document) SetValue added in v1.4.0

func (d *Document) SetValue(b *Block, value string) bool

SetValue sets the value of nosave input b, and of every copy of it, for this session: a textbox's text, or the labels a choice has checked, one per line. The source is left alone, so saving keeps the body the file holds. It reports false, and sets nothing, when b isn't a nosave input.

func (*Document) StepTarget added in v1.3.0

func (d *Document) StepTarget(b *Block, dir int, byBlock bool) (int, error)

StepTarget is where b's unit (see Unit) goes to move one step up (dir < 0) or down: past the top-level markdown block next to it, or with byBlock past the next top-level fenced block. It is ErrNoMove at the top or bottom.

func (*Document) Tape

func (d *Document) Tape(b *Block) *Block

Tape returns the tape for block b, or nil.

func (*Document) Unit added in v1.3.0

func (d *Document) Unit(b *Block) (Span, error)

Unit is what moves with block b: b, its attached output, and its tape when the tape comes right after it. It fails for a block that isn't at the top level, such as one in a list item or a block quote.

type Entry added in v1.6.0

type Entry struct {
	// K is the entry's place: 1 for the run before the current one, 2
	// for the one before that, and so on.
	K int
	// Span covers the entry's parts, prefixes included, from the first
	// part's opening line to the end of its last part.
	Span Span
	// At is the run's start time as its at= has it, or "" when the
	// entry has none.
	At string
	// Exit is its exit= status, and Exited is set when it has exited.
	Exit   int
	Exited bool
	// Region is set when its stdout part is an output region, as for
	// markdown, image and recording output.
	Region bool
	// Parts cover its parts, each from its opening line to its end.
	Parts []Span
	// contains filtered or unexported fields
}

Entry is one earlier run's output, kept under a block's current output by history=N: an output fence or region marked history=K, and its stderr fence, if any, marked the same.

type Fix added in v1.4.0

type Fix struct {
	// Warning is the warning it fixes, as Warnings has it, without the
	// "line N: " in front.
	Warning string
	// Label names it for a button, such as "Delete the copy".
	Label string
	// Detail says what it does, for asking first.
	Detail string
	// Src is the document's source with the fix made.
	Src []byte
}

Fix is an edit that makes one of a document's warnings go away, one so plain it can be offered at a click, after asking.

type Fold added in v1.3.0

type Fold struct {
	Span Span // the line
	Cond Cond
}

Fold is a <!-- mdsh:collapse --> line, optionally with a condition, as in <!-- mdsh:collapse {{$MDSH_VAR_verbose}}!=yes -->. When the condition holds, mdsh-gui opens the file with the section of the heading above the line folded. Printing leaves the line out.

type Heading added in v1.3.0

type Heading struct {
	Level int
	// Span runs from the start of the heading's line to the next
	// heading of the same or a higher level, or the end of the file.
	Span Span
}

Heading is a top-level heading and the section it opens.

func SectionAt added in v1.3.0

func SectionAt(hs []Heading, pos int) (Heading, bool)

SectionAt is the innermost section holding pos: the last heading starting at or before it, since a section runs to the next heading that isn't below it. It is false when pos comes before every heading.

type Include

type Include struct {
	File     string
	From, To int
	// Numbered asks for each line to be shown with its line number in
	// the file. The numbers are for display, never stored in the body.
	Numbered bool
}

Include is what an include block asks for. Lines are numbered from 1 and the range is inclusive. From 0 or 1 is the first line; To 0 is the end of the file.

type Index added in v1.4.1

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

Index answers questions about d that each look over the whole document: where blocks and sections can move to, what uses a block, and how depends= limits a move. Asking d itself scans the document every time; an Index works each answer out once, so a caller asking for every block, as laying out a document's cells does, takes time in proportion to the document rather than its square. An Index holds while d doesn't change.

func (*Index) Boundaries added in v1.4.1

func (x *Index) Boundaries() []int

Boundaries is d.Boundaries.

func (*Index) DeleteBlockers added in v1.4.1

func (x *Index) DeleteBlockers(b *Block) []string

DeleteBlockers is d.DeleteBlockers.

func (*Index) Dep added in v1.4.1

func (x *Index) Dep(id string) *Block

Dep is d.Dep.

func (*Index) DependsLimits added in v1.4.1

func (x *Index) DependsLimits(span Span) MoveLimits

DependsLimits is d.DependsLimits. It looks only at the edges of the blocks in span.

func (*Index) Headings added in v1.4.1

func (x *Index) Headings() []Heading

Headings is d.Headings.

func (*Index) IsBoundary added in v1.4.1

func (x *Index) IsBoundary(pos int) bool

IsBoundary reports whether pos is one of Boundaries.

func (*Index) Section added in v1.4.1

func (x *Index) Section(start int) (Span, int, error)

Section is d.Section.

func (*Index) Unit added in v1.4.1

func (x *Index) Unit(b *Block) (Span, error)

Unit is d.Unit.

type Info added in v1.2.0

type Info struct {
	Lang   string
	Tokens []string // such as #build, env=build, confirm="Go on?", .sh
}

Info is a fence info string split for editing: the language and the attribute tokens as written, so unknown attributes and the order survive an edit.

func SplitInfo added in v1.2.0

func SplitInfo(info string) Info

SplitInfo splits a fence info string for editing.

func (*Info) Del added in v1.2.0

func (in *Info) Del(key string)

Del removes key.

func (*Info) Set added in v1.2.0

func (in *Info) Set(key, value string, bare bool)

Set sets key to value, in place if it is already there, else at the end. bare writes the key without a value, as for skip or confirm. For "#" the value is the id.

func (Info) String added in v1.2.0

func (in Info) String() string

String writes the info string back: lang {tokens}.

type Lookup

type Lookup func(Ref) (value string, ok bool)

Lookup returns a ref's value; ok is false when it isn't known.

type MoveLimits added in v1.3.0

type MoveLimits struct {
	// After is the bottommost block outside the span that a block in it
	// depends on, or -1; Before the topmost block outside it that
	// depends on a block in it, or len(Src).
	After, Before int
	// The depends= that set them, each as the dependent and the block
	// it depends on, or nil.
	AfterDep, AfterOn   *Block
	BeforeDep, BeforeOn *Block
}

MoveLimits say where a block's unit or a heading's section can move without taking a block above one it depends on: to an offset at with After < at <= Before.

type Option added in v1.3.0

type Option struct {
	Label   string `json:"label"`
	Checked bool   `json:"checked"`
}

Option is one of a choice's options.

type Options

type Options struct {
	// Shell runs sh and zsh blocks. Defaults to zsh when the document
	// has zsh blocks, else /bin/sh.
	Shell string `yaml:"shell"`
	// OnError is "continue" (default) or "stop".
	OnError string `yaml:"on_error"`
	// Step asks before running each block, as if every block had the
	// confirm attribute.
	Step bool `yaml:"step"`
	// Interpolate turns {{#block/env(VAR)}} placeholders on or off.
	// Defaults to on.
	Interpolate *bool `yaml:"interpolate"`
	// ShowStderr shows every block's stderr. Blocks can override it
	// with show-stderr=. By default stderr shows only for failed blocks.
	ShowStderr *bool `yaml:"show_stderr"`
	// History is how many earlier runs a block marked with a bare
	// history keeps. 0 means DefaultHistory.
	History int `yaml:"history"`
	// Terminal is the size, in cells, of the terminal tty blocks run on
	// where mdsh draws it, as in the GUI. A zero cols fits the window;
	// a zero rows is 24.
	Terminal struct {
		Cols int `yaml:"cols"`
		Rows int `yaml:"rows"`
	} `yaml:"terminal"`
	HTTP struct {
		// SecretHeaders are response headers, besides the credential
		// ones httpblock.SecretHeaders names, whose values http blocks
		// save masked. The list only adds; matching ignores case.
		SecretHeaders []string `yaml:"secret_headers"`
	} `yaml:"http"`
	Env struct {
		// Share lists the variables passed into the top-level env from
		// the caller, besides env.Base (except in a remote document),
		// and the default for sub-envs. Nil passes only env.Base; "..."
		// passes everything (see FullEnv).
		Share []string `yaml:"share"`
		// Source lists files sourced into every shell as it starts,
		// such as aliases and functions. A leading ~/ is the home
		// directory; other relative paths are relative to the document.
		Source []string `yaml:"source"`
	} `yaml:"env"`
}

Options are the document-wide settings under the mdsh: key of the front matter.

func (Options) FullEnv added in v1.4.0

func (o Options) FullEnv() (full bool, except []string)

FullEnv reports whether env.share brings in the whole environment mdsh was started in, as "..." or "*" in the list does, and the names the list still leaves out with -NAME. Without it, blocks get only the base set (PATH, HOME, USER, ...) and the names the list gives; front ends show a banner on a file that brings in everything.

func (Options) Interpolating

func (o Options) Interpolating() bool

Interpolating reports whether placeholders are filled in.

func (Options) ShareBanner added in v1.5.0

func (o Options) ShareBanner() string

ShareBanner is the line front ends show over a file whose env.share brings in more than the base set: the whole environment, naming what it leaves out, or the names it asks for. It is "" when the file gets only the base set. A file that names GITHUB_TOKEN gets a banner just as one with "..." does, so a secret never comes in unannounced (finding 2 of the v1.4.0 security review).

func (Options) Shared added in v1.5.0

func (o Options) Shared() []string

Shared lists the names env.share brings in from the environment mdsh was started in besides the base set (env.IsBase), in the list's order: the names a file asks for by name, such as GITHUB_TOKEN. "...", -NAME and base names aren't in it.

type OrderProblem added in v1.3.0

type OrderProblem struct {
	Key  string
	Text string
}

OrderProblem is something in a document that depends on the order of its blocks, and might be wrong in this order. Key names it, so the problems before and after a move can be compared (see NewProblems).

func NewProblems added in v1.3.0

func NewProblems(before, after []OrderProblem) []OrderProblem

NewProblems returns the problems in after that weren't in before.

type Placeholder

type Placeholder struct {
	Span Span
	Ref
	// Value is the stored value, unescaped. HasValue is false when the
	// placeholder has no :"..." part.
	Value    string
	HasValue bool
}

Placeholder is a reference in the prose to a variable, as a block left it or from the caller's environment:

{{#setup/env(GREETING)}}
{{#setup/env(GREETING):"hello"}}
{{$USER}}              never saved with a value: see render.Options
{{$?}}                 the most recent block's exit status
{{#build/?:"0"}}       block build's exit status

The quoted part holds the last value seen, so the file reads well without running it. Write-back fills it in.

func (*Placeholder) Source

func (p *Placeholder) Source(value string) string

Source renders the placeholder as it is written in the file, holding value.

type Ref

type Ref struct {
	BlockID string
	Var     string
	// Fn is set for a ref to an http block's response, with Var its
	// argument: "json" ({{#login/json($.token)}}, Var the path),
	// "header" ({{#login/header(Content-Type)}}, Var the name) or
	// "status" ({{#login/status}}, Var empty). It is empty for a
	// variable or a block fact.
	Fn string
}

Ref names a variable: in the caller's environment ({{$VAR}}, BlockID empty), or as a block left it ({{#block/env(VAR)}}). Var can also be one of the block facts below, for the most recent block ({{$?}}) or a named one ({{#block/?}}).

func TextRefs

func TextRefs(text string) []Ref

TextRefs lists the placeholders in text, which unlike prose may be code: a tape's input, say.

func (Ref) Caller added in v1.3.0

func (r Ref) Caller() bool

Caller reports whether r is {{$VAR}} for a variable in mdsh's own environment: not a block's variable, a block fact or an input's var=.

func (Ref) Fact

func (r Ref) Fact() bool

Fact reports whether r is a block fact rather than a variable.

func (Ref) IsStatus

func (r Ref) IsStatus() bool

IsStatus reports whether r is an exit status, under either name.

func (Ref) Response added in v1.6.0

func (r Ref) Response() bool

Response reports whether r reads an http block's response rather than a variable or a fact.

func (Ref) String

func (r Ref) String() string

type Rename added in v1.3.0

type Rename struct {
	Old, New string
}

Rename is a block id that NameBlocks replaced.

type Section

type Section struct {
	If, End Span // the marker lines
	Cond    Cond
}

Section is prose between <!-- mdsh:if COND --> and <!-- mdsh:end --> lines. When COND is false, printing leaves out everything from the if line to the end line, blocks included.

type Span

type Span struct {
	Start, End int
}

Span is a half-open byte range [Start, End) in Document.Src.

type Textbox added in v1.3.0

type Textbox struct {
	// Text is the body without its last newline.
	Text string
	// Lines is the most lines the text may have, at least 1. With Fit
	// it is 1 and means nothing.
	Lines int
	// Fit is set by lines=fit: the text may have any number of lines,
	// and interactive views size the box to it as it is typed.
	Fit bool
	// Placeholder is shown while the text is empty, in interactive views
	// only.
	Placeholder string
}

Textbox is what a textbox block asks for.

Jump to

Keyboard shortcuts

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