Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to customise section headings to start with letters in r markdown

Tags:

r

r-markdown

While we can automate number section by adding the option number_sections: true to in the YAML header, I wonder if we can change the headings style in r markdown. For example, can we customise it with letters like following?

A. Section A

A.1 Subsection

A.1.1 Sub subsection 1

A.1.2 Sub subsection 1

B. Section B

B.1 Subsection

B.1.1 Sub subsection

like image 312
Yongkai Avatar asked Oct 15 '25 16:10

Yongkai


1 Answers

Answer for pdf_document

Save this line in an external file (e.g. inheader.tex):

\renewcommand{\thesection}{\Alph{section}}

and insert the file in document's header with:

---
title: "Lettered sections"
output: 
  pdf_document:
    number_sections: true
    includes:
      in_header: inheader.tex
---

Answer for html_document format

tl;dr

Knit this Rmd file:

---
title: "Lettered sections"
output: html_document
---

```{css, echo=FALSE}
.header-section-number {
  display: none;
}

body {
  counter-reset: counter-level-1;
}

h1:not(.title) {
  counter-increment: counter-level-1;
  counter-reset: counter-level-2;
}

h1:not(.title)::before{
  content: counter(counter-level-1, upper-alpha) ". ";
}

h2 {
  counter-increment: counter-level-2;
  counter-reset: counter-level-3;
}

h2::before {
  content: counter(counter-level-1, upper-alpha) "." counter(counter-level-2) " ";
}

h3 {
  counter-increment: counter-level-3;
}

h3::before {
  content: counter(counter-level-1, upper-alpha) "." counter(counter-level-2) "." counter(counter-level-3) " ";
}
```

# Section

## Subsection

### Sub subsection

### Sub subsection

## Subsection

# Section

## Subsection

### Sub subsection

## Subsection

Explanations
Number sections is a native pandoc's option. It seems that pandoc does not provide any support for hierarchical headings customisation.

So, there are three options with HTML output:

  • deeply dive into pandoc and develop a new writer, because hierarchical headings are declared as integers see here, line #105. Note there's a relevant recent issue in order to facilitate headings customisation.
  • modify HTML rendering using CSS.
  • modify HTML elements with Javascript. This may be necessary for toc: true.

This answer provides an example of hierarchical headings customisation with CSS. It is recommended to save all the CSS code (i.e. lines 7 to 39) to an external file with .css extension and include it in HTML report using this YAML header:

---
title: "Lettered sections"
output: 
  html_document:
    css: "filename.css"
---

Additional note
One can use other counters than numeric or alpha, see here for a list.
You also can define your own set of counter with @counter-style.

like image 68
RLesur Avatar answered Oct 17 '25 07:10

RLesur