Skip to content

Language server

The Gram Language Server (@gram-lang/language-server) is the intelligence engine behind editor integrations. It implements the standard Language Server Protocol (LSP), providing advanced IDE features for Gram files across multiple editors, not just VS Code.

The server acts as a persistent background process that analyzes your .gram files using the @gram-lang/parser, @gram-lang/kitchen, and @gram-lang/scheduler packages.

Real-time workflow:

  1. Editor ➔ Sends file changes on every keystroke.

  2. Language Server ➔ Intercepts document deltas and asks the Kitchen compiler to re-evaluate the AST in memory.

  3. Gram Compiler ➔ Analyzes the structure, resolves dependencies, computes the ALAP schedule, and emits integrity and scheduling diagnostics.

  4. Language Server ➔ Translates these results into standard LSP payloads (Diagnostics, Semantic Tokens, Inlay Hints) and pushes them back to the editor.

The Gram Language Server implements the following standard capabilities:

LSP CapabilityGram Implementation
DiagnosticsReal-time reporting of syntax errors, structural defects (circular dependencies), and scheduling warnings (DAY_OVERFLOW, DURATION_OUT_OF_RANGE, TRACK_CONTENTION).
Semantic TokensAST-driven highlighting for modifiers, units, temperatures, ratio operators (/), and composite ingredients.
CompletionContextual autocomplete for database ingredients, canonical units, and intermediate variables. Offers time units inside ~{…}, resumes unit completion after + or - in sums, and suggests @& / & targets (plus weight units after /) in ratios.
HoverDisplays nutritional breakdowns and volume-to-mass conversions on ingredient hover. On timers, shows the parsed duration (~{1h30} → 1 h 30 min); on section anchors, the lead time and whether it opens a working day; on sums and ratios, the combined total ({1 cup + 1 tbsp} → = 17 tbsp) or per-family breakdown, standardized mass, or reason if unresolved.
Go to DefinitionDirect navigation from an intermediate reference (&ref, including inside ratios) to its original declaration (->&ref).
Find ReferencesLocates every usage of an intermediate variable across the document (including inside ratios).
RenameSafely and atomically renames intermediate variables throughout the file (including inside ratios).
Code ActionsQuick fixes (declaring missing intermediate variables, converting volume to mass, inserting missing + or applying suggested totals in sums, or changing oz after a volume to fl oz).
Document FormattingNormalizes syntax in-place via @gram-lang/format.
Inlay HintsDisplays the recipe’s total time on the title: line (following gram.miseEnPlace and gram.rests), and shows resolved values (= 5, = 16 g, = 24 min) inline after unit ratios and proportional times.
Code LensInjects an action button above the document to open the live preview (▶ Preview).
Document SymbolPopulates the editor’s Outline view for clean structural navigation across recipe sections.
Folding RangeEnables folding of YAML frontmatter blocks and ## section headings.

The server reads the gram configuration section (workspace/configuration) at startup and reloads it upon every workspace/didChangeConfiguration notification. Missing or unrecognized values fall back gracefully to defaults, ensuring an invalid configuration never blanks a view.

  • View settings (gram.miseEnPlace, gram.rests, gram.comments, gram.stepQuantities, gram.nutritionBasis, gram.bakersMathOnly, gram.clock) re-render open recipes directly from their existing compiled state.
  • Analyzer settings (gram.bakersMath, gram.massStandardization, gram.yieldCalculation, gram.nutritionEstimation) re-analyze open recipes from scratch, refreshing compiler diagnostics and derived data.
  • gram.ingredientDatabase.path reloads the ingredient database from disk.

Available values and defaults match those of the VS Code extension, defined centrally in the renderer package (VIEW_SETTINGS, RECIPE_SETTINGS).

Alongside standard LSP capabilities, the server renders recipe views (the recipe and the run sheet) and inspectors (the AST and the compiled JSON) for display in editor client panels. It renders only the views currently open in the client, ensuring closed panels incur no computation overhead.

A client opts into the protocol by providing initializationOptions: { views: true } in its initialize request, then communicates with the server through three custom notifications and two requests:

