# Defining LaTeX Macros

**URL:** https://talk.observablehq.com/t/defining-latex-macros/1310
**Category:** Help
**Created:** [October 11, 2018, 3:12pm UTC](https://talk.observablehq.com/t/defining-latex-macros/1310 "2018-10-11T15:12:21Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![krisrs1128](https://yyz2.discourse-cdn.com/flex030/user_avatar/talk.observablehq.com/krisrs1128/32/2055_2.png) [@krisrs1128](https://talk.observablehq.com/u/krisrs1128)
#### Post date: [October 11, 2018, 3:12pm UTC](https://talk.observablehq.com/t/defining-latex-macros/1310/1 "2018-10-11T15:12:21Z")

</div>

Is it possible to define LaTeX macros in a notebook? For example, I would like to write `${tex`\def\reals{\mathbb{R}`}` somewhere and then be able to refer to `${tex`\reals`}` elsewhere (ideally, across different blocks).

---

<div class="post-metadata">

### Author: ![mbostock](https://yyz2.discourse-cdn.com/flex030/user_avatar/talk.observablehq.com/mbostock/32/9_2.png) [@mbostock](https://talk.observablehq.com/u/mbostock)
#### Post date: [October 11, 2018, 3:48pm UTC](https://talk.observablehq.com/t/defining-latex-macros/1310/2 "2018-10-11T15:48:30Z")

</div>

There are a few ways to do this, but the best option may be to augment the standard library slightly to allow passing options through to KaTeX.

We’re using [KaTeX 0.10-beta](https://github.com/Khan/KaTeX/releases), which _does_ support `\def`, but this only affects the given input to `tex`—it doesn’t persistently change the behavior of `tex`. This is good because it avoids mutable state and nondeterministic behavior. (KaTeX also appears to support `\gdef`, which sounds like it would persistently change the behavior of `tex`, but I couldn’t get it to work and wouldn’t recommend it anyway.)

Defining a macro to use it once isn’t especially useful, but it works:

```auto
tex`\def\reals{\mathbb{R}} \reals^2`

```

To make reusable macros, you could have a _macros_ cell to define your macros, and then embed them wherever you call `tex`. Note you’ll need String.raw to avoid double-backslashes.

```auto
macros = String.raw`\def\reals{\mathbb{R}}`

```

```auto
tex`${macros}\reals^2`

```

You can go one step further and define a wrapper for `tex` that has your macros in it:

```auto
function mtex() {
  return tex`
\def\reals{\mathbb{R}}
${String.raw.apply(String, arguments)}
`;
}

```

```auto
mtex`\reals`

```

If you want total control, here’s how do define your own template literal using KaTeX directly:

```auto
katex = require("katex")

```

```auto
function mtex() {
  const root = document.createElement("div");
  katex.render(String.raw.apply(String, arguments), root, {
    macros: {
      "\\reals": "\\mathbb{R}"
    }
  });
  return root.removeChild(root.firstChild);
}

```

In the future, I’d like something like this:

```auto
mtex = tex.options({
  macros: {
    "\\reals": "\\mathbb{R}"
  }
})

```
