format

package
v1.14.0 Latest Latest
Warning

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

Go to latest
Published: Apr 27, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DefaultHTMLTemplate

func DefaultHTMLTemplate() string

DefaultHTMLTemplate returns the embedded default HTML template. Use this to inspect the template data model or as a starting point for custom templates.

func FormatNames

func FormatNames() []string

FormatNames returns a sorted list of registered format names.

func PartialsTemplate added in v1.10.2

func PartialsTemplate() string

PartialsTemplate returns the embedded shared template partials. These define cm-content, cm-frontmatter, cm-blocks, cm-calc-block, and cm-text-block. Custom templates are automatically parsed with these partials so they can call them via {{template "cm-content" .}} or individual partials for layout control.

func PreviewHTMLTemplate added in v1.8.14

func PreviewHTMLTemplate() string

PreviewHTMLTemplate returns a content-only HTML fragment template for editor webview previews. No <html>/<head>/<body> wrapper — the editor provides its own shell with styles and scripts.

func RegisterFormatter

func RegisterFormatter(name string, formatter Formatter)

RegisterFormatter adds a custom formatter to the registry. This allows third-party formatters to be registered at runtime.

func StyleCSS added in v1.9.2

func StyleCSS() string

StyleCSS returns the shared CalcMark CSS styles. Used by the default HTML template, the watch page, and any consumer that needs CalcMark-styled HTML output.

Types

type AlignedStatement

type AlignedStatement struct {
	// Source is the original source line text.
	Source string

	// Result is the raw, unformatted evaluation result.
	// Nil if this line has no result (blank, result-comment, etc.).
	Result types.Type

	// Variable is the name assigned by this statement (e.g., "x" from "x = 10").
	// Empty for anonymous expressions.
	Variable string

	// IsBlank is true for empty/whitespace-only source lines.
	IsBlank bool

	// IsResultLine is true for previous result comments (e.g., "# = 42", "→ 42").
	// Formatters should typically skip these.
	IsResultLine bool
}

AlignedStatement maps a source line to its evaluated result. This is the shared logic extracted from all formatters to prevent the recurring source-line/result-index alignment bugs.

func AlignResults

func AlignResults(block *document.CalcBlock) []AlignedStatement

AlignResults maps source lines of a calc block to their corresponding evaluation results. It handles the shared alignment logic that was previously duplicated across all four formatters:

  • Result lines (from previous saves) are marked but not assigned results
  • Blank lines are marked but not assigned results
  • Non-blank, non-result lines consume the next result from block.Results()
  • Variable names are extracted from assignment expressions

type CalcMarkFormatter

type CalcMarkFormatter struct{}

CalcMarkFormatter formats CalcMark documents back to CalcMark format. Useful for round-tripping and saving documents with frontmatter.

func (*CalcMarkFormatter) Extensions

func (f *CalcMarkFormatter) Extensions() []string

Extensions returns the file extensions handled by this formatter.

func (*CalcMarkFormatter) Format

func (f *CalcMarkFormatter) Format(w io.Writer, doc *document.Document, opts Options) error

Format writes the document as CalcMark source to the writer. Output is exactly the source as typed, ensuring reproducibility.

type Formatter

type Formatter interface {
	// Format writes the formatted document to the writer
	Format(w io.Writer, doc *document.Document, opts Options) error

	// Extensions returns file extensions this formatter handles
	Extensions() []string
}

Formatter formats CalcMark documents for output. All formatters must implement this interface.

func GetFormatter

func GetFormatter(format string, filename string) Formatter

GetFormatter returns the appropriate formatter based on format name or filename extension. If format is specified, it takes precedence. Otherwise, the filename extension is used. Falls back to text formatter if no match is found.

type HTMLFormatter

type HTMLFormatter struct{}

HTMLFormatter formats CalcMark documents as HTML. Uses an embedded template with modern styling.

func (*HTMLFormatter) Extensions

func (f *HTMLFormatter) Extensions() []string

Extensions returns the file extensions handled by this formatter.

func (*HTMLFormatter) Format

func (f *HTMLFormatter) Format(w io.Writer, doc *document.Document, opts Options) error

Format writes the document as HTML to the writer.

type JSONBlock

type JSONBlock struct {
	Type               string           `json:"type"`
	Source             []string         `json:"source"`
	InterpolatedSource []string         `json:"interpolated_source,omitempty"`
	Results            []JSONResult     `json:"results,omitempty"`
	Error              string           `json:"error,omitempty"`
	Diagnostics        []JSONDiagnostic `json:"diagnostics,omitempty"`
	HTML               string           `json:"html,omitempty"`
}

JSONBlock represents a single block in JSON output.

type JSONConvertTo added in v1.6.2

type JSONConvertTo struct {
	System         string   `json:"system"`
	UnitCategories []string `json:"unit_categories,omitempty"`
}

JSONConvertTo represents convert_to config in JSON output

type JSONDiagnostic

type JSONDiagnostic struct {
	Severity string `json:"severity"`
	Code     string `json:"code,omitempty"`
	Message  string `json:"message"`
	Line     int    `json:"line,omitempty"`
	Column   int    `json:"column,omitempty"`
}

JSONDiagnostic represents an error or warning with position info.

type JSONDocument

type JSONDocument struct {
	Frontmatter *JSONFrontmatter `json:"frontmatter,omitempty"`
	Blocks      []JSONBlock      `json:"blocks"`
}

JSONDocument represents the full document in JSON output

type JSONFormatter

type JSONFormatter struct{}

JSONFormatter formats CalcMark documents as JSON. Useful for programmatic consumption and integration with other tools.