NotificationDirectionContent
gram/setOpenViewsClient ➔ Server{ uri, viewIds }: the complete set of active output IDs for this document ([] when none are open). The server immediately emits updates for each requested view.
gram/setSessionClient ➔ Server{ uri, serveAt?, scale?, stock?, bakersReference? }: transient session parameters for the current working session. serveAt is an ISO-like local date and time ("2026-10-11 13:00"), scale is { type: "factor", value } or { type: "target", id, qty, unit }, and stock lists URIs of pre-prepared imports. Unrecognized properties are ignored; an empty payload clears the session.
gram/viewUpdatedServer ➔ Client{ uri, outputId, kind, state, ... }: emitted for each open output upon initial opening, and refreshed after every edit or configuration change.
gram/serveTimes (request)Client ➔ Server{ uri } → { candidates, rejected, earliest } or null: the serving times to propose next to a serving time field, as the playground proposes them. candidates are the times that work over the next seven days at the project’s mealTimes (default 12:30 and 20:00), best first, each { serveAt, label, title }; rejected says in words why each other time does not; earliest is { serveAt, label, text }, the first time the recipe can be ready if you start now. null when the recipe has nothing to schedule. Ask it only while the suggestions are shown: it plans a few dozen times.
gram/sessionChoices (request)Client ➔ Server{ uri } → { ingredients, imports, bakersMath, scaleError? } or null: what session controls offer, read from the recipe as written so the choices do not move with the scale. ingredients is the shopping list ({ id, name, qty?, unit? }, for a target quantity or the baker’s reference), imports every @use import, nested ones included ({ uri, specifier }, the uri to put in stock), bakersMath whether gram.bakersMath is on, and scaleError why the session’s scale could not be applied. null while the recipe does not compile.

The initialize response advertises available views via capabilities.experimental.gramViews: outputs describes each output’s id, kind, and localized label (matching the editor’s language), plus, for a view, what it needs from the plan (a view that needs runSheet is laid out in time, so a client offers its serving time controls), while strings provides UI translations for surrounding panel controls (strings.serving for the serving time field and its suggestions, strings.session for the scale, baker’s reference and stock controls). Output IDs align with the renderer’s exported list: recipe and runSheet (kind: "renderer"), plus ast, json, and json-tree (kind: "inspector"). Client implementations consuming this list dynamically support newly added views without requiring client-side updates.

  • With state: "ok", payload contains the rendered HTML for a view, or null if the recipe has no corresponding content (such as a run sheet for a recipe without schedulable steps). For inspectors, payload is { presentation, language, text }: formatted source text for a code pane (presentation: "code", highlighted as json or scheme), or structured HTML for an interactive tree view (presentation: "tree").
  • With state: "paused", compilation errors prevent view updates and payload is omitted: editor clients should retain their last valid rendered view and surface the failure via error (title, description, code, message, and source range). The error title is localized using the editor’s configured locale (locale from initialize). Comprehensive error details continue to be reported via standard LSP diagnostics.

Session state is maintained per document strictly in memory: it is discarded when the document closes or the server restarts, and is never persisted to project configuration. When a serving time is provided, the run sheet is projected onto the calendar in the project’s time zone (timezone in .gram/config.yaml, falling back to system time) and within its availability (availability, falling back to all day; a setting that cannot be read also falls back to all day); without a serving time, the plan is organized in relative countdown days. Times of day follow gram.clock: with auto, the clock setting of .gram/config.yaml, else the region of the server’s locale (LC_ALL, then LC_TIME, then LANG; on Windows, the system’s region) v1.5.0. When session overrides (scale, stock, or bakersReference) are defined, the views are recompiled with these parameters while diagnostics, hover tooltips, and inlay hints continue to evaluate the recipe as written on disk. If a scale target cannot be resolved, views gracefully fall back to default proportions.

Clients that do not declare the views protocol and never send gram/setOpenViews continue to receive document views via legacy notifications as { uri, html } payloads, regardless of whether the views are actively displayed in the editor.

NotificationContent
gram/previewUpdatedv1.4.0 HTML rendering of the live recipe preview, or an error panel when compilation fails. Removed in version 2.0.0: migrate to gram/viewUpdated with the recipe output.
gram/ganttUpdatedv1.4.0 HTML rendering of the legacy Gantt chart. Emitted until version 2.0.0 for third-party client compatibility (the official VS Code extension no longer listens to it).