Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Why ductus

Why “ductus”?

Ductus is a Latin word. It means “lead” or “conduct”. In calligraphy, ductus is the direction, the number, and the sequence of the strokes that make a letterform. In linguistics, it is the character of writing as it flows: the direction, the order, and the speed of the strokes.

That is what this language describes. A Ductus program does not draw outlines. It tells how the strokes of a glyph go: where they start, which way they move, and in what order. The name is the design principle.

At its heart, ductus is a language for parametric type design. Imagine a ductus source file as the blueprint for your glyph outlines, crafted directly in code. Every single point on a contour becomes an expression, dynamically responding to named design parameters like weight, contrast, width—or really, whatever your unique design demands. And here’s a detail: you’ll never have to wrestle with curve handles by hand. Instead, you simply provide the on-curve points, their directions, and their types. A clever spline solver then takes care of placing all the control points for you.

Let’s take a peek at a rendered ductus glyph. Here, for example, is the letter o. Notice how its stem thickness, hairline thickness, and overshoot are all dynamic expressions, controlled by just two parameters: weight and contrast:

Now, without changing a single line of the source code, simply dial up the weight to 850. Watch as every point shifts, the solver re-sculpts the curves, and that very same file magically produces the heavier, black version of your design:

This ‘o’, for all its elegance, clocks in at about twenty-five lines of source code. Don’t worry, this book patiently guides you through building it, step by step, in the chapters dedicated to nodes. For now, let’s focus on the heart of those twenty-five lines — the core commitments that drive ductus’s design. Ductus is built upon five foundational principles, and you’ll find that much of what makes the language feel unique stems directly from embracing these ideas wholeheartedly.

Outline-first

In ductus, we consider the filled contour to be the star of the show, the primary artifact. You won’t find any stroke expansion magic baked into the language itself: ductus doesn’t take a centerline and a virtual pen to automatically whip up an outline for you. This is a conscious departure from the approach that sometimes made editing METAFONT’s output feel like an uphill battle — when outlines are automatically generated, every tiny correction can feel like you’re fighting the very system that created it. With ductus, the outline is precisely what you crafted yourself. This means adding a terminal, an ink trap, or a subtle optical correction is just another ordinary, parametric edit that blends into your design.

Skeleton as scaffolding, not geometry

While ductus is quite knowledgeable about strokes, it politely declines to draw them for you. Instead, a node acts as a smart skeleton point, carrying crucial information like the stroke’s local direction and its pen, and then conveniently exposing its precisely calculated edge points:

node w = center + (-rx, 0) dir down pen pen(stem);
# w.left and w.right are now points, exactly stem/2 from w.pos

Your outlines are then elegantly woven through these handy derived points. We never offset curves; instead, we offset individual points. This means you won’t encounter any fuzzy offset-curve approximations. And if your design calls for a little tweak, you can easily nudge any derived point with simple arithmetic, like w.right + (3, 0). Take a look at the debug view, and you’ll see the elegant scaffolding behind our ‘o’. It reveals the skeleton spine serving as a guide, each node proudly displaying its direction and its two derived edge points, along with the fitted handles of the final contours.

e n s w top

Interpolation compatibility by construction

Here’s a key insight: the number and type of on-curve points in a contour are determined directly by your source text, not by the shifting sands of parameter values. This means every single instance across your entire design space shares an identical topology. Our ‘o’ glyph, for example, steadfastly maintains exactly four points on each contour, whether its weight is a slender 100 or a hefty 900. This structural consistency is exactly what you need for smooth interpolation between masters. You’ll notice that ductus’s language constructs are carefully shaped around this important rule. This is precisely why, for instance, ductus’s shape constructors will never let a parameter dictate the number of points in a shape.

The designer owns the outline

Here’s the beautiful truth: anything a node or constructor calculates or derives is completely yours to command. You can replace or adjust it with a perfectly ordinary expression. Ductus simply doesn’t believe in points you’re not allowed to touch. Our intended workflow encourages you to let the scaffolding thoughtfully place points according to design theory. Then, with a designer’s keen eye, you can gently nudge or reposition any points that just don’t quite feel right. And here’s the clever part: even those adjustments remain parametric, because they’re just another expression.

One way to say a thing

Ductus proudly traces its lineage back to METAFONT and MetaPost, so if you’ve ever dabbled with those, ductus’s path syntax will likely feel comfortably familiar. However, ductus consciously, and quite deliberately, streamlines things by letting go of some of their more elaborate cleverness.

  • No equation solver. You might remember MetaPost’s whatever, which allowed you to declare “these lines meet somewhere; now figure it out”. Ductus offers you a focused intersection() function for paths instead. This covers all the practical cases you’ll genuinely use in type design — think a stem meeting a diagonal, or a serif joining a stem — all without needing a full-blown constraint system in the language.
  • No tension. We considered per-joint tension but ultimately decided against it. In the real world of type design, it turns out designers tend to adjust points and directions directly, rather than fine-tuning abstract tension numbers.
  • No path concatenation. Each contour in ductus is a single, unified path expression. Macros elegantly share geometry by simply returning the points and nodes they define, rather than by gluing together path segments (which you might remember from MetaPost’s &). This means you won’t have any tricky seam-merging rules to puzzle over.
  • No implicit variables. You won’t find any mysterious reserved x0/y0 magic here. In ductus, a name holds meaning because you thoughtfully gave it that meaning.

Each of these intentional removals contributes to source files that are wonderfully literal: what your file declares is precisely what your glyph becomes.

What ductus is not, yet

Currently, the core ductus language evaluates to SVG, producing either one drawing per glyph or a convenient sheet of glyphs. We have plans for UFO and designspace emission, along with smart sampling of masters across the parameter space, all envisioned as a powerful layer built on top. (The interpolation-compatibility rule we discussed earlier is specifically designed to make this future layer sing.) It’s worth noting that ductus isn’t an interactive editor in the traditional sense. While the playground offers live rendering and handy parameter sliders, always remember that your source file remains the definitive blueprint of your design.

How to read this book

The next couple of chapters are designed to get your hands dirty, starting with some freehand sketches, and then moving on to crafting a proper glyph. Part II delves into the language itself, while Part III — where we explore nodes, pens, terminals, and pressure — is really where ductus begins to feel less like a programming language and more like an intuitive design tool. If you’re already a seasoned type designer, feel free to peek ahead to Part III. Here’s a friendly tip: keep the playground open in a second browser tab while you read. Almost every example in this book will happily run there, and you’ll find that simply dragging a slider can teach you more quickly than we could ever explain in words. Every single figure you see is compiled directly from the source code embedded in the book build itself, giving you the satisfying assurance that the code you read is indeed code that truly runs. For the definitive word on the language, the normative definition resides in the specification. This book lovingly cites it, but doesn’t aim to replace it.

First strokes

Before you dive into glyphs, metrics, and advance widths, there’s a wonderfully straightforward way to get ductus up and running: we call it a sketch. If your file doesn’t include a glyph block, it’s considered a sketch file. In these files, a top-level draw() call will render your paths as thin spines, and fill() will fill in any closed shapes you’ve made. Sketches are perfect for when you want to doodle around, quickly test out an idea, or simply follow along with the examples in this chapter. Feel free to paste any example into the playground, or you can run it directly from a file:

ductus build sketch.ductus -o sketch.svg

Numbers, names, comments

Each statement you write in ductus should end with a semicolon. If you want to add a helpful note, just use # to start a comment. And when you need to give something a name, the = symbol is your friend. It’s worth noting that bindings are single-assignment here. This means if you try to rebind a name within the same scope, ductus will gently let you know it’s an error. This design choice ensures that every value in your file can be traced back to a single, clear line.

Here’s a neat trick: placing a number directly in front of an expression automatically multiplies it. This means once you’ve set up a unit, your coordinates will start to feel intuitive, almost like working on graph paper. For instance, 3u simply means three units, and 2(a + b) gives you twice the sum.

u = 100;                   # our unit
draw((0, 0) -- (4u, 2u));  # a line segment

The coordinate system is Cartesian and y-up. This means x grows to the right and y grows upwards, just like the mathematics you’re familiar with, and quite unlike most screen APIs. By the way, -- is how you join points with a straight line.

Points are values

In ductus, (x, y) creates a point. These points are quite versatile: you can add them, subtract them, and scale them with ease. What’s more, a point also happily doubles as a 2-D vector, which makes calculating displacements a straightforward arithmetic task:

u = 100;
a = (0, 0);
b = (6u, 2u);
m = 0.5[a, b];             # halfway from a to b

draw(a -- b);
draw(m + (-u/4, 0) -- m + (u/4, 0));   # a cross marking m
draw(m + (0, -u/4) -- m + (0, u/4));

Meet t[a, b], an operation we call mediation. Chances are, this will quickly become one of your most frequently used expressions in ductus. It elegantly finds a point (or number) t of the way from a to b. So, if you’re looking for the exact midpoint, 0.5[a, b] will do the trick. The best part is, t can be any expression you dream up.

Curves

Want to create a beautiful curve? Just connect your points with .. instead of --, and ductus will fit a smooth path right through them. This is truly the heart of the language’s approach to curves: you simply place your on-curve points, and a sophisticated two-parameter spline solver — a clever descendant of the one John Hobby crafted for METAFONT — intelligently selects every control handle for you, ensuring the curve flows smoothly through each and every point.

u = 100;
p = (0, 0) .. (2u, 2u) .. (4u, 0) .. (6u, 2u);
draw(p);

You’ll notice that no handles ever appear in your source code, and they never will. If a curve isn’t quite shaping up how you envisioned, your instinct won’t be to fiddle with handles. Instead, you’ll simply add another point exactly where you feel the geometry needs a bit more definition, or perhaps you’ll constrain its direction.

Try it — Feel encouraged to paste this wave example into the playground and have some fun pushing those numbers around. Try raising a crest, adding a fifth point, or even deleting one. Don’t worry, you really can’t break anything. The fitter is wonderfully responsive, re-solving the curve with every keystroke, and watching it adapt is truly the quickest way to build a rapport with it.

Directions

Sometimes you want a curve to head in a specific direction. You can constrain its tangent at a point by enclosing a direction in braces. For example, {45} tells the curve to leave (or enter) at a 45-degree angle. We use degrees for angles, measured counterclockwise, with 0° pointing to the right. Handy named bindings like right, up, left, and down are also available, representing 0, 90, 180, and 270 degrees respectively. If you place a direction specifier before a point, it constrains the curve entering that point; after a point, it guides the curve leaving it.

u = 100;
a = (0, 0);
b = (4u, 0);

p = a .. (2u, u) .. b;              # the fitter's choice
q = a {up} .. (2u, u) .. {down} b;  # forced vertical ends

draw(p);
draw(q shifted (5u, 0));            # beside it, to compare

Notice how the wave on the left follows the fitter’s gentle, natural route. The wave on the right, however, is constrained, forced to leave point a straight up and then elegantly dive into b straight down. (By the way, shifted is just one of ductus’s handy transform operators – we’ll dedicate an entire chapter to them later.)

Mixing lines and curves

You’ll be pleased to know that -- for lines and .. for curves can be mixed together quite freely within a single path. When a line meets a curve, that intersection point effortlessly transforms into a natural line/curve corner. The curve will arrive perfectly tangent to whatever direction it needs, while the line, of course, remains wonderfully straight.

u = 100;
fill((0, 0) -- (3u, 0) .. (4u, u) .. (3u, 2u) -- (0, 2u) -- cycle);

The cycle keyword thoughtfully closes your path, bringing it right back to its starting point. It’s important to remember that closedness is always explicitly written, never just inferred. And speaking of closed paths, fill() naturally requires one to work its magic.

Corners

What if you want a point to be distinctly sharp between two curves? You can achieve this by marking it with {corner}. When you do, the fitter intelligently treats each side of that point independently, which means you won’t get any automatic smoothness across it.

u = 100;
wave    = (0, 0) .. (u, u) .. (2u, 0) .. (3u, u) .. (4u, 0);
scallop = (0, 0) .. (u, u) .. (2u, 0){corner} .. (3u, u) .. (4u, 0);

draw(wave);
draw(scallop shifted (5u, 0));

We’re using the very same five points in both examples. On the left, you can see how the fitter keeps the curve smooth right through the middle point, allowing it to swing through a rounded valley. On the right, however, that middle point becomes a deliberate corner. Here, each side is fitted entirely independently, causing the two arches to end quite steeply, meeting in a distinct cusp. Corners like these — strategically placed where two curves should visibly break apart — are truly the seeds for crafting every teardrop terminal and ink trap we’ll explore in Part III.

Here’s a little confession, with a valuable lesson tucked inside: in two earlier drafts of this very example, I tried marking the tip of a teardrop as a corner, and absolutely nothing changed. The shape stubbornly remained a smooth egg both times. The trick is, at a perfectly symmetric point, the tangents that the {corner} specifier frees up can simply choose to align perfectly with what the smooth ones would have done anyway. Think of {corner} as granting the fitter the freedom to break smoothness; it’s the surrounding geometry that ultimately decides whether that freedom actually makes a visible difference.

Reading the sheet

Everything you draw in ductus appears together on a single sheet. If you ever want a peek behind the curtain, simply pass --debug to ductus build (or toggle the debug option in the playground), and ductus will thoughtfully draw a coordinate grid right underneath your work. Our debug figures throughout this book also take advantage of this, just like this rendering of our earlier wave:

This grid is essentially graph paper, measured in font units. You’ll see fine lines every 10 units, heavier ones every 50, and the heaviest lines marking every 100 units. So, if you look at our wave, its crests at y = 200 are comfortably sitting two heavy squares above the baseline. For sketches, the sheet simply and conveniently sizes itself to whatever you’ve drawn. A real glyph, however, as we’ll discover in the next chapter, derives its vertical extent from font metrics — which, along with baselines, heights, and all those other helpful indicators, is truly what the debug view is designed for.

A first glyph

Imagine a sketch, freely drawing anything you wish, anywhere you please. Now, meet the glyph — it’s a bit more committed. A glyph isn’t just a drawing; it’s a promise, complete with a name, a defined width, and closed contours ready for a font renderer to bring to life. In this chapter, we’re going to craft the simplest glyph imaginable: a straightforward sans-serif l, essentially just a single rectangle. But we won’t stop there; we’ll transform it into something parametric, which is, after all, the true magic of using ductus.

A complete file

metrics { upm = 1000; x = 500; cap = 700; asc = 750; desc = -220; }

glyph l : U+006C {
  advance = 250;
  stem = 60;
  lsb = (advance - stem) / 2;

  contour main =
      (lsb, 0) -- (lsb + stem, 0)
   -- (lsb + stem, asc) -- (lsb, asc) -- cycle;
}

Let’s break this down, piece by piece:

  • metrics The metrics block is where you define font-level measurements. Five specific keys hold special significance for the renderer: upm (units per em), x (x-height), cap (cap height), asc (ascender), and desc (descender, which is a negative value). These are crucial for setting the overall size of your canvas and for displaying helpful guidelines in the debug view. Any other key you include here is simply a handy named number, ready to be used by any subsequent code.
  • glyph l : U+006C { ... } This line introduces our glyph, giving it the name l and assigning it the Unicode codepoint U+006C. You might notice that the codepoint isn’t always strictly necessary; for ligatures or other unencoded glyphs, you can simply leave it out. And if your glyph needs a name that isn’t a valid identifier, no problem — just write it as a string, like glyph "ka.mlym" : U+0D15.
  • advance The advance measurement is absolutely essential — it’s the one binding every glyph must have, defining its horizontal advance width in font units. Beyond that, everything else inside a glyph’s body functions just like ordinary code. Here, stem and lsb are local bindings. It’s helpful to remember that the origin for a glyph is positioned at its left sidebearing point on the baseline, which means lsb is literally where your ink begins to flow.
  • contour The contour keyword is how you define a filled shape. It’s crucial that its path must always end with cycle. If you leave a contour open, ductus won’t just issue a warning; it will flag an error. That’s because, quite simply, there’s no logical way to fill a shape that isn’t completely closed.

Now, here’s an important convention to start keeping in mind: this contour is drawn counterclockwise. Picture it: the bottom edge moves rightward, then up the right side, and finally back along the top. Ductus uses the nonzero winding rule for filling, which means outer contours should run counterclockwise, while any ‘counters’ — like the hole inside an o — should go clockwise. With our simple rectangle here, it doesn’t make a practical difference yet. However, once we delve into the chapter on nodes, this winding direction becomes absolutely vital.

Building it

To bring your designs to life, the ductus binary is your go-to tool for checking and rendering your source files:

ductus check l.ductus                 # parse errors only, no rendering
ductus build l.ductus -o l.svg        # every glyph, one sheet
ductus build l.ductus --glyph l --debug -o l-debug.svg

The --debug flag activates the construction view, which is the very same rendering style you’ll see used throughout this book. It’s a fantastic way to visualize everything: your metrics guidelines, the underlying grid, all your on-curve points, and those fitted handles.

