# Programming Guide

An Epsil code block runs a program in a notebook. The program can compute and
print values, read what the other blocks of the notebook define, show a plot
that the reader can pan and zoom, and draw. This guide describes how to run a
block, how to write to its console and how to plot. For shapes, colors, pixels,
animation and events, see the [Drawing Guide](/drawing-guide/en/). For plotting
with formulas, see the [Plotting Guide](/plotting-guide/en/); for short tips
about the rest of the application, see [Tips and Tricks](/tips-and-tricks/en/).

For the Epsil language itself (variables, functions, lists, loops and the rest
of its library), see the [Epsil website](https://epsil.dev/): it has an
introduction, a getting-started guide, examples and the language reference.

## Contents

- [Run a Program](#run-a-program)
- [Read the Notebook](#read-the-notebook)
- [Write to the Console](#write-to-the-console)
- [Plot Functions in a Program](#plot-functions-in-a-program)

## Run a Program

To add a block, type `/` and choose **Epsil code block**. Choose **Run** or
press F6 to run it, and press F6 again to stop it.

The output of a block has two parts:

- **The console.** It shows each line that the program prints, from any
  statement of the program.
- **The result.** It is the value of the last statement of the program. When
  that value is a plot or a drawing, the block shows it as a picture. The
  console shows any other value.

A block shows one picture: one plot or one drawing, not both, and not two plots.
Only the last statement gives the result, so the order of the statements
matters:

| Program                           | The block shows             |
| --------------------------------- | --------------------------- |
| `print("hello"); plot(sin(x))`    | the line `hello` and a plot |
| `plot(sin(x)); print("hello")`    | the line `hello` only       |
| `plot(sin(x)); circle((0, 0), 1)` | a circle                    |

In the second program, the last statement is the `print`, which has no value.
The plot of the first statement is made and not shown.

A program can also show a drawing with `draw` (see the
[Drawing Guide](/drawing-guide/en/)). A `draw` from any statement shows its
drawing in place of the picture of the result, also when the result is a plot.
`draw` takes shapes only: a plot shows only as the value of the last statement.

When the block has run, the layout button chooses **Vertical split**,
**Horizontal split** or **Canvas only**.

In the editor, the completion list and the hint under a call show the
documentation of each function.

## Read the Notebook

A program can read the names that the other blocks of the notebook define, such
as a slider `a` or a function `f(x) := …`.

It can also read the answer of another block with `out(n)`, where _n_ is the
number on the block's reference tag, or with `out("label")` for a block that has
a label.

A block runs again when one of the names that it reads changes.

## Write to the Console

`print` writes one line to the console. It takes any number of arguments and
puts one space between them:

```
let n = 12
print("count:", n, "half:", n / 2)
```

The console shows `count: 12 half: 6`. A text prints as it is, and another value
prints as you would write it in a program.

### Put Values in a Text

`\(…)` in a text is replaced by the value of the expression between the
parentheses:

```
let r = 2.5
print("radius \(r), diameter \(2 * r)")
```

The console shows `radius 2.5, diameter 5`.

### Print Several Lines

Call `print` once for each line, or put `\n` in a text where a line ends:

```
print("first line\nsecond line")
```

For a longer text, write it between triple quotes. The text starts on the line
after the first `"""`, and the spaces before the last `"""` are removed from the
start of each line:

```
print("""
  Results
    mean: \(mean([1, 2, 6]))
  """)
```

The console shows `Results` on one line and `  mean: 3` on the next. `print()`
with no argument prints an empty line.

### Format a Line

To format a line, wrap the text:

| Call                  | Shows                                                           |
| --------------------- | --------------------------------------------------------------- |
| `markdown(text)`      | the text as Markdown: headings, **bold**, lists                 |
| `math(latex)`         | the LaTeX as a typeset formula                                  |
| `annotated(x, style)` | `x` in a color: `{color -> "red", backgroundColor -> "yellow"}` |

For example, `print("area:", math("\\pi r^2"))` prints the word "area:" and the
formula $\pi r^2$, and `print(markdown("# Results\n**3** roots"))` prints a
heading and a line with a bold number.

The Console card of the inspector sets the font, the size and the colors of the
console.

## Plot Functions in a Program

To get a plot that the reader can pan and zoom, as in a plot document, use
`plot`. The block shows the plot when `plot(…)` is the last statement of the
program: a plot takes the place of a drawing, and the console stays (see
[Run a Program](#run-a-program)). To show several functions, give them to one
`plot`. Its first argument is one item or a list of items:

```
plot([x => sin(x), (x => cos(x), {color -> "crimson", label -> "cosine"})], {x -> (-pi, pi), legend -> true})
```

| Item                                    | Plots                                               |
| --------------------------------------- | --------------------------------------------------- |
| `sin(x)`                                | a formula in `x`, `y` or `t`, as in a plot document |
| `x => a*sin(x)`                         | the graph of a function                             |
| `t => (cos(t), sin(t))`                 | a parametric curve                                  |
| `(x, y) => x^2 + y^2 - 1`               | an implicit curve, where the value is 0             |
| `(x, y) => x^2 + y^2 < 1`               | a region                                            |
| `g`, a function defined with `function` | the graph of `g`                                    |
| `$x^2 + y^2 = 1$`                       | a LaTeX formula, read as in a plot document         |
| `[(0, 1), (1, 3), (2, 2)]`              | a list of points                                    |
| `histogram(data, width)`                | bars of `width` over the values of `data`           |

A formula such as `plot(sin(x))` is the shortest form: its variables are the
plot variables `x`, `y` and `t`. Use a function when the variable of a graph or
a curve has another name: `u => u^2`.

To style an item, make it a pair of the item and a dictionary. Two keys apply to
every item: `color`, a color as `fill` takes (`"crimson"`, `"#dc143c"`), and
`label`, the name of the item in the legend.

The key `type` picks how the item is drawn, as the "Plot As" menu of a plot
document does: `((x, y) => x*y, {type -> "heatmap"})` is a heatmap, and
`((x, y) => (-y, x), {type -> "vector-field"})` is a vector field. Under `plot`,
the types are `"line"`, `"parametric"`, `"polar"`, `"implicit"`, `"heatmap"`,
`"vector-field"`, `"domainColoring"` and `"analyticLandscape"`; under `plot3d`,
`"surface"`, `"parametric-curve"`, `"parametric-surface"`,
`"spherical-surface"`, `"cylindrical-surface"` and `"implicit-surface"`. When
the item cannot be drawn as that type, it keeps its usual reading, and a note
under the plot says so.

The other keys apply to some kinds of items. On another kind, a key does
nothing. A curve is a graph, or a parametric, implicit or polar curve.

| Key         | Value                                                                                                                           | Applies to                                                      |
| ----------- | ------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------- |
| `width`     | the line width in pixels, above 0 and up to 20                                                                                  | a curve, a vector field, a space curve                          |
| `opacity`   | 0 to 1                                                                                                                          | a curve, a heatmap, a vector field, points, every 3D item       |
| `dash`      | `"solid"`, `"dashed"`, `"dotted"`, `"dot-dash"`, `"dot-dot-dash"`, or a list of 2 to 8 dash and gap lengths in pixels: `[6, 3]` | a curve, the line through points                                |
| `fill`      | `true`, `false` or a color                                                                                                      | a graph, a parametric or polar curve (to the x axis), a surface |
| `arrows`    | `"end"`, `"start"`, `"both"`, `"none"`                                                                                          | a graph, a parametric or polar curve                            |
| `head`      | `"sharp"`, `"bar"`, `"disc"`, `"thin"`, `"wings"`, `"diamond"`, `"triangle"`, `"chevron"`                                       | the arrows of a curve, a vector field                           |
| `marker`    | `"circle"`, `"square"`, `"diamond"`, `"cross"`, `"plus"`, `"triangle"`, or `false` for no markers                               | points                                                          |
| `size`      | the marker size in pixels, above 0 and up to 40                                                                                 | points                                                          |
| `line`      | `true`, `false`: a line through the points, in their order                                                                      | points                                                          |
| `colormap`  | a palette name, such as `"viridis"`, `"magma"` or `"coolwarm"`                                                                  | a heatmap, a surface                                            |
| `contours`  | `true`, `false`, or a number of levels from 1 to 50                                                                             | a heatmap, a surface                                            |
| `grid`      | the number of arrows on each axis, from 2 to 60                                                                                 | a vector field                                                  |
| `scale`     | the arrow length, above 0, or `"auto"`                                                                                          | a vector field                                                  |
| `normalize` | `true`: all arrows have the same length                                                                                         | a vector field                                                  |
| `material`  | a material name, as listed below                                                                                                | a 3D surface or space curve                                     |
| `wireframe` | `true`, `false`                                                                                                                 | a surface                                                       |

The materials are `"default"`, `"chrome"`, `"glass"`, `"metallicPaint"`,
`"ceramic"`, `"rubber"`, `"gemstone"`, `"brushedMetal"`, `"pearl"`, `"normal"`,
`"multiply"`, `"screen"`, `"add"`, `"chalk"`, `"wetWatercolor"` and
`"dryWatercolor"`.

For example, `(x => floor(x), {color -> "gray", width -> 5, opacity -> 0.5})`
draws a thick, light staircase, and this plot draws a heatmap with contour lines
under a dashed line with an arrow:

```
plot([((x, y) => sin(x)*cos(y), {type -> "heatmap", colormap -> "magma", contours -> 8}), (x => x/2, {dash -> "dashed", arrows -> "end"})], {x -> (-3, 3), y -> (-3, 3)})
```

With `colormap`, a heatmap or a surface takes the colors of the palette, also
when the item has a `color`.

The second argument of `plot` is a dictionary of options: `x -> (min, max)`,
`y -> (min, max)`, `t -> (min, max)` (the range of the parameter of a curve),
`title -> "…"`, `legend -> true`, and `aspect -> "equal"` or `aspect -> "auto"`.
When you give both `x` and `y`, the plot shows both ranges whole.

Other options set how the plot looks, as the plot inspector does:

| Option                                   | Values                                                                                     |
| ---------------------------------------- | ------------------------------------------------------------------------------------------ |
| `coordinates`                            | `"cartesian"`, `"polar"` (a function `t => …` of one number is then the radius `r = f(θ)`) |
| `grid`                                   | `true`, `false`, `"lines"`, `"lines-x"`, `"lines-y"`, `"dots"`, `"isometric"`              |
| `axes`, `frame`                          | `true`, `false`                                                                            |
| `xLabel`, `yLabel`                       | a string; math in one `$…$` pair, as `"$\theta$"`                                          |
| `axisPosition`                           | `"edge"`, `"origin"`                                                                       |
| `theme`                                  | `"signal"`, `"vellum"`, `"academic"`, `"seminar"`: the colors of that document preset      |
| `dark`                                   | `true`, `false`: the dark or the light version; Signal has both                            |
| `palette`                                | `"tycho11"`, `"tableau10"`, `"kelly22"`, `"mathematica10"`, `"spectrum12"`                 |
| `background`                             | a color, as `color` takes: `"white"`, `"#fdf6e3"`                                          |
| `vignette`                               | 0 to 1: darken the edges                                                                   |
| `crosshair`, `specialValues`, `lockView` | `true`, `false`; `lockView -> true` stops pan and zoom                                     |

Without `theme`, a plot takes the colors of the document's preset, and without
`dark` it is light or dark as the document is. The older theme names `"light"`,
`"dark"`, `"publication"` and `"presentation"` still work, with a note that
gives the new one.

A 2D plot fills its area, with the tick labels inside it. With `frame -> true`
or `axisPosition -> "edge"`, the plot keeps margins for the tick labels, outside
the area where the curves are drawn.

```
plot(x => sin(x), {grid -> "dots", xLabel -> "$t$", theme -> "vellum"})
```

A run that changes only these options keeps the view that the reader panned or
zoomed to.

With `complex -> true`, a function of `z` is a domain coloring of the complex
plane over the `x` and `y` ranges:

```
plot(z => z^2, {complex -> true, x -> (-2, 2), y -> (-2, 2)})
```

To mark the plot, give the option `markers` a list of dictionaries, one per
marker. The key that gives the position gives the kind of the marker:

| Marker | Dictionary                         | Style keys                                                             |
| ------ | ---------------------------------- | ---------------------------------------------------------------------- |
| point  | `{point -> (1, 2)}`                | `color`, `marker`, `size`, as for points                               |
| label  | `{label -> "max", at -> (1, 2)}`   | `color` (the text), `background` (a box)                               |
| rule   | `{x -> 2}` or `{y -> 0.5}`         | `color`, `width`, `dash` (a name or a list of lengths, as for an item) |
| band   | `{x -> (1, 2)}` or `{y -> (0, 1)}` | `color`, `opacity`                                                     |

A rule is a vertical line at `x` or a horizontal line at `y`, and a band is the
strip between two values. A label is plain text, or math in one `$…$` pair.
Without `color`, a marker takes the marker colors of the plot's preset.

```
plot(x => sin(x), {markers -> [{point -> (pi/2, 1), color -> "crimson"}, {label -> "max", at -> (pi/2, 1.15)}, {x -> pi, dash -> "dashed"}, {y -> (-0.5, 0.5), opacity -> 0.15}]})
```

For a 3D plot that the reader can turn, use `plot3d`. An item is a surface
`(x, y) => sin(x)*cos(y)` or `sin(x)*cos(y)`, a space curve
`t => (cos(t), sin(t), t/5)`, a parametric surface `(u, v) => (…, …, …)` or a
list of points `[(0, 0, 0), (1, 2, 3)]`. An item takes the style keys as for
`plot`. The options are `x`, `y`, `z -> (min, max)`, `t`, `title` and `legend`
as for `plot`, and:

| Option                                       | Values                                                      |
| -------------------------------------------- | ----------------------------------------------------------- |
| `aspect`                                     | `"data"` (equal units, also `"equal"`), `"cube"`, `"auto"`  |
| `environment`                                | `"abstract"`, `"outdoor"`, `"paper"`                        |
| `projection`                                 | `"perspective"`, `"orthographic"`                           |
| `orbit`                                      | `true`, `false`, or a speed in radians per second, up to 10 |
| `grid`, `axes`, `floor`, `walls`, `tooltips` | `true`, `false`                                             |
| `background`                                 | a color, as for `plot`: the sky, or the paper               |
| `theme`, `dark`                              | as for `plot`                                               |
| `lockView`                                   | `true`, `false`                                             |
| `markers`                                    | points and labels, as for `plot`, with `(x, y, z)`          |

A plot takes the values of the names that its functions read when the program
runs. An item that the plot cannot use is left out, and a note under the plot
says why.
