calcmark

package module
v2.2.8 Latest Latest
Warning

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

Go to latest
Published: May 11, 2026 License: MIT Imports: 17 Imported by: 0

README

CalcMark

Calculations embedded in markdown documents.

CalcMark TUI

CalcMark is a terminal-based calculation notepad. Write your thinking in plain text, add calculations that reference each other, and watch results update as you type.

Unlike spreadsheets, CalcMark files are human-readable, diffable, and live in your terminal.

Installation

macOS/Linux (Homebrew):

brew install calcmark/tap/calcmark

Download binary:

Platform Download
macOS (Apple Silicon) calcmark_VERSION_darwin_arm64.tar.gz
macOS (Intel) calcmark_VERSION_darwin_amd64.tar.gz
Linux (x64) calcmark_VERSION_linux_amd64.tar.gz
Linux (arm64) calcmark_VERSION_linux_arm64.tar.gz
Windows (x64) calcmark_VERSION_windows_amd64.zip

After downloading, extract and move cm to a directory in your PATH. On macOS, you may need to run xattr -d com.apple.quarantine ./cm before first use.

Quick Start

  1. Create a file called budget.cm:
# Monthly Budget

income = $5000
rent = $1500
savings_rate = 20%
savings = income * savings_rate
remaining = income - rent - savings
  1. Open in the TUI editor:
cm budget.cm
  1. Or evaluate from command line:
cm eval budget.cm
  1. Or convert to other formats:
cm convert budget.cm --to=html -o budget.html

CalcMark TUI

Examples

Explore example files to see CalcMark in action:

Run any example:

cm testdata/examples/budget.cm

Features

  • Variables flow downward - Define once, reference anywhere below
  • Units are first-class - 5 miles in km, 20 celsius in fahrenheit
  • Currencies - $100, 50 EUR, automatic formatting
  • Percentages - savings_rate = 20%, then income * savings_rate
  • Functions - avg(), sqrt(), capacity(), and more
  • YAML front matter - Define document-level constants (exchange, globals, scale, convert_to, measurement, fiscal_year_starts; see spec/document/frontmatter_registry.go for the authoritative list)
  • Export formats - Convert to HTML, Markdown, JSON, or plain text

Help Commands

cm help              # General help
cm help functions    # List all functions with descriptions
cm help constants    # List built-in constants
cm convert --help    # Export format options

Press Ctrl+H (or F1) in the TUI editor for keybindings.

Learn More

Development

Prerequisites:

  • Go 1.24+
  • Task — task runner (brew install go-task)

Optional (for recording demo GIFs):

  • VHS — terminal recorder (brew install vhs)
  • VHS requires ttyd and ffmpeg, installed automatically by Homebrew
task test       # Run all tests
task quality    # Lint, vet, staticcheck
task build      # Build the cm binary
task record-demos  # Regenerate all demo GIFs (requires VHS)

License

MIT

Documentation

Overview

Package calcmark provides a clean, idiomatic Go API for evaluating CalcMark expressions and documents.

CalcMark is a calculation-oriented markup language that combines markdown with inline calculations.

Basic usage:

result, err := calcmark.Eval("1 + 1")
if err != nil {
    log.Fatal(err)
}
fmt.Println(result.Value) // 2

Stateful sessions (for live editors):

session := calcmark.NewSession()
session.Eval("x = 10")
result, _ := session.Eval("x + 5")
fmt.Println(result.Value) // 15

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Convert

func Convert(input string, opts Options) (string, error)

Convert processes CalcMark input and returns formatted output.

In CM mode, the entire input is parsed as a CalcMark document, evaluated, and formatted to the requested output format.

In Embedded mode, the input is scanned for cm/calcmark fenced code blocks. Each block is evaluated independently and replaced with its formatted output. Surrounding Markdown prose passes through unchanged. Embedded mode supports "md" and "html" formats only.

HTML output returns a fragment by default (no <html>/<head>/<body> wrapper). When Template is set, the fragment is wrapped using the provided Go template.

In Embedded mode, Convert may return both a non-empty result and a non-nil error when some CalcMark blocks fail evaluation. The result contains inline error markers (blockquotes in Markdown, or their HTML rendering) and is still useful for display. The error reports the count of failed blocks.