Making it parametric

Right now, our l is essentially just a drawing, albeit with a few extra steps. But the real fun begins when we make it parametric. We start by clearly stating what parts of our design can change. This is where the params block comes in: it lets you define each design axis, assigning it both a default value and an allowed range. From there, we can elegantly derive properties like our stem.

params { weight = 400 in 100..900; }

metrics { upm = 1000; x = 500; cap = 700; asc = 750; desc = -220; }

stem = 40 + 0.14 * weight;

So, weight has now become a vibrant design axis. What that means is this single file is capable of describing every possible weight value, all the way from 100 to 900, simultaneously. You then pick a specific instance from outside the source file, perhaps by running ductus build l.ductus --set weight=700, or by simply adjusting a slider in the playground. Notice that stem is still just a regular binding, but now it adapts based on that chosen weight.

The glyph’s definition itself hardly needs touching. The main difference is that stem moves to the file level, and we adjust the advance so it elegantly grows alongside the stem, keeping those sidebearings perfectly balanced.

glyph l : U+006C {
  advance = stem + 190;
  lsb = (advance - stem) / 2;

  contour main =
      (lsb, 0) -- (lsb + stem, 0)
   -- (lsb + stem, asc) -- (lsb, asc) -- cycle;
}

That render used the default, weight = 400. The same source at --set weight=150:

and at --set weight=900:

Same file, same four points, same topology — just imagine, only the numbers have shifted. This beautiful invariance is a testament to ductus’s interpolation-compatibility rule doing its job, and it’s precisely what allows you to effortlessly sample an entire designspace from a single, unified source.

Try it — head over to the playground and observe the sidebearings as you adjust the weight. You’ll notice how the advance increases with the stem, ensuring the white space on each side remains perfectly consistent. That magic comes from the advance = stem + 190 line, marking our very first deliberate design decision in this book.

Finally, the debug view of the default instance, now with something to show: the metrics lines from the metrics block, the baseline, and the four on-curve points of the contour:

Our simple rectangle, charming as it is, really doesn’t get to flex any of ductus’s impressive curve-drawing muscles — you won’t find any .. joints, explicit directions, or clever nodes here. But don’t worry, the next part of our journey will dive deep into the language features that do bring those to life: exploring expressions and mediation, crafting intricate paths with the curve fitter, and building upon the powerful parameter system we’ve only just begun to uncover in this chapter.

Expressions

Everything in ductus — be it a stem width, a point on a contour, or an angle — is expressed as, well, an expression. We’ve kept the expression language wonderfully concise, making it easy to learn and use. In this chapter, we’ll dive into arithmetic, mediation, and ductus’s handy numeric builtins. If you’ve already peeked at the first-strokes chapter, some of these ideas might just feel like old friends.

Arithmetic

You’ll find the familiar arithmetic operators here: + - * / ^. They follow the usual precedence rules, with ^ handling exponentiation (and being right-associative), while - pulls double duty by also negating values. Here’s a clever little rule that simplifies things quite a bit: if you place a number literal directly in front of an expression, it automatically multiplies it.

stem = 40 + 0.14 * weight;
hair = 0.8 stem;            # same as 0.8 * stem
gap  = 2(stem + hair);      # parenthesized expressions too

This handy shorthand is why ductus code often looks so neat, peppered with expressions like 2u and 3u, giving it a clean, graph-paper feel. Just remember, this special rule applies only to number literals. Trying stem hair for multiplication would result in a syntax error, not a product. This way, you’ll never accidentally make two names ambiguous.

Points

In ductus, a coordinate pair like (x, y) represents a point, and it’s quite versatile, happily doubling as a 2-D vector. You can easily add and subtract points, and scale them by numbers on either side. It’s wonderfully intuitive:

q = p + (30, 0);        # displace
v = b - a;              # the vector from a to b
m = (a + b) / 2;        # scale by a number; also the midpoint, but see below

Now, a quick heads-up: trying to add point + number directly will lead to an error. There’s no implicit ‘broadcasting’ here. If you’re aiming for something like (p.x + 3, p.y + 3), you’ll need to explicitly construct that point. For peeking at a point’s individual coordinates, you can use p.x and p.y. And a neat trick like (p.x, 0) will effectively drop your point straight down to the baseline.

Mediation

Prepare to meet ductus’s secret weapon: t[a, b]. This wonderful expression calculates a value that’s t of the way from a to b. It works for both numbers and points. Seriously, this is ductus’s most-used expression. You’ll find yourself reaching for it constantly:

0.5[a, b]              # the midpoint
0.25[x, cap]           # a quarter of the way up from x-height to cap
(w / (w + v))[a, b]    # t can be any numeric expression

To get a feel for it, try reading t[a, b] aloud as “t between a and b”. Since ductus wisely avoids traditional indexing, this postfix bracket notation is unambiguous. When you’re working with points, mediation truly shines, making sure your construction lines stay tidy. Just imagine it ruling a perfect ladder between two rails, all without you ever needing to name a single intermediate coordinate. It’s really quite elegant:

u = 100;
a = (0, 0);      b = (6u, u);
c = (u, 3u);     d = (5u, 2u);

draw(a -- b);
draw(c -- d);
draw(0.25[a, c] -- 0.25[b, d]);
draw(0.5[a, c]  -- 0.5[b, d]);
draw(0.75[a, c] -- 0.75[b, d]);

Angles and vectors

In ductus, angles always follow the same trusty conventions: they’re measured in degrees, counterclockwise, with 0° pointing right. You’ll find this consistent behavior throughout, from direction specifications to rotated transformations and all the trigonometric builtins. For your convenience, we’ve even provided right, up, left, and down as helpful prelude bindings for 0, 90, 180, and 270 degrees, respectively.

We’ve got two lovely builtins ready to help you switch between angles and vectors: unitvec(theta) gives you a neat unit vector at a given theta angle, while angle(v) kindly tells you the angle of any vector (using atan2, naturally, in degrees). When paired together, they make expressing “perpendicular to” wonderfully straightforward, saving you from wrestling with trigonometry right there in your code:

u = 100;
a = (0, 0);
b = (6u, 2u);
n = unitvec(angle(b - a) + 90);    # unit normal to the line ab

draw(a -- b);
draw(0.3[a, b] -- 0.3[a, b] + 50n);
draw(0.7[a, b] -- 0.7[a, b] + 50n);

length(v) and distance(a, b) are also on hand, perfectly rounding out your vector toolkit.

Numeric builtins

min(a, b)  max(a, b)  clamp(x, lo, hi)    # clamp errors when lo > hi
abs(a)  sign(a)                           # sign(0) = 0
sqrt(a)  floor(a)  ceil(a)  round(a)
sin(a)  cos(a)  tan(a)                    # degrees, like everything else

These handy builtins pretty much do exactly what their names suggest. You’ll find a complete rundown, detailing the precise behavior of each and every builtin, in the reference section of this book. Oh, and a little heads-up: builtins like point, direction, directionpoint, and intersection are also part of the ductus family, but they’re so special they get their own spotlight in the very next chapter.

Conditional expressions

With a if cond else b, you can elegantly choose between two values. For setting up your conditions, you’ll use familiar comparison operators like < <= > >= == !=, along with logical operators and, or, and not. It’s worth noting that ductus doesn’t have an if statement in the traditional sense. Instead, a conditional is always an expression, and it always requires both arms to be present. This keeps things nicely balanced:

u = 100;
w = 260;
capped = w if w < 2u else 2u;    # by hand; clamp(w, 0, 2u) is the builtin

fill((0, 0) -- (w, 0) -- (w, 30) -- (0, 30) -- cycle);
fill((0, 60) -- (capped, 60) -- (capped, 90) -- (0, 90) -- cycle);

Now, a friendly piece of advice: try to use conditionals with a bit of restraint, and please, stick to using them only with numbers. Imagine a conditional that decided which points even existed — one arm creating a four-point contour, the other a six-point one. This kind of flexibility, while tempting, would give different instances of your design completely different topologies, which unfortunately breaks that important interpolation-compatibility rule we talked about back in the first chapter. So, clamping a counter’s radius is a perfect, intended use case. But swapping out entire pieces of geometry, well, that’s generally not what we’re aiming for here.

Paths and the curve fitter

At the heart of ductus, you’ll find paths: an ordered list of on-curve points, each with optional direction constraints and a point type — smooth, corner, or line-adjacent. That’s the complete picture of what a path keeps. There are no control handles tucked away anywhere; they’re freshly computed each time the path is rendered.

The syntax, completely

p = a {up} .. b .. {theta} c -- d .. e{corner} .. cycle;
  • a .. b — This creates a lovely smooth curve joint, with the solver choosing the tangents for you.
  • a -- b — Just a good old straight line.
  • a {theta} .. — Here, you’re setting a specific direction constraint for the path leaving a. Similarly, .. {theta} b constrains the direction entering b. Feel free to put any numeric expression in degrees inside those braces — {up} does the trick because up is defined as 90 degrees, and {angle(b - a)} is a clever way to aim one point directly at another.
  • e{corner} — This marks a free corner, meaning each side of the point gets fitted independently, with no smoothness flowing across it. You can also create a corner by giving a point different entering and leaving direction constraints; the fitter will then honor those exact tangents.
  • cycle — This handy keyword brings your path full circle, closing it back to its very first point using the joint you just defined. Remember, making a path closed is always an explicit choice here.
  • When a line graciously meets a curve, that shared point automatically transforms into a special line/curve corner. The line, of course, continues its straight journey, while the curve gently lands tangent to it.

You won’t find a path concatenation operator here, and that’s by design. In ductus, a contour is always a single, cohesive path expression. Macros contribute their geometry by simply returning the points that path travels through – we’ll dive deeper into this fascinating topic in the macros chapter.

What the fitter does

Whenever you render a path (or query it, as we’ll see below), ductus gets to work, fitting beautiful cubic Béziers through its points. It uses a clever two-parameter spline, ensuring G2-smoothness at interior points, faithfully honoring every direction constraint and corner you’ve set, and closing the path perfectly when it ends with cycle. Our solver proudly descends from John Hobby’s brilliant METAFONT algorithm, and it boasts one property you’ll definitely want to remember: circular arcs are essentially exact. Let’s see it with four points and no constraints:

u = 100;
c = (2u, 2u);
r = 1.5u;

ring = c + (r, 0) .. c + (0, r) .. c + (-r, 0) .. c + (0, -r) .. cycle;
draw(ring);

Believe it or not, that’s a circle accurate to a remarkable 0.027 % of its radius — truly invisible at any size a glyph might be viewed. And here’s a fun secret: add more points, and it gets even better (with eight points, you’re looking at a mere 0.0004 % error). This incredible precision is precisely why ductus doesn’t bother with a dedicated arc primitive; simply placing points on the circle gives you the arc you need.

The one gotcha: squashed circles

Now, this same property comes with a small but important caveat. While the fitter’s handle lengths are spot-on for circles at every angle, this precision comes at a cost: it means the fit isn’t affine-equivariant. What does that mean? Well, transforming a curve after it’s fitted will give you a different result than fitting the points after they’ve been transformed. In practical terms, this little quirk usually shows up in just one scenario: creating an ellipse by simply scaling a circle.

aspect ratioerror, as a share of the long radius
1.00.03 %
0.721.0 %
0.53.8 %
0.117 %

Imagine a four-point “circle” squashed to half its height, and you’ll find it misses a true ellipse by almost 4 %. So, here’s a friendly tip: avoid scaling circles directly into ellipses. Instead, reach for the ellipse() constructor, which handily places eight points on the true curve for you (check out the reference chapter for more details). For exceptionally flat shapes, you might even want to add a few more points to achieve perfection. But don’t fret about other transformations — things like shifting, rotating, or slanting are perfectly safe, because your points and constraints transform with complete accuracy, and the fitting magic happens afterward.

Paths are values

Think of a path as a first-class citizen in ductus: you can bind it to a variable, pass it to a macro, or transform it in any way you like. And here’s the best part: because the actual fitting happens only when you render it, none of these operations cause you to lose a single shred of information. Even contour and guide names within a glyph are just ordinary path bindings, which means your later code can easily measure them and interact with them.

ductus gives you four wonderful built-in functions to query a path. Crucially, these functions always ‘see’ the fitted curve — that’s the very same beautiful geometry that gets rendered, not just the straight chords between your defined points. When we talk about ‘time t,’ we’re using segment time, much like in METAFONT. This means t runs from 0 to n for a path with n segments, with integer values landing precisely on your on-curve points.

u = 100;
p = (0, 0) .. (2u, 2u) .. (4u, 0) .. (6u, 2u);
draw(p);

mid = point(p, 1.5);            # halfway along the middle segment
crest = directionpoint(p, 0);   # first point whose tangent is 0 degrees

draw(mid + (-15, -15) -- mid + (15, 15));
draw(mid + (-15, 15) -- mid + (15, -15));
draw(crest + (-15, -15) -- crest + (15, 15));
draw(crest + (-15, 15) -- crest + (15, -15));

direction(p, t) acts as the inverse of directionpoint, revealing the tangent angle at a specific moment in time. It’s important to remember that directionpoint looks for a match in orientation, not just parallelism — so 0° means moving rightward, while 180° indicates a leftward journey. If no such point can be found, or if you try to query past the path’s end, it will let you know with an error.

For a wonderfully wavy path, you might find several points sharing the same tangent. No worries, an optional 0-based index is there to help you pick out the later ones. Looking at our example path above, directionpoint(p, 0) will happily find the crest, and directionpoint(p, 0, 1) will pinpoint the trough that comes right after it. Just be mindful not to ask for more matches than actually exist, as that would result in an error.

intersection

Say hello to intersection(p, q), which helpfully returns the very first point where two paths decide to cross each other — with “first” always referring to the earliest point along path p. When it comes to two line segments, this function is perfectly exact, and it handles all those workhorse scenarios that METAFONT’s whatever solver made famous: for instance, where exactly does a diagonal line cross a stem?

u = 100;
stem = (2u, 0) -- (2u, 4u);
diag = (0, 3.5u) -- (4u, u);

draw(stem);
draw(diag);

hit = intersection(stem, diag);
draw(hit + (-15, -15) -- hit + (15, 15));
draw(hit + (-15, 15) -- hit + (15, -15));

A line cutting across an arch meets it twice, and just like directionpoint, intersection accepts an optional 0-based index to reach the later crossings. They’re counted along p, so intersection(arch, cut) is the crossing on the arch’s rising side and intersection(arch, cut, 1) the one on its falling side. Asking for a third crossing that doesn’t exist is an error.

u = 100;
arch = (0, 0) {up} .. (2u, 3u) {right} .. {down} (4u, 0);
cut = (-u, 2u) -- (5u, 2u);

draw(arch);
draw(cut);

rise = intersection(arch, cut);
fall = intersection(arch, cut, 1);
draw(rise + (-15, -15) -- rise + (15, 15));
draw(rise + (-15, 15) -- rise + (15, -15));
draw(fall + (-15, -15) -- fall + (15, 15));
draw(fall + (-15, 15) -- fall + (15, -15));

Because these clever queries employ the very same fitter as the renderer, you can trust that a curved path is always ‘cut’ precisely where it’s drawn. It’s a wonderful principle: what you measure is truly what you see. You’ll find Part III relies on this constantly — directionpoint becomes your go-to for finding perfect pen waists, and intersection is invaluable for building elegant joints. For now, just tuck away this thought: a path in ductus isn’t just a line on a page; it’s a rich source of information you can always inquire about.

Transforms

Transforms are like little helpers that come after the thing they’re transforming. They’re postfix operators, meaning they read left to right, and you can string them together to create a whole sequence of changes:

p shifted (dx, dy)
p scaled k            # uniform, about the origin
p xscaled k
p yscaled k
p rotated theta       # degrees, counterclockwise, about the origin
p slanted k           # (x, y) -> (x + k*y, y)
p reversed            # paths only: reverse the direction of travel
p rotated 10 shifted (50, 0)    # first rotate, then shift

These handy operations work their magic on points, paths, and even nodes – we’ll get to those in Part III. To give you a taste, let’s watch one shape go through a little transformation journey:

u = 100;
f = (0, 0) -- (1.5u, 0) .. (2u, u) .. (1.5u, 2u) -- (0, 2u) -- cycle;

fill(f);
fill(f scaled 0.5 shifted (3u, 0));
fill(f slanted 0.25 shifted (4.5u, 0));
fill(f rotated 90 shifted (9.5u, 0));

About the origin

scaled, rotated, xscaled, yscaled, and slanted all have a special relationship with the origin. They don’t offer a direct “rotate about a specific point” option. Instead, the trick is to build your shape right at the origin, apply your transformations, and then use shifted to move it exactly where you want it. (Thinking about it in reverse – shifting to the origin, transforming, then shifting back – is just the same chain in reverse.) You can see this principle in action with our example above: f starts its life at the origin, which sets it up perfectly for all those cool transformations.