func (*JSONFormatter) Extensions

func (f *JSONFormatter) Extensions() []string

Extensions returns the file extensions handled by this formatter.

func (*JSONFormatter) Format

func (f *JSONFormatter) Format(w io.Writer, doc *document.Document, opts Options) error

Format writes the document as JSON to the writer.

type JSONFrontmatter

type JSONFrontmatter struct {
	Globals   map[string]string `json:"globals,omitempty"`
	Exchange  map[string]string `json:"exchange,omitempty"`
	Scale     *JSONScale        `json:"scale,omitempty"`
	ConvertTo *JSONConvertTo    `json:"convert_to,omitempty"`
}

JSONFrontmatter represents frontmatter in JSON output

type JSONResult

type JSONResult struct {
	Source        string   `json:"source"`
	Value         string   `json:"value,omitempty"`
	Type          string   `json:"type,omitempty"`
	NumericValue  *float64 `json:"numeric_value,omitempty"`
	Numerator     *int64   `json:"numerator,omitempty"`
	Denominator   *int64   `json:"denominator,omitempty"`
	Unit          string   `json:"unit,omitempty"`
	DateValue     string   `json:"date_value,omitempty"`
	IsApproximate bool     `json:"is_approximate,omitempty"`
	IsExplicit    bool     `json:"is_explicit,omitempty"`
	Error         string   `json:"error,omitempty"`
	Variable      string   `json:"variable,omitempty"`
}

JSONResult represents a single evaluated statement's result. Value is the locale-formatted display string. Type is the CalcMark type name (e.g., "number", "currency", "fraction"). NumericValue, Unit, DateValue decompose the value for programmatic consumption.

type JSONScale added in v1.6.2

type JSONScale struct {
	Factor         float64  `json:"factor"`
	UnitCategories []string `json:"unit_categories,omitempty"`
}

JSONScale represents scale config in JSON output

type MarkdownFormatter

type MarkdownFormatter struct{}

MarkdownFormatter formats CalcMark documents as Markdown. Calculation blocks are shown in code fences with results.

func (*MarkdownFormatter) Extensions

func (f *MarkdownFormatter) Extensions() []string

Extensions returns the file extensions handled by this formatter.

func (*MarkdownFormatter) Format

func (f *MarkdownFormatter) Format(w io.Writer, doc *document.Document, opts Options) error

Format writes the document as Markdown to the writer.

type Options

type Options struct {
	Verbose       bool   // Show calculation steps, types, units
	IncludeErrors bool   // Include error details
	Template      string // For template-based formatters (future use)

	// DisplayFormatter is the locale-aware formatter for rendering values.
	// When zero-value, formatters fall back to display.Format() (en-US default).
	DisplayFormatter display.Formatter

	// FrontmatterAsCodeFence renders CalcMark frontmatter as a “`yaml code
	// fence instead of raw --- delimiters. Use when embedding CalcMark output
	// inside a Hugo page that has its own YAML frontmatter.
	FrontmatterAsCodeFence bool

	// SuppressFrontmatter skips frontmatter serialization (used by embedded mode).
	SuppressFrontmatter bool
}

Options controls formatter behavior

type TemplateBlock

type TemplateBlock struct {
	Type              string
	SourceLines       []TemplateLine // For calc blocks with per-line results
	Error             string
	HasLineDiagnostic bool          // True if any SourceLine has a per-line Error
	Warnings          []string      // Diagnostic warnings (e.g., reserved keyword as variable name)
	HTML              template.HTML // For text blocks
	DocLine           int           // 1-indexed document-absolute start line (for scroll sync)
}

TemplateBlock represents a block for template rendering

type TemplateExchange

type TemplateExchange struct {
	From string
	To   string
	Rate string
}

TemplateExchange represents an exchange rate for template rendering

type TemplateExtra added in v1.8.8

type TemplateExtra struct {
	Key   string
	Value string // formatted for display
}

TemplateExtra represents a non-CalcMark frontmatter field

type TemplateFrontmatter

type TemplateFrontmatter struct {
	Globals          []TemplateGlobal
	Exchange         []TemplateExchange
	Scale            string // e.g. "2x" or "0.5x [Length, Mass]"
	ConvertTo        string // e.g. "imperial" or "si [Length]"
	FiscalYearStarts string // e.g. "July" or "July 15"
	Extra            []TemplateExtra
}

TemplateFrontmatter represents frontmatter for template rendering

type TemplateGlobal

type TemplateGlobal struct {
	Name  string
	Value string
}

TemplateGlobal represents a global variable for template rendering

type TemplateLine

type TemplateLine struct {
	Source      string
	Result      string // Formatted result for this line
	Error       string // Error message for this line (empty if successful)
	IsCascading bool   // True if this is a cascading error (hint severity)
	DocLine     int    // 1-indexed document-absolute line number (for scroll sync)
}

TemplateLine represents a single source line with its result

type TextFormatter

type TextFormatter struct{}

TextFormatter formats CalcMark documents as plain text. This is the primary formatter for interactive use (REPL, CLI).

func (*TextFormatter) Extensions

func (f *TextFormatter) Extensions() []string

Extensions returns the file extensions handled by this formatter.

func (*TextFormatter) Format

func (f *TextFormatter) Format(w io.Writer, doc *document.Document, opts Options) error

Format writes the document as plain text to the writer. In verbose mode, it shows source with intermediate results for each line.

Directories

Path Synopsis
Package display provides human-readable formatting for CalcMark types.
Package display provides human-readable formatting for CalcMark types.

Jump to

Keyboard shortcuts

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