Format toc numbers with "01", "02" instead "1", "2" in Rmarkdown

Hi!

I'd like to be able to format the toc number like this:

  • 01 First Section
  • 02 Second Section
  • and so on, until 09

By default it's:

  • 1 First Section
  • 2 Second Section

Is there a dedicated way to do that? At the moment the only way I found was to add some custom JS but it feels like I'm over engineering.

Hi! Formatting TOC numbers with leading zeroes isn’t built into the default behavior, unfortunately.

So theres no official option in R Markdown or Quarto (assuming you're using one of those) to automatically format TOC numbers with leading zeroes out of the box. As you noted, the default just uses plain integers.

If you’ve already tried a JS-based workaround, you’re not over engineering, that’s actually the most common approach when native options are missing. Another (slightly hacky) alternative could be to manually prefix your section headers with 01 , 02 , etc, but that obviously doesn't scale well or work with auto-generated TOCs.

So while it might feel like a bit much, your JS method is probably the cleanest and most flexible solution until a native setting is added. If it's any comfort, others have resorted to the same.

Would be great to see this as a feature request upstream, honestly!

Hi, thanks for the answer. Here is what I ended up doing as the code was fairly quite simple:

const tocNumbers = document.querySelectorAll("#TOC .toc-section-number");

tocNumbers.forEach((span) => {
  const num = parseInt(span.textContent.trim(), 10);
  if (!isNaN(num) && num >= 1 && num <= 9) {
    span.textContent = `0${num}`;
  }
});
1 Like