slanted k gives us that elegant italic effect. It gently nudges every point to the right by k times its height. This means vertical lines will lean into slopes, while horizontal lines stay comfortably in place. For instance, a slanted value of 0.25 gives you a tilt of about 14 degrees.

Transforms preserve the fit’s input, not its output

When you transform a path, you’re actually transforming its underlying points and constraints. The curve then gets a fresh fitting to these new positions. This approach is usually exactly what you’d hope for, with one quirky exception: non-uniform scaling of circles (a little gotcha we met in the previous chapter). For just about everything else, it’s perfect: a rotated o is a truly o-shaped curve nestled in its rotated spot, not just a wobbly, rotated copy. Even your direction constraints come along for the ride; a {up} constraint on a path that’s rotated 90 will happily become a {left} constraint.

reversed

reversed offers a neat trick: it simply flips a path’s direction of travel. This means the points are reordered in reverse, and any entering and leaving constraints get swapped around. If you just draw a spine, you won’t see any immediate difference – the direction really comes into play when the path is filled. Ductus uses the nonzero winding rule for filling, which requires a ‘counter’ path to run in the opposite direction to the contour surrounding it. Later on, when we explore nodes and derive both sides of a stroke from a single skeleton, reversed will be the key to ensuring the inner bank forms a perfectly proper counter. For now, you can tuck this little tidbit away: it’s the same beautiful ink, just heading in the opposite direction.

What transforms cost

Curious about the cost of all these wonderful transformations? The answer is a ‘nothing at all.’ A path value simply holds onto its points, and a transform just maps them once. On the sheet level, everything remains consistent as well. These transformations take place within glyph space, well before any rendering happens, so they don’t concern themselves with sheet layout, metrics, or other glyphs.

Parameters, metrics, and bindings

A ductus file finds its structure through three distinct forms for blocks and bindings. You’ll use params to declare all the variables in your design, metrics to name those essential font-level measurements, and plain bindings to derive everything else. This chapter also dives into how you can read values back out of your design. It’s ductus’s elegant answer to questions like, “how thick did that stem actually turn out?”

params

params { size = 300 in 100..460; }

metrics { upm = 1000; x = 500; cap = 700; asc = 750; desc = -220; }

When you define an entry in params, you’re essentially creating a design axis. Each one needs a name, a default value, and a range specified with in. Within the ductus language itself, a parameter acts just like a regular number binding. What makes it special, though, is its ability to be overridden from outside your source file, allowing for unique instances:

ductus build dot.ductus --set size=460

The ductus playground automatically generates handy sliders from this block, providing one for each parameter and respecting its declared range. When ductus evaluates your file, it follows a clear, single-pass process. First, it handles your parameters — applying defaults, then any --set overrides. Next up are the metrics, and after that, the rest of your file is evaluated from top to bottom.

metrics

The renderer pays special attention to five particular metric keys. These are upm, x, cap, asc, and desc, which together define the overall sheet size and help draw those useful debug guidelines, just as we explored in the first-glyph chapter. Any other key you include here is simply a named number that comfortably lives alongside these essential ones. Metric values behave just like ordinary expressions, and they can even reference your parameters. This means defining something like a weight-dependent overshoot can be as simple as a single line:

metrics {
  upm = 1000; x = 500;
  over = 10 + weight / 200;   # heavier weights overshoot more
}

Bindings are the measuring instrument

A plain binding is how you derive a value; there’s no separate “measure” keyword to worry about. But here’s where numeric bindings serve a dual purpose: ductus is designed to report them directly to tooling. Top-level bindings are reported in source order, and a glyph’s own bindings appear right alongside its advance. Since ductus doesn’t include a traditional print statement, these bindings become your only way to retrieve a computed number from your source file. This powerful feature means that a binding applied to geometry acts as a probe:

glyph dot {
  advance = 500;
  center = (advance / 2, x / 2);
  r = size / 2;

  contour main = circle(center, r);
  bulge = distance(point(main, 0.2), center) - r;
}

Here, bulge gets right into measuring the fitted contour itself. It tells us precisely how far a point, one fifth of the way into the first segment, deviates from a perfect circle. (By the way, circle() is a shape constructor that provides a simple path value with four points; you can explore its relatives in the reference chapter.) Notice that nothing actually uses bulge within the file; its sole purpose is to be observed and understood.

ductus inspect

When you run ductus inspect, it thoroughly evaluates your file and then thoughtfully reports every number contained within. This includes your parameters and their ranges, all your metrics, every binding, and for each glyph, you’ll see its advance, any probes you’ve defined, and the point counts for each contour:

$ ductus inspect dot.ductus
params
  size                     300  in 100..460
metrics
  asc                      750
  cap                      700
  desc                    -220
  upm                     1000
  x                        500

glyph dot
  advance                  500
  bulge                 0.0407
  r                        150
  contour main        4 points

So, that bulge value of 0.0407 font units, when compared to a radius of 150, precisely indicates the fitter’s 0.027 % circle error. And yes, all of this is measured right from within the ductus language itself. You’ll only find numeric bindings appearing in this list. For instance, center is a point, so it’s reported as part of your geometry (like anchors and contours) rather than showing up in this number table. Happily, --set works here too, providing a great way to quickly check a derived value across your design space:

The figure you see above displays the very same file, but this time with --set size=460 applied. If you were to run ductus inspect dot.ductus --set size=460 yourself, you’d observe r at 230 and bulge scaled up right alongside it, still maintaining that consistent 0.027 %.

Try it — load this file in the playground and drag size while watching the inspector. bulge moves, but its share of r never does. Before probes existed, checking this number meant parsing the output SVG with a Python script; the probe exists so that ductus can measure ductus.

Immutability, and why

Here’s an important principle: every single binding in ductus — whether it’s a parameter, a metric, a top-level declaration, or glyph-local — is designed for single-assignment. Trying to rebind a name within the same scope will actually result in an error. Of course, inner scopes, like those within glyph bodies or macro bodies, are allowed to shadow names from outer scopes. When you combine this immutability with ductus’s single-pass evaluation, it makes reasoning about your ductus file straightforward. Any value you see can be traced back to one specific line, evaluated just once, using values that were clearly defined above it. So, if something ever seems amiss, you know there’s exactly one place you need to investigate.

Macros

When you use def, you’re essentially giving a name to a building block of your design. Just like everything else in ductus, a macro’s body is declarative—we’re talking about bindings here, no return statements in sight. And that neat little arrow, well, it’s there to tell us exactly which of those bindings the caller will get back:

u = 100;

def diamond(c, r) -> p {
  p = c + (0, r) -- c + (r, 0) -- c + (0, -r) -- c + (-r, 0) -- cycle;
}

fill(diamond((u, u), 80));
fill(diamond((3u, u), 55));
fill(diamond((4.2u, u), 30));

Parameters are simply names without a specific type, and arguments are always passed by value. What’s really cool is how versatile ductus is: almost any value can travel through your macros. Think numbers, points, paths, and pens—even the nodes that form the backbone of the constructions we’ll explore in Part III.

Returning several things

If you need to send back more than one thing, simply use -> (a, b, c) to return a tuple. Ductus handles the destructuring right at the spot where you call your macro.

Now, this tuple isn’t a general-purpose value you can pass around freely; its existence is quite special, spanning just that bridge between the macro and its caller. Because of this, the destructuring pattern you define becomes the entire handshake protocol for those returned values.

u = 100;

def arch(c, w, h) -> (l, top, r) {
  l = c + (-w/2, 0);
  top = c + (0, h);
  r = c + (w/2, 0);
}

(l1, t1, r1) = arch((2u, 0), 3u, 2u);
draw(l1 {up} .. t1 .. {down} r1);

(l2, t2, r2) = arch((5.5u, 0), 2u, 3u);
draw(l2 {up} .. t2 .. {down} r2);

Just like that, you have two arches, born from a single definition but sporting different proportions. And notice this: the caller takes the reins, crafting the path itself using those handy returned points.

Why macros return geometry, not path pieces

Let’s take a moment to really look at that last example, shall we? It elegantly answers a question that every MetaPost user eventually bumps into: where exactly is the & path concatenation operator in ductus? The short answer is: you won’t find one in ductus.

In ductus, a contour is fundamentally defined as one path expression. This means that instead of giving you little path fragments to glue together, a macro helps out by returning the precise points (or nodes) that your contour will journey through.

This design choice isn’t accidental; it’s quite deliberate. Think about it: path concatenation often requires a whole set of rules for merging the ‘seam.’ You’d need to decide whose direction constraint wins, whether a junction should be smooth or a sharp corner, and all those rules would silently operate, invisible at every single joint. Ductus takes a different route. Here, the caller explicitly defines each junction because, after all, they are crafting the entire path themselves. This keeps what a macro computes wonderfully separate from how the contour ultimately uses those values.

You’ll see this principle again in Part III, where macros return nodes for precisely the same reason. Take the bowl() macro, for instance: it hands you four key ‘skeleton’ points, and then the glyph itself gets to decide exactly how its contours travel through them.

Macros can absolutely call other macros. Imagine building a fancy serif from smaller corner pieces, or crafting an entire letter part out of those serifs. However, there are a couple of ground rules: recursion is not allowed, and just like params and pen blocks, macro definitions must live at the top level of your code.

Scope

A macro body operates within its own ordinary scope. This means it comfortably sees all top-level bindings—like your params, metrics, and anything else defined earlier on. Its own parameters will shadow any outer names, and any local variables within—that’s everything you don’t explicitly export—will simply vanish once you hit that closing brace. It’s a tidy system: nothing leaks out. What you don’t choose to export simply ceases to exist once you step beyond those protective braces.

Lists, loops, and imports

Ductus offers some neat tools for repetition and reuse. They’re pretty lean, much like conditionals, and they come with a special heads-up about how they play with interpolation.

for over a range

for i in a..b is your go-to for stepping through a sequence of numbers. It’ll count from a all the way up to b, making sure to include both ends of that range, and it increments by 1 each time. This is the very same range style you’ll find in the params block.

Each time the loop runs, it gets a brand new, clean scope, with your loop variable ready and waiting. This means absolutely nothing carries over from one iteration to the next. So, what’s it good for? Primarily, it’s there to produce side effects, like draw and fill, or to help you parameterize statements using that handy loop variable:

u = 100;
for i in 0..6 {
  ray = (0, 0) -- (4u, 0);
  draw(ray rotated (15 i));
}

And just like that, you get seven rays, spanning from 0° right up to 90°. Notice how ray gets a fresh assignment each time the loop goes around, which is perfectly fine because, as we saw, every iteration sets up its own clean scope.

for over a list

You can create a list right in your code using [a, b, c]. And guess what? for can happily loop over any values you toss into a list. Take this example, where a list of points lays the groundwork for a charming row of domes:

u = 100;
for c in [(0, 0), (2.5u, 0), (5u, 0)] {
  dome = c .. c + (u, u) .. c + (2u, 0) -- cycle;
  fill(dome);
}

Now, here’s a key point about lists in ductus: you iterate over them, but you can’t index them directly. Ductus doesn’t offer subscripting (that postfix bracket actually means mediation, which is a different beast entirely), and there’s no built-in way to check a list’s length either. If you ever catch yourself wishing for those features, you’ll generally find that a macro, designed to take those values as parameters, is a much better fit for what you’re trying to achieve.

Loops versus the design space

Alright, let’s talk about that warning label we mentioned earlier. Imagine you tie a for loop’s bounds to a parameter – perhaps you want one snazzy decorative diamond for every 100 units of weight. What happens then? Well, different instances of your design would end up with wildly different geometries. This completely breaks interpolation compatibility, much in the same way a structural conditional would. The takeaway here is clear: your loop bounds really ought to be constants inherent to your design.

By the way, the current evaluator isn’t strict about this yet, but the upcoming designspace sampler will certainly be keeping an eye on it.

import

import "file.ductus"; is your way of bringing in goodies from another file. It takes all sorts of items – parameters, metrics, pens, macros, bindings, even entire glyphs – and evaluates them right into your current scope, exactly where you placed the import statement. Think of it as if you had typed all that content directly into your file.

To see it in action, let’s look at examples/units.ductus, a companion file for this chapter. It thoughtfully provides us with a handy unit and a macro:

# examples/units.ductus
u = 100;

def diamond(c, r) -> p {
  p = c + (0, r) -- c + (r, 0) -- c + (0, -r) -- c + (-r, 0) -- cycle;
}

Once we import it, both become instantly available for us to use:

import "examples/units.ductus";

fill(diamond((u, u), 80));
fill(diamond((0, 0), 80) yscaled 0.5 shifted (3u, u));

A few quick rules to keep in mind about importing:

  • Top level only — You’ll want to place your imports at the top level of your file; tucking an import inside a glyph or macro body will result in an error.
  • Include-once per canonical file: No need to worry about duplicate evaluations. Even if you import the same file via different paths, ductus will only evaluate it once. Also, do keep an eye out for import cycles; those will trigger an error.
  • Relative to the importing file, which is super handy. This setup means a library can confidently import its own internal helpers, no matter where your main project file decides to call home.
  • Errors carry the file name — If something goes wrong, say a binding is broken in an imported file, ductus will let you know by reporting the error against that specific file. It helps keep debugging clear.
  • The playground rejects imports for now: Just a heads-up that the playground isn’t quite ready for imports yet. That’s because file resolution is handled by the host environment, and, well, your browser doesn’t have a filesystem to browse. The CLI, on the other hand, handles them , resolving paths relative to your source file.

So, there you have it. Between def for defining things and import for bringing in outside resources, you’ve got ductus’s entire story for reusing your work. Think of it this way: macros are perfect for sharing clever constructions right within a single file, while imports are designed for sharing entire files across a whole family of designs.

And what exactly do they share? Well, from Part III onward, you’ll discover that it’s mostly about nodes – and that’s precisely where we’re headed next in this book.

Nodes and derived points

Up until now, we’ve been crafting outlines point by point. But here’s the thing: type is fundamentally about strokes. Think of an o as a lovely round stroke, or an l as a crisp straight one. Each stroke carries its own direction and thickness, long before it takes on its final outline. And in ductus, a node is how we elegantly capture all of that information:

node n = (x, y) dir theta pen pen(w);

Essentially, a node is a special skeleton point that holds vital information about an imaginary stroke. It knows the local direction of travel (dir, measured in degrees) and the pen that draws through it. pen(w) is the simplest pen there is: a round one, w units across, so the stroke is w thick whichever way it travels. The pens chapter covers the rest of the family. A node is a foundational concept, but it never actually appears on its own. Instead, its true power comes from its ability to derive other points, like so:

n.pos      # the point itself
n.dir      # the direction, a number
n.width    # the stroke's thickness across travel: w
n.left     # n.pos + (w/2) * unitvec(n.dir + 90)
n.right    # n.pos - (w/2) * unitvec(n.dir + 90)

Think of left and right like the banks of a river, always relative to your direction of travel. If you’re standing on the skeleton facing dir, n.left will be half the stroke’s width to your left. No fancy offset-curve magic happening here; these derived points are simply born from straightforward arithmetic. What you see in those formulas above is exactly how it works.

A first stroke

So, how do we actually create outlines with these clever points? We write them through the derived points. Just two nodes are enough to define a beautiful tapered stroke. Imagine a skeleton running down the middle, with one bank stretching out, and the other coming back.

u = 100;
node a = (u, u)      dir 55 pen pen(90);
node b = (5u, 2.5u)  dir 10 pen pen(30);

draw(a.pos {a.dir} .. {b.dir} b.pos);       # the skeleton
draw(a.left {a.dir} .. {b.dir} b.left);     # each bank echoes it
draw(a.right {a.dir} .. {b.dir} b.right);

These banks are simply ordinary curves, passing through ordinary points. The neat trick is that they intelligently reuse the node’s direction as their own constraint, which is precisely what makes them glide so parallel to the skeleton. Now, let’s close off those ends, and voilà, we have a complete contour:

u = 100;
node a = (u, u)      dir 55 pen pen(90);
node b = (5u, 2.5u)  dir 10 pen pen(30);

fill(a.right {a.dir} .. {b.dir} b.right
  -- b.left {b.dir + 180} .. {a.dir + 180} a.left -- cycle);

Picture this path: we journey out along the right bank, then take a straight shot across the far end, cruise back along the left bank (notice how every direction is cleverly reversed with + 180), and finally, complete the loop by crossing the near end with cycle. Those two neat, straight crossings are what we call cut terminals. They’re the most straightforward way a stroke can end, and we’ll dive much deeper into them in a dedicated chapter later on.

It’s important to notice what ductus didn’t do here. It didn’t perform any complex curve offsetting. Instead, it precisely offset four points and then skillfully fitted curves right through them. If a truly parallel curve and our fitted bank ever have a minor disagreement, the solution is simple, just like many other things in ductus: we simply add a witness point. The pens chapter will explain this in fine detail.

