# `Expresso.Element.Math.Rule`
[🔗](https://github.com/rellen/expresso/blob/main/lib/expresso/element/math/rule.ex#L1)

A rule with variables for a rewrite of a derivation

The `rule` option of a rewrite gives a left side and a right side in LaTeX,
such as `{~S"a\,(b + c)", ~S"a\,b + a\,c"}`, and `vars` names the
variables. `match/6` finds the first match of the left side in the old line,
from the left and from the outside in, and binds each variable to one
operand:

  * a symbol or a command, with its scripts unless the pattern puts a
    script after the variable,
  * a brace group,
  * a group in parentheses, from `(` to its `)`.

The match skips spaces, such as `\,`. A variable that occurs two times
must bind equal LaTeX. A brace group or a command of the pattern matches
its groups in full.

The function gives the first binding of each variable the part `var-k-x`
and the match the part `rule-k` in the old line, and it returns the right
side as a template of `Expresso.Element.Math.Rewrite`, with
`\use{var-k-x}` in place of each variable. The match does not cross a
`\part` or a `\from` of the old line, but it looks inside them.
`docs/line-rewrites.md` gives the design.

# `match`

```elixir
@spec match(
  [Expresso.Element.Math.Latex.atom_t()],
  String.t(),
  String.t(),
  [String.t()],
  String.t() | nil,
  pos_integer()
) ::
  {:ok, [Expresso.Element.Math.Latex.atom_t()], String.t()}
  | {:error, String.t()}
```

Match a rule in the atoms of an old line

`scope` is the name of a part that holds the match, or `nil` for the whole
line. The function returns the atoms of the old line with the parts of the
match, and the template of the new content.

    iex> {:ok, atoms} = Expresso.Element.Math.Latex.parse(~S"y = 2\,(x + 1)")
    iex> {:ok, old, template} =
    ...>   Expresso.Element.Math.Rule.match(atoms, ~S"a\,(b + c)", ~S"a\,b + a\,c", ~w(a b c), nil, 2)
    iex> Expresso.Element.Math.Latex.write(old)
    ~S"y = \part{rule-2}{\part{var-2-a}{2}\,(\part{var-2-b}{x} + \part{var-2-c}{1})}"
    iex> template
    ~S"\use{var-2-a}\,\use{var-2-b} + \use{var-2-a}\,\use{var-2-c}"

---

*Consult [api-reference.md](api-reference.md) for complete listing*
