Syntax and types

Syntax basics

In a signature such as name?: String, ? marks an optional argument.

  • Blocks use braces { ... }. Indentation is cosmetic. End a statement with a semicolon or a newline where the next token cannot continue it. A new line starting with ( or [ can continue a call or index expression. Use a semicolon to start a separate statement there.
  • Keep a return value on the same line as return, or open a parenthesis on that line for a multiline value. A bare return produces Unit.
  • Conditions can use if ready { ... } or if (ready) { ... }. Chain branches with else if. Use ready ? 1 : 0 to choose a value. Only the selected branch runs. A nested conditional such as a ? 1 : b ? 2 : 3 groups as a ? 1 : (b ? 2 : 3).
  • Comments begin with # outside strings and run to the end of the line. (Hex colors must be quoted: Color("#3584e4").)
  • Named arguments and record values use = (wait(duration=1s), { field = value }). Colons declare types (name: Type) and separate dictionary entries ({"key": value}).
  • Standard names are protected and shadowing enclosing bindings is an error.
  • "home" / "user" joins path segments using the host platform's path rules. It produces "home/user" on Unix and home\user on Windows.

Bindings and reactivity

Use let for a snapshot, mut for a value you can change, and sig for a derived value. See Signals for an editable example.

Strings and formatting

Ordinary strings interpolate expressions and Python-style format specifications without an f prefix. Raw r"..." strings keep braces literal while retaining standard escapes (\n, \"). Double braces write literal braces. Triple quotes ("""...""" / '''...''') preserve multiline text.

let num = 42
let binary = "bits={num:08b}"
let fraction = "share={0.125:.1%}"
let literal = r"{this is literal text}"
mut count = 1
sig caption = "count={count}"
count = 2
{binary=binary, fraction=fraction, literal=literal, caption=caption}

str(value, format="08b") uses the same formatter (supporting b, o, x, X, d, c, f, F, e, E, g, G, %, conversion="s"|"r"|"a", alignment/fill, sign, and precision; locale n is rejected).

Use text.len() or len(text) to count Unicode scalar values. Strings support trim(), split(separator), and replace(from, to). Split keeps empty pieces and requires a nonempty separator. Use pad_start(width, fill?), pad_end(width, fill?), or pad_center(width, fill?) for a minimum width measured in Unicode scalar values. Fill is one character and defaults to a space.

Receiver methods for values

value.len() and len(value) are equivalent for strings, lists, arrays, dictionaries, data objects and arrays, DataFrames, and series. Collection lookups also use receiver syntax, such as items.get(0) and data.keys(). Use option.unwrap(default) to get a value or its fallback.

Use get for dictionary keys that may be missing and decode<T> to convert an unstructured value to its expected type.

let settings = {"presentation": {"title": "Daily readings"}}
decode<String>(settings["presentation"]["title"])

List edits such as items.append(value), items.pop(), and items.replace_at(index, value) return the updated list. For example, [1, 2].append(3).len() returns 3. Use items.sort() for ascending order, items.sort(reverse=true) for descending order, or items.reverse() to flip the existing order. Pass key=some_function to sort by a value computed for each item.

Slicing

Use items[start:end:step] to take a slice. The end is exclusive. Any bound can be omitted, negative bounds count from the end, and a negative step walks backward. The default step is 1, and a zero step is an error.

let items = [0, 1, 2, 3, 4]
let middle = items[1:4]     # [1, 2, 3]
let tail = items[-2:]       # [3, 4]
let every_other = items[::2] # [0, 2, 4]
let reversed = items[::-1]  # [4, 3, 2, 1]

A slice leaves its source intact. Contiguous slices share collection storage. For Array<T>, slicing selects along the first axis and preserves the remaining dimensions. items.slice(start=1, end=4) uses the same rules.

Functional collections

Lists and dictionaries share storage between snapshots. An edit returns the next value, so other references keep their previous contents.

  • Deque operations use a list. Use append and appendleft to add items, get to read safely, and pop and popleft to remove items.
  • Dict uses string keys. Use with_key(key, value) and without_key(key) to edit it. To supply a missing-key default, use settings.get("theme").unwrap(Data("light")).
  • Counter takes a list of strings, a string to count by character, or a dictionary of signed counts. Counter.count returns zero for a missing key. Counter.update and Counter.subtract produce new dictionaries. Counter.total includes negative counts. Counter.elements repeats keys with positive counts. Counter.most_common returns records with key and count fields, breaking ties in dictionary key order.
  • ChainMap works on a list of dictionaries. ChainMap.get searches from first to last and ChainMap.flatten produces a single dictionary with the same precedence. Use appendleft to add a higher-priority layer.
  • OrderedDict creates a snapshot with entries and insertion-order keys. Use OrderedDict.get, set, remove, and move_to_end. Set last=false to move a key to the front.
  • Named tuples are typed records in Ebi. Use a record type and construct it with named fields.
let counts = Counter(["blue", "red", "blue", "green", "blue", "red"])
let updated = Counter.subtract(counts, ["red", "green"])
Counter.most_common(updated, 2)

Types, records, enums, and unions

Built-in types include Number, Bool, String, Color, numeric units, Fraction, Element, Font, List<T, N>, Option<T>, Array<T>, Dict, Data, records, and enums.

Function calls try a direct match first. If needed, each argument can use one supported scalar cast. For example, a Number parameter can parse "1.5" using the same conversion as float("1.5"). An invalid string reports a conversion error.

A Duration becomes its exact value in seconds when passed to a Number parameter or returned from a Number expression. Mixed arithmetic such as 2 + 500ms and comparisons such as 500ms < 1 also use seconds. Multiplication by a number scales a duration, and dividing two durations gives a unitless ratio. A Number passed to a Duration parameter is interpreted as seconds, so wait(0.5) waits 500 milliseconds. A Number or Duration passed to a String parameter uses the same formatting as str(value), so 500ms becomes "500ms". If two clauses need the same number of casts, Ebi prefers the one that needs fewer string conversions.

Default duration text uses seconds and milliseconds, such as "1s" and "1s500ms". Values between millisecond boundaries use exact fractional seconds, such as "1/3s".

Use float(value) to produce a Number explicitly. It parses decimal strings and converts durations to seconds. int(value) parses integer strings and truncates numeric inputs toward zero. Both accept duration strings such as "1s500ms" and convert booleans to 0 or 1. bool(value) accepts numeric zero and nonzero values as false and true, and parses strings such as "false" and "true". Use str(value) to convert these values to text.

Use Duration(value) to convert a number or fraction of seconds, or to parse unit-bearing text. For example, Duration("1s500ms") equals 1500ms exactly. Use try_int, try_float, try_bool, or try_duration to get an Option when input may fail to parse.

Record types are structural and compose with & and -:

type RunInfo = { run: String, n: Number }
type Measurements = { x: Number, y: Number }
type Sample = RunInfo & Measurements
type Coordinates = Sample - RunInfo

Generic functions and aliases support defaults (<T = Data>) and constraints (<T: Numeric>). Enums support payloads and exhaustive match with case Variant(binding) { ... }.

String literal unions define closed choices. Use a type alias to reuse a set of choices across parameters and bindings:

type Variant = "before" | "after"
fn select_variant(variant: Variant): Variant { return variant }
select_variant("before")

The standard library provides Easing and EditAnimation for timing and text edits. You can also define a narrower alias such as type AnimationType = "type" | "morph".

Match statements

Use match to branch on a string or enum value. Each case has a block, and only the matching block runs. Use a final case _ for any remaining values. For a string without a fixed set of values, a fallback is required.

fn priority(status: String): Number {
    match status {
        case "urgent" { return 0 }
        case "normal" { return 1 }
        case _ { return 2 }
    }
}
priority("urgent")

Units, exact math, and matrices

  • Exact arithmetic: numbers and time use checked rational arithmetic (no floating-point drift in timelines). Fraction(num, den) exposes .numerator and .denominator.
  • Durations: 0.5s, 250ms, 7m, 4m1s, 1s250ms (compound units in decreasing m, s, ms order).
  • Layout & angles: pt, px (96px == 72pt), %, deg. Mismatched units fail explicitly.
  • Vectors & matrices: numeric Lists support pointwise arithmetic, dot, norm, cross, and concat(a, b). Row-major nested Lists (List<List<Number, 3>, 2>) support matrix *, transpose, and inverse (up to 64×64).

Reflected inputs

reflect(default, key=..., label=...) exposes a typed runtime input at module scope:

let title = reflect("Opening titles")
let accent = reflect(Color("blue3"), key="palette.accent", label="Accent Color")
let max_lines: Option<Number> = reflect(None)
let opacity: Percent<0%, 100%, 5%> = reflect(50%)
let style = { fill=reflect(Color("light1")), radius=reflect(12pt) }
{title=title, colors=[accent, style.fill], max_lines=max_lines, opacity=opacity, style=style}

Change the title, choose an accent color, or adjust the opacity to see the record update. Reset restores the original values.

Percent<0%, 100%, 5%> sets an inclusive minimum, an inclusive maximum, and a control step in that order. The step controls the editor’s increment. An explicit value such as 53% is still valid inside the bounds. All three arguments use the base type’s unit. For example, Number<0.25, 3, 0.05> describes a playback speed and Duration<0s, 2s, 50ms> describes a delay. Ebi checks the range on defaults and overrides.

  • Default keys are relative/file.ebi::variable_name (plus nested field paths such as style.fill). Explicit key="..." stays stable across variable renames; duplicate keys fail.
  • reflect must run once at module scope (not inside helpers, loops, branches, or signal initializers).

Loops and modules

  • for item in collection { ... } and repeat count { ... } run bounded preparation loops; recursion is rejected.
  • import resolves modules relative to the current module and checks for cycles. Imported modules never play animations automatically.

Continue with Functions and lists.