A fixed axis

A round pen spreads the stroke perpendicular to the direction of travel, as shown by unitvec(dir + 90) in our earlier formulas. Give pen a height of 0 and an angle, and you get a razor: a flat pen whose edge stays pinned to that angle, whatever the travel direction:

node k = (x, y) dir theta pen pen(w, 0, phi);
# k.left = k.pos + (w/2) * unitvec(phi)  — phi, not theta + 90

A fixed axis like this simulates a broad pen: the stroke becomes wonderfully thick when it travels across the axis, and elegantly thin when it glides along it. Here is the same familiar bowl, with every node’s razor pinned to 30°:

u = 100;

def bowl(cx) -> outline {
  node n = (cx, 2.4u)        dir left  pen pen(70, 0, 30);
  node w = (cx - 1.2u, 1.2u) dir down  pen pen(70, 0, 30);
  node s = (cx, 0)           dir right pen pen(70, 0, 30);

  outline = n.right .. w.right .. s.right
         -- s.left .. w.left .. n.left -- cycle;
}

fill(bowl(1.5u));

node a = (4u, 0)    dir up pen pen(70, 0, 30);
node b = (4u, 2.4u) dir up pen pen(70, 0, 30);
fill(a.right -- b.right -- b.left -- a.left -- cycle);

Take a look at the upright stroke nestled next to our bowl. It showcases another signature of broad-pen behavior: its cut ends align with the pen’s axis, perfectly capturing the entry angle a broad pen would naturally leave. The bowl, however, subtly hints at a fascinating challenge. Somewhere along its path, between two nodes, the travel direction crosses the pen’s axis. At precisely that point, a true stroke would thin to nothing. The good news is, the upcoming pens chapter will teach us how to articulate this behavior perfectly.

Building the o

Let’s finally build the ‘o’ glyph that greeted us at the very beginning of this book, starting from scratch. First, we lay down the essential scaffolding: our parameters, metrics, and the definitions for the two key stroke weights:

params {
  weight   = 400 in 100..900;
  contrast = 0.85 in 0.6..1.0;
}
metrics {
  upm = 1000; x = 500; cap = 700; asc = 750; desc = -220;
  over = 10 + weight / 200;
}

stem = 40 + 0.14 * weight;
hair = contrast * stem;

stem defines our lovely thick stroke, while hair handles the delicate thin one. And over? That’s our clever overshoot value, determining just how much a round shape needs to gently extend beyond the flat metrics to appear perfectly aligned.

Our skeleton is formed by four nodes arranged on an ellipse, traveling counterclockwise. It moves across the top going leftward, sweeps down the left side, glides along the bottom heading rightward, and finally rises up the right side. Horizontal movements are assigned the hair thickness, while vertical movements take on the stem thickness. This simple distinction is the secret to all the contrast in our design.

glyph o : U+006F {
  advance = 2 stem + 380;
  center = (advance / 2, x / 2);

  # mid-stroke radii: the outline's extremes land on x + over and -over
  ry = x / 2 + over - hair / 2;
  rx = advance / 2 - 55 - stem / 2;

  node n = center + (0,  ry) dir left  pen pen(hair);
  node w = center + (-rx, 0) dir down  pen pen(stem);
  node s = center + (0, -ry) dir right pen pen(hair);
  node e = center + (rx, 0)  dir up    pen pen(stem);

  guide spine = n.pos .. w.pos .. s.pos .. e.pos .. cycle;
}
e n s w

The debug view gives us a clear peek at what we’ve crafted so far: four nodes, each proudly displaying its direction arrow, along with its two cleverly derived edge points, and the graceful guide line connecting them all. There are no contours just yet, so nothing would actually render in a typical build. Those radii are quite special and worth a closer look. They’re actually mid-stroke radii, thoughtfully pulled in by half a stroke’s thickness. This ensures that the very extremes of the outline, which are half a stroke further out, land perfectly on our defined overshoot line.

Now, with just two elegant path expressions, we transform our scaffolding into beautiful ink:

glyph o : U+006F {
  advance = 2 stem + 380;
  center = (advance / 2, x / 2);
  ry = x / 2 + over - hair / 2;
  rx = advance / 2 - 55 - stem / 2;

  node n = center + (0,  ry) dir left  pen pen(hair);
  node w = center + (-rx, 0) dir down  pen pen(stem);
  node s = center + (0, -ry) dir right pen pen(hair);
  node e = center + (rx, 0)  dir up    pen pen(stem);

  guide spine = n.pos .. w.pos .. s.pos .. e.pos .. cycle;

  contour outer = n.right .. w.right .. s.right .. e.right .. cycle;
  contour inner = n.left  .. e.left  .. s.left  .. w.left  .. cycle;

  anchor top = (advance / 2, x + over);
}
e n s w top

Without the debug overlay:

And here’s the magic: because every single number in our design traces back to our initial parameters, the entire design space comes along for the ride, absolutely free. For example, setting weight = 850 gives us:

Or perhaps a low contrast look at contrast = 1.0, where hair and stem charmingly become equal:

We’ve created eight distinct points and two flowing contours, all dynamically at every instance. This truly embodies the ‘skeleton-as-scaffolding’ principle introduced in our first chapter, bringing it vividly to life. You defined just four positions and four pens, and the nodes, in their wisdom, effortlessly positioned everything else.

Try it — the playground ships this o among its examples. Go ahead, drag weight and contrast to their limits in the playground and watch the debug view. You’ll see the edge-point dots slide, the guide line gently breathe and reshape, and yet, not a single point will ever mysteriously appear or disappear.

The winding convention

Let’s take a closer look at our two contours, shall we:

contour outer = n.right .. w.right .. s.right .. e.right .. cycle;
contour inner = n.left  .. e.left  .. s.left  .. w.left  .. cycle;

Our skeleton journeys along in a pleasing counterclockwise direction. This means the right bank naturally forms the outside of our ring, while the left bank defines the inside. Notice that the outer contour follows the exact order of our skeleton — n, w, s, e — and it too is counterclockwise. Now, for the inner contour, we smartly walk the left points in reverse order — n, e, s, w. This clever reversal makes it clockwise, which is precisely the orientation the nonzero fill rule expects for a perfect counter. So, here’s a handy rule to tuck away for future reference:

Traverse a closed skeleton counterclockwise: the right points in order form the outer contour, and the left points in reverse order form the counter.

(If you prefer, you could also build both banks in skeleton order and then simply apply the reversed transform from the dedicated transforms chapter to the inner one. But by writing it out in reverse, with each direction implicitly handled as we’ve done here, there’s no need for an explicit reversal.)

The designer owns every point

Here’s a liberating thought: derived points are, at heart, just ordinary points. This means you can do wonderful things: w.right + (3, 0) will gently nudge the left flank of the o three units to the right, all without disturbing the original node. You could even entirely replace s.right with a carefully hand-placed point, which is a perfectly normal edit. And because a nudge is itself an expression, it can be parametric, just like everything else in ductus:

contour outer = n.right .. w.right + (3, 0) .. s.right .. e.right .. cycle;

Nodes themselves are also quite transformable. Functions like shifted, rotated, and their companions will move the node’s position and, at the same time, adjust its direction (and the pen’s angle). scaled, of course, thoughtfully scales the pen as well. So, when a macro like our bowl() example returns nodes, it generously hands the caller everything they might need: the position, the direction, the thickness, and both derived banks, all perfectly ready to be either artfully written through or, if inspiration strikes, confidently overruled.

Pens

Remember how the nodes chapter wrapped up, showing off a broad pen that was actually a flat razor? We also noted something interesting: if your travel path ran right along that razor’s axis, the stroke would just… disappear. Well, a proper pen, the kind you hold, has a distinct body. You can turn it on its own axis, and it will still leave a mark as wide as its nib is thick. Ductus’s pen captures that idea — it’s essentially an ellipse:

italic = pen(120, 12, 30);   # width, height, angle

node m = (x, y) dir theta pen italic;

pen(width, height, angle) takes the ellipse’s full major axis, its full minor axis, and the major axis’s orientation in degrees. height defaults to width, giving a round pen, and angle defaults to 0. The arguments are ordinary expressions, so they can reference params, letting your pen interpolate and adapt across your entire design space, and they can differ from node to node, as the pressure chapter will show. A pen is a first-class value: bind it to a name, pass it to a macro, or write it right in the node, as in pen pen(hair). Every node takes exactly one pen.

Now, it’s important to understand that a pen isn’t some magical stroke expansion tool. Instead, think of it as a clever rule for figuring out a node’s precise edge points. Specifically, n.left and n.right transform into the exact contact points where our ellipse touches the stroke’s two banks. This means you’re still drawing contours through those very points, outline-first, just like you do with everything else in ductus.

The family

While the ellipse is quite versatile, three special, or “degenerate,” cases actually cover most of what you’ll want to do. It’s helpful to think of the ellipse as part of a whole family, with these key members:

  • height = 0 — This gives you a razor pen, pen(w, 0, phi). Its banks sit at ±(w/2) * unitvec(phi) whatever the travel direction. It’s that familiar fixed-axis nib we met in the last chapter.
  • small height — Think of this as a realistic razor. When your travel direction aligns perfectly with the pen’s axis, the stroke thickness won’t vanish entirely. Instead, it bottoms out at that small height value, rather than collapsing to nothing.
  • height = width — Hello, monoline pen, pen(w). This creates a perfect circle, giving you a stroke that’s wonderfully consistent and equally thick no matter which way you travel. It’s the pen every node in the nodes chapter used.

Let’s see how the same C-stroke looks when we apply all three of these:

u = 100;

razor = pen(80, 0, 25);
soft = pen(80, 14, 25);
round = pen(46);

def arc(cx, p) -> outline {
  node n = (cx, 2.4u)        dir left  pen p;
  node w = (cx - 1.2u, 1.2u) dir down  pen p;
  node s = (cx, 0)           dir right pen p;

  outline = n.right .. w.right .. s.right
         -- s.left .. w.left .. n.left -- cycle;
}

fill(arc(1.4u, razor));
fill(arc(4.2u, soft));
fill(arc(7u, round));

Take a look at the razor stroke on the left: you’ll see it pinches down to nothing partway through. This happens because its banks are essentially just the skeleton shifted by a constant vector, meaning even a few sparse samples are enough to perfectly capture that collapse. Now, move to the monoline stroke on the right, and you’ll notice it’s wonderfully smooth and even all the way around. But then there’s that middle stroke, with our elliptical pen designed to bottom out at 14 units… and yet, it stubbornly stays quite chunky through the crossing. Don’t worry, the pen isn’t misbehaving at all. This is actually a classic sampling problem, and it’s perhaps the most crucial insight to grasp when working with pens.

Thin crossings need a witness

Here’s what happens: when your travel direction sweeps across the pen’s major axis, those true edge points actually swing rather dramatically to the ellipse’s opposite end. This swing happens within just a few degrees of travel, defining what we call the “swing zone,” which is roughly atan(height / width) wide. The issue is that the fitter, bless its heart, only sees the on-curve points that you provide in your source. So, if your banks are being fitted between two nodes that simply bracket this crucial crossing point, they’ll just cut straight across at full width. The subtle pinch is happening right there, in between your samples, completely unwitnessed.

The good news is the cure follows a familiar ductus pattern: any feature that’s narrower than your sampling needs a point to witness it. And happily, the pens machinery makes placing that witness remarkably straightforward. The crossing itself occurs precisely where the skeleton’s tangent matches the pen’s angle. Conveniently, directionpoint is designed to find this exact spot, tracking it faithfully across your entire design space.

u = 100;

soft = pen(80, 14, 25);

node n = (u, 2.4u)  dir left  pen soft;
node w = (-0.2u, 1.2u) dir down pen soft;
node s = (u, 0)     dir right pen soft;

skel = n.pos .. w.pos .. s.pos;
node m = directionpoint(skel, 205) dir 205 pen soft;   # 205 = 25 + 180

fill(n.right .. {m.dir} m.right .. w.right .. s.right
  -- s.left .. w.left .. {m.dir + 180} m.left .. n.left -- cycle);

As we travel from top to left to bottom, the tangent passes through 205 degrees. This angle aligns with the pen’s axis, pointing down-left, and it’s precisely where our m node finds its perfect home, right between n and w. At this point, the pen’s banks are exactly height apart, and those clever direction constraints ensure the waist becomes perfectly tangent to the path of travel. Go back and compare this with the middle stroke in our family figure: same pen, same skeleton, but with just one extra node, and what a difference it makes.

This whole process elegantly mirrors how you place points at extrema when you’re working with ordinary outline design. Remember, the razor pen never required a witness because its banks are always just constant translations of the skeleton. The round pen doesn’t need one either, since its banks stay perpendicular to travel. Those are special properties of the two degenerate pens. It’s easy to get used to this behavior, only to feel a bit baffled the first time a “real” pen leaves a crossing looking a bit thick. If that ever happens to you, consider this your friendly reminder to revisit this section.

The edge points, precisely

For those of you who love to dive into the nitty-gritty details — just a heads-up, everything we’ve covered so far works perfectly even if you never look at this part. But for the truly curious, here’s how the magic happens: given semi-axes a = width/2 and b = height/2, and a node traveling at a direction dir, the edge points are actually the ellipse’s support points positioned along the left normal. We calculate this using ψ = dir + 90 − angle:

h       = sqrt(a²·cos²ψ + b²·sin²ψ)        # half thickness across travel
x*      = rotate(angle) · (a²·cos ψ, b²·sin ψ) / h
n.left  = n.pos + x*
n.right = n.pos − x*

When height is greater than zero, n.left consistently represents the true left bank of travel. This is the precise contact point of our rolling ellipse, which means the banks you draw through these points are authentic envelope edges, not mere approximations. You can find the full derivation in the ductus specification, should you wish to explore it further.

Joints

When two strokes come together at an angle, they form a joint, and it’s quite neat how both sides of this joint are handled by tools you’re already familiar with. The outer shoulder is formed by the pen itself, tracing a path between your two travel directions. You achieve this by placing extra nodes at the same position, but giving them intermediate directions, and then simply writing through them. Meanwhile, the inner corner is elegantly found right where the two inner banks intersect — a perfect job for intersection().

u = 100;

main = pen(80, 16, 30);

node a  = (0, 0)    dir right pen main;
node k1 = (2.2u, 0) dir right pen main;
node kj = (2.2u, 0) dir 45    pen main;
node k2 = (2.2u, 0) dir up    pen main;
node b  = (2.2u, 3u) dir up   pen main;

inner = intersection(a.left -- k1.left, k2.left -- b.left);

fill(a.right -- k1.right {right} .. kj.right .. {up} k2.right
  -- b.right -- b.left -- inner -- a.left -- cycle);

Notice how three nodes gather at the corner position: k1 continues its journey right, k2 is already heading up, and kj elegantly sits halfway between them at 45 degrees. Out on the exterior, their right points fan out, showing the pen smoothly rolling around that corner. But on the inside, a single, precisely computed point takes care of the entire corner for you. If you need a broader, more sweeping turn, simply add more intermediate directions. A handy trick for naming them is using 0.5[t1, t2], a concept we explored in the expressions chapter.

You might observe that both ends of this particular stroke are still quite flat. Don’t worry, rounding them off — essentially tracing the pen around a terminal — is exactly what we’ll dive into in the next chapter. We’ll also explore what happens when your pen gets a little too flat for that tracing to hold up.

Terminals and caps

Ductus doesn’t include automatic caps, and that’s a conscious design choice, not something we’ve missed. We believe a terminal should be treated like any other part of an outline. Whether you envision a stroke’s end as a clean flat cut, a traced round cap, a soft teardrop, or even a subtle ink trap, you’ll write it directly into the contour. This approach ensures it remains editable point by point and fully parametric. This chapter provides a detailed look at how you can achieve these.

Cuts

Meet the terminal you’ve likely been creating all along: where the two banks connect straight across, using either -- or the closing cycle. Because you’re in complete control of this cut line, its angle is also entirely up to you. Simply extending one corner, for instance, makes the cut turn oblique. And with a broad-pen node, the cut naturally follows the direction of the nib. Here, we’ll demonstrate three uprights, each with a different kind of end:

def bar(x) -> (a, b) {
  node a = (x, 0)    dir up pen main;
  node b = (x, 2.6u) dir up pen main;
}

(a1, b1) = bar(u);
fill(a1.right -- b1.right -- b1.left -- a1.left -- cycle);

(a2, b2) = bar(2.6u);
fill(a2.right -- b2.right -- b2.left + (0, 55) -- a2.left -- cycle);

(a3, b3) = bar(4.2u);
fill(a3.right -- b3.right {b3.dir} .. {b3.dir + 90} b3.tip
  .. {b3.dir + 180} b3.left -- a3.left -- cycle);

The first example demonstrates a plain, straightforward cut. In the second, we’ve raised one corner by 55 units, giving us an oblique cut—all accomplished within a single expression. The third example introduces a powerful new capability: it traces the pen’s distinctive shape.