func NewDocumentEmbedded added in v2.2.0

func NewDocumentEmbedded(source string) (*specDoc.Document, error)

NewDocumentEmbedded parses an Embedded-mode CalcMark source — standard markdown with `cm` or `calcmark` fenced code blocks — and returns a *specDoc.Document whose blocks reflect the fence boundaries. Each `cm`/`calcmark` fenced segment becomes a *specDoc.CalcBlock (source = fence inner content); each passthrough markdown segment becomes a *specDoc.TextBlock; a leading `---...---` segment is parsed as the document's frontmatter via the existing spec/document.ParseFrontmatter.

The returned document supports the same evaluator semantics as NewDocument: variables defined in any CalcBlock resolve in subsequent CalcBlocks (whole-doc scoping). This intentionally diverges from Convert(Mode: Embedded)'s rendering pipeline, which evaluates each fence in isolation. Consumers that want cross-fence variable resolution and passthrough interpolation (e.g., {{ varName }} in prose) should use this API; consumers that just want a rendered HTML/Markdown string per-fence-isolated can keep using Convert.

Static-rendering escape hatch: any fenced code block whose info-string is NOT exactly `cm` or `calcmark` (for example ```text, ```go, ```output) is a regular markdown code block and projects as part of the surrounding TextBlock content, NOT as a CalcBlock. This is already in the language spec — no new info-string is needed for static rendering. Do not invent constructs like `calcmark-source`.

Empty source returns an empty *Document with zero blocks. Sources with zero `cm`/`calcmark` fences return a single TextBlock containing the whole source — Embedded mode gracefully degrades to "all-passthrough markdown."

Types

type Diagnostic

type Diagnostic struct {
	Severity Severity
	Code     string
	Message  string
	Detailed string // Detailed explanation with context and guidance
}

Diagnostic represents a semantic issue (error, warning, or hint).

type Mode

type Mode int

Mode selects the conversion pipeline.

const (
	// CM processes the entire input as a CalcMark document.
	CM Mode = iota
	// Embedded processes a Markdown document with embedded cm/calcmark fenced code blocks.
	Embedded
)

type Options

type Options struct {
	Mode     Mode   // CM or Embedded (default: CM)
	Format   string // Output format: "html", "md", "text", "json" (default: "html")
	Template string // Go template content for wrapping HTML output (optional)
	Locale   string // BCP 47 locale for number formatting (default: "en-US")

	// DateFormat overrides the locale's default date layout for Date
	// values. Uses the user-friendly DSL ("MON dd, YYYY", etc.) —
	// see format/display/date_format_dsl.go for tokens. Empty string
	// uses locale default.
	DateFormat string

	// PeriodDateFormat overrides the date layout used for endpoints
	// inside Period output. Empty falls back to DateFormat, then to
	// the built-in compact "dd-MON-YYYY".
	PeriodDateFormat string
}

Options configures the Convert pipeline.

type Result

type Result struct {
	// Value is the final computed value (for single expressions).
	// For multi-line documents, this is the last value.
	Value types.Type

	// AllValues contains all computed values (for multi-line documents).
	AllValues []types.Type

	// Diagnostics contains any errors, warnings, or hints from semantic analysis.
	Diagnostics []Diagnostic
}

Result contains the evaluation results and any diagnostics.

func Eval

func Eval(input string) (*Result, error)

Eval evaluates a CalcMark expression or document and returns the result. For single-line expressions, returns the computed value. For multi-line documents, returns per-line results.

Example:

result, err := calcmark.Eval("100 + 20")
if err != nil {
    log.Fatal(err)
}
fmt.Println(result.Value) // 120

type Session

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

Session maintains state for live editor use. Variables persist across Eval calls within the same session.

func NewSession

func NewSession() *Session

NewSession creates a new stateful evaluation session. Variables are preserved across Eval calls.

Example:

session := calcmark.NewSession()
session.Eval("x = 10")
result, _ := session.Eval("x + 5")
fmt.Println(result.Value) // 15

func (*Session) Eval

func (s *Session) Eval(input string) (*Result, error)

Eval evaluates an expression in this session's context. Variables are preserved across calls.

func (*Session) GetVariable

func (s *Session) GetVariable(name string) (any, bool)

GetVariable retrieves a variable value by name. Returns the value and true if found, nil and false otherwise.

func (*Session) Reset

func (s *Session) Reset()

Reset clears all variables in this session.

type Severity

type Severity int

Severity indicates the severity level of a diagnostic.

const (
	// Error indicates a blocking error that prevents interpretation.
	Error Severity = iota
	// Warning indicates a potential issue that doesn't block interpretation.
	Warning
	// Hint indicates a suggestion for improvement.
	Hint
)

func (Severity) String

func (s Severity) String() string

Directories

Path Synopsis
cmd
calcmark command
calcmark/config
Package config provides configuration management for the CalcMark TUI/CLI.
Package config provides configuration management for the CalcMark TUI/CLI.
calcmark/filecheck
Package filecheck validates that file content is safe to interpret as CalcMark.
Package filecheck validates that file content is safe to interpret as CalcMark.
calcmark/tui/editor
Package editor provides the TUI editor for CalcMark documents.
Package editor provides the TUI editor for CalcMark documents.
calcmark/tui/editor/store
Package store defines the interface for remote document storage backends.
Package store defines the interface for remote document storage backends.
calcmark/tui/geometry
Package geometry provides pure layout computation for two-column terminal rendering.
Package geometry provides pure layout computation for two-column terminal rendering.
doceval command
Command doceval scans Hugo markdown files for ```calcmark code blocks, evaluates each through the CalcMark interpreter, and writes the results to site/data/cm_results.json.
Command doceval scans Hugo markdown files for ```calcmark code blocks, evaluates each through the CalcMark interpreter, and writes the results to site/data/cm_results.json.
docgen command
Command docgen generates site/data/features.json from the features registry.
Command docgen generates site/data/features.json from the features registry.
Package constants provides common constants used throughout go-calcmark
Package constants provides common constants used throughout go-calcmark
display
Package display provides human-readable formatting for CalcMark types.
Package display provides human-readable formatting for CalcMark types.
impl
cmd/calcmark command
embedded
Package embedded — Embedded-mode structural parser.
Package embedded — Embedded-mode structural parser.
interpreter
Package interpreter provides the CalcMark expression interpreter.
Package interpreter provides the CalcMark expression interpreter.
types
Package types defines the CalcMark type system
Package types defines the CalcMark type system
Package lsp bridges CalcMark's spec/impl/format layers to the Language Server Protocol.
Package lsp bridges CalcMark's spec/impl/format layers to the Language Server Protocol.
spec
ast
Package ast defines the Abstract Syntax Tree node types for CalcMark
Package ast defines the Abstract Syntax Tree node types for CalcMark
classifier
Package classifier implements line classification for CalcMark
Package classifier implements line classification for CalcMark
document
Package document defines the CalcMark document structure with blocks.
Package document defines the CalcMark document structure with blocks.
features
Package features provides a searchable catalog of CalcMark features for help systems, autocompletion, and documentation generation.
Package features provides a searchable catalog of CalcMark features for help systems, autocompletion, and documentation generation.
identifiers
Package identifiers provides the canonical set of named values accepted by CalcMark functions.
Package identifiers provides the canonical set of named values accepted by CalcMark functions.
lexer
Package lexer implements the CalcMark lexer/tokenizer.
Package lexer implements the CalcMark lexer/tokenizer.
parser
Package parser provides the CalcMark parser implementation.
Package parser provides the CalcMark parser implementation.
semantic
Package semantic provides semantic analysis for CalcMark programs.
Package semantic provides semantic analysis for CalcMark programs.
transform
Package transform applies document-level post-evaluation transforms (scale, convert_to) to CalcMark evaluation results.
Package transform applies document-level post-evaluation transforms (scale, convert_to) to CalcMark evaluation results.
types
Package types defines the CalcMark type system.
Package types defines the CalcMark type system.
units
Package units provides canonical unit name mappings based on UCUM and NIST standards.
Package units provides canonical unit name mappings based on UCUM and NIST standards.

Jump to

Keyboard shortcuts

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