doc

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 29, 2026 License: MIT Imports: 10 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 (
	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 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 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.

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"},
	{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: "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; empty for none"},
	{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: "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 animated GIF"},
	{Name: "frame", Kind: AttrNumber, Default: "the last", Help: "With tty, the frame of the GIF that still views show, counting from 1"},
	{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: "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"},
	{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"},
}

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

Functions

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 RegionStart

func RegionStart(id string) string

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

func UnescapeValue

func UnescapeValue(v string) string

UnescapeValue reverses EscapeValue.

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.
	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"`
}

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. It is empty (Start == End == Span.End) when there
	// is none.
	Output Span
	// 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
	// contains filtered or unexported fields
}

Block is a fenced code block.

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) HasOutput

func (b *Block) HasOutput() bool

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

func (*Block) Include

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

Include reads an include block's attributes.

func (*Block) IsInclude

func (b *Block) IsInclude() bool

IsInclude reports whether b is an include block.

func (*Block) IsTape

func (b *Block) IsTape() bool

IsTape reports whether b is a tape for another block.

type Cond

type Cond struct {
	Ref   *Ref // nil for a constant
	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
true, false                   constants

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
}

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
	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
	// 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(lang, body string) (*Block, error)

AppendBlock adds a fenced block of lang holding body to the end of d, after a blank line, and returns it. 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) Refs

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

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

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) 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. If src doesn't parse, d is left as it was.

func (*Document) Tape

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

Tape returns the tape for block b, or nil.

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 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 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"`
	Env        struct {
		// Share lists the variables passed into the top-level env from
		// the caller, and the default for sub-envs. Nil means all.
		Share []string `yaml:"share"`
	} `yaml:"env"`
}

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

func (Options) Interpolating

func (o Options) Interpolating() bool

Interpolating reports whether placeholders are filled in.

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}}
{{$USER:"j"}}
{{$?}}                 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
}

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) 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) String

func (r Ref) String() string

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.

Jump to

Keyboard shortcuts

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