Tracing the pen: .tip and .tail

Nodes provide you with two more handy points: n.tip and n.tail. n.tip represents the ellipse’s support point right along the direction of travel—essentially, the front of the pen. Conversely, n.tail is its mirror image, found at the back. (A quick note: attempting to use these on razor nodes will result in errors, as a zero-height pen doesn’t have a distinct front or back.) The ellipse’s tangent at these points is always perpendicular to the direction of travel. This crucial detail means that when you’re crafting a terminal that traces the pen, you know the direction constraints for its three key points before you even begin to draw.

... -- b.right {b.dir} .. {b.dir + 90} b.tip .. {b.dir + 180} b.left -- ...

To visualize this: let the right bank continue its journey with the stroke, then gently round the front as it turns left, and finally arrive on the left bank traveling backwards. A .tail cap applied at the start of a stroke works as a perfect mirror image of this sequence. You’ll see this precise idiom in action in the va_pen.ductus example, where it’s used for every stroke end.

... a.left {a.dir + 180} .. {a.dir - 90} a.tail .. cycle;

Where tracing breaks: flat pens

When you use a traced cap, you’re essentially providing the fitter with three specific points and asking it to construct half an ellipse. For a nicely plump pen, this task is usually quite straightforward. But things get a little tricky when you’re working with more eccentric pens. Imagine, for example, a realistic razor pen where the height is only a tenth of its width, and it’s held with its long axis perpendicular to the direction of travel. This creates a very broad stroke with ends that are nearly flat. In these situations, the three support points tend to cluster tightly at the pen’s tips, forcing the fitter to attempt a ninety-degree turn across an almost-zero chord. The visual result often isn’t what you’d hope for: you might see a sharp corner where the cap should curve, and an unexpected bulge where it ought to lie flat:

node a = (u, u)              dir 20 pen flat;
node b = a.pos + 1.8u * unitvec(20) dir 20 pen flat;

fill(a.right -- b.right {b.dir} .. {b.dir + 90} b.tip
  .. {b.dir + 180} b.left -- a.left {a.dir + 180}
  .. {a.dir - 90} a.tail .. cycle);

node c = a.pos + (0, 1.4u)   dir 20 pen flat;
node d = c.pos + 1.8u * unitvec(20) dir 20 pen flat;

fill(c.tailcap .. d.tipcap .. cycle);

Take a close look at the lower stroke; it demonstrates the standard traced idiom. If you inspect its ends, you’ll see how the cap slightly overshoots the pen’s true footprint. Now, for the fix, observe the upper stroke. It introduces .tipcap and .tailcap, which provide cap geometry constructed analytically instead of being fitted. Each of these returns a small path—the exact half-ellipse from one bank contact, around the front (or back), to the other. They carry their own fixed curve segments, making them wonderfully immune to eccentricity. It means that no matter how flat the pen, the cap will perfectly reflect its true shape.

Splicing

Using c.tailcap in that contour revealed one more clever path feature: splicing. When a path value is used as an element within a larger path expression, it essentially splices itself in. Its points and segments seamlessly merge into the host path, and any joints you define on either side will connect smoothly to the splice’s endpoints. The great thing is that the cap’s boundary points inherently carry their exact tangents along with them. This means there’s no need to explicitly write anything at the seam, allowing the entire outline of a stroke to be wonderfully concise, like this:

fill(a.tailcap .. b.tipcap .. cycle);

— a straightforward combination of two caps and the two bank curves that the fitter smoothly connects between them. Just a quick note: you can only splice open paths, not closed ones. While caps are a prime example and a common use case, any open path value will splice in the very same fashion.

Joints

A joint is a terminal’s close relative. Where two strokes meet at a corner, the pen pivots: it stands on the shared point while the direction of travel rotates from the first stroke’s to the second’s. On the outer side of the turn, its boundary sweeps an arc between the two bank contacts — the same silhouette a cap traces, only spanning the turn of the joint instead of a half turn. You could trace that arc with direction constraints, and for a plump pen it works just as well as it did for caps. It also breaks in exactly the same place: a flat pen turns almost all of its corner within a fraction of a degree of pivot, and the fitted curve bulges far off the metal. So joints get the analytic treatment too. jointcap(a, b) takes two nodes declared at the same position with the same pen — a arriving at the corner, b leaving it — and returns the exact arc as fixed curve segments, ready to splice.

The arc comes oriented for the traversal we’ve used throughout: out along the right bank, back along the left. On a left turn the outer corner lies on the right bank, and the arc runs from a’s right contact to b’s. On a right turn it lies on the left bank, and the arc runs from b’s left contact back to a’s. Either way, it drops in right where the outer banks end. The inner side of a joint needs no arc at all: the two banks simply cross there, and intersection() pins the corner. Here is a peaked stroke pair written with the same flat pen that defeated the traced cap earlier — note how the joint carries the pen’s true silhouette, in tune with both terminals:

d1 = 72; d2 = -55;                       # a 127-degree turn at the apex
apex = (2.6u, 2.35u);

node s1 = apex - 2.3u * unitvec(d1) dir d1 pen flat;
node e1 = apex dir d1 pen flat;
node s2 = apex dir d2 pen flat;
node e2 = apex + 2.3u * unitvec(d2) dir d2 pen flat;

inner = intersection(s1.right -- e1.right, s2.right -- e2.right);

fill(s1.tailcap -- inner -- e2.tipcap -- jointcap(e1, s2) -- cycle);

Two caps, one joint arc, one inner corner, four straight banks: the entire two-stroke figure is a single expression. The N-caps-joints.ductus playground example scales this up to an English N — two terminals and two joints, neither of them perpendicular. And to be clear about the boundaries: jointcap wants a genuine corner. Equal directions have no turn to round, and a full 180-degree reversal has no outer side — that one is simply a cap, which you already know how to write.

Teardrops, torn ends, traps

Anything else you can imagine a terminal to be will simply be a creative combination of moves we’ve already explored in this book. And that’s exactly the beauty of not having rigid cap machinery. For example, a sharp break between two curves comes to life with {corner} from the first-strokes chapter. If you’re envisioning a teardrop terminal, that’s just a swell traced around a corner point. An ink trap can be fashioned by pulling an inner corner open—perhaps by nudging an intersection() point into the joint. These are all straightforward edits that remain completely parametric. Our catalogue comes to a close here, and we’re intentionally stopping short. Past this point, terminals evolve into exciting design decisions that are entirely yours to make, rather than being dictated by fixed language features.

Pressure

You might notice ductus doesn’t have a dedicated pressure primitive. But that’s perfectly fine, because it doesn’t really need one. Think of it this way: a node’s pen is just an ordinary expression, which means pressure is simply part of that expression, sampled along a stroke in the very same way an outline takes shape from sampled points. In this chapter, we’ll explore two handy idioms — the classic pointed pen and the versatile pressure-scaled pen — and uncover the shared pattern that makes them both tick.

The pattern: press()

Both of these neat idioms lean on the path queries we explored in earlier chapters to build nodes right on a spine. Imagine this: you give our special press macro a path, a moment in time along that path, and a desired pressure. What you get back is a perfectly sampled node. Both its position and direction are inherited directly from the path, ensuring that the banks you see are always true, faithful offsets of the curve that eventually renders.

def press(path, t, pressure) -> n { ... }

e = press(spine, 2.65, 1);    # "at 2.65 along, full weight"

You’ll typically draw the spine just once, perhaps with a simple gesture of three or four points. Then, the magic happens: pressure is carefully placed along it. What’s really cool is that sampling density is completely up to you, and this flexibility is quite important. Picture an arch shoulder making a sharp 125° turn in a single segment. Without a few nodes tucked inside that bend, the inner bank would simply have nothing to trace, leading to some unexpected results.

The pointed pen

Imagine a classic pointed pen: its tines graciously spread under pressure, moving across the direction of travel. In essence, the slit runs along the stroke. Conveniently, that’s exactly where a round pen puts its thickness: always across travel. So a round pen whose diameter follows pressure, pen(hair + pressure * (shade - hair)), tells the whole story, shaping the stroke.

u = 100;
shade = 60;              # full-pressure thickness
hair  = 5;               # the unloaded mark

def press(path, t, pressure) -> n {
  node n = point(path, t) dir direction(path, t)
           pen pen(hair + pressure * (shade - hair));
}

spine = (2u, 4u) {265} .. (1.85u, 2u) .. {275} (2u, 0);

a = press(spine, 0,   0);
b = press(spine, 0.6, 0.9);
c = press(spine, 1.4, 0.9);
d = press(spine, 2,   0);

fill(a.right .. b.right .. c.right .. d.right
  -- d.left .. c.left .. b.left .. a.left -- cycle);

Here we see a graceful copperplate full-pressure pull: starting with a delicate hairline into the stroke, swelling through the middle, and then gently releasing back to a hairline as it exits. That lovely pressure profile you’re seeing is really just the story told by those four press lines. It’s fascinating how the point where a stroke reaches its full weight, and how quickly it then lets go, often defines the unique character of one hand from another. And here, that artistry is captured quite in just four numbers, ready for you to tweak and experiment with.

The terminals in this idiom emerge quite naturally and authentically. A pointed pen, after all, leaves you with either a crisp flat cut, where the banks simply join straight across, or a sharp end when pressure drops to 0, causing the banks to almost perfectly meet. What you’ll never see from this tool, however, is a round cap. A round pen does offer tip, tail and their caps, but this idiom consciously leaves them alone: using them would introduce caps that the very tool we’re modeling simply cannot produce.

The pressure-scaled pen

Now for our other charming idiom: this one embraces the pen’s body. We take an elegant ellipse complete with its own aspect and angle, and size the entire nib by pressure. Since a pen is an ordinary expression, each sample simply builds its own.

u = 100;
shade = 46;
hair  = 5;

def press(path, t, pressure) -> n {
  w = hair + pressure * (shade - hair);
  node n = point(path, t) dir direction(path, t) pen pen(w, 0.35 w, 20);
}

spine = (0, 0) .. (2u, 2u) .. (4u, 0) .. (6u, 2u);

a = press(spine, 0, 0);
b = press(spine, 1, 0.22);
c = press(spine, 2, 0.73);
d = press(spine, 3, 1);

fill(a.tailcap .. b.right{b.dir} .. c.right{c.dir} .. d.tipcap
  .. c.left{c.dir + 180} .. b.left{b.dir + 180} .. cycle);

A couple of details truly make this example sing. First, both the width and height of the pen shrink together. This clever design ensures that the pen’s aspect ratio and angle remain absolutely constant. Even a ‘shut’ pen will still print a hairline-sized ellipse, rather than just a crude point. Second, for our terminals, we rely on the elegant tailcap/tipcap splices from our last chapter, which maintain their precision no matter the pressure.

Choosing between them

When deciding between these two approaches, simply consider the tool you’re trying to model. If you’re working with tines that spread, think of a round pen and leave its caps alone. Here, the thickness truly lives across the direction of travel, and your stroke ends will naturally be crisp cuts or sharp points. But if your tool has a distinct nib body — perhaps a brush, a stub, or anything that leaves round ends — then opt for an elliptical pen sized by pressure, complete with its lovely, real caps. The wonderful news is that these two idioms really only differ by a handful of lines of code. What truly unites them, though, is how pressure is authored with such precision, sample by sample, as plain numbers you can easily examine with ductus inspect.

Where it runs out

Now, every powerful toolkit has its honest limits, and ours inherits a few from the very nature of sampling:

  • Between samples, pressure’s shape is the fitter’s choice. The banks will swell and flow right along with how the spline itself swells. Your only real control here is to add more samples, though naturally, that comes with a corresponding cost in computational effort.
  • Pressure and curvature interact, silently. It’s important to remember that half the stroke width needs to stay comfortably within the spine’s radius of curvature. If it doesn’t, the inner bank might unfortunately fold over itself, giving your stroke a rather ‘gnawed’ appearance. Interestingly, real calligraphers instinctively obey this rule — they press firmly on the straight pulls and gently release into the turns. Ductus doesn’t yet have a specific diagnostic for this, so for now, the shape itself will be your tell-tale symptom.

And there you have it, the complete strokes toolkit in all its glory. Get ready, because the exciting case studies ahead will put all these concepts to wonderful use, bringing real letters to life.

Glyph organization

Up until now, we’ve thought of a glyph as a name paired with its contours. But as you start building an entire font full of them, some important organizational questions pop up. You might wonder: what’s a proper name for a glyph, what essential bits go inside its definition, and how exactly do a bunch of files collaborate on a shared design. Luckily, Ductus’s answers to these questions are nothing new – they’re all concepts you’ve already bumped into, just arranged.

Names and codepoints

glyph o : U+006F { ... }          # encoded, identifier name
glyph "ka.mlym" : U+0D15 { ... }  # names that aren't identifiers
glyph "t_t" { ... }               # unencoded: ligatures, alternates

That codepoint is entirely optional, by the way. If you’re defining a ligature or a stylistic alternate, you can simply leave it out. And for those tricky names an identifier just can’t handle – think script-suffixed conventions often found in complex-script fonts – a string name comes to the rescue. Each glyph gets its own little block, and the sheet kindly renders them exactly as they appear in your source file.

What lives in a glyph body

When it comes to the glyph’s body, only four specific kinds of statements actually tell the renderer what to do. Everything else you write there is just plain old code:

  • advance = expr; — This one is essential: it sets the horizontal space your glyph takes up.
  • contour name = path; — These define the actual ‘ink’ that gets filled, and remember, they always need to end with cycle to close the shape.
  • guide name = path; — Think of guides as your trusty construction geometry: things like skeletons, diagonals, or those helpful alignment lines. They’re never filled with ink and you’ll only see them in the debug view. Since guide names are just regular path bindings, you can poke around with them using directionpoint and other handy tools. Essentially, a guide is a piece of documentation that your compiler thoughtfully checks and your tooling draws for you.
  • anchor name = point; — These create named positions, perfect for attaching marks. Imagine where an accent might perch over this glyph, or where a matra gently clips on. Ductus itself simply records and displays these points (you’ll spot them in the debug view or with ductus inspect), but the actual attachment magic happens with the font compiler further down the line.

Sharing a design: one file, then several

When you keep related glyphs together in a single file, they naturally share everything defined above them – that’s just how scoping works its charm. Take a peek at the playground’s latin_set.ductus file, for instance. It crafts an entire broad-nib lowercase alphabet this very way: a single params block, one shared pen, and then glyph after glyph.

But what happens when one file grows a bit too big to manage comfortably? That’s where import (a friend you met in the language chapters) steps in as your go-to organizational superhero. You can tuck away your axes, metrics, stroke weights, and construction macros into a dedicated ‘foundation’ file, and then simply have each glyph file – or even an entire family file – import it. Here’s a glimpse at our example foundation for this chapter:

# examples/family.ductus
params { weight = 400 in 100..900; }

metrics {
  upm = 1000; x = 500; cap = 700; asc = 750; desc = -220;
  over = 10 + weight / 200;
}

stem = 40 + 0.14 * weight;
hair = 0.85 * stem;

def bowl(c, rx, ry) -> (n, w, s, e) { ... }

Now, let’s look at two glyphs built upon this foundation. Notice how much isn’t explicitly defined within each glyph, because our trusty foundation file is carrying all that weight for us:

import "examples/family.ductus";

glyph o : U+006F {
  advance = 2 stem + 380;
  center = (advance / 2, x / 2);
  ry = x / 2 + over - hair / 2;
  rx = advance / 2 - 55 - stem / 2;

  (n, w, s, e) = bowl(center, rx, ry);
  guide spine = n.pos .. w.pos .. s.pos .. e.pos .. cycle;

  contour outer = n.right .. w.right .. s.right .. e.right .. cycle;
  contour inner = n.left  .. e.left  .. s.left  .. w.left  .. cycle;

  anchor top = (advance / 2, x + over);
}

glyph c : U+0063 {
  advance = 2 stem + 330;
  center = (advance / 2 + 30, x / 2);
  ry = x / 2 + over - hair / 2;
  rx = advance / 2 - 40 - stem / 2;

  (n, w, s, e) = bowl(center, rx, ry);
  guide spine = n.pos .. w.pos .. s.pos;

  contour main = n.right .. w.right .. s.right
              -- s.left .. w.left .. n.left -- cycle;
}

The sheet will present both glyphs, carefully advanced and nestled side by side, exactly as they appear in your source file. The ‘c’ cleverly reuses the ’o’s bowl, simply choosing not to follow the path down the right side. It’s the same set of nodes, just a different contour story. This perfectly illustrates the pattern from the macros chapter – where macros kindly hand back geometry, and callers then get to craft their own paths – now doing some fantastic family-scale heavy lifting.

So, for a real-world font family, here’s a layout that tends to work :

family.ductus          # imports everything below; ductus build family.ductus
foundation.ductus      # params, metrics, stroke weights
pens.ductus            # shared pens
constructions.ductus   # bowl(), arch(), serif() macros
latin.ductus           # glyph blocks
malayalam.ductus       # glyph blocks

A neat detail: import works as an include-once mechanism and resolves paths relative to the importing file. This means your individual glyph files can also be built on their own – each one simply begins with import "foundation.ductus"; and instantly gains access to that consistent design space.

Anchors and guides in the debug view

In the debug rendering, you’ll see everything the glyph body declared labeled. Take a look at those spine guides, each individual node, and the ’o’s top anchor floating above its ring.

e n s w top

Everything you see on that sheet, apart from the two actual contours, is what we call metadata. It’s wonderfully visible scaffolding there just for you, the designer, but it remains completely invisible to the final rendered output. Our next chapter will delve into the single, crucial promise that all this thoughtful organization needs to uphold across the entire design space.

Interpolation compatibility

We talked about the rule before, and now it’s time to put it to work. For any two instances within your parameter space, it’s essential that every contour yields the same number of Bézier segments with the same point types. This consistent structure is precisely what interpolation between masters requires—think of point 3 of a light o needing to correspond perfectly to point 3 of a black o. It’s also the fundamental promise that our future designspace sampler will rely on when it’s ready to cut masters from a single ductus source.

Why you mostly can’t break it

Good news: Ductus is designed to prevent you from breaking this rule almost entirely. It’s baked right into the core design of the language itself. The number and type of on-curve points in a contour are determined by your source text, not by the values of your parameters. When you adjust a parameter, you’re moving coordinates, never changing the underlying topology. We’ve thoughtfully shaped every construct that could potentially threaten this rule to keep it safe:

  • Shape constructors inherently have fixed point counts. For instance, an ellipse() will always result in eight points. That’s why you’ll find ellipse(c, r, r) rather than a separate circle(c, r) function.
  • You won’t find boolean geometry or “remove this point if” conditions here. We also don’t use conditional statements that alter structure. Instead, Ductus offers conditional expressions, which simply select between different values.
  • A witness node, like one created by directionpoint, will consistently be a single point at every instance, no matter where its crossing point happens to move.

Want to double-check yourself, or see how the tooling thinks about it? Point counts are readily available in ductus inspect:

glyph o
  advance                  636
  contour outer       4 points
  contour inner       4 points

If you see the same counts when you run ductus inspect with --set weight=100 and again with --set weight=900, you know your masters are compatible.

The trapdoors

Even with Ductus’s protective design, there are still three specific constructs where you might accidentally introduce a topology change. We made sure to flag all of these when we introduced them in earlier language chapters:

  • Conditionals over geometry choices. Something like r if weight < 500 else 0 is perfectly fine, as it simply chooses a number. It’s also fine to use a conditional to swap between different constructions for a contour, provided that both options result in the exact same number of points. What you absolutely must avoid is creating arms with different point counts. We refer to this specific limitation as the intended-use boundary in the conditional chapter.
  • for bounds that depend on a parameter. Imagine wanting one decorative element per 100 units of weight. This approach would mean your light master and your black master end up with entirely different contours, which is a no-go for interpolation.
  • Count arguments. When superellipse(c, rx, ry, n, count) asks for its point count as an argument, it’s precisely because that count needs to stay constant. If you pass in a count that’s derived from a parameter, you’re reintroducing the very problem that these constructors were designed to avoid.

The evaluator doesn’t currently police any of these situations in v0.1. Until the sampler arrives, keeping the rule solid is on you. The good news is that running ductus inspect at the corners of your design space offers a super quick audit.

The other failure mode: existence

Even if your topology is perfectly stable, there’s another kind of hiccup that can occur: an instance might still fail to evaluate. Think of it this way: sometimes your design asks for something that simply isn’t there in a particular instance. Whether something exists can, in turn, depend on your parameters:

  • A directionpoint(skel, pen_angle) witness only comes into existence while the skeleton’s tangent actually sweeps through that pen_angle. If you rotate the pen axis past the sweep of a leg, that specific instance will lead to an error.
  • An intersection() between a serif line and a diagonal will only exist if the diagonal reaches far enough to actually cross the serif.
  • clamp(x, lo, hi) will signal an error if a parameter-derived lo value ever manages to overtake hi.

A great example of this in action lives in latin_set.ductus from the playground. Its header carefully documents a real-world case: the pen_angle range is intentionally narrowed to ensure that a specific witness node on one leg of the a is present across the entire design space. For now, the best strategy is to choose parameter ranges so every query stays satisfiable, and then make sure to note this constraint in a comment where you declare the range. Want a quick way to check this yourself? Building at each corner of your design space offers a straightforward regression test:

ductus check family.ductus
ductus build family.ductus --set weight=100 -o /dev/null
ductus build family.ductus --set weight=900 -o /dev/null

When our designspace sampler eventually joins the party, it will take on the important task of exploring the entire space and reporting both incompatibilities and unsatisfiable queries.

Working in an editor

The playground is a fine place to sketch: nothing to install, a slider for every param, a picture that redraws as you type. A font, though, soon outgrows a single buffer. It becomes a handful of files that import a shared foundation, kept in version control and edited in your own editor. Ductus follows you there. Its language server, ductus lsp, checks your code as you type, tells you what names mean and what they evaluate to, and serves a page that draws the glyph under your cursor while you write it.

This chapter sets that up with Neovim and then walks through the loop it gives you.

Setting up

Install the ductus binary from the repository; the language server is one of its commands:

cargo install --path crates/ductus-cli

Neovim 0.11 or later starts it for .ductus files with a few lines in init.lua:

vim.filetype.add({ extension = { ductus = "ductus" } })

vim.lsp.config("ductus", {
  cmd = { "ductus", "lsp" },
  filetypes = { "ductus" },
  root_markers = { ".git" },
})
vim.lsp.enable("ductus")

-- Comments are `#` to the end of the line; `gc` needs to know.
vim.api.nvim_create_autocmd("FileType", {
  pattern = "ductus",
  callback = function() vim.bo.commentstring = "# %s" end,
})

The last few lines are for Neovim rather than the language server: gc comments lines out with the buffer’s commentstring, which Neovim leaves empty for a language it doesn’t know. That is enough for everything in this chapter except the preview, which needs two more pieces: a :DuctusPreview command, and an autocmd that tells the server where your cursor is, since the protocol has no standard message for that. Both are about twenty lines; the ductus-lsp README has them, along with inlay hints and completion as you type. Any other editor that speaks the Language Server Protocol can run ductus lsp too; only the preview’s cursor-following needs that one editor-side addition.

Two windows

Open a glyph file, put the cursor in a glyph, and run :DuctusPreview. A page opens at http://127.0.0.1:45974/ (45974 spells “glyph” on a phone keypad). Put it on a second screen, or beside the editor, and leave it there.

The preview page: the broad-nib a of latin_set.ductus in the construction view, with labelled nodes, the pen's outline and the fitted handles, beside a panel with a glyph selector, a construction toggle and sliders for pen_angle and pen_width.

From then on the page follows you:

  • It shows the glyph you are in. Move the cursor from glyph a into glyph b, and the page switches to b. Move into params, a def, or a file you import, and it keeps the glyph you were looking at, so you can tune a shared macro and watch one of the glyphs that uses it redraw.
  • It redraws as you type, from the unsaved buffer; there is nothing to save or rebuild. Each change is evaluated and drawn in a few milliseconds.
  • It draws the construction: nodes with their names, the pen’s extent at each, skeleton guides, fitted handles and anchors. This is the debug view of the next chapter, always at hand. Untick Construction to see the ink alone.
  • It keeps the last good picture through a mistake. Half-typed code, an undefined name, a contour left open: the page dims the last rendering and shows the error with its line above it, and brightens again once the code is whole.
  • Its sliders move through the design space. There is one for each param, within its declared range. They change what the page draws and nothing else: the file keeps its defaults, and so do the values the editor shows you. It is the quick way to see whether a construction holds at the corners before you check them properly with ductus inspect --set.

The selector at the top of the panel pins one glyph in place, or shows all of them side by side, when following the cursor is not what you want.

What the editor knows

While the page shows what your code draws, the editor tells you what it says.

Errors as you type. Every syntax error is underlined as soon as you make it, and once the syntax is whole, the first evaluation error is too: a name used before it is bound, a name bound twice in one scope, a contour that doesn’t close, a point where a number belongs.

Values where they are computed. Hover over a name to see its declaration and its value for the default params. Turn on inlay hints and every computed number shows its value at the end of its line:

stem = 40 + 0.14 * weight;  ▸ 96
hair = 0.85 * stem;  ▸ 81.6

This is the probe binding from the next chapter without the round trip through ductus inspect: write waist = distance(…); in a glyph and its value appears beside it. Numbers, params and metrics have values, and so do a glyph’s nodes (position, direction and width), contours and guides (point counts) and anchors. Points, pens and other paths show their declaration only, for now.

Finding your way. Go to definition follows a name to where it is bound, including into an imported file, and on an import line it opens the file. Find references lists every use of a binding across your project. The document outline lists params, metrics, defs and glyphs, with each glyph’s contours, guides, nodes and anchors beneath it, and a workspace symbol search finds params, metrics, defs, glyphs and top-level bindings in any file of the project.

Writing. Completion offers what fits where you are: contour, guide and anchor at the start of a statement in a glyph; names in scope, functions and the direction constants inside an expression; pos, left, tip and the other node fields after n.. Calls complete with a placeholder per argument. Inside a call, signature help shows the parameters, the current one highlighted, along with the function’s description. For your own defs, the description is the comment directly above it. Formatting is ductus format, so it can run on every save.

Renaming safely. Rename changes a binding and every use of it, in every file. In a language where bindings never change and inner scopes may reuse outer names, a rename can quietly change what some other line means. Rename a glyph’s local w to stem, and a later advance = stem; in that glyph would stop reading the top-level stem. The server checks for this, and for names bound twice in one scope, and refuses the rename with the line it would change.

Where the playground fits

The two complement each other. The playground needs nothing installed and is the place to try an idea or share a snippet; it cannot follow imports, since a browser has no filesystem. The editor is where a font gets built: many files, imports, version control, and the same picture, redrawn as you type.

Debugging and inspecting

Ductus is pretty good about pointing out errors, giving you clear file, line, and column details, and its renderer certainly never stays quiet about problems. But let’s be honest, often the real head-scratcher isn’t an error message at all. It’s when your ink compiles perfectly but just doesn’t look right. That’s where these trusty tools come in: the debug view, the probe bindings you’ve seen in the language chapters, and the playground’s dynamic live loop. This chapter will show you how to make the most of each.

Reading the debug view

e n s w top

Here’s everything ductus build --debug (or the playground’s debug toggle) will draw for you, laid out from back to front:

  • The grid — Think of it as your trusty graph paper, marked out in font units. You’ll see fine lines every 10 units, heavier ones every 50, and the heaviest lines every 100. There’s also a major line pinned to the baseline and to each glyph’s origin, making it easy to read coordinates directly.
  • Metrics lines — These helpful horizontal lines mark out every renderer-meaningful metric, like x, cap, asc, desc, and overshoot. Each is labeled at the margin, and the baseline stands out with a heavier line.
  • Guides — Your guide paths appear as graceful gray spines, unfilled, tracing the paths you’ve laid out.
  • Nodes — You’ll spot a bright pink marker for each skeleton node, complete with an arrow to show its dir. Plus, there’s a blue dot for every derived point, like left, right, and tip/tail when the node has a pen. If a stroke bank looks a bit off, compare it against these dots first. Remember, the dots are exact, while the bank between them is fitted.
  • On-curve points and handles — Here’s where the rubber meets the road. Every point the contours pass through is shown, along with the fitted control handles as thin gray struts. This is where the fitter’s decisions truly become visible.
  • Anchors — Anchors pop up as labeled mauve markers, just like the top you see above the ring.

This careful layering helps you answer that age-old question — is the problem my skeleton, my derived points, or the fit? You can check each step in turn: is the guide looking right, are the node dots where they should be, and then, finally, take a close look at those handles.

Failure modes and their looks

Consider this your little field guide to common mishaps. Everything on it appears somewhere earlier in this book — and more than one entry was met the hard way while the book’s own figures were being drawn:

  • A fat crossing where a stroke should pinch — Oh, that frustrating moment when a stroke should be pinching, but instead you get a chunky crossing. This often means a thin crossing without a witness node. If the debug view shows no node dot anywhere near the waist, the directionpoint witness from the pens chapter is usually the perfect fix.
  • An inner bank that folds over itself — Sometimes an inner bank gets a little ambitious and folds right over itself. This typically happens when the stroke width pushes past the skeleton’s radius of curvature, a classic trap from the pressure chapter. You’ll see the outline crossing itself near the tightest turn. The solution is often to add more samples or reduce the weight in that tricky spot.
  • A cap that bulges past its stroke — Ever notice a cap looking a bit too proud, bulging past its stroke? That’s usually a traced terminal on a flat pen. The fix is to simply switch to tipcap/tailcap.
  • A counter that fills solid — When a counter decides to go rogue and fill itself solid, it’s often because both contours are winding in the same direction. The renderer will actually warn you about this one, saying nested contours share a winding direction. The solution, as covered in the nodes chapter, is to reverse the inner traversal.
  • A curve that ignores its constraint — If a curve seems to be having a mind of its own and ignoring a constraint, it’s often a simple matter of a direction being placed on the wrong side of the point. Remember, {theta} p constrains entering the point, while p {theta} constrains leaving it.

Probing numbers

While the debug view helps you spot where things are, probe bindings are your go-to for figuring out how big they are. Any measurement worth checking is certainly worth a binding. It costs just one line of code, shows up in ductus inspect and the playground inspector, and even tracks along with your sliders:

glyph o {
  ...
  waist = distance(directionpoint(outer, 45),
                   directionpoint(inner, 225));  # stroke width at 45°
}

(A quick heads-up on that 225: because the inner contour travels the other way, the point opposite the outer’s 45° tangent will carry the reversed tangent.)

With ductus inspect file.ductus --set weight=900, you can get a precise readout of your design’s measurements at a specific instance. Even better, the playground brings these numbers to life, letting you drag weight and watch waist respond in real-time. This transforms a vague suspicion like “doesn’t the stroke get too thin in the black?” into a clear graph you can explore.

The loop

So, what’s the recommended workflow for putting all these tools to good use? It goes something like this: first, run ductus check for syntax every time you save your work. Then, you’ll spend most of your time shaping in your editor with the live preview open beside it (or in the playground, for a quick sketch). Finally, before you call a glyph done, you’ll use probes alongside ductus inspect --set … to thoroughly test the corners of your design space. This is exactly where those existence failures from the previous chapter tend to surface. The case studies that follow will put all these practices into action on real letters.

Case studies

We’re exploring three distinct case studies here, each showcasing a unique letter, tradition, and construction style. In each study, we’ll build a complete, working glyph, guiding it from its initial skeleton right through to a smoothly interpolating result. And don’t worry, we’ll only be using the tools and concepts you’ve already learned in earlier chapters.

studyconstructionexercises
A slab-serifed stemdirect outline, no nodesline/curve corners, brackets, serifs from expressions
A broad-nib open nodes on a closed skeletonwitness nodes, winding, a pen across its axes
Malayalam tharound-pen nodes on an open skeletonsymmetry macros, counters as measures, hand-built round caps

We’ve intentionally made these studies quite distinct in their underlying philosophy. For instance, the slab stem is truly outline-first, skipping the skeleton altogether. Then there’s the broad-nib o, which takes a tool-first approach where the pen dictates every detail. Finally, the Malayalam tha is space-first, its overall advance stemming directly from its counters. In the real world of type design, you’ll often find a wonderful blend of all three of these registers, sometimes even within a single glyph.

A slab-serifed stem

Let’s kick things off with our simplest exploration – a capital stem boasting a bracketed slab serif, crafted as a single, uninterrupted outline. It’s the only one that doesn’t even need a skeleton. This example illustrates just how much you can achieve with simple paths and automatic line/curve corners before you even think about placing a node. Plus, it highlights how elegantly serif proportions remain fully parametric when they’re simply derived from the stem itself.

The design

Think of a slab serif as a neat rectangle nestled right beneath the stem. Now, the bracket is that lovely little curve that gently coaxes the serif into the stem, ensuring the joint feels smooth and never abruptly angular. We describe it using just four key numbers. The clever part is that they all spring from stem, which means your serif holds onto its perfect proportions no matter how the weight changes:

params { weight = 400 in 100..900; }

metrics { upm = 1000; x = 500; cap = 700; asc = 750; desc = -220; }

stem = 40 + 0.14 * weight;

sl = 30 + 0.45 * stem;    # serif overhang beyond the stem
sh = 24 + 0.20 * stem;    # serif slab height
br = 26 + 0.30 * stem;    # bracket size

The outline

We’ll trace this shape counterclockwise, starting from the serif’s bottom-left corner. You’ll notice that every corner along the slab is a simple line-to-line transition, so there’s no need for any special annotations. The two brackets, though, achieve their lovely smoothness precisely because their entry and exit directions are so thoughtfully constrained. For instance, {left} .. {up} effortlessly guides the curve from a horizontal path right into a vertical one:

glyph stem {
  advance = stem + 2 sl + 100;
  xl = (advance - stem) / 2;    # stem left edge
  xr = xl + stem;               # stem right edge

  contour main =
      (xl - sl, 0) -- (xr + sl, 0) -- (xr + sl, sh)
   -- (xr + br, sh) {left} .. {up} (xr, sh + 2br)
   -- (xr, cap) -- (xl, cap)
   -- (xl, sh + 2br) {down} .. {left} (xl - br, sh)
   -- (xl - sl, sh) -- cycle;
}

Let’s take a closer look at that right bracket. The path makes a graceful entrance along the serif’s top, heading {left}, then gently curves, and finally departs heading {up} right into the stem. It’s truly amazing: just one segment and two constraints, and ductus’s fitter somehow magically figures out the perfect, smooth ease. What’s more, those points where the bracket’s curve meets the straight lines on either side? They seamlessly become line/curve corners all on their own.

The debug view gives us a wonderful look at the entire structure – do note how the on-curve points cluster just at the brackets, and nowhere else:

Across the space

Here’s where the magic really happens: because sl, sh, and br all grow alongside the stem (though not purely proportionally, as each has a constant floor), our serif builds a wonderful sturdiness in the heavier weights without ever turning into a clunky brick. And in the lighter weights, it remains present and refuses to simply disappear:

Imagine, just ten points at every single instance. Now, if there’s one design decision here truly worth borrowing, it’s all about these derivations, not just the path itself. Crafting a serif proportioned as floor + k · stem ensures that it interpolates sensibly across all weights. And believe me, no amount of clever outline trickery can ever save a design if the fundamental numbers underneath aren’t quite right.

A broad-nib o

This is a tool-first study, a charming o where its whole personality flows from a single pen. Forget fiddling with per-node widths or complex contrast expressions. Here, an ellipse, simply held at an angle, elegantly dictates where the stroke grows thick, where it tapers to thin, and precisely how slender ‘thin’ gets. It’s a wonderful demonstration of the pens chapter’s core ideas in action: a closed skeleton, two witness nodes, and two contours, all working in harmony.

Pen and skeleton

params {
  # Below 45 the upper witness sits too asymmetrically in its leg and
  # the inner bank folds — see "Working the axes". The range is the fix.
  pen_angle  = 45 in 45..60;
  pen_width  = 105 in 70..150;
  pen_height = 12 in 2..40;
}

metrics { upm = 1000; u=100; x = 500; cap = 700; asc = 750; desc = -220; }

broad_nib_pen = pen(pen_width, pen_height, pen_angle);

It’s all about the pen here. Its three defining axes — the angle it’s held at, its generous breadth, and how distinct it is from a mere razor-thin line — truly steer the show. The glyph itself, you’ll find, is quite content to let the pen do most of the talking. It’s a simple setup: just four nodes arranged on a counterclockwise skeleton, each one holding onto that very same pen.

glyph o : U+006F {
  advance =  5u;
  node m = (2.5u, 0) dir left pen broad_nib_pen;
  node n = (0, 3u) dir up pen broad_nib_pen;
  node o = (2.5u, 6u) dir right pen broad_nib_pen;
  node p = (5u, 3u) dir down pen broad_nib_pen;

  guide skel = m.pos .. n.pos .. o.pos .. p.pos .. cycle;

  # Thin-crossing witness nodes: banks are exactly `height` apart there,
  # and the query keeps them on the crossing as pen_angle moves.
  node w1 = directionpoint(skel, pen_angle) dir pen_angle pen broad_nib_pen;
  node w2 = directionpoint(skel, pen_angle + 180) dir pen_angle + 180 pen broad_nib_pen;

  contour c1 =  m.right .. n.right .. {w1.dir} w1.right .. o.right
    .. p.right .. {w2.dir} w2.right .. cycle;
  contour c2 = m.left .. {w2.dir + 180} w2.left .. p.left .. o.left
     .. {w1.dir + 180} w1.left .. n.left .. m.left
   ..cycle;
}
m n o p w1 w2

The real magic of this whole exploration truly blossoms within those two clever directionpoint lines and the graceful pair of contours. Our witness nodes are positioned right where the skeleton’s tangent perfectly aligns with the pen’s axis. If you peek at the debug view, you’ll spot them as those two helpful extra nodes nestled between the main compass points. Their banks are precisely pen_height apart, ensuring the ring gently pinches down to the pen’s absolute minimum thickness at just these specific spots, and nowhere else. As for the contours, they charmingly adhere to the winding rule we learned in the nodes chapter: right points follow the skeleton’s order for our counterclockwise outer contour, while left points, with our witnesses included and constraints reversed, trace the clockwise inner counter.

The result, plain:

Working the axes

Ah, but here’s where the witnesses truly shine: because they operate as queries rather than fixed coordinates, they adapt to every single axis. Want to steepen the pen’s angle? Watch as those delicate thin spots migrate around the ring. Or perhaps you’d prefer to plump the pen towards a stubbier shape? Then you’ll see the pinch simply relax. The best part? It’s all from the very same source code, without a single manual edit.

The range is part of the design

You’ll find two intriguing constraints tucked away in that params block, both offering wonderful real-world insights from the interpolation chapter. Let’s look at the first one: it’s all about existence. A witness node can only truly come to life when the skeleton’s tangent sweep covers the pen angle. Happily, with our closed skeleton here, the sweep spans a full circle, meaning every pen_angle effortlessly satisfies both queries. But if you were to cut the skeleton open — imagine an ‘c’, for example — that freedom vanishes, and a careful balance is needed. The latin_set.ductus documentation thoughtfully details this precise negotiation right in its header.

The second constraint revealed itself in the most honest way, simply by building out the instances and seeing what happened. We discovered that below pen_angle = 45, the upper crossing drifts a bit too close to the top node. This causes the inner bank’s fitted curve to fold right over itself, resulting in a rather unexpected black teardrop hanging into the counter. Curiously, the system reports no error whatsoever, because technically, nothing is ‘wrong’ except for the visual shape itself. (Incidentally, our debugging chapter’s field guide points out this very scenario.) While adding more skeleton samples around the crossing would certainly expand the safe range, narrowing the declared range to 45..60 offered a much simpler and more direct fix. Plus, it has the lovely benefit of keeping that crucial constraint clearly noted right alongside where the axis is declared. Regardless of the approach, the range always comes to mean something quite specific: it marks precisely where this thoughtful construction is known to hold true, because, well, someone took the time to truly look.

Malayalam tha

Meet Malayalam ത (tha), a double bowl character with tips that gently curl inwards. It’s a shape utterly devoid of straight lines, generously featuring four distinct counters of white space, and possessing a left/right symmetry that practically begs to be designed just once. This character is a fantastic example of a ‘space-first’ design approach. Here, the advance is cleverly derived directly from the counters, which means the width axis adjusts the white space, rather than simply squashing the strokes. Come along as we explore the actual tha.ductus file, pulled straight from our collection of examples.

Foundation

params {
  weight   = 400 in 100..900;
  contrast = 0.85 in 0.4..1.0;
  width    = 100 in 60..120;
}
metrics {
  upm = 1000; x = 500; cap = 700; asc = 750; desc = -220;
  over = 10 + weight / 200;
}

stem = 40 + 0.14 * weight;
hair = contrast * stem;
term = 0.75 * hair;          # the tips taper before their round caps

Take a peek at the third axis: width. It’s important to remember this isn’t about the stroke weight (that’s what weight is for), but rather about how open the letter feels.

Symmetry as a macro

You’ll notice right away that the letter’s right half is a perfect mirror image of its left. Naturally, we use a macro to mirror a node across a vertical axis. There’s just one clever trick to remember: the direction needs to be negated. This is because a mirrored node is read by a traversal moving in the opposite direction.

def mirror(n, axis) -> m {
  node m = (2 * axis - n.pos.x, n.pos.y) dir -n.dir pen pen(n.width);
}

Here, we see the promise from the macros chapter delivered. A macro accepts a node, hands back a mirrored node, and then it’s entirely up to the caller to decide how to handle its banks.

Counters first, then the glyph

glyph tha : U+0D24 {
  bowl = 1.6 * width;             # bowl counter width
  gap  = 0.55 * width;            # counter between the central strokes

  wx  = 45 + stem / 2;            # left outer stroke, centre
  lcx = wx + stem + bowl;         # left central stroke, centre
  rcx = lcx + stem + gap;         # right central stroke, centre
  ex  = rcx + stem + bowl;        # right outer stroke, centre
  advance = ex + stem / 2 + 45;
  mid = 0.5[lcx, rcx];

  ax = 0.5[wx, lcx] + 14;         # tip hovers just right of bowl centre

  # Left half of the skeleton, travelling from the tip into the letter:
  # curl up over the left shoulder, down around the left bowl, in to
  # the centre.
  node a = (ax, 0)                            dir 150   pen pen(term);
  node b = (wx, 0.48 * x)                     dir up    pen pen(term);
  node c = (0.5[wx, lcx], x + hair / 2 - over) dir right pen pen(hair);
  node d = (mid + 2gap, b.pos.y)              dir down  pen pen(hair);
  node e = (mid, over)                        dir left  pen pen(hair);

  # Right half by symmetry.
  f = mirror(d, mid);
  g = mirror(c, mid);
  h = mirror(b, mid);
  i = mirror(a, mid);

  guide skeleton = a.pos .. b.pos .. c.pos .. d.pos .. e.pos
                .. f.pos .. g.pos .. h.pos .. i.pos;

  # Round caps by hand: one extra point past each tip, half a width
  # out along the travel direction, tangents pinned to a semicircle.
  acap = a.pos - (a.width / 2) * unitvec(a.dir);
  icap = i.pos + (i.width / 2) * unitvec(i.dir);

  contour main =
       {a.dir} a.right {a.dir}
    .. b.right .. c.right .. d.right .. e.right .. f.right .. g.right
    .. h.right
    .. {i.dir} i.right {i.dir}
    .. icap {i.dir + 90}
    .. {i.dir + 180} i.left {i.dir + 180}
    .. h.left .. g.left .. f.left .. e.left .. d.left .. c.left
    .. b.left
    .. a.left {a.dir + 180}
    .. acap {a.dir + 270}
    .. cycle;
}

Let’s unpack three key insights, presented in order of their significance.

The advance is a sum of counters and strokes. Take a close look at the wx → lcx → rcx → ex chain. You’ll observe that each stroke center is carefully positioned by adding the previous center, a stroke’s width, and then a counter (bowl or gap). This means the letter is quite literally constructed as alternating black and white spaces. So, when the width axis shifts, every counter expands or contracts , while each stroke holds its intended weight. It’s a wonderfully precise approach, completely unlike naive scaling.

One contour, eighteen-plus points, still just two banks. Our skeleton elegantly snakes from tip to tip, passing through nine distinct nodes. The contour then traces its path outward along the right bank, curves around the right cap, and returns along the left bank, before completing its journey around the left cap. It’s the very same shape we explored with the pressure chapter’s strokes, now brought to life at letter scale.

The caps are ordinary points. These nodes use plain round pens, and although a round pen offers tip and tipcap, you won’t find them here. Instead, a round cap is thoughtfully constructed from its fundamental essence: a point positioned half a width beyond the tip (look for acap and icap), with its entry and exit precisely guided along pinned semicircle tangents. This adherence to Ductus’s ‘no-cap-machinery’ principle means we achieve this with just two bindings and four constraints. And, as a bonus, the taper into the cap (using term, which is thinner than hair) was completely free for us to design exactly as we wished.

Our construction view offers a clear glimpse of the skeleton, snaking its way through both bowls, alongside the helpful node dots that precisely place every single bank point.

a b c d e f g h i

Across the space

When we adjust the weight, we’re directly influencing the ink; meanwhile, the counters faithfully maintain their elegant proportions:

Now, for the width axis, it’s all about moving white space. At width=60, for instance, the bowls gently tighten, and the letter condenses , all without a single stroke thinning out. This is why the black version of the same instance remains wonderfully credible: black and white are truly independent design elements here.

Among the three studies we’ve looked at, this one feels most aligned with real-world practice. In complex script design, a glyph often comes down to a negotiation between its various counters. Having a source format where the advance is explicitly expressed as that negotiation ensures this vital information remains clearly on the page, ready for the next designer to easily understand and appreciate.

Built-in functions

Let’s explore each built-in function, understanding its exact behavior and any conditions that might lead to an error. As you dive in, keep a few handy conventions in mind: all angles are measured in degrees (counting counterclockwise, with 0° pointing to +x); if you provide the wrong number of arguments or arguments of the wrong type, you’ll encounter an evaluation error that conveniently names the function; and finally, built-in names are reserved—so you can’t use a def to redefine one.

Numbers

functionreturnsnotes
min(a, b)the smaller
max(a, b)the larger
clamp(x, lo, hi)x limited to [lo, hi]error when lo > hi
abs(a)absolute value
sign(a)−1, 0, or 1sign(0) is 0, exactly
sqrt(a)square root
floor(a) ceil(a) round(a)integers as numbers
sin(a) cos(a) tan(a)trigonometryargument in degrees

The way clamp throws an error is quite intentional, not just a defensive measure. We see a lo value that goes beyond hi as a strong signal that something has likely gone awry with your parameter range. The interpolation chapter even relies on these issues being brought to your attention, rather than quietly absorbed.

Points and vectors

A single point in ductus is wonderfully versatile, effectively doubling as a 2-D vector. These next four functions help you smoothly convert between seeing things as vectors and understanding their angular representations (you can find more details in the Expressions chapter):

functionreturns
angle(v)the angle of vector v, degrees (atan2)
unitvec(theta)the unit vector (cos theta, sin theta)
length(v)`
distance(a, b)length(b - a)

Path queries

These four functions all take a close look at the fitted curve. This is the very same geometry that gets rendered, ensuring you’re never dealing with just the chords between on-curve points. When we talk about time t, we’re referring to segment time. It runs from 0 all the way to n for a path made of n segments. Integer values of t will land you precisely on the on-curve points, while fractional values will place you somewhere inside the corresponding segment. If you’d like a deeper dive, the paths chapter covers all of this in detail.

functionreturnserrors when
point(p, t)the position on p at time tt outside 0..n
direction(p, t)tangent angle at t, degreest outside 0..n
directionpoint(p, d)first point of p whose tangent is dno such point
directionpoint(p, d, i)the i-th such point, 0-basedfewer than i + 1 such points
intersection(p, q)first intersection of the two pathsthey don’t meet
intersection(p, q, i)the i-th intersection, 0-basedfewer than i + 1 intersections

Here’s some fine print worth knowing:

  • directionpoint cares about the orientation of the tangent, not just whether it’s parallel. For instance, 0° means the path is traveling rightward. This is super handy for common tasks like finding where a pen’s thin stroke crosses a certain direction.
  • When we say “First” for both directionpoint and intersection, we mean the point with the least position along the first path. This involves checking its segments in path order, and then the earliest time within a segment. Both functions also offer an optional index, allowing you to count matches in that same order, starting from 0. So, directionpoint(p, d, 0) is simply another way to write directionpoint(p, d), and intersection(p, q, 0) another way to write intersection(p, q). If a match happens to land exactly on a joint of either path (or on a closed path’s start point), it counts as a single match. To count intersections along q instead, swap the arguments.
  • intersection delivers exact results when applied to two line segments. This is where those classic METAFONT “whatever” idioms—like a stem meeting a diagonal or a serif touching a stem—really shine.
  • A path that only grazes another, touching it tangentially without crossing, makes a fragile intersection: depending on rounding it may count once, or not at all. Index the crossings you can see clearly, not the near-misses.
  • Keep in mind that zero-length segments (like what you’d find with roundrect when its radius is 0) don’t have a tangent and won’t show up in these queries.

Pens

functionreturnserrors when
pen(w)a round pen, w acrossw <= 0
pen(w, h)an ellipse: full major axis w along 0°, full minor axis hw <= 0 or h < 0
pen(w, h, angle)the same ellipse with its major axis at anglew <= 0 or h < 0

h = 0 gives a razor. The pens chapter covers the whole family.

Shape constructors

Meet circle, ellipse, roundrect, and superellipse—these functions return closed, counterclockwise path values. They’re so important, they even get their very own next chapter to shine in.

Sketch commands

functioneffect
draw(path, ...)render each path as a thin spine
fill(path, ...)fill each closed path

These commands are special; you’ll only find them meaningful at the top level of sketch files. If your file happens to include any glyph block, ductus will happily render those glyphs instead. A quick note: fill is designed to work with closed paths. Each fill operation works independently. This means if you’re trying to create a counter (that’s a fancy word for a hole), you’ll need to define it using a glyph’s contours, rather than trying to use two separate fill commands.

Shape constructors

Instead of meticulously plotting points one by one, ductus offers four built-in functions to conjure up common closed shapes. What you get back are ordinary path values — complete with on-curve points and tangent constraints, with the fine-tuning of handles left to the fitter. This means these shapes are incredibly versatile: you can transform them, query their paths, and ultimately, anything they craft, you could also painstakingly draw by hand if you truly wished:

u = 100;

fill(circle((u, u), 0.8u));
fill(ellipse((3.2u, u), 1.1u, 0.65u));
fill(roundrect((4.8u, 0.3u), (6.4u, 1.7u), 30));
fill(superellipse((8u, u), 0.8u, 0.8u, 4, 16));

These four handy constructors share a couple of key traits, both carefully considered design choices:

  • Counterclockwise: We’ve set them up this way so the shapes are immediately ready to serve as an outer contour. If you need a counter (an inner hole), simply pop reversed on the call.
  • Consistent Point Count: Here’s a neat trick: the number of points defining your shape depends only on the constructor you choose, never on any specific value you feed it. This ensures your shape maintains its topology throughout the entire design space, perfectly aligning with ductus’s clever interpolation rule.

circle(c, r) — 4 points

Imagine placing a point right at each axis extreme, with tangents pinned. That’s how circle works its magic. Because ductus’s fitter is wonderfully precise with circular arcs, these four points are more than enough to describe a circle with astonishing accuracy — we’re talking a mere 0.027 % of r, an error you’d never spot at any typical type size.

ellipse(c, rx, ry) — 8 points

You might notice ellipse uses eight points, not four, and it’s a distinct constructor rather than simply scaling a circle(...). There’s a good reason for both. While four points are plenty for a circle, they only capture an ellipse to about 1% accuracy. That’s because the fitter’s handle rule is absolutely spot-on for circles, but not quite for ellipses — it’s a little gotcha you’ll find in the fitter chapter. So, to give you a precise ellipse, ellipse thoughtfully allocates eight points, achieving a much tighter 0.06%. And here’s another key detail: using ellipse(c, r, r) is intentionally not the same as circle(c, r). If ductus were to cleverly switch between them when rx == ry, it would unfortunately alter the point count as an axis crossed that 1.0 threshold, messing with your design space consistency.

For those really flat ellipses, you might want to consider spending a few more points. Happily, superellipse(c, rx, ry, 2, count) offers the very same elliptical curve, but lets you pick your desired point count. For instance, with a dramatic 1:5 aspect ratio, you’ll see a precision jump from 3.9% with eight points, to a much nicer 0.6% with sixteen, and an impressive 0.05% with thirty-two.

roundrect(p, q, r) — 8 points

roundrect takes two opposite corners (you can give them in any order) and a corner radius to create its charming shape: four straight lines meeting four gentle quarter-arcs. Just a heads-up: the radius is cleverly clamped to half the shorter side of the rectangle. Go beyond that, and the neighboring arcs would start bumping into each other. Even if you set r = 0, it’s still a rectangle that carries eight points — though four of its segments magically become zero-length. This might seem a bit curious, but it’s crucial: by maintaining eight points instead of shrinking to a four-point path, your roundrect keeps its consistent point count, even if a parameter smoothly drives the radius all the way down to zero across your design space:

u = 100;
fill(roundrect((0, 0), (1.6u, 1.6u), 0));
fill(roundrect((2.2u, 0), (3.8u, 1.6u), 24));
fill(roundrect((4.4u, 0), (6u, 1.6u), 60));
fill(roundrect((6.6u, 0), (8.2u, 1.6u), 500));   # clamped to 80

There’s a little consequence of those zero-length segments: since they don’t have a tangent, path queries won’t be able to “see” them. For example, if you ask for a directionpoint on a radius-0 roundrect, you’ll find points along the main sides, but never on those perfectly sharp, degenerate corners.

superellipse(c, rx, ry, n, count)

Here we have the wonderfully versatile superellipse, defined by the family |x/rx|^n + |y/ry|^n = 1. Think of it as a spectrum of shapes: when n = 2, you get a classic ellipse, but as you increase n, the shape squares off, pushing outward toward its bounding box. You can use any expression for n as long as it’s ≥ 2 (values below that would lead to an error here, as this family isn’t defined for the diamond-like shapes). And since n primarily shifts positions rather than changing the fundamental structure, it makes a perfect candidate for a parameter — imagine defining a whole ‘squareness’ axis for your type design.

u = 100;
fill(superellipse((u, u),    0.8u, 0.8u, 2, 16));
fill(superellipse((3.2u, u), 0.8u, 0.8u, 4, 16));
fill(superellipse((5.4u, u), 0.8u, 0.8u, 10, 16));

The count argument determines how many points are sampled along the superellipse. You’ll need at least 4 points, and you can go up to 1024; it’s also a multiple of 4, ensuring a point always lands perfectly on each axis extreme. We’ve made count an explicit argument for a very good reason: it ensures it can never silently change on you. As we detail in the interpolation chapter, passing a count derived from a parameter is a classic ‘trapdoor’ for unexpected behavior. Here, it’s the sampling process, not the fitter, that truly limits accuracy. For instance, sixteen points keep n = 4 accurate to a lovely 0.15% of the side, but only achieve 0.69% at n = 10. It’s a good rule of thumb that both flatter and squarer shapes will generally sing with a few more points.

Constructors in glyphs

When you bring these constructors inside a glyph, they truly shine as contour factories. And remember our friend reversed? That’s your go-to for creating counters, or inner holes. Take a peek at this washer example, where both the outer edge’s squareness and the inner hole are parametric:

metrics { upm = 1000; asc = 750; desc = -220; }

glyph washer {
  advance = 500;
  c = (250, 250);

  contour rim  = superellipse(c, 210, 210, 3, 16);
  contour hole = circle(c, 90) reversed;
}

Just a quick note: all those handy winding rules from the debugging chapter still apply here, precisely as you’d expect. These constructors kindly give you a counterclockwise path, and if you need to turn it into a lovely hole, reversed is truly all you need.

CLI and file reference

The ductus binary

ductus check file.ductus

This command is all about parsing. It quickly checks your file.ductus for syntax errors, pointing out the first one it finds with handy line and column numbers. If everything looks good, you’ll simply see OK. Because it doesn’t do any heavy lifting like evaluation or rendering, it’s super fast — perfect for running every time you hit save.

ductus format file.ductus [more.ductus ...] [--check]

This command rewrites your source files, in place, into the one canonical ductus style — so you can stop thinking about layout and let the formatter agree with your collaborators for you. The rules are simple: two spaces per indent level, one space around = and every operator, and ranges stay tight (30..45). Paths get the signature treatment: a short one stays on a single line, but the moment a statement passes 80 columns it breaks at every joint, each .. or -- leading its own line:

  contour bowl = {up} a.left
      .. w1.left {w1.dir}
      .. b.left {b.dir}
      -- c.left
      .. d.left
      -- cycle;

Your comments — own-line ones, trailing ones, even the ones between path joints — all survive, and formatting never changes what your file means. One firm safety rule: a file with syntax errors is refused untouched, so a broken parse can never mangle your code. Fix the error format points at, then run it again.

  • --check — Writes nothing at all; it just exits with a failure listing every file that would change. Perfect for CI, right next to ductus check.
ductus build file.ductus [--glyph NAME] [--set PARAM=VALUE ...] [--debug] [-o OUT.svg]

This command is where the magic happens: it takes your file.ductus, evaluates it, and renders your design directly to an SVG file. By default, it’ll save it as output.svg.

  • --glyph NAME — Want to focus on just one part of your design? Use this to render only a specific glyph. Without it, ductus will cheerfully render all your glyphs, arranging them side by side in the order they appear in your source file. Each glyph’s origin will snap right to a 100-unit grid. Oh, and any draw or fill output from your sketch will join the party on the same sheet, appearing at x = 0.
  • --set PARAM=VALUE — This lets you pick a specific instance of your design by setting a parameter to a particular value. You can repeat this option for each parameter you want to adjust. Just a heads up: using an unknown parameter or providing a non-numeric value will trigger an error.
  • --debug — Enable this for a peek behind the curtain at the construction view. You’ll see helpful overlays like the grid, metrics guidelines, and your own guides. Plus, it reveals the skeleton nodes with their derived points, on-curve points, fitted handles, and anchors — all labeled for clarity. Think of the debugging chapter as your trusty field guide for interpreting all this visual information.
  • The generated SVG will be filled with currentColor and thoughtfully includes only a viewBox. This means it plays nicely with its surroundings, effortlessly inheriting its size and color from wherever you embed it. One more thing to note: while your source coordinates always work with y-up, the y-axis actually flips during the output stage to match standard SVG conventions.
ductus inspect file.ductus [--set PARAM=VALUE ...] [--glyph NAME]

Curious about the nitty-gritty details of your evaluated file? This command spills all the numeric beans, presenting every number as plain text. You’ll see parameters complete with their ranges, metrics, and top-level bindings presented in source order. After that, it dives into each glyph’s advance, its numeric bindings (yes, even your handy probes are included), the point counts for each contour and guide, and all your anchor positions.

ductus lsp

This runs a language server over stdin and stdout, for editors that speak the Language Server Protocol. It reports syntax and evaluation errors as you type, formats, lists a file’s symbols, and jumps to definitions, across imports too. It also serves a live preview page that draws the glyph under your cursor as you type. You don’t run it by hand; your editor starts it. Working in an editor walks through the workflow, and the ductus-lsp README has the full Neovim setup.

A quick note on imports: they always find their way by looking relative to your source file’s directory. Speaking of handy tools, the online playground actually uses the very same evaluator (compiled right into WebAssembly). It comes equipped with neat sliders for your params, an inspector that mirrors what you get with ductus inspect, a convenient debug toggle, and the same formatter behind a format button (or Ctrl+Shift+F). However, do remember that it can’t handle import statements — browsers just don’t have access to a filesystem.

A file, completely

Let’s explore what a ductus source file can hold, diving into each level of its structure. For the truly authoritative reference, you’ll find the normative grammar in the specification. Here, we’ll give you a friendly overview of its general shape.

Top level, in any order. Just a friendly reminder, though: ductus works in a single pass, so make sure your names are bound before you try to use them:

itemform
paramsparams { name = default in min..max; ... }
metricsmetrics { name = expr; ... } — These special names (upm, x, cap, asc, desc) carry particular meaning for the renderer.
bindingname = expr; — Remember, it’s single-assignment, and that rule applies everywhere.
nodenode name = point dir expr pen expr; — the pen expression evaluates to a pen, e.g. pen(w) or a name bound to one.
macrodef name(a, b) -> (x, y) { ... }
glyphglyph name [: U+XXXX] { ... }
importimport "file.ductus"; — This is an include-once operation, resolves relatively, and will flag an error if it detects cycles.
loopfor i in a..b { ... } / for x in list { ... }
sketchdraw(path); fill(path); — You’ll only find these in sketch files.

Inside a glyph body, things get specific. You’ll definitely need an advance = expr; (it’s required to make your glyph complete). You can also define contour name = path; (and remember, contours must cycle), guide name = path;, and anchor name = point;. Beyond those, feel free to include any bindings, nodes, loops, or macro calls you need. Just keep in mind that def, params, and import are exclusively for the top level.

A few general syntax notes: comments start with a # and continue all the way to the end of the line. Every statement wraps up with a semicolon ;, and you’ll be glad to know that newlines don’t carry any special significance — use them freely for readability.

Keywords and prelude

These words are special and are reserved for ductus’s internal use:

params in glyph contour guide anchor node dir pen cycle
corner def for if else and or not import shifted scaled xscaled
yscaled rotated slanted reversed metrics draw fill

The prelude thoughtfully sets up some handy direction constants for you: right = 0, up = 90, left = 180, and down = 270. These are treated just like ordinary numbers. It also introduces all the builtins. Just a friendly tip: you shouldn’t try to reuse their names when defining your own defs.

Errors, briefly

Nobody likes errors, but when they pop up, ductus makes sure you have all the context you need. Every error message comes complete with the file name, line, and column number. You might encounter syntax errors, which check and every other command will dutifully report. During evaluation, ductus will flag issues like unbound or rebound names, type mismatches, arity errors, unsatisfiable queries, and constructor arguments that are out of range. Then, during glyph validation, it watches out for open contours and any missing advance declarations. Finally, the renderer might give you a gentle warning: if it spots nested contours sharing the same winding direction, it’s almost always a sign that a counter simply forgot to run backwards.

Ductus for MetaPost users

If you’re already comfy with METAFONT and MetaPost, you’ll feel right at home with ductus. It’s got the same familiar path syntax, mediation, and transform operators, practically unchanged. But wait, there are a few things that didn’t make the journey: the equation solver, how pens stroke, and the idea of mutation. That’s because ductus embraces a single-assignment, single-pass, outline-first philosophy. This little appendix will serve as your trusty translation guide, explaining what’s different and why those changes came to be.

What transfers directly

Good news: many things you love about MetaPost slide right into ductus without a hitch, making your transition extra smooth.

MetaPostductusnotes
z1 .. z2 -- z3 .. cyclesamejoints, cycle — unchanged
z1{up} .. {right}z2samedirection specs, degrees or vectors via angle()
0.5[a, b]samemediation, ductus’s favourite expression too
p shifted (x,y) rotated t scaled k slanted ssamepostfix, chaining, degrees
reverse pp reversedpostfix like the rest
subpath, point t of ppoint(p, t), direction(p, t)functions, not operators; fitted curve, not chords
directionpoint d of pdirectionpoint(p, d)matches orientation, errors if absent
for i = 0 upto 5:for i in 0..5 { }inclusive both ends
beginchar("o", ...)glyph o : U+006F { advance = ...; }advance is a required binding

What changed shape

Some concepts have taken on a slightly different form in ductus, thoughtfully reshaped to align with its unique way of doing things.

MetaPostductuswhy
x1 = whatever[z2, z3]; ... equationsintersection(p, q)no linear solver; the type-design uses of whatever are path intersections, which are explicit and exact on lines
penpos1(w, phi)node n = ... dir theta pen pen(w, 0, phi);the node also carries travel direction, and derives n.left/n.right exactly
pickup pencircle xscaled w yscaled h rotated phiname = pen(w, h, phi);a pen derives edge points; it never strokes anything
penstroke / draw with a penwrite both banks through derived pointsoutline-first: the contour is the artifact, and terminals are outline too
fill / unfillcontours with opposite windingnonzero rule; unfill is a reversed counter
p & q concatenationmacros return points; one path expression per contourno seam-merging rules to learn — the macros chapter argues this out
vardef returning a pathdef name(...) -> value { }tuple exports, destructured at the call site
numeric equations, :=name = expr; oncesingle-assignment; any value traces to one line

What is gone on purpose

A few things have stepped aside to make room for ductus’s distinct approach.

  • whatever and the equation solver. First up, say goodbye to whatever and the equation solver. Ductus prefers a single-pass, declarative dance, giving you exact derived points (like nodes or intersection results) where METAFONT used to wrestle with constraints. Everything else becomes a neat arithmetic calculation.
  • tension. We’ve also bid farewell to tension. In our experience, designers naturally gravitate towards tweaking points and directions directly, rather than fiddling with tension numbers. Feel free to add a point or a direction constraint if you need that extra control.
  • curl. curl has also sailed off. Open ends in ductus now happily accept direction constraints, with the default behavior handled by the fitter.
  • Pens that stroke. And then there are pens. In ductus, a pen is less of a brush that paints and more of a precision measuring device. It’s brilliant at placing bank contact points and defining cap geometry (you can dive deeper into pens and caps). The whole idea is to cleverly avoid that METAFONT conundrum of having uneditable stroked output.
  • Implicit x0/y0 coordinate variables and suffix magic. You’ll also find that implicit x0/y0 coordinate variables and suffix magic have stepped aside. In ductus, a name gets its meaning because you’ve lovingly given it one.

The habit to unlearn, the habit to learn

It’s time to gently unlearn the habit of ‘solving.’ You won’t be stating relationships and then letting the program magically discover the numbers. Ductus prefers a strict top-to-bottom journey, where every value finds its definition just once, building upon the values that came before it.

Instead, let’s embrace the design-space discipline. This is something rather special that ductus asks for, a little different from METAFONT. Think about maintaining the same number of points and types across every instance (that’s our interpolation compatibility), and carefully selecting parameter ranges so every query always finds a happy solution. You’ll get friendly with ductus inspect to peek at the corners of your design space. Where METAFONT programs used to describe a shape with a few knobs, a ductus file paints a picture of the interpolable region those knobs elegantly sweep. Once you get comfortable with this way of thinking, you’ll find that masters, instances, and even a variable font all live harmoniously in the very same file.